Metadata
Key | Value |
---|---|
engine | transformers |
prompt | completion |
temp | 0.2 |
top_p | 0.95 |
max_new_tokens | 1024 |
n_completions | 10 |
Solutions
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
for i in 0..<numbers.count {
for j in (i + 1)..<numbers.count {
if abs(numbers[i] - numbers[j]) < threshold {
return true
}
}
}
return false
}
```
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup = ""
var parenStack: [Character] = []
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
currentGroup.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
if currentGroup.count > 0 {
result.append(currentGroup)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup = ""
var parenStack: [Character] = []
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
currentGroup.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
if currentGroup.count > 0 {
result.append(currentGroup)
}
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "()") == ["()"])
assert(separateParenGroups(parenString: "(())") == ["(())"])
assert(separateParenGroups(parenString: "()()()") == ["()", "()", "()", "()"])
assert(separateParenGroups(parenString: "()(((())))") == ["()", "(((())))"])
assert(separateParenGroups(parenString: "()()()(((())))()()()()") == ["()", "()", "()", "(((())))", "()", "()", "()", "()"])
assert(separateParenGroups(parenString: "()(((())))()()()()(((()))()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup = ""
var parenCount = 0
for char in parenString {
if char == "(" {
parenCount += 1
} else if char == ")" {
parenCount -= 1
} else if char == " " && parenCount == 0 {
result.append(currentGroup)
currentGroup = ""
} else {
currentGroup.append(char)
}
}
result.append(currentGroup)
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup = ""
var parenCount = 0
for char in parenString {
if char == "(" {
parenCount += 1
} else if char == ")" {
parenCount -= 1
} else if char == " " && parenCount == 0 {
result.append(currentGroup)
currentGroup = ""
} else {
currentGroup.append(char)
}
}
result.append(currentGroup)
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "()()()") == ["()()()"])
assert(separateParenGroups(parenString: "()(((()))())()") == ["()(((()))())()"])
assert(separateParenGroups(parenString: "()(((()))())()()") == ["()(((()))())()()", "()()()"])
assert(separateParenGroups(parenString: "()(((()))())()()()(())()()()") == ["()(((()))())()()", "()()()"])
assert(separateParenGroups(parenString: "()(((()))())()()()(((()))()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
//: [Next](@next)
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenCount = 0
for char in parenString {
if char == "(" {
parenCount += 1
} else if char == ")" {
parenCount -= 1
} else if char == " " {
continue
}
currentGroup += String(char)
if parenCount == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenCount = 0
for char in parenString {
if char == "(" {
parenCount += 1
} else if char == ")" {
parenCount -= 1
} else if char == " " {
continue
}
currentGroup += String(char)
if parenCount == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "((()))") == ["((()))"])
assert(separateParenGroups(parenString: "()()()") == ["()()()", "()()()"])
assert(separateParenGroups(parenString: "()((()())") == ["()((()()", "()((()()"])
assert(separateParenGroups(parenString: "()()(((()())") == ["()()(((()()", "()()(((()()"])
assert(separateParenGroups(parenString: "()()(((()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup: String = ""
var parenStack: [Character] = []
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
currentGroup.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
if currentGroup.count > 0 {
result.append(currentGroup)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result: [String] = []
var currentGroup: String = ""
var parenStack: [Character] = []
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
currentGroup.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
if currentGroup.count > 0 {
result.append(currentGroup)
}
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "( ( ( a ) ) )") == ["( ( ( a ) ) )"])
assert(separateParenGroups(parenString: "a ( b ) ( c ) d ( e ) f") == ["a ( b ) ( c )", "d ( e ) f"])
assert(separateParenGroups(parenString: "a ( b ( c ) d ( e ) f ) g") == ["a ( b ( c ) d ( e ) f )", "g"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ( e ( f ) g ) h ) i ) j ) k") == ["a ( b ( c ( d ( e ( f ) g ) h ) i ) j )", "k"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )") == ["a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l ) m ( n ( o ( p ) q ) r ) s") == ["a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )", "m ( n ( o ( p ) q ) r )", "s"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l ) m ( n ( o ( p ) q ) r ) s ( t ( u ( v ) w ) x ) y") == ["a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )", "m ( n ( o ( p ) q ) r )", "s ( t ( u ( v ) w ) x )", "y"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l ) m ( n ( o ( p ) q ) r ) s ( t ( u ( v ) w ) x ) y z") == ["a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )", "m ( n ( o ( p ) q ) r )", "s ( t ( u ( v ) w ) x )", "y", "z"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l ) m ( n ( o ( p ) q ) r ) s ( t ( u ( v ) w ) x ) y z ( a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l ) m ( n ( o ( p ) q ) r ) s ( t ( u ( v ) w ) x ) y )") == ["a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )", "m ( n ( o ( p ) q ) r )", "s ( t ( u ( v ) w ) x )", "y", "z", "a ( b ( c ( d ( e ( f ( g ) h ) i ) j ) k ) l )", "m ( n ( o ( p ) q ) r )", "s ( t ( u ( v ) w ) x )", "y"])
assert(separ
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var parenStack = [Character]()
var parenGroups = [String]()
for char in parenString {
if char == "(" {
parenStack.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
} else {
parenGroups.append("()")
}
} else {
parenGroups.append("\(char)")
}
}
return parenGroups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var parenStack = [Character]()
var parenGroups = [String]()
for char in parenString {
if char == "(" {
parenStack.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
} else {
parenGroups.append("()")
}
} else {
parenGroups.append("\(char)")
}
}
return parenGroups
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "((()))") == ["((()))"])
assert(separateParenGroups(parenString: "()()()") == ["()()()", "()()()"])
assert(separateParenGroups(parenString: "()((())") == ["()((())"])
assert(separateParenGroups(parenString: "()()()()()") == ["()()()()()"])
assert(separateParenGroups(parenString: "()()(((()))()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()")OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenCount = 0
for char in parenString {
if char == "(" {
parenCount += 1
} else if char == ")" {
parenCount -= 1
} else if char == " " {
continue
} else {
currentGroup += String(char)
}
if parenCount == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenCount = 0
for char in parenString {
if char == "(" {
parenCount += 1
} else if char == ")" {
parenCount -= 1
} else if char == " " {
continue
} else {
currentGroup += String(char)
}
if parenCount == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "( ( ( ) ) )") == ["( ( ( ) ) )"])
assert(separateParenGroups(parenString: "()()()") == ["()()", "()()()"])
assert(separateParenGroups(parenString: "()(((()))()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenStack = [Character]()
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
currentGroup.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
result.append(currentGroup)
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenStack = [Character]()
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
currentGroup.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
result.append(currentGroup)
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "( ( ( ) ) )") == ["((())"])
assert(separateParenGroups(parenString: "()()()") == ["()","()","()"])
assert(separateParenGroups(parenString: "()(((()))())()") == ["()(((()))())()", "()()"])
assert(separateParenGroups(parenString: "()(((()))())()()") == ["()(((()))())()", "()()"])
assert(separateParenGroups(parenString: "()(((()))())()()()(())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
//: [Next](@next)
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var parenStack: [Character] = []
var parenGroup: [Character] = []
var parenGroups: [String] = []
for paren in parenString {
if paren == " " {
continue
}
if paren == "(" {
parenStack.append(paren)
parenGroup.append(paren)
} else if paren == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
parenGroup.append(paren)
} else {
parenGroups.append(String(parenGroup))
parenGroup = []
}
}
}
if parenGroup.count > 0 {
parenGroups.append(String(parenGroup))
}
return parenGroups
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var parenStack: [Character] = []
var parenGroup: [Character] = []
var parenGroups: [String] = []
for paren in parenString {
if paren == " " {
continue
}
if paren == "(" {
parenStack.append(paren)
parenGroup.append(paren)
} else if paren == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
parenGroup.append(paren)
} else {
parenGroups.append(String(parenGroup))
parenGroup = []
}
}
}
if parenGroup.count > 0 {
parenGroups.append(String(parenGroup))
}
return parenGroups
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "( ( ( ) ) )") == ["((())"])
assert(separateParenGroups(parenString: "()") == [""])
assert(separateParenGroups(parenString: "( ( ( ( () () ) ) ) )") == ["((())", "()()()"])
assert(separateParenGroups(parenString: "()()()") == ["()()()"])
assert(separateParenGroups(parenString: "()((())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
//: [Next](@next)
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [Character]()
var currentGroup = ""
for char in parenString {
if char == " " {
continue
}
if char == "(" {
stack.append(char)
currentGroup.append(char)
} else if char == ")" {
if stack.count > 0 {
stack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
result.append(currentGroup)
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var stack = [Character]()
var currentGroup = ""
for char in parenString {
if char == " " {
continue
}
if char == "(" {
stack.append(char)
currentGroup.append(char)
} else if char == ")" {
if stack.count > 0 {
stack.removeLast()
currentGroup.append(char)
} else {
result.append(currentGroup)
currentGroup = ""
}
} else {
currentGroup.append(char)
}
}
result.append(currentGroup)
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "( ( ( a ) ) ( b ) )") == [ "( ( ( a ) ) ( b ) )" ])
assert(separateParenGroups(parenString: "a ( b ) ( c ) d ( e ) f") == ["a ( b ) ( c )", "d ( e ) f"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ) g") == ["a ( b ( c ( d ) e ) f )", "g"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m )") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j ( k ( l ) m )"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m ) n") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j ( k ( l ) m )", "n"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m ) n ( o ( p ) q )") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j ( k ( l ) m )", "n ( o ( p ) q )"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m ) n ( o ( p ) q ) r") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j ( k ( l ) m )", "n ( o ( p ) q )", "r"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m ) n ( o ( p ) q ) r ( s ( t ) u ) v") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j ( k ( l ) m )", "n ( o ( p ) q )", "r ( s ( t ) u )", "v"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m ) n ( o ( p ) q ) r ( s ( t ) u ) v ( w ( x ) y ) z") == ["a ( b ( c ( d ) e ) f ( g ( h ) i ) )", "j ( k ( l ) m )", "n ( o ( p ) q )", "r ( s ( t ) u )", "v ( w ( x ) y )", "z"])
assert(separateParenGroups(parenString: "a ( b ( c ( d ) e ) f ( g ( h ) i ) ) j ( k ( l ) m ) n ( o ( p ) q ) r ( s ( t ) u ) v ( w ( x ) y ) z ( a ( b ( c ( d ) e ) f ( g ( h ) i )
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenStack = [Character]()
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
} else {
currentGroup += String(char)
}
} else {
currentGroup += String(char)
}
if parenStack.count == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var currentGroup = ""
var parenStack = [Character]()
for char in parenString {
if char == " " {
continue
}
if char == "(" {
parenStack.append(char)
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
} else {
currentGroup += String(char)
}
} else {
currentGroup += String(char)
}
if parenStack.count == 0 {
result.append(currentGroup)
currentGroup = ""
}
}
return result
}
// Test cases
assert(separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"])
assert(separateParenGroups(parenString: "((()))") == ["((()))"])
assert(separateParenGroups(parenString: "()()()") == ["()()()"])
assert(separateParenGroups(parenString: "()((()())") == ["()((()()", "()((()()"])
assert(separateParenGroups(parenString: "()((()())") == ["()((()()", "()((()()"])
assert(separateParenGroups(parenString: "()((()())()()()()") == ["()((()()", "()((()()"])
assert(separateParenGroups(parenString: "()((()())()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
// XCTAssertTrue failed
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt128) -> Double {
return Double(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))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt128) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, it can be decomposed into
func truncateNumber(_ number: UInt128) -> Double { // cannot find type 'UInt128' in scope
func truncateNumber(number: Double) -> Double {
return number - floor(number)
}
func truncateNumber(number: Int) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: Int) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: Double) -> Double {
return number - floor(number)
}
func truncateNumber(_ number: Float) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - floor(Double(number))
}
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - floor(Double(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 integer, 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: 35) == 0.5
func truncateNumber(number: Int) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: Int) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: Double) -> Double {
return number - floor(number)
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: Float) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - floor(Double(number))
}
// Given a positive integer, 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: 35) == 0.5
func truncateNumber(_ number: UInt128) -> Double {
return Double(number) - floor(Double(number))
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func nextSmallestPalindrome(number: Int) -> Int {
let numberString = String(number)
let reversedString = String(numberString.characters.reverse())
let reversedPlusNumber = numberString + reversedString
let plusOne = Int(reversedPlusNumber)! + 1
let plusOneString = String(plusOne)
let plusOneReversed = String(plusOneString.characters.reverse())
let plusOneReversedPlusNumber = plusOneString + plusOneReversed
return Int(plusOneReversedPlusNumber)!
}
func nextLargestPalindrome(number: Int) -> Int {
let numberString = String(number)
let reversedString = String(numberString.characters.reverse())
let reversedPlusNumber = numberString + reversedString
return Int(reversedPlusNumber)!
}
func digits(number: Int) -> Int {
return String(number).characters.count
}
func sumDigits(number: Int) -> Int {
var sum = 0
let numberString = String(number)
for character in numberString.characters {
sum += Int(String(character))!
}
return sum
}
func sumSquaredDigits(number: Int) -> Int {
var sum = 0
let numberString = String(number)
for character in numberString.characters {
let digit = Int(String(character))!
sum += digit * digit
}
return sum
}
func difference(number: Int) -> Int {
return sumDigits(number) - sumSquaredDigits(number)
}
func isPalindrome(number: Int) -> Bool {
let numberString = String(number)
let reversedString = String(numberString.characters.reverse())
return numberString == reversedString
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
func nextPrime(number: Int) -> Int {
var nextPrime = number
while true {
nextPrime += 1
if isPrime(nextPrime) {
return nextPrime
}
}
}
func previousPrime(number: Int) -> Int {
var previousPrime = number
while true {
previousPrime -= 1
if isPrime(previousPrime) {
return previousPrime
}
}
}
```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))
}
// Given a positive integer, return the next smallest palindrome.
// nextSmallestPalindrome(123) == 121
// nextSmallestPalindrome(100) == 909
func nextSmallestPalindrome(number: Int) -> Int {
let numberString = String(number)
let reversedString = String(numberString.characters.reverse())
let reversedPlusNumber = numberString + reversedString
let plusOne = Int(reversedPlusNumber)! + 1
let plusOneString = String(plusOne)
let plusOneReversed = String(plusOneString.characters.reverse())
let plusOneReversedPlusNumber = plusOneString + plusOneReversed
return Int(plusOneReversedPlusNumber)!
}
// Given a positive integer, return the next largest palindrome.
// nextLargestPalindrome(123) == 321
// nextLargestPalindrome(100) == 999
func nextLargestPalindrome(number: Int) -> Int {
let numberString = String(number)
let reversedString = String(numberString.characters.reverse())
let reversedPlusNumber = numberString + reversedString
return Int(reversedPlusNumber)!
}
// Given a positive integer, return the number of digits in it.
// digits(123) == 3
// digits(100) == 2
func digits(number: Int) -> Int {
return String(number).characters.count
}
// Given a positive integer, return the sum of its digits.
// sumDigits(123) == 6
// sumDigits(100) == 1
func sumDigits(number: Int) -> Int {
var sum = 0
let numberString = String(number)
for character in numberString.characters {
sum += Int(String(character))!
}
return sum
}
// Given a positive integer, return the sum of its digits squared.
// sumSquaredDigits(123) == 14
// sumSquaredDigits(100) == 100
func sumSquaredDigits(number: Int) -> Int {
var sum = 0
let numberString = String(number)
for character in numberString.characters {
let digit = Int(String(character))!
sum += digit * digit
}
return sum
}
// Given a positive integer, return the difference between the sum of its
// digits and the sum of its squared digits.
// difference(123) == 6
// difference(100) == 2
func difference(number: Int) -> Int {
return sumDigits(number) - sumSquaredDigits(number)
}
// Given a positive integer, return true if it is a palindrome.
// isPalindrome(121) == true
// isPalindrome(123) == false
func isPalindrome(number: Int) -> Bool {
let numberString = String(number)
let reversedString = String(numberString.characters.reverse())
return numberString == reversedString
}
// Given a positive integer, return true if it is a prime number.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(4) == false
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
// Given a positive integer, return the next prime number.
// nextPrime(1) == 2
// nextPrime(2) == 3
// nextPrime(4) == 5
func nextPrime(number: Int) -> Int {
var nextPrime = number
while true {
nextPrime += 1
if isPrime(nextPrime) {
return nextPrime
}
}
}
// Given a positive integer, return the previous prime number.
// previousPrime(1) == 1
// previousPrime(2) == 1
// previousPrime(3) == 2
func previousPrime(number: Int) -> Int {
var previousPrime = number
while true {
previousPrime -= 1
if isPrime(previousPrime) {
return previousPrime
}
}
}
// Given a positive integer
let reversedString = String(numberString.characters.reverse()) // value of type 'String' has no member 'reverse'
let reversedString = String(numberString.characters.reverse()) // value of type 'String' has no member 'reverse'
return String(number).characters.count // 'characters' is unavailable: Please use String directly
for character in numberString.characters { // 'characters' is unavailable: Please use String directly
for character in numberString.characters { // 'characters' is unavailable: Please use String directly
return sumDigits(number) - sumSquaredDigits(number) // missing argument label 'number:' in call
return sumDigits(number) - sumSquaredDigits(number) // missing argument label 'number:' in call
let reversedString = String(numberString.characters.reverse()) // value of type 'String' has no member 'reverse'
if isPrime(nextPrime) { // missing argument label 'number:' in call
if isPrime(previousPrime) { // missing argument label 'number:' in call
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncate
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt128) -> Double {
return Double(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))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt128) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, it can be decomposed into
func truncateNumber(_ number: UInt128) -> Double { // cannot find type 'UInt128' in scope
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
func truncateNumber(number: Int) -> Int {
return 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))
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt128) -> Double {
return Double(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))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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: 35) == 5
func truncateNumber(_ number: UInt128) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, it can be decomposed into
func truncateNumber(_ number: UInt128) -> Double { // cannot find type 'UInt128' in scope
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
func truncateNumber(number: Int) -> Int {
return number
}
func truncateNumber(_ number: Int) -> Int {
return 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))
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, it can be decomposed into
// and integer part (largest integer smaller than given number)
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Double) -> Int {
return Int(number)
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
func truncateNumber(number: Int) -> Int {
return number
}
func truncateNumber(_ number: Int) -> Int {
return 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))
}
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
return Int(number)
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(number)
}
// Given a positive integer, 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) == 3
func truncateNumber(number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, 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) == 3
func truncateNumber(_ number: Int) -> Int {
return number
}
// Given a positive integer, it can be decomposed into
// and integer part (largest integer smaller than given number)
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
func truncateNumber(_ number: UInt128) -> Double {
return Double(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))
}
// Given a positive integer, 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) == 0
func truncateNumber(number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: Int) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: Double) -> Double {
return number - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: Float) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: UInt) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: UInt8) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: UInt16) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: UInt32) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: UInt64) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, 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) == 0
func truncateNumber(_ number: UInt128) -> Double {
return Double(number) - Double(Int(number))
}
// Given a positive integer, it can be decomposed into
// and integer part (largest integer smaller
func truncateNumber(_ number: UInt128) -> Double { // cannot find type 'UInt128' in scope
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
```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
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 10, 100, 1000]) == 999
func difference(array: [Int]) -> Int {
return array.max()! - array.min()!
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
//
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func difference(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return max - min
}
func sum(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return min + max
}
func product(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return min * max
}
func average(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return Double(max - min) / Double(array.count)
}
func averageSum(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return Double(min + max) / Double(array.count)
}
func squareAverage(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return Double((max - min) * (max - min)) / Double(array.count)
}
```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
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// difference([1, 2, 3]) == 2
// difference([5, 2, 1, 8, 3]) == 7
func difference(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return max - min
}
// You're given an array of integers. Your task is to return the sum of the largest and smallest
// numbers in the array.
// sum([1, 2, 3]) == 6
// sum([5, 2, 1, 8, 3]) == 14
func sum(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return min + max
}
// You're given an array of integers. Your task is to return the product of the largest and smallest
// numbers in the array.
// product([1, 2, 3]) == 6
// product([5, 2, 1, 8, 3]) == 40
func product(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return min * max
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers divided by the length of the array.
// average([1, 2, 3]) == 2/3
// average([5, 2, 1, 8, 3]) == 11/5
func average(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return Double(max - min) / Double(array.count)
}
// You're given an array of integers. Your task is to return the sum of the largest and smallest
// numbers divided by the length of the array.
// averageSum([1, 2, 3]) == 2/3
// averageSum([5, 2, 1, 8, 3]) == 11/5
func averageSum(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return Double(min + max) / Double(array.count)
}
// You're given an array of integers. Your task is to return the difference between the largest and
// smallest numbers squared and divided by the length of the array.
// squareAverage([1, 2, 3]) == 2/3
// squareAverage([5, 2, 1, 8, 3]) == 11/5
func squareAverage(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return Double((max - min) * (max - min)) / Double(array.count)
}
// You're given an array of integers. Your task is to return the sum of the largest and smallest
// numbers squared and divided by the length of the array.
// squareSum([1, 2, 3]) == 2/3
// squareSum([5, 2, 1, 8, 3]) == 11/5
func squareSum(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for element in array {
if element < min {
min = element
}
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func difference(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for number in array {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
func average(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for number in array {
if number > max {
max = number
}
if number < min {
min = number
}
}
return Double(max - min) / Double(array.count)
}
func greaterAverage(array: [Int]) -> Int {
var count = 0
let average = average(array: array)
for number in array {
if number > average {
count += 1
}
}
return count
}
func lessAverage(array: [Int]) -> Int {
return array.count - greaterAverage(array: array)
}
func divisibleByThree(array: [Int]) -> Int {
var count = 0
for number in array {
if number % 3 == 0 {
count += 1
}
}
return count
}
func sumDivisibleByThree(array: [Int]) -> Int {
var sum = 0
for number in array {
if number % 3 == 0 {
sum += number
}
}
return sum
}
func countDivisibleByThree(array: [Int]) -> Int {
var count = 0
for number in array {
if number % 3 == 0 {
count += 1
}
}
return count
}
func sumDivisibleByFive(array: [Int]) -> Int {
var sum = 0
for number in array {
if number % 5 == 0 {
sum += number
}
}
return sum
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// You're given an array of integers. Your task is to return the difference between the largest
// and smallest numbers in the array.
// difference([1, 2, 3]) == 2
// difference([5, 2, 3, 1]) == 4
func difference(array: [Int]) -> Int {
var min = Int.max
var max = Int.min
for number in array {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
// You're given an array of integers. Your task is to return the difference between the largest
// and smallest numbers divided by the length of the array.
// average([1, 2, 3]) == 2/3
// average([5, 2, 3, 1]) == 4/4
func average(array: [Int]) -> Double {
var min = Int.max
var max = Int.min
for number in array {
if number > max {
max = number
}
if number < min {
min = number
}
}
return Double(max - min) / Double(array.count)
}
// You're given an array of integers. Your task is to return the number of values that are
// greater than the average value.
// greaterAverage([1, 2, 3]) == 0
// greaterAverage([5, 2, 3, 1]) == 2
func greaterAverage(array: [Int]) -> Int {
var count = 0
let average = average(array: array)
for number in array {
if number > average {
count += 1
}
}
return count
}
// You're given an array of integers. Your task is to return the number of values that are
// less than the average value.
// lessAverage([1, 2, 3]) == 3
// lessAverage([5, 2, 3, 1]) == 1
func lessAverage(array: [Int]) -> Int {
return array.count - greaterAverage(array: array)
}
// You're given an array of integers. Your task is to return the number of values that are
// divisible by 3.
// divisibleByThree([1, 2, 3]) == 0
// divisibleByThree([3, 6, 9]) == 1
func divisibleByThree(array: [Int]) -> Int {
var count = 0
for number in array {
if number % 3 == 0 {
count += 1
}
}
return count
}
// You're given an array of integers. Your task is to return the sum of the values that are
// divisible by 3.
// sumDivisibleByThree([1, 2, 3]) == 0
// sumDivisibleByThree([3, 6, 9]) == 18
func sumDivisibleByThree(array: [Int]) -> Int {
var sum = 0
for number in array {
if number % 3 == 0 {
sum += number
}
}
return sum
}
// You're given an array of integers. Your task is to return the number of values that are
// divisible by 3.
// countDivisibleByThree([1, 2, 3]) == 0
// countDivisibleByThree([3, 6, 9]) == 1
func countDivisibleByThree(array: [Int]) -> Int {
var count = 0
for number in array {
if number % 3 == 0 {
count += 1
}
}
return count
}
// You're given an array of integers. Your task is to return the sum of the values that are
// divisible by 3.
// sumDivisibleByThree([1, 2, 3]) == 0
// sumDivisibleByThree([3, 6, 9]) == 18
func sumDivisibleByFive(array: [Int]) -> Int {
var sum = 0
for number in array {
if number % 5 == 0 {
sum += number
}
}
return sum
}
// You're
if number > average { // binary operator '>' cannot be applied to operands of type 'Int' and 'Double'
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func countChange(numbers: [Int]) -> [Int] {
var result = [0, 0]
for number in numbers {
if number > result[0] {
result[1] += 1
} else if number < result[0] {
result[1] += 1
result[0] = number
}
}
return result
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than the previous element, and the count of numbers that are smaller than
// the previous element. The first element should be a count of 0.
// countChange([1, 2, 3, 4, 5]) == [0, 1, 1, 2, 3]
// countChange([5, 4, 3, 2, 1]) == [1, 0, 0, 0, 0]
func countChange(numbers: [Int]) -> [Int] {
var result = [0, 0]
for number in numbers {
if number > result[0] {
result[1] += 1
} else if number < result[0] {
result[1] += 1
result[0] = number
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than the previous element, and the count of numbers that are smaller than
// the previous element. The first element should be a count of 0.
// countChange([1, 2, 3, 4, 5]) == [0, 1, 1, 2, 3]
// countChange([5, 4, 3, 2, 1]) == [1, 0, 0, 0, 0]
func countChange(numbers: [Int]) -> [Int] {
var result = [0, 0]
for number in numbers {
if number > result[0] {
result[1] += 1
} else if number < result[0] {
result[1] += 1
result[0] = number
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than the previous element, and the count of numbers that are smaller than
// the previous element. The first element should be a count of 0.
// countChange([1, 2, 3, 4, 5]) == [0, 1, 1, 2, 3]
// countChange([5, 4, 3, 2, 1]) == [1, 0, 0, 0, 0]
func countChange(numbers: [Int]) -> [Int] {
var result = [0, 0]
for number in numbers {
if number > result[0] {
result[1] += 1
} else if number < result[0] {
result[1] += 1
result[0] = number
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than the previous element, and the count of numbers that are smaller than
// the previous element. The first element should be a count of 0.
// countChange([1, 2, 3, 4, 5]) == [0, 1, 1, 2, 3]
// countChange([5, 4, 3, 2, 1]) == [1, 0, 0, 0, 0]
func countChange(numbers: [Int]) -> [Int] {
var result = [0, 0]
for number in numbers {
if number > result[0] {
result[1] += 1
} else if number < result[0] {
result[1] += 1
result[0] = number
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than the previous element, and the count of numbers that are smaller than
// the previous element. The first element should be a count of 0.
// countChange([1, 2, 3, 4, 5]) == [0, 1, 1, 2, 3]
// countChange([5, 4, 3, 2, 1]) == [1, 0, 0, 0, 0]
func countChange(numbers:
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func difference(array: [Int]) -> Int {
var min = array[0]
var max = array[0]
for number in array {
if number > max {
max = number
} else if number < min {
min = number
}
}
return max - min
}
func sumAndDifference(array: [Int]) -> (Int, Int) {
var min = array[0]
var max = array[0]
for number in array {
if number > max {
max = number
} else if number < min {
min = number
}
}
return (min + max, max - min)
}
func countZerosAndOnes(array: [Int]) -> Int {
var zeros = 0
var ones = 0
for element in array {
if element == 0 {
zeros += 1
} else {
ones += 1
}
}
return zeros == ones? array.count : 0
}
func countZerosAndOnesExcludingSelf(array: [Int]) -> Int {
var zeros = 0
var ones = 0
var result = 0
for element in array {
if element == 0 {
zeros += 1
} else {
ones += 1
}
if zeros!= ones {
result += 1
}
}
return result
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// You're given an array of integers. Your task is to return the difference between the largest
// and smallest numbers in the array.
// difference([5, 2, 7, 1, 9]) == 8
// difference([1, 2, 3, 4, 5]) == 4
func difference(array: [Int]) -> Int {
var min = array[0]
var max = array[0]
for number in array {
if number > max {
max = number
} else if number < min {
min = number
}
}
return max - min
}
// You're given an array of integers. Your task is to return the sum of the largest and smallest
// numbers, and the difference between the largest and smallest numbers.
// sumAndDifference([5, 2, 7, 1, 9]) == (19, 8)
// sumAndDifference([1, 2, 3, 4, 5]) == (15, 4)
func sumAndDifference(array: [Int]) -> (Int, Int) {
var min = array[0]
var max = array[0]
for number in array {
if number > max {
max = number
} else if number < min {
min = number
}
}
return (min + max, max - min)
}
// You're given an array of integers. Your task is to return the number of subarrays that have an
// equal number of 0s and 1s.
// countZerosAndOnes([0, 1, 1, 0, 1]) == 4
// countZerosAndOnes([1, 1, 1, 1, 1]) == 0
func countZerosAndOnes(array: [Int]) -> Int {
var zeros = 0
var ones = 0
for element in array {
if element == 0 {
zeros += 1
} else {
ones += 1
}
}
return zeros == ones? array.count : 0
}
// You're given an array of integers. Your task is to return the number of subarrays that have an
// equal number of 0s and 1s, excluding subarrays where the number of 0s and 1s are the same.
// countZerosAndOnesExcludingSelf([0, 1, 1, 0, 1]) == 3
// countZerosAndOnesExcludingSelf([1, 1, 1, 1, 1]) == 0
func countZerosAndOnesExcludingSelf(array: [Int]) -> Int {
var zeros = 0
var ones = 0
var result = 0
for element in array {
if element == 0 {
zeros += 1
} else {
ones += 1
}
if zeros!= ones {
result += 1
}
}
return result
}
// You're given an array of integers. Your task is to return the number of subarrays that have an
// equal number of 0s and 1s, excluding subarrays where the number of 0s and 1s are the same.
// countZerosAndOnesExcludingSelf([0, 1, 1, 0, 1]) == 3
// countZerosAndOnesExcludingSelf([1, 1, 1, 1, 1]) == 0
func countZerosAndOnesExcludingSelf(array: [Int]) -> Int {
var zeros = 0
var ones = 0
var result = 0
for element in array {
if element == 0 {
zeros += 1
} else {
ones += 1
}
if zeros!= ones {
result += 1
}
}
return result
}
// You're given an array of integers. Your task is to return the number of subarrays that have an
// equal number of 0s and 1s, excluding subarrays where the number of 0s and 1s are the same.
// countZerosAndOnesExcludingSelf([0, 1, 1, 0, 1]) == 3
// countZerosAndOnesExcludingSelf([1, 1, 1, 1, 1]) ==
return zeros == ones? array.count : 0 // consecutive statements on a line must be separated by ';'
return zeros == ones? array.count : 0 // cannot convert return expression of type 'Bool' to return type 'Int'
return zeros == ones? array.count : 0 // expression of type 'Int' is unused
return zeros == ones? array.count : 0 // cannot use optional chaining on non-optional value of type 'Int'
return zeros == ones? array.count : 0 // consecutive statements on a line must be separated by ';'
return zeros == ones? array.count : 0 // expected expression
if zeros!= ones { // cannot force unwrap value of non-optional type 'Int'
if zeros!= ones { // use of '=' in a boolean context, did you mean '=='?
if zeros!= ones { // '=' must have consistent whitespace on both sides
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func difference(numbers: [Int]) -> Int {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
func average(numbers: [Int]) -> Double {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
if number < min {
min = number
}
}
return Double(max - min) / Double(numbers.count)
}
func sumSquares(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number
}
return sum
}
func sumCubes(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number * number
}
return sum
}
func sumNumbers(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func sumEven(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number % 2 == 0 {
sum += number
}
}
return sum
}
func sumOdd(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number % 2!= 0 {
sum += number
}
}
return sum
}
func sumPositive(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number > 0 {
sum += number
}
}
return sum
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// You're given an array of numbers. Your task is to return the difference between the largest
// and smallest numbers in the array.
// difference([5, 1, 3, 5]) == 4
// difference([1, 5, 7, 2]) == 4
func difference(numbers: [Int]) -> Int {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
// You're given an array of numbers. Your task is to return the difference between the largest
// and smallest numbers divided by the number of elements in the array.
// average([5, 1, 3, 5]) == 1.67
// average([1, 5, 7, 2]) == 3.5
func average(numbers: [Int]) -> Double {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number > max {
max = number
}
if number < min {
min = number
}
}
return Double(max - min) / Double(numbers.count)
}
// You're given an array of numbers. Your task is to return the sum of the squares of the
// numbers.
// sumSquares([5, 1, 3, 5]) == 56
// sumSquares([1, 5, 7, 2]) == 53
func sumSquares(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number
}
return sum
}
// You're given an array of numbers. Your task is to return the sum of the cubes of the
// numbers.
// sumCubes([5, 1, 3, 5]) == 125
// sumCubes([1, 5, 7, 2]) == 175
func sumCubes(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number * number
}
return sum
}
// You're given an array of numbers. Your task is to return the sum of the numbers.
// sumNumbers([5, 1, 3, 5]) == 15
// sumNumbers([1, 5, 7, 2]) == 12
func sumNumbers(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// You're given an array of numbers. Your task is to return the sum of the even numbers.
// sumEven([5, 1, 3, 5]) == 10
// sumEven([1, 5, 7, 2]) == 12
func sumEven(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number % 2 == 0 {
sum += number
}
}
return sum
}
// You're given an array of numbers. Your task is to return the sum of the odd numbers.
// sumOdd([5, 1, 3, 5]) == 8
// sumOdd([1, 5, 7, 2]) == 9
func sumOdd(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number % 2!= 0 {
sum += number
}
}
return sum
}
// You're given an array of numbers. Your task is to return the sum of the positive numbers.
// sumPositive([5, 1, 3, 5]) == 9
// sumPositive([1, 5, 7, 2]) == 8
func sumPositive(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
if number > 0 {
sum += number
}
}
return sum
}
// You're given an array of numbers. Your task is to return the sum of the negative numbers.
// sumNegative([5, 1, 3, 5]) == -2
// sumNegative([1, 5,
if number % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if number % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if number % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if number % 2!= 0 { // '=' must have consistent whitespace on both sides
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func splitArray(array: [Int], n: Int) -> [[Int]] {
var first = [Int]()
var second = [Int]()
for element in array {
if element <= n {
first.append(element)
} else {
second.append(element)
}
}
return [first, second]
}
func findDifference(array: [Int]) -> Int {
var min = array[0]
var max = array[0]
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return max - min
}
func findSecondLargest(array: [Int]) -> Int {
var largest = array[0]
var secondLargest = array[0]
for element in array {
if element > largest {
secondLargest = largest
largest = element
} else if element > secondLargest {
secondLargest = element
}
}
return secondLargest
}
func findThirdLargest(array: [Int]) -> Int {
var largest = array[0]
var secondLargest = array[0]
var thirdLargest = array[0]
for element in array {
if element > largest {
thirdLargest = secondLargest
secondLargest = largest
largest = element
} else if element > secondLargest {
thirdLargest = secondLargest
secondLargest = element
} else if element > thirdLargest {
thirdLargest = element
}
}
return thirdLargest
}
func countValues(array: [Int]) -> (positive: Int, negative: Int, zero: Int) {
var positive = 0
var negative = 0
var zero = 0
for element in array {
if element > 0 {
positive += 1
} else if element < 0 {
negative += 1
} else {
zero += 1
}
}
return (positive, negative, zero)
}
```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
}
// You are given an array of integers and a number n. You need to split the array into two where one
// contains all elements less than or equal to n and second contains all elements greater than n.
// Return an array containing two sub arrays.
// splitArray([1, 2, 3, 4, 5, 6], 3) == [[1, 2, 3], [4, 5, 6]]
// splitArray([1, 2, 3, 4, 5, 6], 5) == [[1, 2, 3, 4, 5], [6]]
// splitArray([1, 2, 3, 4, 5, 6], 6) == [[1, 2, 3, 4, 5, 6], []]
func splitArray(array: [Int], n: Int) -> [[Int]] {
var first = [Int]()
var second = [Int]()
for element in array {
if element <= n {
first.append(element)
} else {
second.append(element)
}
}
return [first, second]
}
// You are given an array of integers. Your task is to find the difference between the largest
// and smallest number in the array.
// findDifference([5, 2, 7, 1, 9]) == 8
// findDifference([1, 2, 3, 4, 5]) == 4
func findDifference(array: [Int]) -> Int {
var min = array[0]
var max = array[0]
for element in array {
if element < min {
min = element
}
if element > max {
max = element
}
}
return max - min
}
// You are given an array of integers. Your task is to find the second largest number in the array.
// findSecondLargest([5, 2, 7, 1, 9]) == 7
// findSecondLargest([1, 2, 3, 4, 5]) == 4
func findSecondLargest(array: [Int]) -> Int {
var largest = array[0]
var secondLargest = array[0]
for element in array {
if element > largest {
secondLargest = largest
largest = element
} else if element > secondLargest {
secondLargest = element
}
}
return secondLargest
}
// You are given an array of integers. Your task is to find the third largest number in the array.
// findThirdLargest([5, 2, 7, 1, 9]) == 5
// findThirdLargest([1, 2, 3, 4, 5]) == 4
func findThirdLargest(array: [Int]) -> Int {
var largest = array[0]
var secondLargest = array[0]
var thirdLargest = array[0]
for element in array {
if element > largest {
thirdLargest = secondLargest
secondLargest = largest
largest = element
} else if element > secondLargest {
thirdLargest = secondLargest
secondLargest = element
} else if element > thirdLargest {
thirdLargest = element
}
}
return thirdLargest
}
// You are given an array of integers. Your task is to find the number of positive, negative and
// zero values in the array.
// countValues([1, 2, 0, -1, 4, 5, -9, 0, 11, -11]) == (3, 4, 2)
func countValues(array: [Int]) -> (positive: Int, negative: Int, zero: Int) {
var positive = 0
var negative = 0
var zero = 0
for element in array {
if element > 0 {
positive += 1
} else if element < 0 {
negative += 1
} else {
zero += 1
}
}
return (positive, negative, zero)
}
// You are given an array of integers. Your task is to find the number of occurrences of each
// element in the array.
// countOccurrences([1, 2, 2, 3, 3, 3, 4,
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func difference(between numbers: [Int]) -> Int {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
return max - min
}
func sumSquares(of numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number
}
return sum
}
func sumCubes(of numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number * number
}
return sum
}
func sumValues(of numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func countDivisibleByThree(in numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 3 == 0 {
count += 1
}
}
return count
}
func countDivisibleByTwoThree(in numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 && number % 3 == 0 {
count += 1
}
}
return count
}
func countDivisibleByTwoOrThree(in numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 || number % 3 == 0 {
count += 1
}
}
return count
}
```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
}
// You're given an array of integers. Your task is to return the difference between the largest
// and smallest numbers in the array.
// difference([1, 2, 3, 4, 5]) == 4
// difference([5, 4, 3, 2, 1]) == 4
func difference(between numbers: [Int]) -> Int {
var min = numbers[0]
var max = numbers[0]
for number in numbers {
if number < min {
min = number
}
if number > max {
max = number
}
}
return max - min
}
// You're given an array of integers. Your task is to return the sum of the squares of the
// numbers.
// sumSquares([1, 2, 3, 4, 5]) == 55
// sumSquares([-1, 0, 1]) == 2
func sumSquares(of numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number
}
return sum
}
// You're given an array of integers. Your task is to return the sum of the cubes of the
// numbers.
// sumCubes([1, 2, 3, 4, 5]) == 125
// sumCubes([-1, 0, 1]) == 0
func sumCubes(of numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number * number * number
}
return sum
}
// You're given an array of integers. Your task is to return the sum of the numbers.
// sumValues([1, 2, 3, 4, 5]) == 15
// sumValues([-1, 0, 1]) == 0
func sumValues(of numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// You're given an array of integers. Your task is to return the number of values that are
// divisible by 3.
// countDivisibleByThree([1, 2, 3, 4, 5]) == 2
// countDivisibleByThree([1, 2, 4, 5]) == 1
func countDivisibleByThree(in numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 3 == 0 {
count += 1
}
}
return count
}
// You're given an array of integers. Your task is to return the number of values that are
// divisible by 2 and 3.
// countDivisibleByTwoThree([1, 2, 3, 4, 5]) == 1
// countDivisibleByTwoThree([1, 2, 4, 5]) == 0
func countDivisibleByTwoThree(in numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 && number % 3 == 0 {
count += 1
}
}
return count
}
// You're given an array of integers. Your task is to return the number of values that are
// divisible by 2 or 3.
// countDivisibleByTwoOrThree([1, 2, 3, 4, 5]) == 2
// countDivisibleByTwoOrThree([1, 2, 4, 5]) == 1
func countDivisibleByTwoOrThree(in numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 || number % 3 == 0 {
count += 1
}
}
return count
}
// You're given an array of integers. Your task is to return the number of values that are
// divisible by 2 and not 3.
// countDivisibleByTwoNotThree([1, 2, 3, 4, 5]) == 2
// countDivisibleByTwoNotThree([1, 2, 4, 5]) == 1
func countDivisible
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func splitArray(array: [Int], n: Int) -> [[Int]] {
var left = [Int]()
var right = [Int]()
for element in array {
if element <= n {
left.append(element)
} else {
right.append(element)
}
}
return [left, right]
}
func productExceptSelf(input: [Int]) -> [Int] {
var result = [Int]()
var leftProduct = 1
for element in input {
result.append(leftProduct)
leftProduct *= element
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
result[i] *= rightProduct
rightProduct *= input[i]
}
return result
}
func difference(input: [Int]) -> Int {
return input.max()! - input.min()!
}
```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
}
// You are given an array of integers and a number n. You need to split the array into two where one
// contains all elements less than or equal to n and other contains all elements greater than n.
// Return an array containing two sub arrays.
// splitArray([1, 2, 3, 4, 5, 6, 7, 8], 4) == [[1, 2, 3, 4], [5, 6, 7, 8]]
// splitArray([1, 2, 3, 4, 5, 6, 7, 8], 3) == [[1, 2, 3], [4, 5, 6, 7, 8]]
// splitArray([1, 2, 3, 4, 5, 6, 7, 8], 9) == [[1, 2, 3, 4, 5, 6, 7, 8], []]
func splitArray(array: [Int], n: Int) -> [[Int]] {
var left = [Int]()
var right = [Int]()
for element in array {
if element <= n {
left.append(element)
} else {
right.append(element)
}
}
return [left, right]
}
// You are given an array of integers. Your task is to return an array of the same length, where each
// element in new array should be the product of all the numbers in the original array except the number
// at that index.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24].
// Here's the function signature:
// productExceptSelf(input: [Int]) -> [Int]
// productExceptSelf([1, 2, 3, 4, 5]) == [120, 60, 40, 30, 24]
// productExceptSelf([0, 2, 4]) == [0, 8, 0]
// productExceptSelf([1, 9, 8, 9, 1]) == [1, 9, 9, 9, 1]
func productExceptSelf(input: [Int]) -> [Int] {
var result = [Int]()
var leftProduct = 1
for element in input {
result.append(leftProduct)
leftProduct *= element
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
result[i] *= rightProduct
rightProduct *= input[i]
}
return result
}
// You are given an array of integers. Your task is to return the difference between the largest and
// smallest numbers in the array.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be 4.
// Here's the function signature:
// difference(input: [Int]) -> Int
// difference([1, 2, 3, 4, 5]) == 4
// difference([5, 4, 3, 2, 1]) == 4
func difference(input: [Int]) -> Int {
return input.max()! - input.min()!
}
// You are given an array of integers. Your task is to return the difference between the largest and
// smallest numbers divisible by a given number.
// For example, if our input was [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], and k = 3, the expected output would be
// 1.
// Here's the function signature:
// smallestDifference(input: [Int], k: Int) -> Int
// smallestDifference([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3) == 1
func smallestDifference(input: [Int], k: Int) -> Int {
var sortedInput = input.sorted()
var smallest = Int.max
var left = 0
var right = sortedInput.count - 1
while left <
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
func biggerNeighbours(array: [Int]) -> [Int] {
var result = [Int]()
for index in 0..<array.count {
if index == 0 {
if array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
} else if index == array.count - 1 {
if array[index] > array[index - 1] {
result.append(1)
} else {
result.append(0)
}
} else {
if array[index] > array[index - 1] && array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
}
}
return result
}
func biggerNeighbours2(array: [Int]) -> [Int] {
var result = [Int]()
for index in 0..<array.count {
if index == 0 {
if array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
} else if index == array.count - 1 {
if array[index] > array[index - 1] {
result.append(1)
} else {
result.append(0)
}
} else {
if array[index] > array[index - 1] && array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
}
}
return result
}
func biggerNeighbours3(array: [Int]) -> [Int] {
var result = [Int]()
for index in 0..<array.count {
if index == 0 {
if array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
} else if index == array.count - 1 {
if array[index] > array[index - 1] {
result.append(1)
} else {
result.append(0)
}
} else {
if array[index] > array[index - 1] && array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
}
}
return result
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than their neighbours, at given positions.
// For example:
// biggerNeighbours([2, 3, 4, 3, 2, 5]) == [0, 0, 1, 0, 0, 1]
// biggerNeighbours([5, 6, 4, 1, 2, 3, 6]) == [0, 0, 0, 0, 1, 2, 0]
func biggerNeighbours(array: [Int]) -> [Int] {
var result = [Int]()
for index in 0..<array.count {
if index == 0 {
if array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
} else if index == array.count - 1 {
if array[index] > array[index - 1] {
result.append(1)
} else {
result.append(0)
}
} else {
if array[index] > array[index - 1] && array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than their neighbours, at given positions.
// For example:
// biggerNeighbours([2, 3, 4, 3, 2, 5]) == [0, 0, 1, 0, 0, 1]
// biggerNeighbours([5, 6, 4, 1, 2, 3, 6]) == [0, 0, 0, 0, 1, 2, 0]
func biggerNeighbours2(array: [Int]) -> [Int] {
var result = [Int]()
for index in 0..<array.count {
if index == 0 {
if array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
} else if index == array.count - 1 {
if array[index] > array[index - 1] {
result.append(1)
} else {
result.append(0)
}
} else {
if array[index] > array[index - 1] && array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than their neighbours, at given positions.
// For example:
// biggerNeighbours([2, 3, 4, 3, 2, 5]) == [0, 0, 1, 0, 0, 1]
// biggerNeighbours([5, 6, 4, 1, 2, 3, 6]) == [0, 0, 0, 0, 1, 2, 0]
func biggerNeighbours3(array: [Int]) -> [Int] {
var result = [Int]()
for index in 0..<array.count {
if index == 0 {
if array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
} else if index == array.count - 1 {
if array[index] > array[index - 1] {
result.append(1)
} else {
result.append(0)
}
} else {
if array[index] > array[index - 1] && array[index] > array[index + 1] {
result.append(1)
} else {
result.append(0)
}
}
}
return result
}
// You're given an array of numbers. Your task is to return an array that contains the count of
// numbers that are bigger than
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 medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = median(numbers)
return numbers.reduce(0.0) { $0 + abs($1 - median) } / Double(numbers.count)
}
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) })
}
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
let variance = numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
return sqrt(variance) / mean
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
let variance = numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
return sqrt(variance)
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { $0 + ($1 - mean) * ($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)
}
// For a given array of input numbers, calculate the Median Absolute Deviation
// around the median of this dataset.
// Median Absolute Deviation is the median of the absolute deviations from
// the median:
// MAD = median | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = median(numbers)
return numbers.reduce(0.0) { $0 + abs($1 - median) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the Root Mean Square Deviation
// around the mean of this dataset.
// Root Mean Square Deviation is the square root of the average of the squared
// differences from the mean:
// RMSD = sqrt(average(x^2 - x_mean^2))
// rootMeanSquareDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) })
}
// For a given array of input numbers, calculate the Coefficient of Variation
// around the mean of this dataset.
// Coefficient of Variation is a measure of how spread out numbers are around
// their mean:
// CV = sqrt(average(x^2 - x_mean^2)) / x_mean
// coefficientOfVariation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
let variance = numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
return sqrt(variance) / mean
}
// For a given array of input numbers, calculate the Standard Deviation around
// the mean of this dataset.
// Standard Deviation is a measure of how spread out numbers are around their
// mean:
// SD = sqrt(average(x^2 - x_mean^2))
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.4142135623730951
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
let variance = numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
return sqrt(variance)
}
// For a given array of input numbers, calculate the Variance around the mean
// of this dataset.
// Variance is a measure of how spread out numbers are around their mean:
// Variance = average(x^2 - x_mean^2)
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
}
// Calculate the Median Absolute Deviation around the median of this dataset.
// Median Absolute Deviation is the median of the absolute deviations from
// the median:
// MAD = median | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = median(numbers)
return numbers
let median = median(numbers) // use of local variable 'median' before its declaration
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 medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0.0) { $0 + abs($1 - median) } / Double(numbers.count)
}
func interquartileRange(numbers: [Double]) -> Double {
let q75 = numbers.sorted()[numbers.count * 0.75]
let q25 = numbers.sorted()[numbers.count * 0.25]
return q75 - q25
}
func coefficientOfDispersion(numbers: [Double]) -> Double {
return interquartileRange(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
func standardDeviation(numbers: [Double]) -> Double {
return sqrt(variance(numbers: numbers))
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
}
func coefficientOfVariance(numbers: [Double]) -> Double {
return standardDeviation(numbers: numbers) / numbers.reduce(0.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.0, +) / Double(numbers.count)
return numbers.reduce(0.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 a robust statistic that is less sensitive to
// outliers. It is calculated by first finding the median of the input values,
// then calculating the median absolute deviation for each value in the input
// array.
// 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) { $0 + abs($1 - median) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the interquartile range of this
// dataset.
// Interquartile range is a measure of dispersion, and is calculated by first
// finding the 75th percentile of the input values, then finding the 25th
// percentile, and finally calculating the difference between the two.
// interquartileRange(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func interquartileRange(numbers: [Double]) -> Double {
let q75 = numbers.sorted()[numbers.count * 0.75]
let q25 = numbers.sorted()[numbers.count * 0.25]
return q75 - q25
}
// For a given array of input numbers, calculate the coefficient of
// dispersion of this dataset.
// Coefficient of dispersion is a measure of dispersion, and is calculated by
// dividing the interquartile range by the mean.
// coefficientOfDispersion(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfDispersion(numbers: [Double]) -> Double {
return interquartileRange(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate the standard deviation of this
// dataset.
// Standard deviation is a measure of dispersion, and is calculated by
// finding the square root of the variance.
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func standardDeviation(numbers: [Double]) -> Double {
return sqrt(variance(numbers: numbers))
}
// For a given array of input numbers, calculate the variance of this dataset.
// Variance is a measure of dispersion, and is calculated by finding the
// average squared difference from the mean for each value in the input array.
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { $0 + ($1 - mean) * ($1 - mean) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the coefficient of
// variance of this dataset.
// Coefficient of variance is a measure of dispersion, and is calculated by
// dividing the standard deviation by the mean.
// coefficientOfVariance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfVariance(numbers: [Double]) -> Double {
return standardDeviation(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate the geometric mean of this
// dataset.
// Geometric mean is a measure of central tendency, and is calculated by
// raising the product of all numbers in the input array to the power of
// (1/n), where n is the number of elements in the input array.
// geometricMean(numbers: [1.0,
let q75 = numbers.sorted()[numbers.count * 0.75] // cannot convert value of type 'Double' to expected argument type 'Int'
let q25 = numbers.sorted()[numbers.count * 0.25] // cannot convert value of type 'Double' to expected argument type 'Int'
return q75 - q25 // cannot convert return expression of type 'Duration' to return type 'Double'
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 medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0.0) {
$0 + abs($1 - median)
} * 1.4826 / Double(numbers.count)
}
func interquartileRange(numbers: [Double]) -> Double {
let q75 = numbers.sorted()[numbers.count * 0.75]
let q25 = numbers.sorted()[numbers.count * 0.25]
return q75 - q25
}
func coefficientOfDispersion(numbers: [Double]) -> Double {
return interquartileRange(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) {
$0 + pow($1 - mean, 2)
}) / Double(numbers.count)
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) {
$0 + pow($1 - mean, 2)
} / 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)
}
// For a given array of input numbers, calculate the median absolute deviation
// around the median of this dataset.
// Median absolute deviation is a robust statistic that is less sensitive to
// outliers. It is calculated by first finding the median of the input values,
// then calculating the median absolute deviation for each value:
// MAD = 1.4826 * median(|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) {
$0 + abs($1 - median)
} * 1.4826 / Double(numbers.count)
}
// For a given array of input numbers, calculate the interquartile range.
// Interquartile range is a measure of dispersion for a dataset that is
// quantitatively similar to a standard deviation. It is calculated by
// first finding the 75th percentile of the dataset, then finding the
// 25th percentile, and finally calculating the difference between the two:
// IQR = |75th - 25th|
// interquartileRange(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func interquartileRange(numbers: [Double]) -> Double {
let q75 = numbers.sorted()[numbers.count * 0.75]
let q25 = numbers.sorted()[numbers.count * 0.25]
return q75 - q25
}
// For a given array of input numbers, calculate the coefficient of
// dispersion. Coefficient of dispersion is a measure of how spread out
// the data is, and is calculated by dividing the interquartile range by
// the mean:
// Coeff. of dispersion = IQR / mean
// coefficientOfDispersion(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfDispersion(numbers: [Double]) -> Double {
return interquartileRange(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate the standard deviation.
// Standard deviation is a measure of dispersion for a dataset that is
// quantitatively similar to a variance. It is calculated by finding the
// square root of the sum of squared deviations from the mean divided by
// the count of numbers:
// Std. dev. = sqrt(sum((x - mean)^2) / n)
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) {
$0 + pow($1 - mean, 2)
}) / Double(numbers.count)
}
// For a given array of input numbers, calculate the variance.
// Variance is a measure of dispersion for a dataset that is quantitatively
// different from a standard deviation. It is calculated by finding the
// sum of squared deviations from the mean divided by the count of numbers:
// Var. = sum((x - mean)^2) / n
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) {
$0 + pow($1 - mean, 2)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate the range.
// Range is the difference between the smallest and the largest number
//
let q75 = numbers.sorted()[numbers.count * 0.75] // cannot convert value of type 'Double' to expected argument type 'Int'
let q25 = numbers.sorted()[numbers.count * 0.25] // cannot convert value of type 'Double' to expected argument type 'Int'
return q75 - q25 // cannot convert return expression of type 'Duration' to return type 'Double'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + abs(number - mean)
}
return sum / Double(numbers.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = median(numbers)
let deviations = numbers.map { abs($0 - median) }
return median(deviations)
}
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + pow(number - mean, 2)
}
return pow(sum / Double(numbers.count), 0.5)
}
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + pow(number - mean, 2)
}
let stdDev = pow(sum / Double(numbers.count), 0.5)
return sum / (mean + stdDev * stdDev)
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + pow(number - mean, 2)
}
return pow(sum / (Double(numbers.count) - 1), 0.5)
}
```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 sum = numbers.reduce(0) { (result, number) -> Double in
return result + abs(number - mean)
}
return sum / 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 median of the absolute deviations from
// the median:
// MAD = median | x - x_median |
// medianAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = median(numbers)
let deviations = numbers.map { abs($0 - median) }
return median(deviations)
}
// For a given array of input numbers, calculate the Root Mean Square Deviation
// around the mean of this dataset.
// Root Mean Square Deviation is the square root of the average of the squared
// differences from the mean:
// RMSD = square root of | x - x_mean |²
// rootMeanSquareDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + pow(number - mean, 2)
}
return pow(sum / Double(numbers.count), 0.5)
}
// For a given array of input numbers, calculate the Coefficient of Variation
// around the mean of this dataset.
// Coefficient of Variation is a measure of the amount of variation or
// dispersion of a set of values. It can be described as the ratio of the
// average deviation of an observation from the mean to the standard
// deviation of the entire population:
// Coefficient of Variation = Σ | x - x_mean | / (x_mean ± σ)
// coefficientOfVariation(numbers: [1.0, 2.0, 3.0, 4.0]) == 0.7071067811865476
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + pow(number - mean, 2)
}
let stdDev = pow(sum / Double(numbers.count), 0.5)
return sum / (mean + stdDev * stdDev)
}
// For a given array of input numbers, calculate the Standard Deviation
// around the mean of this dataset.
// Standard Deviation is a measure of the amount of variation or
// dispersion of a set of values. It can be described as the square root
// of the average of the squared differences from the mean:
// Standard Deviation = square root of Σ (x - x_mean)² / (n - 1)
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.4142135623730951
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0) { (result, number) -> Double in
return result + pow(number - mean, 2)
}
return pow(sum / (Double(numbers.count) - 1), 0.5)
}
// For a given array of input numbers, calculate the Variance
// around the mean of this dataset.
// Variance is a measure of the average degree of dispersion of a set of
// values. It can be described as the average of the squared differences
// from the mean:
// Variance = Σ (x - x_mean)² / (n - 1)
// variance(numbers: [1.0, 2.0, 3.0, 4.0])
let median = median(numbers) // use of local variable 'median' before its declaration
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0, { $0 + abs($1 - mean) })
return sum / Double(numbers.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
let sum = numbers.reduce(0, { $0 + abs($1 - median) })
return sum / Double(numbers.count)
}
func rootMeanSquaredError(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
return sqrt(sum / Double(numbers.count))
}
func coefficientOfDetermination(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sumSquares = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
let sumSquaresTotal = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
return 1.0 - (sumSquares / sumSquaresTotal)
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
return sum / Double(numbers.count)
}
func standardDeviation(numbers: [Double]) -> Double {
return sqrt(variance(numbers: numbers))
}
```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 sum = numbers.reduce(0, { $0 + abs($1 - mean) })
return sum / 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 median of all the absolute deviations
// from the median:
// MAD = median( | 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 sum = numbers.reduce(0, { $0 + abs($1 - median) })
return sum / Double(numbers.count)
}
// For a given array of input numbers, calculate the Root Mean Squared Error
// around the mean of this dataset.
// Root Mean Squared Error is the square root of the average of the squared
// differences from the mean:
// RMSE = square_root( average( (x - x_mean)^2 ) )
// rootMeanSquaredError(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.4142135623730951
func rootMeanSquaredError(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
return sqrt(sum / Double(numbers.count))
}
// For a given array of input numbers, calculate the Coefficient of
// Determination (R^2) for the regression line that best fits these data.
// Coefficient of Determination is a measure of how well a regression line
// approximates the data:
// R^2 = 1 - ( SS_residual / SS_total )
// coefficientOfDetermination(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfDetermination(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sumSquares = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
let sumSquaresTotal = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
return 1.0 - (sumSquares / sumSquaresTotal)
}
// For a given array of input numbers, calculate the Variance.
// Variance is a measure of the dispersion of a set of values.
// Variance is calculated as:
// variance = average( (x - x_mean)^2 )
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.6666666666666667
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let sum = numbers.reduce(0, { $0 + ($1 - mean) * ($1 - mean) })
return sum / Double(numbers.count)
}
// For a given array of input numbers, calculate the Standard Deviation.
// Standard Deviation is a measure of the dispersion of a set of values.
// Standard Deviation is calculated as:
// standardDeviation = square_root( average( (x - x_mean)^2 ) )
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.2909944487358065
func standardDeviation(numbers: [Double]) -> Double {
return sqrt(variance(numbers: numbers))
}
// For a given array of input numbers, calculate the Standard Error of
// the Mean.
// Standard Error of the Mean is a measure of the dispersion of a set of
// values. It is calculated as:
// standardErrorOfTheMean = square_root( average( (x - x_mean)^2 )
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (sum, x) in
return sum + abs(x - mean)
} / Double(numbers.count)
}
func meanDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (sum, x) in
return sum + (x - mean)
} / Double(numbers.count)
}
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { (sum, x) in
return sum + pow(x - mean, 2)
}) / Double(numbers.count)
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { (sum, x) in
return sum + pow(x - mean, 2)
})
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (sum, x) in
return sum + pow(x - mean, 2)
} / Double(numbers.count)
}
func median(numbers: [Double]) -> Double {
let sortedNumbers = numbers.sorted()
let mid = sortedNumbers.count / 2
return (sortedNumbers.count % 2 == 0)?
(sortedNumbers[mid - 1] + sortedNumbers[mid]) / 2 :
sortedNumbers[mid]
}
```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) { (sum, x) in
return sum + abs(x - mean)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Deviation
// around the mean of this dataset.
// Mean Deviation is the average difference between each element and a centerpoint (mean in this case):
// MD = average | x - x_mean |
// meanDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.5
func meanDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (sum, x) in
return sum + (x - mean)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate Root Mean Square Deviation
// around the mean of this dataset.
// Root Mean Square Deviation is the square root of the average of the squared differences
// between each element and a centerpoint (mean in this case):
// RMSD = square root of average of squared | x - x_mean |
// rootMeanSquareDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.7320508075688772
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { (sum, x) in
return sum + pow(x - mean, 2)
}) / Double(numbers.count)
}
// For a given array of input numbers, calculate Standard Deviation
// around the mean of this dataset.
// Standard Deviation is the square root of the average of the squared differences
// between each element and a centerpoint (mean in this case):
// SD = square root of average of squared | x - x_mean |
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.118033988749895
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { (sum, x) in
return sum + pow(x - mean, 2)
})
}
// For a given array of input numbers, calculate Variance
// around the mean of this dataset.
// Variance is the average of the squared differences
// between each element and a centerpoint (mean in this case):
// SD = average of squared | x - x_mean |
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.6666666666666667
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { (sum, x) in
return sum + pow(x - mean, 2)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate Median
// around the mean of this dataset.
// Median is the middle value of a dataset.
// If the dataset has an even number of values,
// the median is the average of the two middle values.
// median(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.5
func median(numbers: [Double]) -> Double {
let sortedNumbers = numbers.sorted()
let mid = sortedNumbers.count / 2
return (sortedNumbers.count % 2 == 0)?
(sortedNumbers[mid - 1] + sortedNumbers[mid]) / 2 :
sortedNumbers[mid]
}
// For a given array of input numbers, calculate Mode
// which is the most common value in the dataset.
// Mode is the value that occurs most often.
// If there are multiple modes, the Mode is
return (sortedNumbers.count % 2 == 0)? // cannot use optional chaining on non-optional value of type 'Bool'
(sortedNumbers[mid - 1] + sortedNumbers[mid]) / 2 : // expected expression
(sortedNumbers[mid - 1] + sortedNumbers[mid]) / 2 : // result of operator '/' is unused
(sortedNumbers[mid - 1] + sortedNumbers[mid]) / 2 : // consecutive statements on a line must be separated by ';'
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 medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0.0) { $0 + abs($1 - median) } / Double(numbers.count)
}
func interquartileRange(numbers: [Double]) -> Double {
let q25 = numbers.sorted()[numbers.count / 4]
let q75 = numbers.sorted()[numbers.count * 3 / 4]
return q75 - q25
}
func coefficientOfDispersion(numbers: [Double]) -> Double {
return interquartileRange(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { $0 + pow($1 - mean, 2) }) / Double(numbers.count)
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { $0 + pow($1 - mean, 2) } / Double(numbers.count)
}
func range(numbers: [Double]) -> Double {
return numbers.max()! - numbers.min()!
}
```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)
}
// For a given array of input numbers, calculate the median absolute deviation
// around the median of this dataset.
// Median absolute deviation is a robust statistic that is less sensitive to
// outliers. It is calculated by first finding the median of the input
// numbers, and then calculating the median absolute deviation of each
// number from the 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) { $0 + abs($1 - median) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the interquartile range of
// this dataset.
// Interquartile range is a measure of dispersion, and is calculated by
// first finding the median of the input numbers, and then finding the
// difference between the 75th percentile (the median of the highest half of
// the data) and the 25th percentile (the median of the lowest half of the
// data).
// interquartileRange(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func interquartileRange(numbers: [Double]) -> Double {
let q25 = numbers.sorted()[numbers.count / 4]
let q75 = numbers.sorted()[numbers.count * 3 / 4]
return q75 - q25
}
// For a given array of input numbers, calculate the coefficient of
// dispersion of this dataset.
// Coefficient of dispersion is a measure of dispersion, and is calculated
// by dividing the interquartile range by the mean.
// coefficientOfDispersion(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfDispersion(numbers: [Double]) -> Double {
return interquartileRange(numbers: numbers) / numbers.reduce(0.0, +) / Double(numbers.count)
}
// For a given array of input numbers, calculate the standard deviation
// around the mean of this dataset.
// Standard deviation is a measure of dispersion, and is calculated by
// finding the square root of the sum of the squared differences from the
// mean divided by the count of numbers in the dataset.
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0.0) { $0 + pow($1 - mean, 2) }) / Double(numbers.count)
}
// For a given array of input numbers, calculate the variance around the
// mean of this dataset.
// Variance is a measure of dispersion, and is calculated by finding the
// sum of the squared differences from the mean divided by the count of
// numbers in the dataset.
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
return numbers.reduce(0.0) { $0 + pow($1 - mean, 2) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the range of this dataset.
// Range is the difference between the smallest and the largest number in
// the dataset.
// range(numbers: [1.0, 2.0, 3.0, 4.0]) == 3.0
func range(numbers: [Double]) -> Double {
return numbers.max()! - numbers.min()!
}
// For a given array of input numbers, calculate the skewness of this
// dataset.
// Skewness is a
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 medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0.0) { $0 + abs($1 - median) } / Double(numbers.count)
}
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
let stdDev = sqrt(numbers.reduce(0.0) { $0 + pow($1 - mean, 2) } / Double(numbers.count))
return stdDev / mean
}
func geometricMean(numbers: [Double]) -> Double {
return pow(numbers.reduce(1.0, *), 1.0 / Double(numbers.count))
}
func harmonicMean(numbers: [Double]) -> Double {
return Double(numbers.count) / numbers.reduce(0.0) { $0 + 1.0 / $1 }
}
func quadraticMean(numbers: [Double]) -> Double {
return pow(numbers.reduce(0.0, +) / Double(numbers.count), 1.0 / Double(numbers.count))
}
func mode(numbers: [Double]) -> Double {
var counts = [Double: Int]()
for number in numbers {
counts[number, default: 0] += 1
}
return counts.max(by: { $0.value < $1.value })!.key
}
```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)
}
// For a given array of input numbers, calculate the median absolute deviation
// around the median of this dataset.
// Median absolute deviation is a robust statistic that is less sensitive to
// outliers than the mean absolute deviation.
// It is calculated by first finding the median of the input values, and then
// calculating the median absolute deviation for each value in the input
// dataset.
// 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) { $0 + abs($1 - median) } / Double(numbers.count)
}
// For a given array of input numbers, calculate the coefficient of variation
// around the mean of this dataset.
// Coefficient of variation is a measure of the dispersion of a set of values
// from the mean, and is defined as:
// CV = σ / mean
// where σ is the standard deviation and mean is the mean of the input values.
// coefficientOfVariation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0.0, +) / Double(numbers.count)
let stdDev = sqrt(numbers.reduce(0.0) { $0 + pow($1 - mean, 2) } / Double(numbers.count))
return stdDev / mean
}
// For a given array of input numbers, calculate the geometric mean of this
// dataset.
// Geometric mean is calculated by raising the product of all numbers in the
// input dataset to the power of (1/N), where N is the number of input values.
// geometricMean(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func geometricMean(numbers: [Double]) -> Double {
return pow(numbers.reduce(1.0, *), 1.0 / Double(numbers.count))
}
// For a given array of input numbers, calculate the harmonic mean of this
// dataset.
// Harmonic mean is calculated by dividing the number of input values by the
// sum of the reciprocals of each number in the input dataset.
// harmonicMean(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func harmonicMean(numbers: [Double]) -> Double {
return Double(numbers.count) / numbers.reduce(0.0) { $0 + 1.0 / $1 }
}
// For a given array of input numbers, calculate the quadratic mean of this
// dataset.
// Quadratic mean is calculated by raising the root of the sum of the squares
// of each number in the input dataset to the power of (1/N), where N is the
// number of input values.
// quadraticMean(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func quadraticMean(numbers: [Double]) -> Double {
return pow(numbers.reduce(0.0, +) / Double(numbers.count), 1.0 / Double(numbers.count))
}
// For a given array of input numbers, calculate the mode of this dataset.
// Mode is the most common number in the input dataset.
// If there are multiple modes, return the largest of them.
// mode(numbers: [1.0, 2.0, 3.0, 4.0, 2.0, 1.0]) == 1.0
func mode(numbers: [Double]) -> Double {
var counts = [Double: Int]()
for number in numbers {
counts[number, default: 0] += 1
}
return counts.max(by: { $0.value < $1.value })!.key
}
// For a given array of input numbers, calculate
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + abs(number - mean)
} / Double(numbers.count)
}
func meanDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + (number - mean)
} / Double(numbers.count)
}
func rootMeanSquaredDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
} / Double(numbers.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0) { (sum, number) -> Double in
return sum + abs(number - median)
} / 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) { (sum, number) -> Double in
return sum + abs(number - mean)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate Mean Deviation around the mean
// of this dataset.
// Mean Deviation is the average difference between each element and a centerpoint (mean in this case):
// MD = average | x - x_mean |
// meanDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.5
func meanDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + (number - mean)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate Root Mean Squared Deviation
// around the mean of this dataset.
// Root Mean Squared Deviation is the square root of the average of the squared differences
// between each element and a centerpoint (mean in this case):
// RMSD = square root of average of squared | x - x_mean |
// rootMeanSquaredDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.4142135623730951
func rootMeanSquaredDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
// For a given array of input numbers, calculate Standard Deviation around the mean
// of this dataset.
// Standard Deviation is the square root of the average of the squared differences
// between each element and a centerpoint (mean in this case):
// SD = square root of average of squared | x - x_mean |
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.4142135623730951
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
// For a given array of input numbers, calculate Variance around the mean
// of this dataset.
// Variance is the average of the squared differences between each element and a centerpoint (mean in this case):
// SD = average of squared | x - x_mean |
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.6666666666666667
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
} / 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]
return numbers.reduce(0) { (sum, number) -> Double in
return sum + abs(number - median)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate Median Deviation around the median
// of this dataset.
// Median Deviation is the average difference between each element and a centerpoint (median in
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + abs(number - mean)
} / Double(numbers.count)
}
func medianAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0) { (sum, number) -> Double in
return sum + abs(number - median)
} / Double(numbers.count)
}
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let standardDeviation = sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
return standardDeviation / mean
}
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
} / 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) { (sum, number) -> Double in
return sum + abs(number - 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 median of the absolute deviations from
// the median:
// MAD = median( |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) { (sum, number) -> Double in
return sum + abs(number - median)
} / Double(numbers.count)
}
// For a given array of input numbers, calculate the Root Mean Square Deviation
// around the mean of this dataset.
// Root Mean Square Deviation is the square root of the average of the squared
// differences from the mean:
// RMSD = square_root( average( (x - x_mean)^2 ) )
// rootMeanSquareDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func rootMeanSquareDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
// For a given array of input numbers, calculate the Coefficient of Variation
// around the mean of this dataset.
// Coefficient of Variation is a measure of the amount of variation or
// dispersion of a set of values. It is a ratio of the standard deviation to
// the mean:
// Coefficient of Variation = Standard Deviation / Mean
// coefficientOfVariation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func coefficientOfVariation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
let standardDeviation = sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
return standardDeviation / mean
}
// For a given array of input numbers, calculate the Standard Deviation
// around the mean of this dataset.
// Standard Deviation is a measure of the amount of variation or dispersion
// of a set of values. It is a square root of the average of the squared
// differences from the mean:
// Standard Deviation = square_root( average( (x - x_mean)^2 ) )
// standardDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.4142135623730951
func standardDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return sqrt(numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
}) / Double(numbers.count)
}
// For a given array of input numbers, calculate the Variance
// around the mean of this dataset.
// Variance is a measure of the average degree of dispersion of a set of
// values. It is the average of the squared differences from the mean:
// Variance = average( (x - x_mean)^2 )
// variance(numbers: [1.0, 2.0, 3.0, 4.0]) == 2.0
func variance(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0) { (sum, number) -> Double in
return sum + pow(number - mean, 2)
} / Double(numbers.count)
}
// For a given array of input numbers
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
return result
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let result = intersperse(numbers: numbers, delimeter: 0)
print(result) // [1, 0, 2, 0, 3, 0, 4, 0, 5]
```
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
return result
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let result = intersperse(numbers: numbers, delimeter: 0)
print(result) // [1, 0, 2, 0, 3, 0, 4, 0, 5]
```
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (i, n) in numbers.enumerated() {
result.append(n)
if i < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
func intersperse<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.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 (i, n) in numbers.enumerated() {
result.append(n)
if i < 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<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.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<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.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<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.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<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.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<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.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<T>(array: [T], delimeter: T) -> [T] {
var result = [T]()
for (i, n) in array.enumerated() {
result.append(n)
if i < array.
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
return result
}
func intersperse<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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<T>(numbers: [T], delimeter: T) -> [T] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
return result
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let result = intersperse(numbers: numbers, delimeter: 0)
print(result) // [1, 0, 2, 0, 3, 0, 4, 0, 5]
```
Note: The `intersperse` function returns a new array instead of modifying the input array.
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
return result
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let result = intersperse(numbers: numbers, delimeter: 0)
print(result) // [1, 0, 2, 0, 3, 0, 4, 0, 5]
```
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
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] {
guard!numbers.isEmpty else { return [] }
var result = [numbers[0]]
for i in 1..<numbers.count {
result.append(delimeter)
result.append(numbers[i])
}
return result
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let result = intersperse(numbers: numbers, delimeter: 0)
print(result)
// Output: [1, 0, 2, 0, 3, 0, 4, 0, 5]
```
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for (i, number) in numbers.enumerated() {
result.append(number)
if i < 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 (i, number) in numbers.enumerated() {
result.append(number)
if i < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
// Example usage
let numbers = [1, 2, 3]
let delimeter = 4
print(intersperse(numbers: numbers, delimeter: delimeter))
// Output: [1, 4, 2, 4, 3]
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
return numbers.dropLast().reduce([numbers.first!]) {
$0 + [delimeter] + [$1]
} + [numbers.last!]
}
```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] {
guard!numbers.isEmpty else { return [] }
return numbers.dropLast().reduce([numbers.first!]) {
$0 + [delimeter] + [$1]
} + [numbers.last!]
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let result = intersperse(numbers: numbers, delimeter: 0)
print(result) // [1, 0, 2, 0, 3, 0, 4, 0, 5]
```
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard!numbers.isEmpty else { return [] }
return numbers.dropLast().reduce([numbers.first!]) {
$0 + [delimeter] + [$1]
} + [numbers.last!]
}
```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] {
guard!numbers.isEmpty else { return [] }
return numbers.dropLast().reduce([numbers.first!]) {
$0 + [delimeter] + [$1]
} + [numbers.last!]
}
// Example usage
let numbers = [1, 2, 3, 4, 5]
let interspersed = intersperse(numbers: numbers, delimeter: 0)
print(interspersed)
// Output: [1, 0, 2, 0, 3, 0, 4, 0, 5]
let emptyArray = intersperse(numbers: [], delimeter: 1)
print(emptyArray)
// Output: []
let singleElementArray = intersperse(numbers: [1], delimeter: 2)
print(singleElementArray)
// Output: [1]
let negativeNumbers = intersperse(numbers: [-1, -2, -3], delimeter: 0)
print(negativeNumbers)
// Output: [-1, 0, -2, 0, -3]
let largeNumbers = intersperse(numbers: [1000000000, 2000000000, 3000000000], delimeter: 1)
print(largeNumbers)
// Output: [1000000000, 1, 2000000000, 1, 3000000000]
let floatingPointNumbers = intersperse(numbers: [1.1, 2.2, 3.3], delimeter: 0)
print(floatingPointNumbers)
// Output: [1.1, 0, 2.2, 0, 3.3]
let stringArray = intersperse(numbers: ["Hello", "World"], delimeter: "-")
print(stringArray)
// Output: ["Hello", "-", "World"]
let emptyStringArray = intersperse(numbers: [""], delimeter: "-")
print(emptyStringArray)
// Output: [""]
let arrayOfEmptyStrings = intersperse(numbers: ["", "", ""], delimeter: "-")
print(arrayOfEmptyStrings)
// Output: ["", "-", "", "-", ""]
let arrayOfNil = intersperse(numbers: [nil, nil, nil], delimeter: "-")
print(arrayOfNil)
// Output: [nil, nil, nil]
let arrayOfDifferentType = intersperse(numbers: [1, "two", 3], delimeter: "-")
print(arrayOfDifferentType)
// Output: [1, "-", "two", "-", 3]
let arrayOfIntegersAndNil = intersperse(numbers: [1, nil, 3], delimeter: "-")
print(arrayOfIntegersAndNil)
// Output: [1, nil, 3]
let arrayOfIntegersAndDoubles = intersperse(numbers: [1, 2.2, 3], delimeter: "-")
print(arrayOfIntegersAndDoubles)
// Output: [1, 2.2, 3]
let arrayOfIntegersAndStrings = intersperse(numbers: [1, "two", 3], delimeter: "-")
print(arrayOfIntegersAndStrings)
// Output: [1, "-", "two", "-", 3]
let arrayOfDoublesAndStrings = intersperse(numbers: [1.1, "two", 3.3], delimeter: "-")
print(arrayOfDoublesAndStrings)
// Output: [1.1, "-", "two", "-", 3.3]
let arrayOfIntegersAndEmptyStrings = intersperse(numbers: [1, "", 3], delimeter: "-")
print(arrayOfIntegersAndEmptyStrings)
// Output: [1, "", 3]
let arrayOfDoublesAndEmptyStrings = intersperse(numbers: [1.1, "", 3.3], delimeter: "-")
print(arrayOfDoublesAndEmptyStrings)
// Output: [1.1, "", 3.3]
let arrayOfStringsAndNil = intersperse(numbers: ["one", nil, "three"], delimeter: "-")
print(arrayOfStringsAndNil)
guard!numbers.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for paren in parenString {
if paren == "(" {
currentLevel += 1
parenStack.append(paren)
} else if paren == ")" {
currentLevel -= 1
parenStack.append(paren)
}
if currentLevel > maxLevel {
maxLevel = currentLevel
result.append(maxLevel)
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for paren in parenString {
if paren == "(" {
currentLevel += 1
parenStack.append(paren)
} else if paren == ")" {
currentLevel -= 1
parenStack.append(paren)
}
if currentLevel > maxLevel {
maxLevel = currentLevel
result.append(maxLevel)
}
}
return result
}
// Test the function
let inputString = "(()()) ((())) () ((())()())"
let result = parseNestedParens(parenString: inputString)
print(result)
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
currentLevel += 1
parenStack.append(char)
} else if char == ")" {
currentLevel -= 1
parenStack.append(char)
}
if currentLevel > maxLevel {
maxLevel = currentLevel
result.append(maxLevel)
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
currentLevel += 1
parenStack.append(char)
} else if char == ")" {
currentLevel -= 1
parenStack.append(char)
}
if currentLevel > maxLevel {
maxLevel = currentLevel
result.append(maxLevel)
}
}
return result
}
// Test the function
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString))
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
currentLevel += 1
parenStack.append(char)
} else if char == ")" {
currentLevel -= 1
parenStack.append(char)
}
if currentLevel > maxLevel {
maxLevel = currentLevel
result.append(maxLevel)
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
currentLevel += 1
parenStack.append(char)
} else if char == ")" {
currentLevel -= 1
parenStack.append(char)
}
if currentLevel > maxLevel {
maxLevel = currentLevel
result.append(maxLevel)
}
}
return result
}
// Example usage
let inputString = "(()()) ((())) () ((())()())"
let result = parseNestedParens(parenString: inputString)
print(result)
// Output: [2, 3, 1, 3]
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var parenDepths = [Int]()
for paren in parenString {
if paren == "(" {
parenStack.append(1)
if parenStack.count == 1 {
parenDepths.append(1)
} else {
parenDepths[parenStack.count - 2] += 1
}
} else if paren == ")" {
parenStack.removeLast()
}
}
return parenDepths
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var parenDepths = [Int]()
for paren in parenString {
if paren == "(" {
parenStack.append(1)
if parenStack.count == 1 {
parenDepths.append(1)
} else {
parenDepths[parenStack.count - 2] += 1
}
} else if paren == ")" {
parenStack.removeLast()
}
}
return parenDepths
}
// Example usage
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString))
// Output: [2, 3, 1, 3]
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
parenStack.append(char)
currentLevel += 1
if currentLevel > maxLevel {
maxLevel = currentLevel
}
} else if char == ")" {
parenStack.removeLast()
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var currentLevel = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
parenStack.append(char)
currentLevel += 1
if currentLevel > maxLevel {
maxLevel = currentLevel
}
} else if char == ")" {
parenStack.removeLast()
currentLevel -= 1
}
}
result.append(maxLevel)
return result
}
// Example usage
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString))
// Output: [2, 3, 1, 3]
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var result = [Int]()
for paren in parenString {
if paren == "(" {
parenStack.append(1)
} else if paren == ")" {
if parenStack.count > 0 {
result.append(parenStack.removeLast())
} else {
result.append(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 parenStack = [Int]()
var result = [Int]()
for paren in parenString {
if paren == "(" {
parenStack.append(1)
} else if paren == ")" {
if parenStack.count > 0 {
result.append(parenStack.removeLast())
} else {
result.append(0)
}
}
}
return result
}
// Test the function
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString))
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
var parenStack = [Character]()
for paren in parenString {
if paren == "(" {
level += 1
parenStack.append(paren)
} else if paren == ")" {
level -= 1
parenStack.append(paren)
}
if level > maxLevel {
maxLevel = level
result.append(maxLevel)
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
var parenStack = [Character]()
for paren in parenString {
if paren == "(" {
level += 1
parenStack.append(paren)
} else if paren == ")" {
level -= 1
parenStack.append(paren)
}
if level > maxLevel {
maxLevel = level
result.append(maxLevel)
}
}
return result
}
// Test the function
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString))
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var maxDepth = 0
var depth = 0
for paren in parenString {
if paren == "(" {
depth += 1
parenStack.append(depth)
maxDepth = max(maxDepth, depth)
} else if paren == ")" {
depth = parenStack.popLast()!
}
}
return Array(repeating: maxDepth, count: parenString.count)
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var parenStack = [Int]()
var maxDepth = 0
var depth = 0
for paren in parenString {
if paren == "(" {
depth += 1
parenStack.append(depth)
maxDepth = max(maxDepth, depth)
} else if paren == ")" {
depth = parenStack.popLast()!
}
}
return Array(repeating: maxDepth, count: parenString.count)
}
// Example usage
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString)) // [2, 3, 1, 3]
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
parenStack.append(char)
level += 1
if level > maxLevel {
maxLevel = level
}
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
level -= 1
}
}
}
for _ in 0..<maxLevel {
result.append(maxLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
var parenStack = [Character]()
for char in parenString {
if char == "(" {
parenStack.append(char)
level += 1
if level > maxLevel {
maxLevel = level
}
} else if char == ")" {
if parenStack.count > 0 {
parenStack.removeLast()
level -= 1
}
}
}
for _ in 0..<maxLevel {
result.append(maxLevel)
}
return result
}
// Test the function
let inputString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: inputString))
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
var parenStack = [Character]()
for paren in parenString {
if paren == "(" {
parenStack.append(paren)
level += 1
if level > maxLevel {
maxLevel = level
}
} else if paren == ")" {
parenStack.removeLast()
level -= 1
}
}
for _ in 0..<maxLevel {
result.append(maxLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var level = 0
var maxLevel = 0
var parenStack = [Character]()
for paren in parenString {
if paren == "(" {
parenStack.append(paren)
level += 1
if level > maxLevel {
maxLevel = level
}
} else if paren == ")" {
parenStack.removeLast()
level -= 1
}
}
for _ in 0..<maxLevel {
result.append(maxLevel)
}
return result
}
// Test the function
let parenString = "(()()) ((())) () ((())()())"
print(parseNestedParens(parenString: parenString))
```
// XCTAssertTrue failed
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
return input.filter {
if let number = $0 as? Int {
return number % divisor == 0
} else if let string = $0 as? String {
return Int(string)!= nil && Int(string)! % divisor == 0
} else {
return false
}
}
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, +)
}
func sum(strings: [String]) -> Int {
return sum(numbers: strings.compactMap { Int($0) })
}
func sum(input: [Any]) -> Int {
return sum(numbers: input.compactMap {
if let number = $0 as? Int {
return number
} else if let string = $0 as? String {
return Int(string)
} else {
return nil
}
})
}
func product(numbers: [Int]) -> Int {
return numbers.reduce(1, *)
}
func product(strings: [String]) -> Int {
return product(numbers: strings.compactMap { Int($0) })
}
```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 integers only for ones that are divisible by given divisor
// filterByDivisibility(numbers: [] as [Int], divisor: 1) == [] as [Int]
// filterByDivisibility(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Filter an input array of strings and integers only for ones that are divisible by given divisor
// filterByDivisibility(input: [] as [Any], divisor: 1) == [] as [Any]
// filterByDivisibility(input: ["abc", 1, 2, 3, 4, "def", 5, 6, 7, "ghi", 8, 9, "jkl", 10], divisor: 3) == ["abc", 3, "def", 6, "ghi", 9]
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
return input.filter {
if let number = $0 as? Int {
return number % divisor == 0
} else if let string = $0 as? String {
return Int(string)!= nil && Int(string)! % divisor == 0
} else {
return false
}
}
}
// Return the sum of all numbers in an input array of integers
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, +)
}
// Return the sum of all numbers in an input array of strings that can be converted to integers
// sum(strings: [] as [String]) == 0
// sum(strings: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]) == 55
func sum(strings: [String]) -> Int {
return sum(numbers: strings.compactMap { Int($0) })
}
// Return the sum of all numbers in an input array of integers and strings that can be converted to integers
// sum(input: [] as [Any]) == 0
// sum(input: ["1", 2, "3", 4, "5", 6, "7", 8, "9", 10, "abc"]) == 55
func sum(input: [Any]) -> Int {
return sum(numbers: input.compactMap {
if let number = $0 as? Int {
return number
} else if let string = $0 as? String {
return Int(string)
} else {
return nil
}
})
}
// Return the product of all numbers in an input array of integers
// product(numbers: [] as [Int]) == 1
// product(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 3628800
func product(numbers: [Int]) -> Int {
return numbers.reduce(1, *)
}
// Return the product of all numbers in an input array of strings that can be converted to integers
// product(strings: [] as [String]) == 1
// product(strings: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]) == 3628800
func product(strings: [String]) -> Int {
return product(numbers: strings.compactMap { Int($0) })
}
// Return the product of all numbers in an input array of integers and strings that can be converted to integers
// product(input: [] as [Any]) == 1
// product(input: ["1", 2, "3", 4, "5", 6, "7", 8, "9", 10, "abc"]) ==
return Int(string)!= nil && Int(string)! % divisor == 0 // cannot assign through '!': function call returns immutable value
return Int(string)!= nil && Int(string)! % divisor == 0 // 'nil' is not compatible with expected argument type 'Bool'
return Int(string)!= nil && Int(string)! % divisor == 0 // cannot assign value of type 'Bool' to type 'Int'
return Int(string)!= nil && Int(string)! % divisor == 0 // use of '=' in a boolean context, did you mean '=='?
return Int(string)!= nil && Int(string)! % divisor == 0 // '=' must have consistent whitespace on both sides
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func filterByKeyAndValue(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.filter { $0[key] == value }
}
func extractDigits(strings: [String]) -> [Int] {
return strings.compactMap { Int($0) }
}
func extractKeyValues(strings: [String]) -> [Dictionary<String, Int>] {
return strings.compactMap {
let components = $0.components(separatedBy: ":")
guard components.count == 2, let key = Int(components[0]), let value = Int(components[1]) else {
return nil
}
return [components[0] : value]
}
}
```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 integers only for ones that are divisible by given divisor
// filterByDivisibility(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisibility(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Filter an input array of dictionaries only for ones that have a given key and value
// filterByKeyAndValue(dictionaries: [] as [Dictionary<String, Int>], key: "key", value: 1) == [] as [Dictionary<String, Int>]
// filterByKeyAndValue(dictionaries: [["key": 1, "value": 2], ["key": 2, "value": 3], ["key": 3, "value": 4]], key: "key", value: 2) == [["key": 2, "value": 3]]
func filterByKeyAndValue(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.filter { $0[key] == value }
}
// Return an array of integers from an input array of strings, where each string contains only digits
// extractDigits(strings: [] as [String]) == [] as [Int]
// extractDigits(strings: ["abc123", "1a2b3", "789", "0"]) == [123, 123, 789, 0]
func extractDigits(strings: [String]) -> [Int] {
return strings.compactMap { Int($0) }
}
// Return an array of dictionaries from an input array of strings, where each string contains key-value pairs
// in the format "key:value". The function should handle cases where the strings are not in the correct format
// and should return an empty array in those cases.
// extractKeyValues(strings: [] as [String]) == [] as [Dictionary<String, Int>]
// extractKeyValues(strings: ["key1:1", "key2:2", "key3:3", "key4:4", "key5:5", "key6:6", "key7:7", "key8:8", "key9:9", "key10:10"]) == [["key1": 1], ["key2": 2], ["key3": 3], ["key4": 4], ["key5": 5], ["key6": 6], ["key7": 7], ["key8": 8], ["key9": 9], ["key10": 10]]
func extractKeyValues(strings: [String]) -> [Dictionary<String, Int>] {
return strings.compactMap {
let components = $0.components(separatedBy: ":")
guard components.count == 2, let key = Int(components[0]), let value = Int(components[1]) else {
return nil
}
return [components[0] : value]
}
}
// Return an array of strings from an input array of dictionaries, where each dictionary contains only key-value
// pairs in the format "key:value". The function should handle cases where the dictionaries are not in the correct format
// and should return an empty array in those cases.
// extractKeyValuePairs(dictionaries: [] as [Dictionary<String, Int>]) == [] as [String]
// extractKeyValuePairs(dictionaries: [["key1": 1], ["key2": 2], ["key3": 3], ["key4": 4], ["key5": 5], ["key6": 6], ["key7": 7], ["key8": 8], ["key9": 9], ["key10": 10]]) == ["key1:1", "key2:2", "key3:3", "key4:4", "key5:5", "key6:6", "key7:7", "key8:8", "key9:9", "key10:10"]
func extractKeyValuePairs(dictionaries: [Dictionary<String, Int>])
guard components.count == 2, let key = Int(components[0]), let value = Int(components[1]) else { // immutable value 'key' was never used; consider replacing with '_' or removing it
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterBySubstringAndLength(strings: [String], substring: String, length: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count > length {
result.append(string)
}
}
return result
}
func filterBySubstringLengthAndCapital(strings: [String], substring: String, length: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count > length && string.first!.isUppercase {
result.append(string)
}
}
return result
}
func addPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(prefix + string)
}
return result
}
func addSuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(string + suffix)
}
return result
}
func addPrefixSuffix(strings: [String], prefix: String, suffix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(prefix + string + suffix)
}
return result
}
func removeCharacter(strings: [String], character: Character) -> [String] {
var result = [String]()
for string in strings {
result.append(string.replacingOccurrences(of: String(character), with: ""))
}
return result
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that contain given substring and are longer than given length
// filterBySubstringAndLength(strings: [] as [String], substring: "a", length: 0) == [] as [String]
// filterBySubstringAndLength(strings: ["abc", "bacd", "cde", "array"], substring: "a", length: 3) == ["abc", "array"]
func filterBySubstringAndLength(strings: [String], substring: String, length: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count > length {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that contain given substring, are longer than given length,
// and start with a capital letter
// filterBySubstringLengthAndCapital(strings: [] as [String], substring: "a", length: 0) == [] as [String]
// filterBySubstringLengthAndCapital(strings: ["abc", "bacd", "cde", "array"], substring: "a", length: 3) == ["abc"]
func filterBySubstringLengthAndCapital(strings: [String], substring: String, length: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count > length && string.first!.isUppercase {
result.append(string)
}
}
return result
}
// Return a new array of strings with the given prefix added to the beginning of each string in the input array
// addPrefix(strings: [] as [String], prefix: "") == [] as [String]
// addPrefix(strings: ["abc", "bacd", "cde", "array"], prefix: "f") == ["fabc", "fbacd", "fcde", "farray"]
func addPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(prefix + string)
}
return result
}
// Return a new array of strings with the given suffix added to the end of each string in the input array
// addSuffix(strings: [] as [String], suffix: "") == [] as [String]
// addSuffix(strings: ["abc", "bacd", "cde", "array"], suffix: "f") == ["abcf", "bacdf", "cdef", "arrayf"]
func addSuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(string + suffix)
}
return result
}
// Return a new array of strings with the given prefix and suffix added to each string in the input array
// addPrefixSuffix(strings: [] as [String], prefix: "", suffix: "") == [] as [String]
// addPrefixSuffix(strings: ["abc", "bacd", "cde", "array"], prefix: "f", suffix: "f") == ["fabc", "fbacd", "fcde", "farray"]
func addPrefixSuffix(strings: [String], prefix: String, suffix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(prefix + string + suffix)
}
return result
}
// Return a new array of strings with the given character removed from each string in the input array
// removeCharacter(strings: [] as [String], character: "") == [] as [String]
// removeCharacter(strings: ["abc", "bacd", "cde", "array"], character: "a") == ["bc", "bcd", "cde", "ray"]
func removeCharacter(strings: [String], character: Character) -> [String] {
var result = [String]()
for string in strings {
result.append(string.replacingOccurrences(of: String(character), with: ""))
}
return result
}
// Return a new array of strings with all whitespace characters removed from each string in the input array
// removeWhitespace(strings: [] as [String]) == [] as [String]
// removeWhitespace(strings: ["abc", "bacd", "cde", "array
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func filterByKeyAndValue(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.filter { $0[key] == value }
}
func appendToEach(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.map { $0 + [key: value] }
}
func doubleEach(dictionary: [String: Int]) -> [String: Int] {
return dictionary.mapValues { $0 * 2 }
}
func incrementEach(dictionary: [String: Int]) -> [String: Int] {
return dictionary.map { key, value in ["kittens-\(key)": value + 1] }.flatMap { $0 }
}
func doubleEachKey(dictionary: [String: Int]) -> [String: Int] {
return dictionary.mapKeys { "\($0)-awesome" }
}
```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 integers only for ones that are divisible by given divisor
// filterByDivisibility(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisibility(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Filter an input array of dictionaries only for ones that have a given key and value
// filterByKeyAndValue(dictionaries: [] as [Dictionary<String, Int>], key: "a", value: 1) == [] as [Dictionary<String, Int>]
// filterByKeyAndValue(dictionaries: [["a": 1, "b": 2], ["a": 2, "b": 3], ["a": 3, "b": 4]], key: "a", value: 2) == [["a": 2, "b": 3]]
func filterByKeyAndValue(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.filter { $0[key] == value }
}
// Return a new array of dictionaries where each one has a new key-value pair appended
// appendToEach(dictionaries: [] as [Dictionary<String, Int>], key: "a", value: 1) == [] as [Dictionary<String, Int>]
// appendToEach(dictionaries: [["a": 1, "b": 2], ["a": 2, "b": 3], ["a": 3, "b": 4]], key: "a", value: 2) == [["a": 1, "b": 2, "a": 2], ["a": 2, "b": 3, "a": 2], ["a": 3, "b": 4, "a": 2]]
func appendToEach(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.map { $0 + [key: value] }
}
// Return a new dictionary where each key-value pair is doubled
// doubleEach(dictionary: [:]) == [:]
// doubleEach(dictionary: ["a": 1, "b": 2, "c": 3]) == ["a": 2, "b": 4, "c": 6]
func doubleEach(dictionary: [String: Int]) -> [String: Int] {
return dictionary.mapValues { $0 * 2 }
}
// Return a new dictionary where each key is prefixed with "kittens-" and each value is incremented by 1
// incrementEach(dictionary: [:]) == [:]
// incrementEach(dictionary: ["a": 1, "b": 2, "c": 3]) == ["kittens-a": 2, "kittens-b": 3, "kittens-c": 4]
func incrementEach(dictionary: [String: Int]) -> [String: Int] {
return dictionary.map { key, value in ["kittens-\(key)": value + 1] }.flatMap { $0 }
}
// Return a new dictionary where each key is suffixed with "-awesome" and each value is doubled
// doubleEachKey(dictionary: [:]) == [:]
// doubleEachKey(dictionary: ["a": 1, "b": 2, "c": 3]) == ["a-awesome": 2, "b-awesome": 4, "c-awesome": 6]
func doubleEachKey(dictionary: [String: Int]) -> [String: Int] {
return dictionary.mapKeys { "\($0)-awesome" }
}
// Return a new dictionary where each value is suffixed with "ly" and each key is doubled
// doubleEachValue(dictionary: [:]) == [:]
// doubleEachValue(dictionary: ["a": 1, "b": 2, "c": 3]) == ["a": 2, "b": 4, "c":
return dictionaries.map { $0 + [key: value] } // referencing operator function '+' on 'Sequence' requires the types 'Dictionary<String, Int>.Element' (aka '(key: String, value: Int)') and 'String' be equivalent
return dictionary.map { key, value in ["kittens-\(key)": value + 1] }.flatMap { $0 } // cannot convert return expression of type '[Dictionary<String, Int>.Element]' to return type '[String : Int]'
return dictionary.mapKeys { "\($0)-awesome" } // value of type '[String : Int]' has no member 'mapKeys'
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
var result = [Int]()
for number in numbers {
if number % divisor == 0 {
result.append(number)
}
}
return result
}
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
var result = [Any]()
for item in input {
if let number = item as? Int {
if number % divisor == 0 {
result.append(number)
}
} else if let string = item as? String {
if Int(string)!= nil && Int(string)! % divisor == 0 {
result.append(string)
}
}
}
return result
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of integers only for ones that are divisible by given divisor
// filterByDivisibility(numbers: [] as [Int], divisor: 1) == [] as [Int]
// filterByDivisibility(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
var result = [Int]()
for number in numbers {
if number % divisor == 0 {
result.append(number)
}
}
return result
}
// Filter an input array of strings and integers only for ones that are divisible by given divisor
// filterByDivisibility(input: [] as [Any], divisor: 1) == [] as [Any]
// filterByDivisibility(input: ["abc", 1, "def", 2, "ghi", 3, "jkl", 4, "mno", 5], divisor: 3) == ["abc", "def", "ghi", "jkl", "mno"]
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
var result = [Any]()
for item in input {
if let number = item as? Int {
if number % divisor == 0 {
result.append(number)
}
} else if let string = item as? String {
if Int(string)!= nil && Int(string)! % divisor == 0 {
result.append(string)
}
}
}
return result
}
// Filter an input array of strings and integers only for ones that are divisible by given divisor
// filterByDivisibility(input: [] as [Any], divisor: 1) == [] as [Any]
// filterByDivisibility(input: ["abc", 1, "def", 2, "ghi", 3, "jkl", 4, "mno", 5], divisor: 3) == ["abc", "def", "ghi", "jkl", "mno"]
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
var result = [Any]()
for item in input {
if let number = item as? Int {
if number % divisor == 0 {
result.append(number)
}
} else if let string = item as? String {
if Int(string)!= nil && Int(string)! % divisor == 0 {
result.append(string)
}
}
}
return result
}
// Filter an input array of strings and integers only for ones that are divisible by given divisor
// filterByDivisibility(input: [] as [Any], divisor: 1) == [] as [Any]
// filterByDivisibility(input: ["abc", 1, "def", 2, "ghi", 3, "jkl", 4, "mno", 5], divisor: 3) == ["abc", "def", "ghi", "jkl", "mno"]
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
var result = [Any]()
for item in input {
if let number = item as? Int {
if number % divisor == 0 {
result.append(number)
}
} else if let string = item as? String {
if Int(string)!= nil && Int(string)! % divisor == 0 {
result.append(string)
}
}
}
return result
}
// Filter an input array of strings and integers only for ones that are divisible by given divisor
// filterByDivisibility(input: [] as [Any], divisor: 1) == [] as [Any]
// filterByDivisibility(input: ["abc", 1, "def", 2, "ghi", 3, "jkl", 4, "mno", 5], divisor: 3) == ["abc", "def", "ghi", "jkl", "mno"]
func
if Int(string)!= nil && Int(string)! % divisor == 0 { // cannot assign through '!': function call returns immutable value
if Int(string)!= nil && Int(string)! % divisor == 0 { // use of '=' in a boolean context, did you mean '=='?
if Int(string)!= nil && Int(string)! % divisor == 0 { // '=' must have consistent whitespace on both sides
if Int(string)!= nil && Int(string)! % divisor == 0 { // cannot assign value of type 'Bool' to type 'Int'
if Int(string)!= nil && Int(string)! % divisor == 0 { // 'nil' is not compatible with expected argument type 'Bool'
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
return input.filter {
if let number = $0 as? Int {
return number % divisor == 0
} else if let string = $0 as? String {
return Int(string)!= nil && Int(string)! % divisor == 0
}
return false
}
}
func getDivisibleNumbers(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func getDivisibleStrings(strings: [String], divisor: Int) -> [String] {
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 }
}
func getLetterStarts(dictionary: [String: Int], letter: String) -> [String: Int] {
return dictionary.filter { $0.key.hasPrefix(letter) }
}
```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 integers only for ones that are divisible by given divisor
// filterByDivisibility(numbers: [] as [Int], divisor: 1) == [] as [Int]
// filterByDivisibility(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Filter an input array of strings and integers only for ones that are divisible by given divisor
// filterByDivisibility(input: [] as [Any], divisor: 1) == [] as [Any]
// filterByDivisibility(input: ["abc", 1, 2, 3, 4, "5", 6, "7", 8, 9, "10"], divisor: 3) == ["abc", 3, 6, "7", 9]
func filterByDivisibility(input: [Any], divisor: Int) -> [Any] {
return input.filter {
if let number = $0 as? Int {
return number % divisor == 0
} else if let string = $0 as? String {
return Int(string)!= nil && Int(string)! % divisor == 0
}
return false
}
}
// Return a new array of integers containing only the numbers from the input array that are divisible by given divisor
// getDivisibleNumbers(numbers: [] as [Int], divisor: 1) == [] as [Int]
// getDivisibleNumbers(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func getDivisibleNumbers(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Return a new array of strings containing only the strings from the input array that are divisible by given divisor
// getDivisibleStrings(strings: [] as [String], divisor: 1) == [] as [String]
// getDivisibleStrings(strings: ["abc", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"], divisor: 3) == ["abc", "3", "6", "9"]
func getDivisibleStrings(strings: [String], divisor: Int) -> [String] {
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 }
}
// Return a new dictionary with only the key-value pairs from the input dictionary that have a key that starts with a given letter
// getLetterStarts(dictionary: [:], letter: "a") == [: ]
// getLetterStarts(dictionary: ["abc": 1, "bcd": 2, "cde": 3, "def": 4, "efg": 5, "fgh": 6, "ghi": 7, "hji": 8, "ijk": 9, "jkl": 10], letter: "b") == ["bcd": 2, "cde": 3, "def": 4, "efg": 5, "fgh": 6, "ghi": 7, "hji": 8, "ijk": 9, "jkl": 10]
func getLetterStarts(dictionary: [String: Int], letter: String) -> [String: Int] {
return dictionary.filter { $0.key.hasPrefix(letter) }
}
// Return a new dictionary with only the key-value pairs from the input dictionary that have a key that ends with a given letter
// getLetterEnds(dictionary: [:], letter: "a") == [: ]
// getLetterEnds(dictionary: ["abc": 1, "bcd": 2, "cde": 3, "def": 4, "efg": 5, "fgh": 6, "ghi": 7, "hji":
return Int(string)!= nil && Int(string)! % divisor == 0 // cannot assign through '!': function call returns immutable value
return Int(string)!= nil && Int(string)! % divisor == 0 // 'nil' is not compatible with expected argument type 'Bool'
return Int(string)!= nil && Int(string)! % divisor == 0 // cannot assign value of type 'Bool' to type 'Int'
return Int(string)!= nil && Int(string)! % divisor == 0 // use of '=' in a boolean context, did you mean '=='?
return Int(string)!= nil && Int(string)! % divisor == 0 // '=' must have consistent whitespace on both sides
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 } // cannot convert value of type '()' to closure result type 'Bool'
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 } // '=' must have consistent whitespace on both sides
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 } // 'nil' is not compatible with expected argument type 'Bool'
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 } // cannot assign through '!': function call returns immutable value
return strings.filter { Int($0)!= nil && Int($0)! % divisor == 0 } // cannot assign value of type 'Bool' to type 'Int'
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func filterByKeyAndValue(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.filter { $0[key] == value }
}
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 filterBySubstringAnyPosition(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterBySubstringBeginning(strings: [String], substring: String) -> [String] {
return strings.filter { $0.hasPrefix(substring) }
}
func filterBySubstringEnd(strings: [String], substring: String) -> [String] {
return strings.filter { $0.hasSuffix(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 integers only for ones that are divisible by given divisor
// filterByDivisibility(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisibility(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 3) == [3, 6, 9]
func filterByDivisibility(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Filter an input array of dictionaries only for ones that have a given key and value
// filterByKeyAndValue(dictionaries: [] as [Dictionary<String, Int>], key: "a", value: 1) == [] as [Dictionary<String, Int>]
// filterByKeyAndValue(dictionaries: [["a": 1, "b": 2], ["a": 2, "b": 3], ["a": 3, "b": 4], ["a": 4, "b": 5]], key: "a", value: 2) == [["a": 2, "b": 3], ["a": 3, "b": 4]]
func filterByKeyAndValue(dictionaries: [Dictionary<String, Int>], key: String, value: Int) -> [Dictionary<String, Int>] {
return dictionaries.filter { $0[key] == value }
}
// 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", "bacd", "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", "bacd", "cde", "array"], suffix: "a") == ["cde"]
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 in any position
// filterBySubstringAnyPosition(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringAnyPosition(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstringAnyPosition(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// Filter an input array of strings only for ones that contain a given substring at the beginning of a string
// filterBySubstringBeginning(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringBeginning(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc"]
func filterBySubstringBeginning(strings: [String], substring: String) -> [String] {
return strings.filter { $0.hasPrefix(substring) }
}
// Filter an input array of strings only for ones that contain a given substring at the end of a string
// filterBySubstringEnd(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringEnd(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["cde", "array"]
func filterBySubstringEnd(strings: [String], substring: String) -> [String] {
return strings.filter { $0.hasSuffix(substring) }
}
// Filter an input array of dictionaries only for ones that have a given key and value, regardless of case
// filterByKeyAndValueCaseInsensitive(dictionaries: [] as [Dictionary<String, Int>], key: "a", value
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"],
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterBySubstringCaseInsensitive(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().contains(substring.lowercased()) }
}
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmed(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespaces).contains(substring.lowercased().trimmingCharacters(in:.whitespaces)) }
}
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemoved(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).contains(substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)) }
}
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemoved(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).count == 1 }
}
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemovedOverlapping(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
// Filter an input array of strings only for ones that contain given substring, ignoring case
// filterBySubstringCaseInsensitive(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringCaseInsensitive(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "array"]
func filterBySubstringCaseInsensitive(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().contains(substring.lowercased()) }
}
// Filter an input array of strings only for ones that contain given substring, ignoring case and whitespace
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmed(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmed(strings: ["abc", " bacd ", " cde", "array "], substring: "a") == ["abc", "array"]
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmed(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespaces).contains(substring.lowercased().trimmingCharacters(in:.whitespaces)) }
}
// Filter an input array of strings only for ones that contain given substring, ignoring case, whitespace and punctuation
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemoved(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemoved(strings: ["abc", " bacd ", " cde", "array."], substring: "a") == ["abc", "array"]
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemoved(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).contains(substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)) }
}
// Filter an input array of strings only for ones that contain given substring, ignoring case, whitespace, punctuation and multiple occurrences
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemoved(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemoved(strings: ["abc", " bacd ", " cde", "array.", "array"], substring: "a") == ["abc", "array"]
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemoved(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).count == 1 }
}
// Filter an input array of strings only for ones that contain given substring, ignoring case, whitespace, punctuation, multiple occurrences and overlapping occurrences
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemovedOverlapping(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemovedOverlapping(strings: ["abc", " bacd ", " cde", "array.", "array"], substring: "a") == ["abc", "array"]
func filterBySubstringCaseInsensitiveAndWhitespaceTrimmedPunctuationRemovedMultipleOccurrencesRemovedOverlapping(strings: [String], substring: String) -> [String] {
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 }
}
// Filter an input array
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).contains(substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)) } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).contains(substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)) } // type 'CharacterSet' has no member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).contains(substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)) } // cannot infer contextual base in reference to member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).count == 1 } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).count == 1 } // type 'CharacterSet' has no member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).count == 1 } // cannot infer contextual base in reference to member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 } // cannot assign through '!': '$0' is immutable
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 } // trailing closure passed to parameter of type 'Predicate<String>' that does not accept a closure
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 } // type 'CharacterSet' has no member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 } // cannot infer contextual base in reference to member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 } // type 'CharacterSet' has no member 'whitespacesAndPunctuation'
return strings.filter { $0.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation).components(separatedBy: substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation)).filter { $0!= substring.lowercased().trimmingCharacters(in:.whitespacesAndPunctuation) }.count == 1 } // '=' must have consistent whitespace on both sides
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterBySubstringAndLength(strings: [String], substring: String, length: Int) -> [String] {
return strings.filter { $0.contains(substring) && $0.count > length }
}
func filterBySubstringLengthAndCharacterCount(strings: [String], substring: String, length: Int, characterCount: Int) -> [String] {
return strings.filter { $0.contains(substring) && $0.count > length && $0.filter { $0 == substring }.count >= characterCount }
}
func filterBySubstringLengthCharacterCountAndNoRepeatedCharacters(strings: [String], substring: String, length: Int, characterCount: Int) -> [String] {
return strings.filter {
$0.contains(substring) &&
$0.count > length &&
$0.filter { $0 == substring }.count >= characterCount &&
$0.filter { $0 == substring }.count == $0.count
}
}
func filterBySubstringLengthCharacterCountNoRepeatedCharactersNotStartWithVowel(strings: [String], substring: String, length: Int, characterCount: Int) -> [String] {
return strings.filter {
$0.contains(substring) &&
$0.count > length &&
$0.filter { $0 == substring }.count >= characterCount &&
$0.filter { $0 == substring }.count == $0.count &&
!"aeiou".contains($0.prefix(1).lowercased())
}
}
```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 and are longer than given length
// filterBySubstringAndLength(strings: [] as [String], substring: "a", length: 1) == [] as [String]
// filterBySubstringAndLength(strings: ["abc", "bacd", "cde", "array"], substring: "a", length: 1) == ["abc", "array"]
func filterBySubstringAndLength(strings: [String], substring: String, length: Int) -> [String] {
return strings.filter { $0.contains(substring) && $0.count > length }
}
// Filter an input array of strings only for ones that contain given substring, are longer than given length,
// and have at least given number of characters.
// filterBySubstringLengthAndCharacterCount(strings: [] as [String], substring: "a", length: 1, characterCount: 1) == [] as [String]
// filterBySubstringLengthAndCharacterCount(strings: ["abc", "bacd", "cde", "array"], substring: "a", length: 1, characterCount: 1) == ["abc"]
func filterBySubstringLengthAndCharacterCount(strings: [String], substring: String, length: Int, characterCount: Int) -> [String] {
return strings.filter { $0.contains(substring) && $0.count > length && $0.filter { $0 == substring }.count >= characterCount }
}
// Filter an input array of strings only for ones that contain given substring, are longer than given length,
// have at least given number of characters, and do not contain any repeated characters.
// filterBySubstringLengthCharacterCountAndNoRepeatedCharacters(strings: [] as [String], substring: "a", length: 1, characterCount: 1) == [] as [String]
// filterBySubstringLengthCharacterCountAndNoRepeatedCharacters(strings: ["abc", "bacd", "cde", "array"], substring: "a", length: 1, characterCount: 1) == ["abc"]
func filterBySubstringLengthCharacterCountAndNoRepeatedCharacters(strings: [String], substring: String, length: Int, characterCount: Int) -> [String] {
return strings.filter {
$0.contains(substring) &&
$0.count > length &&
$0.filter { $0 == substring }.count >= characterCount &&
$0.filter { $0 == substring }.count == $0.count
}
}
// Filter an input array of strings only for ones that contain given substring, are longer than given length,
// have at least given number of characters, do not contain any repeated characters, and do not start with a vowel.
// filterBySubstringLengthCharacterCountNoRepeatedCharactersNotStartWithVowel(strings: [] as [String], substring: "a", length: 1, characterCount: 1) == [] as [String]
// filterBySubstringLengthCharacterCountNoRepeatedCharactersNotStartWithVowel(strings: ["abc", "bacd", "cde", "array"], substring: "a", length: 1, characterCount: 1) == ["array"]
func filterBySubstringLengthCharacterCountNoRepeatedCharactersNotStartWithVowel(strings: [String], substring: String, length: Int, characterCount: Int) -> [String] {
return strings.filter {
$0.contains(substring) &&
$0.count > length &&
$0.filter { $0 == substring }.count >= characterCount &&
$0.filter { $0 == substring }.count == $0.count &&
!"aeiou".contains($0.prefix(1).lowercased())
}
}
// Filter an input array of strings only for ones that contain given substring, are longer than given length,
// have at least given number of characters, do not contain any repeated characters, start with a vowel,
// and are in lexicographically increasing order.
// filterBySubstringLengthCharacterCountNoRepeatedCharactersStartWithVowelInLexicographicallyIncreasingOrder(strings: [] as [String], substring: "a", length: 1, characterCount: 1) == [] as [String]
// filterBySubstringLengthCharacterCountNoRepeatedCharactersStartWithVowelInLexicographicallyIncreasingOrder(strings: ["abc", "bacd", "cde
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)
}
// Test Cases
sumProduct(numbers: []) == (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)
}
```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)
}
sumProduct(numbers: []) // (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)
}
```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)
}
// Test cases
sumProduct(numbers: []) // (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)
}
```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)
}
// Test Cases
sumProduct(numbers: []) // (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)
}
```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)
}
sumProduct(numbers: [])
sumProduct(numbers: [1, 2, 3, 4])
```
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)
}
// Test Cases
sumProduct(numbers: []) == (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)
}
```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)
}
sumProduct(numbers: [])
sumProduct(numbers: [1, 2, 3, 4])
```
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)
}
// Test Cases
sumProduct(numbers: []) == (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)
}
```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)
}
sumProduct(numbers: [1, 2, 3, 4])
sumProduct(numbers: [])
```
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)
}
let numbers = [1, 2, 3, 4]
let (sum, product) = sumProduct(numbers: numbers)
print("Sum: \(sum), Product: \(product)")
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for i in numbers {
sum += i
result.append(sum)
}
return result
}
func rollingAverage(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
for i in numbers {
sum += i
result.append(Double(sum) / Double(i))
}
return result
}
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumSquared = 0
for i in numbers {
sum += i
sumSquared += i * i
result.append(sqrt(Double(sumSquared - sum * sum) / Double(i)))
}
return result
}
func rollingVariance(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumSquared = 0
for i in numbers {
sum += i
sumSquared += i * i
result.append(Double(sumSquared - sum * sum) / Double(i))
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for i in numbers {
sum += i
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling average element found until given moment
// in the sequence.
// rollingAverage(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 2, 2, 2, 3, 3]
func rollingAverage(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
for i in numbers {
sum += i
result.append(Double(sum) / Double(i))
}
return result
}
// From a given array of integers, generate an array of rolling standard deviation element found until given moment
// in the sequence.
// rollingStandardDeviation(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.4, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 1.1581139000331498, 1.1581139000331498]
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumSquared = 0
for i in numbers {
sum += i
sumSquared += i * i
result.append(sqrt(Double(sumSquared - sum * sum) / Double(i)))
}
return result
}
// From a given array of integers, generate an array of rolling variance element found until given moment
// in the sequence.
// rollingVariance(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.4, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 1.1581139000331498, 1.1581139000331498]
func rollingVariance(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumSquared = 0
for i in numbers {
sum += i
sumSquared += i * i
result.append(Double(sumSquared - sum * sum) / Double(i))
}
return result
}
// From a given array of integers, generate an array of moving average element found until given moment
// in the sequence.
// movingAverage
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for i in numbers {
sum += i
result.append(sum)
}
return result
}
func cumulativeSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
result.append(sum)
for i in numbers {
sum += i
result.append(sum)
}
return result
}
func cumulativeProduct(numbers: [Int]) -> [Int] {
var result = [Int]()
var product = 1
result.append(product)
for i in numbers {
product *= i
result.append(product)
}
return result
}
func cumulativeMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in numbers {
max = max(max, i)
result.append(max)
}
return result
}
func cumulativeMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in numbers {
min = min(min, i)
result.append(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 = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum found until given moment in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for i in numbers {
sum += i
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative sum found until given moment in the sequence.
// cumulativeSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 15]
func cumulativeSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
result.append(sum)
for i in numbers {
sum += i
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative product found until given moment in the sequence.
// cumulativeProduct(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 6, 12, 18, 24, 48]
func cumulativeProduct(numbers: [Int]) -> [Int] {
var result = [Int]()
var product = 1
result.append(product)
for i in numbers {
product *= i
result.append(product)
}
return result
}
// From a given array of integers, generate an array of cumulative maximum element found until given moment
// in the sequence.
// cumulativeMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func cumulativeMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in numbers {
max = max(max, i)
result.append(max)
}
return result
}
// From a given array of integers, generate an array of cumulative minimum element found until given moment
// in the sequence.
// cumulativeMin(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 1, 2, 2, 2, 3]
func cumulativeMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in numbers {
min = min(min, i)
result.append(min)
}
return result
}
// From a given array of integers, generate an array of cumulative sum found until given moment in the sequence.
// cumulativeSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 15]
func cumulativeSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, i) // cannot call value of non-function type 'Int'
min = min(min, i) // cannot call value of non-function type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingMax(numbers: [Int], window: Int) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
if i >= window {
max = max(max, numbers[i - window])
}
result.append(max)
}
return result
}
func rollingMin(numbers: [Int], window: Int) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
if i >= window {
min = min(min, numbers[i - window])
}
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
func rollingSum(numbers: [Int], window: Int) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
if i >= window {
sum -= numbers[i - window]
}
result.append(sum)
}
return result
}
func cumulativeSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// 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], window: Int) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
if i >= window {
max = max(max, numbers[i - window])
}
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int], window: Int) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
if i >= window {
min = min(min, numbers[i - window])
}
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2], window: 3) == [3, 6, 9, 6, 9, 12, 9]
func rollingSum(numbers: [Int], window: Int) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
if i >= window {
sum -= numbers[i - window]
}
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative sum element found until given moment
// in the sequence.
// cumulativeSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 15]
func cumulativeSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative sum element found until given moment
// in
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, numbers[i - window]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i - window]) // cannot call value of non-function type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingMax(numbers: [Int], window: Int) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
if i >= window {
max = max(max, numbers[i - window])
}
result.append(max)
}
return result
}
func rollingMin(numbers: [Int], window: Int) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
if i >= window {
min = min(min, numbers[i - window])
}
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
func rollingSum(numbers: [Int], window: Int) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
if i >= window {
sum -= numbers[i - window]
}
result.append(sum)
}
return result
}
func cumulativeSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 2]
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// 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], window: Int) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
if i >= window {
max = max(max, numbers[i - window])
}
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, 1, 2, 2, 2, 2]
func rollingMin(numbers: [Int], window: Int) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
if i >= window {
min = min(min, numbers[i - window])
}
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int], window: Int) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
if i >= window {
sum -= numbers[i - window]
}
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative sum element found until given moment
// in the sequence.
// cumulativeSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 15]
func cumulativeSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative sum element found until given moment
// in the sequence.
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, numbers[i - window]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i - window]) // cannot call value of non-function type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingMax(numbers: [Int], windowSize: Int) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
if i >= windowSize {
max = max(max, numbers[i - windowSize])
}
result.append(max)
}
return result
}
func rollingMin(numbers: [Int], windowSize: Int) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
if i >= windowSize {
min = min(min, numbers[i - windowSize])
}
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
func rollingSum(numbers: [Int], windowSize: Int) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
if i >= windowSize {
sum -= numbers[i - windowSize]
}
sum += numbers[i]
result.append(sum)
}
return result
}
func cumulativeSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// 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], windowSize: Int) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
if i >= windowSize {
max = max(max, numbers[i - windowSize])
}
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int], windowSize: Int) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
if i >= windowSize {
min = min(min, numbers[i - windowSize])
}
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2], windowSize: 3) == [3, 5, 8, 8, 11, 13, 13]
func rollingSum(numbers: [Int], windowSize: Int) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
if i >= windowSize {
sum -= numbers[i - windowSize]
}
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of cumulative sum element found until given moment
// in the sequence.
// cumulativeSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 15]
func cumulativeSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
max = max(max, numbers[i - windowSize]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i - windowSize]) // cannot call value of non-function type 'Int'
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
func rollingAverage(numbers: [Int]) -> [Double] {
let sums = rollingSum(numbers: numbers)
let max = max(1, numbers.count)
return sums.map { Double($0) / Double(max) }
}
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
let averages = rollingAverage(numbers: numbers)
let squaredDiffs = zip(averages, numbers).map { pow(($0 - $1), 2) }
let sums = rollingSum(numbers: squaredDiffs)
let max = max(1, numbers.count)
return sums.map { Double($0) / Double(max) }
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int]) -> [Int] {
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var sum = 0
var result = [sum]
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling average found until given moment
// in the sequence.
// rollingAverage(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 2, 2.5, 2.5, 3, 3]
func rollingAverage(numbers: [Int]) -> [Double] {
let sums = rollingSum(numbers: numbers)
let max = max(1, numbers.count)
return sums.map { Double($0) / Double(max) }
}
// From a given array of integers, generate an array of rolling standard deviation found until given moment
// in the sequence.
// rollingStandardDeviation(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.4, 0.7071067811865476, 0.816496580927726, 0.8775824676337209, 0.9092974268256817, 0.9092974268256817]
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
let averages = rollingAverage(numbers: numbers)
let squaredDiffs = zip(averages, numbers).map { pow(($0 - $1), 2) }
let sums = rollingSum(numbers: squaredDiffs)
let max = max(1, numbers.count)
return sums.map { Double($0) / Double(max) }
}
// From a given array of integers, generate an array of rolling variance found until given moment
// in the sequence.
// rollingVariance(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.4, 0.16666666666666663, 0.06666666666666667, 0.03333333333333333, 0.013888888888888888, 0.013888888888888888]
func rollingVariance(numbers: [Int]) -> [Double] {
let averages = rollingAverage(numbers: numbers)
let squaredDiffs = zip(averages, numbers).map { pow(($0 - $1), 2) }
let sums = rollingSum(numbers: squaredDiffs)
let max = max(1, numbers.count)
return sum
max = max(max, numbers[i]) // cannot call value of non-function type 'Int'
min = min(min, numbers[i]) // cannot call value of non-function type 'Int'
let squaredDiffs = zip(averages, numbers).map { pow(($0 - $1), 2) } // cannot convert value of type 'Int' to expected argument type 'Double'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = 0
for number in numbers {
if number < min {
min = number
}
result.append(min)
}
return result
}
func rollingMax(numbers: [Int], window: Int) -> [Int] {
var result = [Int]()
var max = 0
var index = 0
for number in numbers {
if index >= window {
max -= numbers[index - window]
}
if number > max {
max = number
}
result.append(max)
index += 1
}
return result
}
func rollingMin(numbers: [Int], window: Int) -> [Int] {
var result = [Int]()
var min = 0
var index = 0
for number in numbers {
if index >= window {
min -= numbers[index - window]
}
if number < min {
min = number
}
result.append(min)
index += 1
}
return result
}
func sums(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for number in numbers {
sum += number
result.append(sum)
}
return result
}
func sums(numbers: [Int], window: Int) -> [Int] {
var result = [Int]()
var sum = 0
var index = 0
for _ in numbers {
if index >= window {
sum -= numbers[index - window]
}
sum += numbers[index]
result.append(sum)
index += 1
}
return result
}
func cumulativeSums(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for number in numbers {
sum += number
result.append(sum)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = 0
for number in numbers {
if number > max {
max = number
}
result.append(max)
}
return result
}
// 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, 1, 2, 2, 2, 2]
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = 0
for number in numbers {
if number < min {
min = number
}
result.append(min)
}
return result
}
// 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], window: Int) -> [Int] {
var result = [Int]()
var max = 0
var index = 0
for number in numbers {
if index >= window {
max -= numbers[index - window]
}
if number > max {
max = number
}
result.append(max)
index += 1
}
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, 1, 2, 2, 2, 2]
func rollingMin(numbers: [Int], window: Int) -> [Int] {
var result = [Int]()
var min = 0
var index = 0
for number in numbers {
if index >= window {
min -= numbers[index - window]
}
if number < min {
min = number
}
result.append(min)
index += 1
}
return result
}
// Given an array of integers, generate an array of sums of all consecutive elements in the array.
// sums(numbers: [1, 2, 3, 4]) == [1, 3, 6, 10]
func sums(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for number in numbers {
sum += number
result.append(sum)
}
return result
}
// Given an array of integers, generate an array of sums of all consecutive elements in the array.
// sums(numbers: [1, 2, 3, 4]) == [1, 3, 6, 10]
func sums(numbers: [Int], window: Int) -> [Int] {
var result = [Int]()
var sum = 0
var index = 0
for _ in numbers {
if index >= window {
sum -= numbers[index - window]
}
sum += numbers[index]
result.append(sum)
index += 1
}
return result
}
// Given an array of integers, generate an array of cumulative sums of all consecutive elements in the array.
// cumulativeSums(numbers: [1, 2, 3, 4]) == [1, 3, 6, 10]
func cumulativeSums(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for number in numbers {
sum += number
result.append(sum)
}
return result
}
// Given an array of integers, generate an array of cumulative sums of all consecutive elements in the array.
// cumulativeSums(numbers: [1, 2, 3, 4]) == [1, 3, 6, 10]
func cumulativeSums(numbers: [Int], window: Int) -> [Int] {
var result = [Int]()
var index = 0
for _ in numbers {
var sum = 0
for i in index..<index + window {
sum += numbers[i]
}
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(numbers[i], max)
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(numbers[i], min)
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var sum = numbers[0]
var result = [sum]
for i in 1..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
func rollingAverage(numbers: [Int]) -> [Double] {
guard numbers.count > 0 else { return [] }
let sums = rollingSum(numbers: numbers)
let divs = rollingMax(numbers: numbers)
return zip(sums, divs).map { Double($0.0) / Double($0.1) }
}
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
guard numbers.count > 0 else { return [] }
let averages = rollingAverage(numbers: numbers)
let squaredDiffs = zip(averages, numbers).map { pow(($0.0 - $0.1), 2) }
let sums = rollingSum(numbers: squaredDiffs)
let divs = rollingMax(numbers: numbers)
return zip(sums, divs).map { Double($0.0) / Double($0.1) }
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var max = numbers[0]
var result = [max]
for i in 1..<numbers.count {
max = max(numbers[i], max)
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, 1, 2, 2, 2, 2]
func rollingMin(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var min = numbers[0]
var result = [min]
for i in 1..<numbers.count {
min = min(numbers[i], min)
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var sum = numbers[0]
var result = [sum]
for i in 1..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling average element found until given moment
// in the sequence.
// rollingAverage(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 2, 2.5, 2.5, 3, 3]
func rollingAverage(numbers: [Int]) -> [Double] {
guard numbers.count > 0 else { return [] }
let sums = rollingSum(numbers: numbers)
let divs = rollingMax(numbers: numbers)
return zip(sums, divs).map { Double($0.0) / Double($0.1) }
}
// From a given array of integers, generate an array of rolling standard deviation element found until given moment
// in the sequence.
// rollingStandardDeviation(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.4, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476]
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
guard numbers.count > 0 else { return [] }
let averages = rollingAverage(numbers: numbers)
let squaredDiffs = zip(averages, numbers).map { pow(($0.0 - $0.1), 2) }
let sums = rollingSum(numbers: squaredDiffs)
let divs = rollingMax(numbers: numbers)
return zip(sums, divs).map { Double($0.0) / Double($0.1) }
}
// From a given array of integers, generate an array of rolling median element found until given moment
// in the sequence.
// rollingMedian(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 2, 2, 2, 3, 3]
func rollingMedian(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var result = [Int]()
var sorted = numbers
while sorted.count > 0 {
let median = sorted.count % 2 == 0? (sorted[sorted.count / 2 - 1] + sorted[sorted.count / 2]) /
max = max(numbers[i], max) // cannot call value of non-function type 'Int'
min = min(numbers[i], min) // cannot call value of non-function type 'Int'
let squaredDiffs = zip(averages, numbers).map { pow(($0.0 - $0.1), 2) } // cannot convert value of type 'Int' to expected argument type 'Double'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for i in numbers {
sum += i
result.append(sum)
}
return result
}
func rollingAverage(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
for i in numbers {
sum += i
result.append(Double(sum) / Double(i))
}
return result
}
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumOfSquares = 0
for i in numbers {
sum += i
sumOfSquares += i * i
result.append(sqrt(Double(sumOfSquares - sum * sum / Double(i)) / Double(i - 1)))
}
return result
}
func rollingMedian(numbers: [Int]) -> [Int] {
var result = [Int]()
var sortedNumbers = [Int]()
for i in numbers {
sortedNumbers.append(i)
result.append(sortedNumbers.median)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 3]
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
for i in numbers {
sum += i
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling average found until given moment
// in the sequence.
// rollingAverage(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1.0, 1.5, 2.0, 2.5, 2.6666666666666665, 2.857142857142857, 2.9285714285714285]
func rollingAverage(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
for i in numbers {
sum += i
result.append(Double(sum) / Double(i))
}
return result
}
// From a given array of integers, generate an array of rolling standard deviation found until given moment
// in the sequence.
// rollingStandardDeviation(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0.0, 0.4, 0.816496580927726, 0.9486832980505138, 0.9748794418604652, 0.9869565217391304, 0.9939387755102041]
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumOfSquares = 0
for i in numbers {
sum += i
sumOfSquares += i * i
result.append(sqrt(Double(sumOfSquares - sum * sum / Double(i)) / Double(i - 1)))
}
return result
}
// From a given array of integers, generate an array of rolling median found until given moment
// in the sequence.
// rollingMedian(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 2, 2, 2, 3, 3]
func rollingMedian(numbers: [Int]) -> [Int] {
var result = [Int]()
var sortedNumbers = [Int]()
for i in numbers {
sortedNumbers.append(i)
result.append(sortedNumbers.median)
}
return result
}
// From a given array of integers, generate an array of rolling mode found until given moment
// in the sequence.
// rollingMode(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 1, 2, 2, 2,
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
result.append(max)
}
return result
}
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
result.append(sum)
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
func rollingAverage(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
result.append(Double(sum) / Double(numbers.count))
for i in 0..<numbers.count {
sum += numbers[i]
result.append(Double(sum) / Double(i + 1))
}
return result
}
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumSquared = 0
result.append(0)
for i in 0..<numbers.count {
sum += numbers[i]
sumSquared += numbers[i] * numbers[i]
result.append(sqrt(Double(sumSquared - sum * sum / Double(i + 1)) / Double(i)))
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
result.append(max)
for i in 1..<numbers.count {
max = max(max, numbers[i])
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, 1, 2, 2, 2, 2]
func rollingMin(numbers: [Int]) -> [Int] {
var result = [Int]()
var min = numbers[0]
result.append(min)
for i in 1..<numbers.count {
min = min(min, numbers[i])
result.append(min)
}
return result
}
// From a given array of integers, generate an array of rolling sum element found until given moment
// in the sequence.
// rollingSum(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 3, 6, 8, 11, 13, 13]
func rollingSum(numbers: [Int]) -> [Int] {
var result = [Int]()
var sum = 0
result.append(sum)
for i in 0..<numbers.count {
sum += numbers[i]
result.append(sum)
}
return result
}
// From a given array of integers, generate an array of rolling average element found until given moment
// in the sequence.
// rollingAverage(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 2, 2.5, 2.5, 3, 3]
func rollingAverage(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
result.append(Double(sum) / Double(numbers.count))
for i in 0..<numbers.count {
sum += numbers[i]
result.append(Double(sum) / Double(i + 1))
}
return result
}
// From a given array of integers, generate an array of rolling standard deviation element found until given moment
// in the sequence.
// rollingStandardDeviation(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.4, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476, 0.7071067811865476]
func rollingStandardDeviation(numbers: [Int]) -> [Double] {
var result = [Double]()
var sum = 0
var sumSquared = 0
result.append(0)
for i in 0..<numbers.count {
sum += numbers[i]
sumSquared += numbers[i] * numbers[i]
result.append(sqrt(Double(sumSquared - sum * sum / Double(i + 1)) / Double(i)))
}
return result
}
// From a given array of integers, generate an array of rolling variance element found until given moment
// in the sequence.
// rollingVariance(numbers: [1, 2, 3, 2, 3, 4, 2]) == [0, 0.6666666666666666, 1.3333333333333333, 1.3333333333333333, 1.3333333333333333, 1.3333333333333333, 1.3333333333333333]
func rollingVariance(numbers: [Int]) -> [Double] {
var result = [
func makePalindrome(string: String) -> String {
guard string.count > 1 else { return string }
var suffix = ""
var prefix = ""
for i in stride(from: string.count - 1, through: 0, by: -1) {
suffix.append(string[i])
if isPalindrome(string: suffix) {
break
}
}
for i in 0..<string.count {
prefix.append(string[i])
if isPalindrome(string: prefix) {
break
}
}
return prefix + String(suffix.reversed())
}
func isPalindrome(string: String) -> Bool {
return string == String(string.reversed())
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard string.count > 1 else { return string }
var suffix = ""
var prefix = ""
for i in stride(from: string.count - 1, through: 0, by: -1) {
suffix.append(string[i])
if isPalindrome(string: suffix) {
break
}
}
for i in 0..<string.count {
prefix.append(string[i])
if isPalindrome(string: prefix) {
break
}
}
return prefix + String(suffix.reversed())
}
// Check if a string is a palindrome.
func isPalindrome(string: String) -> Bool {
return string == String(string.reversed())
}
// Test the algorithm.
let input = "cat"
let output = makePalindrome(string: input)
print("Input: \(input)")
print("Output: \(output)")
assert(output == "catac")
let input2 = "cata"
let output2 = makePalindrome(string: input2)
print("Input: \(input2)")
print("Output: \(output2)")
assert(output2 == "catac")
let input3 = "a"
let output3 = makePalindrome(string: input3)
print("Input: \(input3)")
print("Output: \(output3)")
assert(output3 == "a")
let input4 = "ab"
let output4 = makePalindrome(string: input4)
print("Input: \(input4)")
print("Output: \(output4)")
assert(output4 == "ab")
let input5 = "abc"
let output5 = makePalindrome(string: input5)
print("Input: \(input5)")
print("Output: \(output5)")
assert(output5 == "abc")
let input6 = "abcd"
let output6 = makePalindrome(string: input6)
print("Input: \(input6)")
print("Output: \(output6)")
assert(output6 == "abcdabcd")
let input7 = "abcde"
let output7 = makePalindrome(string: input7)
print("Input: \(input7)")
print("Output: \(output7)")
assert(output7 == "abcdeabcde")
let input8 = "abcdef"
let output8 = makePalindrome(string: input8)
print("Input: \(input8)")
print("Output: \(output8)")
assert(output8 == "abcdefabcdef")
let input9 = "abfdef"
let output9 = makePalindrome(string: input9)
print("Input: \(input9)")
print("Output: \(output9)")
assert(output9 == "abcdefabcdefabfdef")
let input10 = "abfdefg"
let output10 = makePalindrome(string: input10)
print("Input: \(input10)")
print("Output: \(output10)")
assert(output10 == "abcdefabcdefabcdefg")
let input11 = "abfdefgz"
let output11 = makePalindrome(string: input11)
print("Input: \(input11)")
print("Output: \(output11)")
assert(output11 == "abcdefabcdefabcdefgz")
let input12 = "a"
let output12 = makePalindrome(string: input12)
print("Input: \(input12)")
print("Output: \(output12)")
assert(output12 == "a")
let input13 = "aa"
let output13 = makePalindrome(string: input13)
print("Input: \(input13)")
print("Output: \(output13)")
assert(output13 == "aa")
let input14 = "aaa"
let output14 = makePalindrome(string: input14)
print("Input: \(input14)")
print("Output: \(output14)")
assert(output14 == "aaa")
let input15 = "aab"
let output15 = makePalindrome(string: input15)
print("Input: \(input15)")
print("Output: \(output15)")
assert(output15 == "aabaa")
let input16 = "aabb"
let output16 = makePalindrome(string:
suffix.append(string[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
prefix.append(string[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func makePalindrome(string: String) -> String {
if string.isEmpty {
return ""
}
let reversedString = String(string.characters.reverse())
let reversedStringPrefix = longestPrefix(string: reversedString)
return reversedStringPrefix + string + reversedStringPrefix
}
func longestPrefix(string: String) -> String {
var prefix = ""
for (i, char) in string.characters.enumerated() {
if i == 0 {
prefix += String(char)
} else {
if prefix.characters.last == char {
prefix += String(char)
} else {
break
}
}
}
return prefix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
if string.isEmpty {
return ""
}
let reversedString = String(string.characters.reverse())
let reversedStringPrefix = longestPrefix(string: reversedString)
return reversedStringPrefix + string + reversedStringPrefix
}
func longestPrefix(string: String) -> String {
var prefix = ""
for (i, char) in string.characters.enumerated() {
if i == 0 {
prefix += String(char)
} else {
if prefix.characters.last == char {
prefix += String(char)
} else {
break
}
}
}
return prefix
}
makePalindrome(string: "cat")
makePalindrome(string: "cata")
makePalindrome(string: "c")
makePalindrome(string: "ab")
makePalindrome(string: "abc")
makePalindrome(string: "aac")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "b")
makePalindrome(string: "ba")
makePalindrome(string: "bb")
makePalindrome(string: "bbb")
makePalindrome(string: "abcba")
makePalindrome(string: "abccab")
makePalindrome(string: "abcdabcd")
makePalindrome(string: "abcdeabcd")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz")
makePalindrome(string: "ab")
makePalindrome(string: "abcba")
makePalindrome(string: "abccab")
makePalindrome(string: "abcdabcd")
makePalindrome(string: "abcdeabcd")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "b")
makePalindrome(string: "ba")
makePalindrome(string: "bb")
makePalindrome(string: "bbb")
makePalindrome(string: "abcba")
makePalindrome(string: "abccab")
makePalindrome(string: "abcdabcd")
makePalindrome(string: "abcdeabcd")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyza")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyza")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzab")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabc")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcd")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcde")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdef")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefg")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefgh")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghi")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghij")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghijk")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghijkl")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghijklm")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghijklmn")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghijklmno")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdefghijklmnop")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabcdef
let reversedString = String(string.characters.reverse()) // value of type 'String' has no member 'reverse'
for (i, char) in string.characters.enumerated() { // 'characters' is unavailable: Please use String directly
if prefix.characters.last == char { // 'characters' is unavailable: Please use String directly
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.reversed())
let prefix = longestPrefix(string: reversedString)
return prefix + string + String(reversedString.suffix(prefix.count))
}
func longestPrefix(string: String) -> String {
var i = 0
while i < string.count / 2 {
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] {
return String(string.prefix(i))
}
i += 1
}
return String(string.prefix(i))
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.reversed())
let prefix = longestPrefix(string: reversedString)
return prefix + string + String(reversedString.suffix(prefix.count))
}
func longestPrefix(string: String) -> String {
var i = 0
while i < string.count / 2 {
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] {
return String(string.prefix(i))
}
i += 1
}
return String(string.prefix(i))
}
// Test cases
assert(makePalindrome(string: "cat") == "catac")
assert(makePalindrome(string: "cata") == "catac")
assert(makePalindrome(string: "c") == "c")
assert(makePalindrome(string: "ab") == "abba")
assert(makePalindrome(string: "abc") == "abcba")
assert(makePalindrome(string: "aac") == "aacaa")
assert(makePalindrome(string: "a") == "a")
assert(makePalindrome(string: "abcd") == "abcdabcd")
assert(makePalindrome(string: "abcdcba") == "abcdcbaabcdcba")
assert(makePalindrome(string: "abcdcbaa") == "abcdcbaabcdcba")
assert(makePalindrome(string: "abcdcbaaa") == "abcdcbaabcdcbaa")
assert(makePalindrome(string: "abcdcbaaaa") == "abcdcbaabcdcbaaa")
assert(makePalindrome(string: "abcdcbaaaaa") == "abcdcbaabcdcbaaa")
assert(makePalindrome(string: "abcdcbaaaaaa") == "abcdcbaabcdcbaaaaaa")
assert(makePalindrome(string: "abcdcbaaaaaaa") == "abcdcbaabcdcbaaaaaaa")
assert(makePalindrome(string: "abcdcbaaaaaaaa") == "abcdcbaabcdcbaaaaaaaa")
assert(makePalindrome(string: "abcdcbaaaaaaaaa") == "abcdcbaabcdcbaaaaaaaaa")
assert(makePalindrome(string: "abcdcbaaaaaaaaaa") == "abcdcbaabcdcbaaaaaaaaaa")
assert(makePalindrome(string: "abcdcbaaaaaaaaaaa") == "abcdcbaabcdcbaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalindrome(string: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
assert(makePalind
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // cannot force unwrap value of non-optional type 'Character'
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // use of '=' in a boolean context, did you mean '=='?
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // '=' must have consistent whitespace on both sides
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.reversed())
let reversedPrefix = longestPrefix(string: reversedString)
let palindrome = reversedString + reversedPrefix
return palindrome
}
func longestPrefix(string: String) -> String {
var i = 0
let j = string.count - 1
while i < j {
if string[i]!= string[j] {
break
}
i += 1
j -= 1
}
return String(string[i...j])
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.reversed())
let reversedPrefix = longestPrefix(string: reversedString)
let palindrome = reversedString + reversedPrefix
return palindrome
}
func longestPrefix(string: String) -> String {
var i = 0
let j = string.count - 1
while i < j {
if string[i]!= string[j] {
break
}
i += 1
j -= 1
}
return String(string[i...j])
}
makePalindrome(string: "cat")
makePalindrome(string: "cata")
makePalindrome(string: "c")
makePalindrome(string: "ab")
makePalindrome(string: "abc")
makePalindrome(string: "aac")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "aba")
makePalindrome(string: "abac")
makePalindrome(string: "abca")
makePalindrome(string: "aacb")
makePalindrome(string: "aacbb")
makePalindrome(string: "aacbbb")
makePalindrome(string: "aacbbbb")
makePalindrome(string: "aacbbbbb")
makePalindrome(string: "aacbbbbbb")
makePalindrome(string: "aacbbbbbbb")
makePalindrome(string: "aacbbbbbbbca")
makePalindrome(string: "aacbbbbbbbcaa")
makePalindrome(string: "aacbbbbbbbcaaa")
makePalindrome(string: "aacbbbbbbbcaaac")
makePalindrome(string: "aacbbbbbbbcaaacb")
makePalindrome(string: "aacbbbbbbbcaaacbb")
makePalindrome(string: "aacbbbbbbbcaaacbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbba")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaab")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbba")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbba")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaab")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbba")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaab")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabbba")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabbbaab")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabbbaabb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabbbaabbbb")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabbbaabbbbba")
makePalindrome(string: "aacbbbbbbbcaaacbbbbbbbbaabbbbbaabbbbbaabbbaabbbbba
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
if string[i]!= string[j] { // use of '=' in a boolean context, did you mean '=='?
if string[i]!= string[j] { // cannot force unwrap value of non-optional type 'Character'
if string[i]!= string[j] { // '=' must have consistent whitespace on both sides
j -= 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
return String(string[i...j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
guard let (prefix, suffix) = longestPalindrome(string: string) else { return string }
return prefix + reverse(string: suffix)
}
func longestPalindrome(string: String) -> (prefix: String, suffix: String)? {
guard!string.isEmpty else { return nil }
var prefix = ""
var suffix = ""
for i in 0..<string.count {
let (newPrefix, newSuffix) = longestPalindrome(string: string, from: i)
if newSuffix.count > suffix.count {
prefix = newPrefix
suffix = newSuffix
}
}
return (prefix, suffix)
}
func longestPalindrome(string: String, from index: Int) -> (prefix: String, suffix: String) {
var prefix = ""
var suffix = ""
var i = index
var j = string.count - 1 - index
while i >= 0 && j < string.count && string[i] == string[j] {
prefix = String(string[i]) + prefix
suffix = suffix + String(string[j])
i -= 1
j += 1
}
return (prefix, suffix)
}
func reverse(string: String) -> String {
var reversed = ""
for i in 0..<string.count {
reversed = String(string[string.index(string.endIndex, offsetBy: -i - 1)]) + reversed
}
return reversed
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
guard let (prefix, suffix) = longestPalindrome(string: string) else { return string }
return prefix + reverse(string: suffix)
}
func longestPalindrome(string: String) -> (prefix: String, suffix: String)? {
guard!string.isEmpty else { return nil }
var prefix = ""
var suffix = ""
for i in 0..<string.count {
let (newPrefix, newSuffix) = longestPalindrome(string: string, from: i)
if newSuffix.count > suffix.count {
prefix = newPrefix
suffix = newSuffix
}
}
return (prefix, suffix)
}
func longestPalindrome(string: String, from index: Int) -> (prefix: String, suffix: String) {
var prefix = ""
var suffix = ""
var i = index
var j = string.count - 1 - index
while i >= 0 && j < string.count && string[i] == string[j] {
prefix = String(string[i]) + prefix
suffix = suffix + String(string[j])
i -= 1
j += 1
}
return (prefix, suffix)
}
func reverse(string: String) -> String {
var reversed = ""
for i in 0..<string.count {
reversed = String(string[string.index(string.endIndex, offsetBy: -i - 1)]) + reversed
}
return reversed
}
//: [Next](@next)
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
guard!string.isEmpty else { return nil } // expected expression, var, let or case in 'guard' condition
while i >= 0 && j < string.count && string[i] == string[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while i >= 0 && j < string.count && string[i] == string[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
prefix = String(string[i]) + prefix // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
suffix = suffix + String(string[j]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.characters.reverse())
let reversedStringPrefix = longestPrefix(string: reversedString)
return reversedStringPrefix + string + reversedStringPrefix
}
func longestPrefix(string: String) -> String {
var i = 0
while i < string.count / 2 {
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] {
return String(string.characters.prefix(i))
}
i += 1
}
return String(string.characters.prefix(i))
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.characters.reverse())
let reversedStringPrefix = longestPrefix(string: reversedString)
return reversedStringPrefix + string + reversedStringPrefix
}
func longestPrefix(string: String) -> String {
var i = 0
while i < string.count / 2 {
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] {
return String(string.characters.prefix(i))
}
i += 1
}
return String(string.characters.prefix(i))
}
makePalindrome(string: "cat")
makePalindrome(string: "cata")
makePalindrome(string: "c")
makePalindrome(string: "ab")
makePalindrome(string: "abc")
makePalindrome(string: "aac")
makePalindrome(string: "a")
makePalindrome(string: "abcd")
makePalindrome(string: "abca")
makePalindrome(string: "aacb")
makePalindrome(string: "abcba")
makePalindrome(string: "abcb")
makePalindrome(string: "ab")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "aba")
makePalindrome(string: "abac")
makePalindrome(string: "aac")
makePalindrome(string: "abacab")
makePalindrome(string: "abacaba")
makePalindrome(string: "aacb")
makePalindrome(string: "abcba")
makePalindrome(string: "abcb")
makePalindrome(string: "ab")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "aba")
makePalindrome(string: "abac")
makePalindrome(string: "aac")
makePalindrome(string: "abacab")
makePalindrome(string: "abacaba")
makePalindrome(string: "aacb")
makePalindrome(string: "abcba")
makePalindrome(string: "abcb")
makePalindrome(string: "ab")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "aba")
makePalindrome(string: "abac")
makePalindrome(string: "aac")
makePalindrome(string: "abacab")
makePalindrome(string: "abacaba")
makePalindrome(string: "aacb")
makePalindrome(string: "abcba")
makePalindrome(string: "abcb")
makePalindrome(string: "ab")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "aba")
makePalindrome(string: "abac")
makePalindrome(string: "aac")
makePalindrome(string: "abacab")
makePalindrome(string: "abacaba")
makePalindrome(string: "aacb")
makePalindrome(string: "abcba")
makePalindrome(string: "abcb")
makePalindrome(string: "ab")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "aba")
makePalindrome(string: "abac")
makePalindrome(string: "aac")
makePalindrome(string: "abacab")
makePalindrome(string: "abacaba")
makePalindrome(string: "aacb")
makePalindrome(string: "abcba")
makePalindrome(string: "abcb")
makePalindrome(string: "ab")
makePalindrome(string
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
let reversedString = String(string.characters.reverse()) // value of type 'String' has no member 'reverse'
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // cannot force unwrap value of non-optional type 'Character'
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // use of '=' in a boolean context, did you mean '=='?
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // '=' must have consistent whitespace on both sides
return String(string.characters.prefix(i)) // 'characters' is unavailable: Please use String directly
return String(string.characters.prefix(i)) // 'characters' is unavailable: Please use String directly
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversed = String(string.reversed())
var prefix = ""
var suffix = ""
for (i, char) in string.enumerated() {
if reversed[i] == char {
prefix.append(char)
} else {
suffix = String(reversed[i...]) + suffix
break
}
}
return prefix + 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 {
guard!string.isEmpty else { return "" }
let reversed = String(string.reversed())
var prefix = ""
var suffix = ""
for (i, char) in string.enumerated() {
if reversed[i] == char {
prefix.append(char)
} else {
suffix = String(reversed[i...]) + suffix
break
}
}
return prefix + string + suffix
}
// Tests
assert(makePalindrome(string: "cat") == "catac")
assert(makePalindrome(string: "cata") == "catac")
assert(makePalindrome(string: "c") == "c")
assert(makePalindrome(string: "ab") == "abba")
assert(makePalindrome(string: "abc") == "abcba")
assert(makePalindrome(string: "abcd") == "abcdabcd")
assert(makePalindrome(string: "abcde") == "abcdeabcde")
assert(makePalindrome(string: "abcdef") == "abcdefabcdef")
assert(makePalindrome(string: "abcdefg") == "abcdefgabcdefg")
assert(makePalindrome(string: "abcdefgh") == "abcdefghabcdefgh")
assert(makePalindrome(string: "abcdefghi") == "abcdefghiabcdefghi")
assert(makePalindrome(string: "abcdefghij") == "abcdefghijabcdefghij")
assert(makePalindrome(string: "abcdefghijkl") == "abcdefghijklabcdefghijkl")
assert(makePalindrome(string: "abcdefghijklmn") == "abcdefghijklmnabcdefghijklmn")
assert(makePalindrome(string: "abcdefghijklmno") == "abcdefghijklmnoabcdefghijklmno")
assert(makePalindrome(string: "abcdefghijklmnop") == "abcdefghijklmnopabcdefghijklmnop")
assert(makePalindrome(string: "abcdefghijklmnopq") == "abcdefghijklmnopqabcdefghijklmnopq")
assert(makePalindrome(string: "abcdefghijklmnopqr") == "abcdefghijklmnopqrabcdefghijklmnopqr")
assert(makePalindrome(string: "abcdefghijklmnopqrs") == "abcdefghijklmnopqrsabcdefghijklmnopqrs")
assert(makePalindrome(string: "abcdefghijklmnopqrst") == "abcdefghijklmnopqrstabcdefghijklmnopqrst")
assert(makePalindrome(string: "abcdefghijklmnopqrstu") == "abcdefghijklmnopqrstuabcdefghijklmnopqrstu")
assert(makePalindrome(string: "abcdefghijklmnopqrstuv") == "abcdefghijklmnopqrstuvabcdefghijklmnopqrstuv")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvw") == "abcdefghijklmnopqrstuvwabcdefghijklmnopqrstuvw")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvwx") == "abcdefghijklmnopqrstuvwxabcdefghijklmnopqrstuvwx")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvwxy") == "abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxy")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvwxyz") == "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvwxyza") == "abcdefghijklmnopqrstuvwxyzaabcdefghijklmnopqrstuvwxyza")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvwxyzab") == "abcdefghijklmnopqrstuvwxyzababcdefghijklmnopqrstuvwxyzab")
assert(makePalindrome(string: "abcdefghijklmnopqrstuvwxyzabc") == "abcdefghijklmnopqrstuvwxyzabcabcdefgh
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
if reversed[i] == char { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
suffix = String(reversed[i...]) + suffix // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.reversed())
let reversedStringWithPrefix = reversedString + string
let palindrome = findLongestPrefix(string: reversedStringWithPrefix)
return palindrome + string
}
func findLongestPrefix(string: String) -> String {
var left = 0
var right = string.count - 1
while left < right {
if string[left]!= string[right] {
return String(string[left...right])
}
left += 1
right -= 1
}
return String(string[left...right])
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversedString = String(string.reversed())
let reversedStringWithPrefix = reversedString + string
let palindrome = findLongestPrefix(string: reversedStringWithPrefix)
return palindrome + string
}
func findLongestPrefix(string: String) -> String {
var left = 0
var right = string.count - 1
while left < right {
if string[left]!= string[right] {
return String(string[left...right])
}
left += 1
right -= 1
}
return String(string[left...right])
}
makePalindrome(string: "cat")
makePalindrome(string: "cata")
makePalindrome(string: "c")
makePalindrome(string: "ab")
makePalindrome(string: "abc")
makePalindrome(string: "aac")
makePalindrome(string: "a")
makePalindrome(string: "aa")
makePalindrome(string: "aab")
makePalindrome(string: "b")
makePalindrome(string: "bb")
makePalindrome(string: "bbb")
makePalindrome(string: "bbbb")
makePalindrome(string: "cbbd")
makePalindrome(string: "abcd")
makePalindrome(string: "abcde")
makePalindrome(string: "abcdef")
makePalindrome(string: "abcdefg")
makePalindrome(string: "abcdefgh")
makePalindrome(string: "abcdefghi")
makePalindrome(string: "abcdefghij")
makePalindrome(string: "abcdefghijk")
makePalindrome(string: "abcdefghijkl")
makePalindrome(string: "abcdefghijklmn")
makePalindrome(string: "abcdefghijklmno")
makePalindrome(string: "abcdefghijklmnop")
makePalindrome(string: "abcdefghijklmnopq")
makePalindrome(string: "abcdefghijklmnopqr")
makePalindrome(string: "abcdefghijklmnopqrs")
makePalindrome(string: "abcdefghijklmnopqrst")
makePalindrome(string: "abcdefghijklmnopqrstu")
makePalindrome(string: "abcdefghijklmnopqrstuv")
makePalindrome(string: "abcdefghijklmnopqrstuvw")
makePalindrome(string: "abcdefghijklmnopqrstuvwx")
makePalindrome(string: "abcdefghijklmnopqrstuvwxy")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01234")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012345")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01234567")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012345678")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456789")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456789a")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456789ab")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456789abc")
makePalindrome(string: "
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
if string[left]!= string[right] { // use of '=' in a boolean context, did you mean '=='?
if string[left]!= string[right] { // cannot force unwrap value of non-optional type 'Character'
if string[left]!= string[right] { // '=' must have consistent whitespace on both sides
return String(string[left...right]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return String(string[left...right]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func makePalindrome(string: String) -> String {
guard!string.isEmpty else { return "" }
let reversed = String(string.reversed())
let prefix = longestPrefix(string: reversed)
return prefix + string + String(reversed[prefix.count..<reversed.count])
}
func longestPrefix(string: String) -> String {
var i = 0
while i < string.count / 2 {
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] {
return String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: string.count - i - 1)])
}
i += 1
}
return String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: string.count - i - 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 {
guard!string.isEmpty else { return "" }
let reversed = String(string.reversed())
let prefix = longestPrefix(string: reversed)
return prefix + string + String(reversed[prefix.count..<reversed.count])
}
func longestPrefix(string: String) -> String {
var i = 0
while i < string.count / 2 {
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] {
return String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: string.count - i - 1)])
}
i += 1
}
return String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: string.count - i - 1)])
}
makePalindrome(string: "cat") // "catac"
makePalindrome(string: "cata") // "catac"
makePalindrome(string: "c") // "c"
makePalindrome(string: "ab") // "ab"
makePalindrome(string: "abc") // "abc"
makePalindrome(string: "abcd") // "abcd"
makePalindrome(string: "abcde") // "abcde"
makePalindrome(string: "abcdef") // "abcdef"
makePalindrome(string: "abcdefg") // "abcdefg"
makePalindrome(string: "abacdfgdcaba") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaa") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaa") // "abacdfgdcabaa"
makePalindrome(string: "abacdfgdcabaab") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabbba") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabbab") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabbabb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabbbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaabbbbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaab") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabbba") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabbab") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabbabb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabbbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaabbbbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaaab") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaaabb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaaabbb") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaaabbba") // "abacdfgdcaba"
makePalindrome(string: "abacdfgdcabaaaabbab") // "abacdfgdcaba
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
return prefix + string + String(reversed[prefix.count..<reversed.count]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // cannot force unwrap value of non-optional type 'Character'
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // use of '=' in a boolean context, did you mean '=='?
if string[string.index(string.startIndex, offsetBy: i)]!= string[string.index(string.startIndex, offsetBy: string.count - i - 1)] { // '=' must have consistent whitespace on both sides
func makePalindrome(string: String) -> String {
guard string.count > 1 else { return string }
let reversedString = String(string.reversed())
var longestPrefix = ""
var longestSuffix = ""
for (index, char) in string.enumerated() {
let reversedIndex = reversedString.index(reversedString.startIndex, offsetBy: index)
let currentPrefix = String(string[string.index(string.startIndex, offsetBy: index)...])
let currentSuffix = String(reversedString[reversedIndex...])
if currentPrefix == currentSuffix {
longestPrefix = currentPrefix
longestSuffix = currentSuffix
break
}
}
return longestPrefix + string + longestSuffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard string.count > 1 else { return string }
let reversedString = String(string.reversed())
var longestPrefix = ""
var longestSuffix = ""
for (index, char) in string.enumerated() {
let reversedIndex = reversedString.index(reversedString.startIndex, offsetBy: index)
let currentPrefix = String(string[string.index(string.startIndex, offsetBy: index)...])
let currentSuffix = String(reversedString[reversedIndex...])
if currentPrefix == currentSuffix {
longestPrefix = currentPrefix
longestSuffix = currentSuffix
break
}
}
return longestPrefix + string + longestSuffix
}
makePalindrome(string: "cat")
makePalindrome(string: "cata")
makePalindrome(string: "c")
makePalindrome(string: "ab")
makePalindrome(string: "abc")
makePalindrome(string: "abcd")
makePalindrome(string: "abcde")
makePalindrome(string: "abcdef")
makePalindrome(string: "abcdefg")
makePalindrome(string: "abcdefgh")
makePalindrome(string: "abcdefghi")
makePalindrome(string: "abcdefghij")
makePalindrome(string: "abcdefghijk")
makePalindrome(string: "abcdefghijkl")
makePalindrome(string: "abcdefghijklm")
makePalindrome(string: "abcdefghijklmn")
makePalindrome(string: "abcdefghijklmno")
makePalindrome(string: "abcdefghijklmnop")
makePalindrome(string: "abcdefghijklmnopq")
makePalindrome(string: "abcdefghijklmnopqr")
makePalindrome(string: "abcdefghijklmnopqrs")
makePalindrome(string: "abcdefghijklmnopqrst")
makePalindrome(string: "abcdefghijklmnopqrstu")
makePalindrome(string: "abcdefghijklmnopqrstuv")
makePalindrome(string: "abcdefghijklmnopqrstuvw")
makePalindrome(string: "abcdefghijklmnopqrstuvwx")
makePalindrome(string: "abcdefghijklmnopqrstuvwxy")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01234")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012345")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01234567")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012345678")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456789")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01234567890")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012345678901")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz0123456789012")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz01234567890123")
makePalindrome(string: "abcdefghijklmnopqrstuvwxyz012345678901234")
makePalindrome(string: "abcdef
for (index, char) in string.enumerated() { // immutable value 'char' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(characterA.asciiValue! ^ characterB.asciiValue!))
}
return result
}
func xor(a: Int, b: Int) -> Int {
return a ^ b
}
func xor(a: Double, b: Double) -> Double {
return Double(Int(a) ^ Int(b))
}
func xor(a: Float, b: Float) -> Float {
return Float(Int(a) ^ Int(b))
}
func xor(a: UInt, b: UInt) -> UInt {
return a ^ b
}
func xor(a: UInt8, b: UInt8) -> UInt8 {
return UInt8(Int(a) ^ Int(b))
}
func xor(a: UInt16, b: UInt16) -> UInt16 {
return UInt16(Int(a) ^ Int(b))
}
func xor(a: UInt32, b: UInt32) -> UInt32 {
return a ^ b
}
func xor(a: UInt64, b: UInt64) -> UInt64 {
return a ^ b
}
func xor(a: Int8, b: Int8) -> Int8 {
return Int8(Int(a) ^ Int(b))
}
func xor(a: Int16, b: Int16) -> Int16 {
return Int16(Int(a) ^ Int(b))
}
func xor(a: Int32, b: Int32) -> Int32 {
return Int32(Int(a) ^ Int(b))
}
func xor(a: Int64, b: Int64) -> Int64 {
return a ^ b
}
```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 (characterA, characterB) in zip(a, b) {
result.append(String(characterA.asciiValue! ^ characterB.asciiValue!))
}
return result
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Int, b: Int) -> Int {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Double, b: Double) -> Double {
return Double(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Float, b: Float) -> Float {
return Float(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: UInt, b: UInt) -> UInt {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: UInt8, b: UInt8) -> UInt8 {
return UInt8(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: UInt16, b: UInt16) -> UInt16 {
return UInt16(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: UInt32, b: UInt32) -> UInt32 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: UInt64, b: UInt64) -> UInt64 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Int8, b: Int8) -> Int8 {
return Int8(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Int16, b: Int16) -> Int16 {
return Int16(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Int32, b: Int32) -> Int32 {
return Int32(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Int64, b: Int64) -> Int64 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary X
func stringXor(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! ^ charB.asciiValue!))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (charA, charB) in zip(a, b) {
result = result << 1
result = result | (charA.asciiValue! ^ charB.asciiValue!)
}
return result
}
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ⊻ Int(b, radix: 2)
}
```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 (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! ^ charB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (charA, charB) in zip(a, b) {
result = result << 1
result = result | (charA.asciiValue! ^ charB.asciiValue!)
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ⊻ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ⊻ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a
result = result | (charA.asciiValue! ^ charB.asciiValue!) // cannot convert value of type 'UInt8' to expected argument type 'Int'
func stringXor(a: String, b: String) -> Int { // invalid redeclaration of 'stringXor(a:b:)'
return Int(a, radix: 2) ^ Int(b, radix: 2) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return Int(a, radix: 2) ^ Int(b, radix: 2) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func stringXor(a: String, b: String) -> Int { // invalid redeclaration of 'stringXor(a:b:)'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func stringXor(a: String, b: String) -> Int { // invalid redeclaration of 'stringXor(a:b:)'
return Int(a, radix: 2) ⊻ Int(b, radix: 2) // cannot find operator '⊻' in scope
func stringXor(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! ^ charB.asciiValue!))
}
return result
}
func stringAnd(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! & charB.asciiValue!))
}
return result
}
func stringOr(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! | charB.asciiValue!))
}
return result
}
func stringNot(a: String) -> String {
var result = ""
for char in a {
result.append(String(char.asciiValue! ^ 1))
}
return result
}
func stringRightShift(a: String, b: Int) -> String {
var result = ""
for char in a {
result.append(String(char.asciiValue! >> b))
}
return result
}
func stringLeftShift(a: String, b: Int) -> String {
var result = ""
for char in a {
result.append(String(char.asciiValue! << b))
}
return result
}
func stringAddition(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (charA, charB) in zip(a, b) {
let sum = charA.asciiValue! + charB.asciiValue! + overflow
result.append(String(sum % 2))
overflow = sum / 2
}
if overflow > 0 {
result.append(String(overflow))
}
return result
}
func stringSubtraction(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (charA, charB) in zip(a, b) {
let difference = charA.asciiValue! - charB.asciiValue! - overflow
result.append(String(difference % 2))
overflow = difference / 2
}
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 (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! ^ charB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary AND (&) on these inputs and return result also as a string.
// stringAnd(a: "010", b: "110") == "010"
func stringAnd(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! & charB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary OR (|) on these inputs and return result also as a string.
// stringOr(a: "010", b: "110") == "110"
func stringOr(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! | charB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary NOT (!) on these inputs and return result also as a string.
// stringNot(a: "010") == "101"
func stringNot(a: String) -> String {
var result = ""
for char in a {
result.append(String(char.asciiValue! ^ 1))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform right shift (>>) on these inputs and return result also as a string.
// stringRightShift(a: "010", b: 1) == "001"
func stringRightShift(a: String, b: Int) -> String {
var result = ""
for char in a {
result.append(String(char.asciiValue! >> b))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform left shift (<<) on these inputs and return result also as a string.
// stringLeftShift(a: "010", b: 1) == "100"
func stringLeftShift(a: String, b: Int) -> String {
var result = ""
for char in a {
result.append(String(char.asciiValue! << b))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform addition (+) on these inputs and return result also as a string.
// stringAddition(a: "010", b: "110") == "1000"
func stringAddition(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (charA, charB) in zip(a, b) {
let sum = charA.asciiValue! + charB.asciiValue! + overflow
result.append(String(sum % 2))
overflow = sum / 2
}
if overflow > 0 {
result.append(String(overflow))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform subtraction (-) on these inputs and return result also as a string.
// stringSubtraction(a: "010", b: "110") == "100"
func stringSubtraction(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (charA, charB) in zip(a, b) {
let difference = charA.asciiValue! - charB.asciiValue! - overflow
result.append(String(difference % 2))
overflow = difference / 2
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform multiplication (*) on these inputs and return result also as a string.
// stringMultiplication(a:
let sum = charA.asciiValue! + charB.asciiValue! + overflow // binary operator '+' cannot be applied to operands of type 'UInt8' and 'Int'
let difference = charA.asciiValue! - charB.asciiValue! - overflow // binary operator '-' cannot be applied to operands of type 'UInt8' and 'Int'
func stringXor(a: String, b: String) -> String {
var result = ""
for (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! ^ charB.asciiValue!))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (charA, charB) in zip(a, b) {
result = result << 1
result = result | (charA.asciiValue! ^ charB.asciiValue!)
}
return result
}
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
```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 (charA, charB) in zip(a, b) {
result.append(String(charA.asciiValue! ^ charB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (charA, charB) in zip(a, b) {
result = result << 1
result = result | (charA.asciiValue! ^ charB.asciiValue!)
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String,
result = result | (charA.asciiValue! ^ charB.asciiValue!) // cannot convert value of type 'UInt8' to expected argument type 'Int'
func stringXor(a: String, b: String) -> Int { // invalid redeclaration of 'stringXor(a:b:)'
return Int(a, radix: 2) ^ Int(b, radix: 2) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return Int(a, radix: 2) ^ Int(b, radix: 2) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func stringXor(a: String, b: String) -> Int { // invalid redeclaration of 'stringXor(a:b:)'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return (Int(a, radix: 2) &+ Int(b, radix: 2)) &+ (Int(a, radix: 2) &* Int(b, radix: 2)) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func stringXor(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(bitPattern: characterA.asciiValue! ^ characterB.asciiValue!))
}
return result
}
func stringAnd(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(bitPattern: characterA.asciiValue! & characterB.asciiValue!))
}
return result
}
func stringOr(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(bitPattern: characterA.asciiValue! | characterB.asciiValue!))
}
return result
}
func stringNot(a: String) -> String {
var result = ""
for character in a {
result.append(String(bitPattern: ~character.asciiValue!))
}
return result
}
func stringRightShift(a: String, b: Int) -> String {
var result = ""
for character in a {
result.append(String(bitPattern: character.asciiValue! >> b))
}
return result
}
func stringLeftShift(a: String, b: Int) -> String {
var result = ""
for character in a {
result.append(String(bitPattern: character.asciiValue! << b))
}
return result
}
func stringAddition(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (characterA, characterB) in zip(a, b) {
let characterAValue = characterA.asciiValue!
let characterBValue = characterB.asciiValue!
let characterSum = characterAValue + characterBValue + overflow
overflow = characterSum >> 8
result.append(String(bitPattern: characterSum & 0xFF))
}
if overflow!= 0 {
result.append(String(bitPattern: overflow))
}
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 (characterA, characterB) in zip(a, b) {
result.append(String(bitPattern: characterA.asciiValue! ^ characterB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary AND on these inputs and return result also as a string.
// stringAnd(a: "010", b: "110") == "010"
func stringAnd(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(bitPattern: characterA.asciiValue! & characterB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary OR on these inputs and return result also as a string.
// stringOr(a: "010", b: "110") == "110"
func stringOr(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(bitPattern: characterA.asciiValue! | characterB.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary NOT on these inputs and return result also as a string.
// stringNot(a: "010") == "101"
func stringNot(a: String) -> String {
var result = ""
for character in a {
result.append(String(bitPattern: ~character.asciiValue!))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform right shift on string a by b positions and return result as a string.
// stringRightShift(a: "010", b: 1) == "001"
func stringRightShift(a: String, b: Int) -> String {
var result = ""
for character in a {
result.append(String(bitPattern: character.asciiValue! >> b))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform left shift on string a by b positions and return result as a string.
// stringLeftShift(a: "010", b: 1) == "100"
func stringLeftShift(a: String, b: Int) -> String {
var result = ""
for character in a {
result.append(String(bitPattern: character.asciiValue! << b))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform addition on string a and b and return result as a string.
// stringAddition(a: "010", b: "110") == "1000"
func stringAddition(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (characterA, characterB) in zip(a, b) {
let characterAValue = characterA.asciiValue!
let characterBValue = characterB.asciiValue!
let characterSum = characterAValue + characterBValue + overflow
overflow = characterSum >> 8
result.append(String(bitPattern: characterSum & 0xFF))
}
if overflow!= 0 {
result.append(String(bitPattern: overflow))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform subtraction on string a and b and return result as a string.
// stringSubtraction(a: "010", b: "110") == "000"
func stringSubtraction(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (characterA, characterB) in zip(a, b) {
let characterAValue = characterA.asciiValue!
let characterBValue = characterB.asciiValue!
let characterDifference = characterAValue - characterBValue - overflow
overflow = (characterDifference >> 7) & 1
result.append(String(bit
result.append(String(bitPattern: characterA.asciiValue! ^ characterB.asciiValue!)) // no exact matches in call to initializer
result.append(String(bitPattern: characterA.asciiValue! & characterB.asciiValue!)) // no exact matches in call to initializer
result.append(String(bitPattern: characterA.asciiValue! | characterB.asciiValue!)) // no exact matches in call to initializer
result.append(String(bitPattern: ~character.asciiValue!)) // no exact matches in call to initializer
result.append(String(bitPattern: character.asciiValue! >> b)) // no exact matches in call to initializer
result.append(String(bitPattern: character.asciiValue! << b)) // no exact matches in call to initializer
let characterSum = characterAValue + characterBValue + overflow // binary operator '+' cannot be applied to operands of type 'UInt8' and 'Int'
result.append(String(bitPattern: characterSum & 0xFF)) // no exact matches in call to initializer
if overflow!= 0 { // use of '=' in a boolean context, did you mean '=='?
if overflow!= 0 { // '=' must have consistent whitespace on both sides
if overflow!= 0 { // cannot force unwrap value of non-optional type 'Int'
result.append(String(bitPattern: overflow)) // no exact matches in call to initializer
func stringXor(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
func xor(a: Int, b: Int) -> Int {
return a ^ b
}
func xor(a: Double, b: Double) -> Double {
return Double(Int(a) ^ Int(b))
}
func xor(a: Float, b: Float) -> Float {
return Float(Int(a) ^ Int(b))
}
func xor(a: UInt, b: UInt) -> UInt {
return a ^ b
}
func xor(a: Bool, b: Bool) -> Bool {
return a!= b
}
func xor(a: Int8, b: Int8) -> Int8 {
return a ^ b
}
func xor(a: Int16, b: Int16) -> Int16 {
return a ^ b
}
func xor(a: Int32, b: Int32) -> Int32 {
return a ^ b
}
func xor(a: Int64, b: Int64) -> Int64 {
return a ^ b
}
func xor(a: UInt8, b: UInt8) -> UInt8 {
return a ^ b
}
func xor(a: UInt16, b: UInt16) -> UInt16 {
return a ^ b
}
func xor(a: UInt32, b: UInt32) -> UInt32 {
return a ^ b
}
func xor(a: UInt64, b: UInt64) -> UInt64 {
return a ^ b
}
```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 (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Int, b: Int) -> Int {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Double, b: Double) -> Double {
return Double(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10.5, b: 20.5) == 30.0
func xor(a: Float, b: Float) -> Float {
return Float(Int(a) ^ Int(b))
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: UInt, b: UInt) -> UInt {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Bool, b: Bool) -> Bool {
return a!= b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Int8, b: Int8) -> Int8 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Int16, b: Int16) -> Int16 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Int32, b: Int32) -> Int32 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: Int64, b: Int64) -> Int64 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: UInt8, b: UInt8) -> UInt8 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: UInt16, b: UInt16) -> UInt16 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: UInt32, b: UInt32) -> UInt32 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a: UInt64, b: UInt64) -> UInt64 {
return a ^ b
}
// Input are two numbers a and b.
// Perform binary XOR on these inputs and return result.
// xor(a: 10, b: 20) == 30
func xor(a
result.append(String(Int(characterA) ^ Int(characterB))) // no exact matches in call to initializer
result.append(String(Int(characterA) ^ Int(characterB))) // no exact matches in call to initializer
return a!= b // cannot force unwrap value of non-optional type 'Bool'
return a!= b // use of '=' in a boolean context, did you mean '=='?
return a!= b // '=' must have consistent whitespace on both sides
func stringXor(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (characterA, characterB) in zip(a, b) {
result = result << 1
result = result | (Int(characterA) ^ Int(characterB))
}
return result
}
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
```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 (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (characterA, characterB) in zip(a, b) {
result = result << 1
result = result | (Int(characterA) ^ Int(characterB))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
//
result.append(String(Int(characterA) ^ Int(characterB))) // no exact matches in call to initializer
result.append(String(Int(characterA) ^ Int(characterB))) // no exact matches in call to initializer
result = result | (Int(characterA) ^ Int(characterB)) // no exact matches in call to initializer
result = result | (Int(characterA) ^ Int(characterB)) // no exact matches in call to initializer
func stringXor(a: String, b: String) -> Int { // invalid redeclaration of 'stringXor(a:b:)'
return Int(a, radix: 2) ^ Int(b, radix: 2) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return Int(a, radix: 2) ^ Int(b, radix: 2) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func stringXor(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (characterA, characterB) in zip(a, b) {
result = result << 1
result = result | (Int(characterA) ^ Int(characterB))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, characterA) in a.enumerated() {
result = result << 1
result = result | (Int(characterA) ^ Int(b[index]))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, _) in a.enumerated() {
result = result << 1
result = result | (Int(a[index]) ^ Int(b[index]))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for characterA in a {
result = result << 1
result = result | (Int(characterA) ^ Int(b[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 (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (characterA, characterB) in zip(a, b) {
result = result << 1
result = result | (Int(characterA) ^ Int(characterB))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, characterA) in a.enumerated() {
result = result << 1
result = result | (Int(characterA) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, _) in a.enumerated() {
result = result << 1
result = result | (Int(a[index]) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for characterA in a {
result = result << 1
result = result | (Int(characterA) ^ Int(b[result & 1]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, characterA) in a.enumerated() {
result = result << 1
result = result | (Int(characterA) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, characterA) in a.enumerated() {
result = result << 1
result = result | (Int(characterA) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, characterA) in a.enumerated() {
result = result << 1
result = result | (Int(characterA) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010",
func stringXor(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
func stringAnd(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) & Int(characterB)))
}
return result
}
func stringOr(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) | Int(characterB)))
}
return result
}
func stringLeftShift(a: String, b: Int) -> String {
var result = a
for _ in 0..<b {
result.insert(result.first!, at: result.startIndex)
}
return result
}
func stringRightShift(a: String, b: Int) -> String {
var result = a
for _ in 0..<b {
result.removeFirst()
}
return result
}
func stringNot(a: String) -> String {
var result = ""
for character in a {
result.append(String(1 - Int(character)))
}
return result
}
func stringOneComplement(a: String) -> String {
return stringNot(a: stringAnd(a: a, b: "11111111"))
}
func stringTwoComplement(a: String) -> String {
return stringOneComplement(a: stringNot(a: a)) + "0"
}
func stringAddition(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (characterA, characterB) in zip(a.reversed(), b.reversed()) {
let addition = Int(characterA) + Int(characterB) + overflow
result.insert(String(addition % 2), at: result.startIndex)
overflow = addition / 2
}
if overflow > 0 {
result.insert(String(overflow), at: result.startIndex)
}
return result.reversed()
}
```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 (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) ^ Int(characterB)))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary AND on these inputs and return result also as a string.
// stringAnd(a: "010", b: "110") == "010"
func stringAnd(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) & Int(characterB)))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary OR on these inputs and return result also as a string.
// stringOr(a: "010", b: "110") == "110"
func stringOr(a: String, b: String) -> String {
var result = ""
for (characterA, characterB) in zip(a, b) {
result.append(String(Int(characterA) | Int(characterB)))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary Left Shift on these inputs and return result also as a string.
// stringLeftShift(a: "010", b: 2) == "00010"
func stringLeftShift(a: String, b: Int) -> String {
var result = a
for _ in 0..<b {
result.insert(result.first!, at: result.startIndex)
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary Right Shift on these inputs and return result also as a string.
// stringRightShift(a: "010", b: 2) == "10"
func stringRightShift(a: String, b: Int) -> String {
var result = a
for _ in 0..<b {
result.removeFirst()
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary NOT on these inputs and return result also as a string.
// stringNot(a: "010") == "101"
func stringNot(a: String) -> String {
var result = ""
for character in a {
result.append(String(1 - Int(character)))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary One's Complement on these inputs and return result also as a string.
// stringOneComplement(a: "010") == "101"
func stringOneComplement(a: String) -> String {
return stringNot(a: stringAnd(a: a, b: "11111111"))
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary Two's Complement on these inputs and return result also as a string.
// stringTwoComplement(a: "010") == "101"
func stringTwoComplement(a: String) -> String {
return stringOneComplement(a: stringNot(a: a)) + "0"
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform addition on these inputs and return result also as a string.
// stringAddition(a: "101", b: "101") == "1100"
func stringAddition(a: String, b: String) -> String {
var result = ""
var overflow = 0
for (characterA, characterB) in zip(a.reversed(), b.reversed()) {
let addition = Int(characterA) + Int(characterB) + overflow
result.insert(String(addition % 2), at: result.startIndex)
overflow = addition / 2
}
if overflow > 0 {
result.insert(String(overflow), at: result.startIndex)
}
return result.reversed()
}
// Input
func stringXor(a: String, b: String) -> String {
var result = ""
for (index, character) in a.enumerated() {
result.append(String(Int(character) ^ Int(b[index])))
}
return result
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in a.enumerated() {
result = result | (Int(character) ^ Int(b[index]))
}
return result
}
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in zip(a, b) {
result = result | (Int(character) ^ Int(index))
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for (index, character) in a.enumerated() {
result.append(String(Int(character) ^ Int(b[index])))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in a.enumerated() {
result = result | (Int(character) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
return Int(a, radix: 2) ^ Int(b, radix: 2)
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in a.enumerated() {
result = result | (Int(character) ^ Int(b[index]))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in zip(a, b) {
result = result | (Int(character) ^ Int(index))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in zip(a, b) {
result = result | (Int(character) ^ Int(index))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in zip(a, b) {
result = result | (Int(character) ^ Int(index))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result as an integer.
// stringXor(a: "010", b: "110") == 100
func stringXor(a: String, b: String) -> Int {
var result = 0
for (index, character) in zip(a, b) {
result = result | (Int(character) ^ Int(index))
}
return result
}
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func average(numbers: [Int]) -> Int {
return sum(numbers: numbers) / numbers.count
}
func median(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
let sortedNumbers = numbers.sorted()
let middleIndex = sortedNumbers.count / 2
if sortedNumbers.count % 2 == 0 {
return (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2
} else {
return sortedNumbers[middleIndex]
}
}
func positiveCount(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of integers, return the smallest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [1, 2, 3, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of integers, return the largest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [1, 2, 3, 1]) == 1
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of integers, return the sum of all values. Return 0 in case the input array is empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 1]) == 7
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of integers, return the average of all values. Return 0 in case the input array is empty.
// average(numbers: [] as [Int]) == 0
// average(numbers: [1, 2, 3]) == 2
// average(numbers: [1, 2, 3, 1]) == 2
func average(numbers: [Int]) -> Int {
return sum(numbers: numbers) / numbers.count
}
// Out of array of integers, return the median value. Return nil in case the input array is empty.
// median(numbers: [] as [Int]) == nil
// median(numbers: [1, 2, 3]) == 2
// median(numbers: [1, 2, 3, 1]) == 2
// median(numbers: [1, 2, 3, 4]) == 2.5
func median(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
let sortedNumbers = numbers.sorted()
let middleIndex = sortedNumbers.count / 2
if sortedNumbers.count % 2 == 0 {
return (sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2
} else {
return sortedNumbers[middleIndex]
}
}
// Out of array of integers, return the count of all positive values. Return 0 in case the input array is empty.
// positiveCount(numbers: [] as [Int]) == 0
// positiveCount(numbers: [1, 2, 3]) == 3
// positiveCount(numbers: [1, 2, 3, -1]) == 3
// positiveCount(numbers: [1, 2, 3, -1, 0]) == 3
func positiveCount(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
// Out of array of integers, return the count of all negative values. Return 0 in case the input array is empty.
// negativeCount(numbers: [] as [Int]) == 0
// negativeCount(numbers: [1, 2, 3]) == 0
// negativeCount(numbers: [1, 2, 3, -1]) == 1
// negativeCount(numbers: [1, 2, 3, -1,
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func count(numbers: [Int]) -> Int {
return numbers.count
}
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(count(numbers: numbers))
}
func median(numbers: [Int]) -> Double? {
if numbers.isEmpty {
return nil
}
let sortedNumbers = numbers.sorted()
let count = sortedNumbers.count
if count % 2 == 0 {
let middleIndex = count / 2
return Double(sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2
} else {
let middleIndex = count / 2
return Double(sortedNumbers[middleIndex])
}
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of integers, return the smallest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [1, 2, 3, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of integers, return the largest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [1, 2, 3, 1]) == 1
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of integers, return the sum of all integers. Return 0 in case the input array is empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 1]) == 7
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of integers, return the count of all integers. Return 0 in case the input array is empty.
// count(numbers: [] as [Int]) == 0
// count(numbers: [1, 2, 3]) == 3
// count(numbers: [1, 2, 3, 1]) == 4
func count(numbers: [Int]) -> Int {
return numbers.count
}
// Out of array of integers, return the average of all integers. Return 0 in case the input array is empty.
// average(numbers: [] as [Int]) == 0
// average(numbers: [1, 2, 3]) == 2
// average(numbers: [1, 2, 3, 1]) == 2
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(count(numbers: numbers))
}
// Out of array of integers, return the median of all integers.
// Return nil in case the input array is empty.
// median(numbers: [] as [Int]) == nil
// median(numbers: [1, 2, 3]) == 2
// median(numbers: [1, 2, 3, 1]) == 2
// median(numbers: [1, 2, 3, 4]) == 2.5
func median(numbers: [Int]) -> Double? {
if numbers.isEmpty {
return nil
}
let sortedNumbers = numbers.sorted()
let count = sortedNumbers.count
if count % 2 == 0 {
let middleIndex = count / 2
return Double(sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2
} else {
let middleIndex = count / 2
return Double(sortedNumbers[middleIndex])
}
}
// Out of array of integers, return the mode of all integers.
// Return nil in case the input array is empty.
// mode(numbers: [] as [Int]) == nil
// mode(numbers: [1, 2, 3]) == nil
// mode(numbers: [1, 2, 3, 1]) == 1
// mode(numbers: [1, 2, 3, 4]) == 1
// mode(numbers: [1, 2, 3, 4, 1, 2, 3, 4, 1,
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func longest(strings: [String?]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if let string = string, string.count > longest!.count {
longest = string
}
}
return longest
}
func longest(strings: [String]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty")
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func longest(strings: [String?]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty")
}
var longest = strings[0]
for string in strings {
if let string = string, string.count > longest!.count {
longest = string
}
}
return longest!
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(strings: [String?]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if let string = string, string.count > longest!.count {
longest = string
}
}
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 longest(strings: [String]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty")
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(strings: [String?]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty")
}
var longest = strings[0]
for string in strings {
if let string = string, string.count > longest!.count {
longest = string
}
}
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 longest(strings: [String]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty")
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(strings: [String?]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty")
}
var longest = strings[0]
for string in strings {
if let string = string, string.count > longest!.count {
longest = string
}
}
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 longest(strings: [String]) -> String {
if strings.isEmpty {
fatalError("Input array cannot be empty
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
func median(numbers: [Int]) -> Double {
if numbers.isEmpty {
return 0
}
let sortedNumbers = numbers.sorted()
let middleIndex = sortedNumbers.count / 2
if sortedNumbers.count % 2 == 0 {
return Double(sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2
} else {
return Double(sortedNumbers[middleIndex])
}
}
func positiveCount(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
func negativeCount(numbers: [Int]) -> Int {
return numbers.filter{$0 < 0}.count
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of numbers, return the smallest one. Return the first one in case of multiple
// numbers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [1, 2, 3, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of numbers, return the largest one. Return the first one in case of multiple
// numbers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [1, 2, 3, 1]) == 1
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of numbers, return the sum of all numbers. Return 0 in case the input array is
// empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 4, 5]) == 15
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of numbers, return the average of all numbers. Return 0 in case the input array
// is empty.
// average(numbers: [] as [Int]) == 0
// average(numbers: [1, 2, 3]) == 2
// average(numbers: [1, 2, 3, 4, 5]) == 3
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
// Out of array of numbers, return the median of all numbers. Return 0 in case the input array
// is empty.
// median(numbers: [] as [Int]) == 0
// median(numbers: [1, 2, 3]) == 2
// median(numbers: [1, 2, 3, 4, 5]) == 3
func median(numbers: [Int]) -> Double {
if numbers.isEmpty {
return 0
}
let sortedNumbers = numbers.sorted()
let middleIndex = sortedNumbers.count / 2
if sortedNumbers.count % 2 == 0 {
return Double(sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2
} else {
return Double(sortedNumbers[middleIndex])
}
}
// Out of array of numbers, return the count of all positive numbers. Return 0 in case the input
// array is empty.
// positiveCount(numbers: [] as [Int]) == 0
// positiveCount(numbers: [-1, 0, 1]) == 1
// positiveCount(numbers: [-1, 0, 1, -2, 3]) == 3
func positiveCount(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
// Out of array of numbers, return the count of all negative numbers. Return 0 in case the input
// array is empty.
// negativeCount(numbers: [] as [Int]) == 0
// negativeCount(numbers: [-1, 0, 1]) == 0
// negativeCount(numbers: [-1, 0, 1, -2, 3]) == 2
func negativeCount(numbers: [Int]) -> Int {
return numbers.filter{$0 < 0}.count
}
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func count(numbers: [Int]) -> Int {
return numbers.count
}
func countEven(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 {
count += 1
}
}
return count
}
func countOdd(numbers: [Int]) -> Int {
return count(numbers: numbers) - countEven(numbers: numbers)
}
func countPositive(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of integers, return the smallest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [3, 2, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of integers, return the largest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [3, 2, 1]) == 3
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of integers, return the sum of all integers. Return 0 in case the input array is
// empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [-1, 0, 1]) == 0
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of integers, return the count of all integers. Return 0 in case the input array is
// empty.
// count(numbers: [] as [Int]) == 0
// count(numbers: [1, 2, 3]) == 3
// count(numbers: [-1, 0, 1]) == 3
func count(numbers: [Int]) -> Int {
return numbers.count
}
// Out of array of integers, return the count of all even integers. Return 0 in case the input
// array is empty.
// countEven(numbers: [] as [Int]) == 0
// countEven(numbers: [1, 2, 3]) == 0
// countEven(numbers: [-1, 0, 1]) == 1
func countEven(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 {
count += 1
}
}
return count
}
// Out of array of integers, return the count of all odd integers. Return 0 in case the input
// array is empty.
// countOdd(numbers: [] as [Int]) == 0
// countOdd(numbers: [1, 2, 3]) == 3
// countOdd(numbers: [-1, 0, 1]) == 2
func countOdd(numbers: [Int]) -> Int {
return count(numbers: numbers) - countEven(numbers: numbers)
}
// Out of array of integers, return the count of all positive integers. Return 0 in case the input
// array is empty.
// countPositive(numbers: [] as [Int]) == 0
// countPositive(numbers: [1, 2, 3]) == 3
// countPositive(numbers: [-1, 0, 1]) == 1
func countPositive(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
// Out of array of integers, return the count of all negative integers. Return 0 in case the input
// array is empty.
// countNegative(numbers: [] as [Int]) == 0
// countNegative(numbers: [1, 2, 3]) == 0
// countNegative(numbers: [-1, 0, 1]) == 3
func countNegative(numbers
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func longest2(strings: [String]) -> String? {
return strings.reduce(nil) {
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0)
}
}
func longest3(strings: [String]) -> String? {
return strings.reduce("") {
$0.count > $1.count? $0 : $1
}
}
func longest4(strings: [String]) -> String? {
return strings.reduce("", combine: {
$0.count > $1.count? $0 : $1
})
}
func longest5(strings: [String]) -> String? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
func longest6(strings: [String]) -> String? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
func longest7(strings: [String]) -> String? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
func longest8(strings: [String]) -> String? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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? {
return strings.reduce(nil) {
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0)
}
}
// 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? {
return strings.reduce("") {
$0.count > $1.count? $0 : $1
}
}
// 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? {
return strings.reduce("", combine: {
$0.count > $1.count? $0 : $1
})
}
// 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? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
// 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? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
// 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? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
// 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? {
return strings.reduce("", {
$0.count > $1.count? $0 : $1
})
}
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0) // expected expression
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0) // '?' must be followed by a call, member lookup, or subscript
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0) // consecutive statements on a line must be separated by ';'
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0) // consecutive statements on a line must be separated by ';'
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0) // result of operator '==' is unused
$0 == nil? $1 : ($1?.count > $0!.count? $1 : $0) // expression of type 'String' is unused
$0.count > $1.count? $0 : $1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0.count > $1.count? $0 : $1 // expected expression
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // cannot use optional chaining on non-optional value of type 'Int'
return strings.reduce("", combine: { // extraneous argument label 'combine:' in call
$0.count > $1.count? $0 : $1 // expected expression
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // cannot use optional chaining on non-optional value of type 'Int'
$0.count > $1.count? $0 : $1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0.count > $1.count? $0 : $1 // expected expression
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // cannot use optional chaining on non-optional value of type 'Int'
$0.count > $1.count? $0 : $1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0.count > $1.count? $0 : $1 // cannot use optional chaining on non-optional value of type 'Int'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // expected expression
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // cannot use optional chaining on non-optional value of type 'Int'
$0.count > $1.count? $0 : $1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0.count > $1.count? $0 : $1 // expected expression
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // cannot use optional chaining on non-optional value of type 'Int'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
$0.count > $1.count? $0 : $1 // expected expression
$0.count > $1.count? $0 : $1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
$0.count > $1.count? $0 : $1 // consecutive statements on a line must be separated by ';'
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func countPositive(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
func countNegative(numbers: [Int]) -> Int {
return countPositive(numbers: numbers.map { -$0 })
}
func countZeros(numbers: [Int]) -> Int {
return countPositive(numbers: numbers.map { $0 == 0? 1 : 0 })
}
func countFives(numbers: [Int]) -> Int {
return countPositive(numbers: numbers.map { $0 % 5 == 0? 1 : 0 })
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of integers, return the smallest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [1, 2, 3, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of integers, return the largest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [1, 2, 3, 1]) == 1
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of integers, return the sum of all the values. Return 0 in case the input
// array is empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 1]) == 4
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of integers, return the count of all positive values. Return 0 in case the
// input array is empty.
// countPositive(numbers: [] as [Int]) == 0
// countPositive(numbers: [1, 2, 3]) == 3
// countPositive(numbers: [1, 2, 3, -1]) == 3
func countPositive(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 0 {
count += 1
}
}
return count
}
// Out of array of integers, return the count of all negative values. Return 0 in case the
// input array is empty.
// countNegative(numbers: [] as [Int]) == 0
// countNegative(numbers: [1, 2, 3]) == 0
// countNegative(numbers: [1, 2, 3, -1]) == 1
func countNegative(numbers: [Int]) -> Int {
return countPositive(numbers: numbers.map { -$0 })
}
// Out of array of integers, return the count of all zeros. Return 0 in case the input array
// is empty.
// countZeros(numbers: [] as [Int]) == 0
// countZeros(numbers: [1, 2, 3]) == 0
// countZeros(numbers: [0, 0, 0, 1]) == 1
func countZeros(numbers: [Int]) -> Int {
return countPositive(numbers: numbers.map { $0 == 0? 1 : 0 })
}
// Out of array of integers, return the count of all values that can be divided by 5. Return
// 0 in case the input array is empty.
// countFives(numbers: [] as [Int]) == 0
// countFives(numbers: [1, 2, 3]) == 0
// countFives(numbers: [1, 2, 3, 5]) == 1
// countFives(numbers: [1, 2, 3, 5, 5, 5]) == 3
func countFives(numbers: [Int]) -> Int {
return countPositive(numbers: numbers.map { $0 % 5 == 0? 1 : 0 })
}
// Out of array of integers, return the count of all
return countPositive(numbers: numbers.map { $0 == 0? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return countPositive(numbers: numbers.map { $0 == 0? 1 : 0 }) // expected expression
return countPositive(numbers: numbers.map { $0 == 0? 1 : 0 }) // cannot use optional chaining on non-optional value of type 'Int'
return countPositive(numbers: numbers.map { $0 == 0? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return countPositive(numbers: numbers.map { $0 % 5 == 0? 1 : 0 }) // consecutive statements on a line must be separated by ';'
return countPositive(numbers: numbers.map { $0 % 5 == 0? 1 : 0 }) // expected expression
return countPositive(numbers: numbers.map { $0 % 5 == 0? 1 : 0 }) // cannot use optional chaining on non-optional value of type 'Int'
return countPositive(numbers: numbers.map { $0 % 5 == 0? 1 : 0 }) // consecutive statements on a line must be separated by ';'
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func count(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 3 == 0 {
count += 1
}
}
return count
}
func unique(numbers: [Int]) -> Int {
var unique = Set<Int>()
for number in numbers {
unique.insert(number)
}
return unique.count
}
func negative(numbers: [Int]) -> Int {
var negative = 0
for number in numbers {
if number < 0 {
negative += 1
}
}
return negative
}
func positive(numbers: [Int]) -> Int {
return count(numbers: numbers.filter { $0 > 0 })
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of integers, return the smallest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [1, 2, 3, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of integers, return the largest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [1, 2, 3, 1]) == 1
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of integers, return the sum of all integers. Return 0 in case the input array is
// empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 4]) == 10
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of integers, return the count of all integers that are divisible by 3. Return 0
// in case the input array is empty.
// count(numbers: [] as [Int]) == 0
// count(numbers: [1, 2, 3]) == 0
// count(numbers: [1, 2, 3, 4]) == 1
func count(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 3 == 0 {
count += 1
}
}
return count
}
// Out of array of integers, return the count of all unique integers. Return 0 in case the input
// array is empty.
// unique(numbers: [] as [Int]) == 0
// unique(numbers: [1, 2, 3]) == 3
// unique(numbers: [1, 2, 3, 1, 2, 3]) == 3
func unique(numbers: [Int]) -> Int {
var unique = Set<Int>()
for number in numbers {
unique.insert(number)
}
return unique.count
}
// Out of array of integers, return the count of all negative integers. Return 0 in case the input
// array is empty.
// negative(numbers: [] as [Int]) == 0
// negative(numbers: [1, 2, 3]) == 0
// negative(numbers: [-1, -2, -3]) == 3
func negative(numbers: [Int]) -> Int {
var negative = 0
for number in numbers {
if number < 0 {
negative += 1
}
}
return negative
}
// Out of array of integers, return the count of all positive integers. Return 0 in case the input
// array is empty.
// positive(numbers: [] as [Int]) == 0
// positive(numbers: [1, 2, 3]) == 3
// positive(numbers: [-1, -2, -3]) == 0
func positive(numbers: [Int]) -> Int {
return count(numbers: numbers.filter { $0 > 0 })
}
// Out of array of integers, return the count of all even integers. Return 0 in case the input
// array is empty.
// even(numbers: [] as [Int]) == 0
// even(numbers: [1
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
func count(numbers: [Int]) -> Int {
return numbers.count
}
func countEven(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 {
count += 1
}
}
return count
}
func countOdd(numbers: [Int]) -> Int {
return countEven(numbers: numbers) - count(numbers: numbers)
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
// Out of array of integers, return the smallest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// smallest(numbers: [] as [Int]) == nil
// smallest(numbers: [1, 2, 3]) == 1
// smallest(numbers: [1, 2, 3, 1]) == 1
func smallest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var smallest = numbers[0]
for number in numbers {
if number < smallest {
smallest = number
}
}
return smallest
}
// Out of array of integers, return the largest one. Return the first one in case of multiple
// integers of the same value. Return nil in case the input array is empty.
// largest(numbers: [] as [Int]) == nil
// largest(numbers: [1, 2, 3]) == 3
// largest(numbers: [1, 2, 3, 1]) == 1
func largest(numbers: [Int]) -> Int? {
if numbers.isEmpty {
return nil
}
var largest = numbers[0]
for number in numbers {
if number > largest {
largest = number
}
}
return largest
}
// Out of array of integers, return the sum of all integers. Return 0 in case the input array is empty.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3]) == 6
// sum(numbers: [1, 2, 3, 1]) == 7
func sum(numbers: [Int]) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
// Out of array of integers, return the count of all integers. Return 0 in case the input array is empty.
// count(numbers: [] as [Int]) == 0
// count(numbers: [1, 2, 3]) == 3
// count(numbers: [1, 2, 3, 1]) == 4
func count(numbers: [Int]) -> Int {
return numbers.count
}
// Out of array of integers, return the count of even integers. Return 0 in case the input array is empty.
// countEven(numbers: [] as [Int]) == 0
// countEven(numbers: [1, 2, 3]) == 0
// countEven(numbers: [1, 2, 3, 4]) == 2
func countEven(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number % 2 == 0 {
count += 1
}
}
return count
}
// Out of array of integers, return the count of odd integers. Return 0 in case the input array is empty.
// countOdd(numbers: [] as [Int]) == 0
// countOdd(numbers: [1, 2, 3]) == 3
// countOdd(numbers: [1, 2, 3, 4]) == 1
func countOdd(numbers: [Int]) -> Int {
return countEven(numbers: numbers) - count(numbers: numbers)
}
// Out of array of integers, return the count of prime integers. Return 0 in case the input array is empty.
// countPrime(numbers: [] as [Int]) == 0
// countPrime(numbers: [1, 2, 3]) == 0
// countPrime(numbers: [1, 2, 3, 4]) == 1
// countPrime(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 4
func countPrime(numbers: [Int]) -> Int {
var count = 0
for number in numbers {
if number > 1 {
var isPrime = true
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
isPrime = false
break
}
}
if isPrime {
count += 1
}
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func longest(_ strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func longest(_ strings: [String]?) -> String? {
guard let strings = strings else {
return nil
}
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(_ strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(_ strings: [String]?) -> String? {
guard let strings = strings else {
return nil
}
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(_ strings: [String]?) -> String? {
guard let strings = strings else {
return nil
}
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(_ strings: [String]?) -> String? {
guard let strings = strings else {
return nil
}
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(_ strings: [String]?) -> String? {
guard let strings = strings else {
return nil
}
if strings.isEmpty {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
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 longest(_ strings: [String]?) -> String? {
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
return greatestCommonDivisor(a: b % a, b: a)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
return a * b / greatestCommonDivisor(a: a, b: b)
}
func leastCommonMultiple(of numbers: [Int]) -> Int {
return numbers.reduce(1, *) { leastCommonMultiple(a: $0, b: $1) }
}
func sumOfNumbersUpTo(n: Int) -> Int {
return (1...n).reduce(0, +)
}
func sumOfSquaresUpTo(n: Int) -> Int {
return (1...n).map { $0 * $0 }.reduce(0, +)
}
func squareOfSumUpTo(n: Int) -> Int {
return sumOfNumbersUpTo(n: n) * sumOfNumbersUpTo(n: n)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
return greatestCommonDivisor(a: b % a, b: a)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
return a * b / greatestCommonDivisor(a: a, b: b)
}
// Return the least common multiple of an array of integers
// leastCommonMultiple(of: [3, 5, 7, 11]) == 315
func leastCommonMultiple(of numbers: [Int]) -> Int {
return numbers.reduce(1, *) { leastCommonMultiple(a: $0, b: $1) }
}
// Return the sum of all the numbers between 1 and n
// sumOfNumbersUpTo(n: 5) == 15
// sumOfNumbersUpTo(n: 10) == 55
func sumOfNumbersUpTo(n: Int) -> Int {
return (1...n).reduce(0, +)
}
// Return the sum of all the squares between 1 and n
// sumOfSquaresUpTo(n: 5) == 55
// sumOfSquaresUpTo(n: 10) == 385
func sumOfSquaresUpTo(n: Int) -> Int {
return (1...n).map { $0 * $0 }.reduce(0, +)
}
// Return the square of the sum of all the numbers between 1 and n
// squareOfSumUpTo(n: 5) == 55
// squareOfSumUpTo(n: 10) == 385
func squareOfSumUpTo(n: Int) -> Int {
return sumOfNumbersUpTo(n: n) * sumOfNumbersUpTo(n: n)
}
// Print the result of the exercise
print("Greatest common divisor:", greatestCommonDivisor(a: 3, b: 5))
print("Least common multiple:", leastCommonMultiple(a: 3, b: 5))
print("Least common multiple of 7, 12, 15, 20:", leastCommonMultiple(of: [7, 12, 15, 20]))
print("Sum of numbers up to 10:", sumOfNumbersUpTo(n: 10))
print("Sum of squares up to 10:", sumOfSquaresUpTo(n: 10))
print("Square of sum up to 10:", squareOfSumUpTo(n: 10))
return numbers.reduce(1, *) { leastCommonMultiple(a: $0, b: $1) } // extra trailing closure passed in call
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Calculate the GCD using the greatestCommonDivisor function
let gcd = greatestCommonDivisor(a: a, b: b)
// Return the product of the two numbers divided by the GCD
return (a / gcd) * 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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Calculate the GCD using the greatestCommonDivisor function
let gcd = greatestCommonDivisor(a: a, b: b)
// Return the product of the two numbers divided by the GCD
return (a / gcd) * b
}
// Test the greatestCommonDivisor and leastCommonMultiple functions
greatestCommonDivisor(a: 3, b: 5) // Returns 1
leastCommonMultiple(a: 3, b: 5) // Returns 15
greatestCommonDivisor(a: 7, b: 12) // Returns 1
leastCommonMultiple(a: 7, b: 12) // Returns 42
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Use the GCD to calculate the LCM
return a * b / greatestCommonDivisor(a: a, b: 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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Use the GCD to calculate the LCM
return a * b / greatestCommonDivisor(a: a, b: b)
}
// Test the function
print(greatestCommonDivisor(a: 3, b: 5)) // Output: 1
print(greatestCommonDivisor(a: 25, b: 15)) // Output: 5
print(leastCommonMultiple(a: 3, b: 5)) // Output: 15
print(leastCommonMultiple(a: 7, b: 12)) // Output: 42
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Use the GCD to calculate the multiplication factor
let multiplicationFactor = greatestCommonDivisor(a: a, b: b)
// Return the least common multiple using the multiplication factor
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor
}
```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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Use the GCD to calculate the multiplication factor
let multiplicationFactor = greatestCommonDivisor(a: a, b: b)
// Return the least common multiple using the multiplication factor
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor
}
// Test the function
print(greatestCommonDivisor(a: 3, b: 5)) // Output: 1
print(greatestCommonDivisor(a: 25, b: 15)) // Output: 5
print(leastCommonMultiple(a: 3, b: 5)) // Output: 15
print(leastCommonMultiple(a: 7, b: 12)) // Output: 42
```
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor // expected expression
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor // consecutive statements on a line must be separated by ';'
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor // cannot convert return expression of type 'Bool' to return type 'Int'
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor // consecutive statements on a line must be separated by ';'
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor // integer literal is unused
return multiplicationFactor == 0? 0 : a * b / multiplicationFactor // cannot use optional chaining on non-optional value of type 'Int'
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Calculate the GCD
let gcd = greatestCommonDivisor(a: a, b: b)
// Calculate the LCM using the formula: lcm * gcd = a * b
return a * b / gcd
}
```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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Calculate the GCD
let gcd = greatestCommonDivisor(a: a, b: b)
// Calculate the LCM using the formula: lcm * gcd = a * b
return a * b / gcd
}
// Example usage
print(greatestCommonDivisor(a: 3, b: 5)) // Output: 1
print(greatestCommonDivisor(a: 25, b: 15)) // Output: 5
print(leastCommonMultiple(a: 3, b: 5)) // Output: 15
print(leastCommonMultiple(a: 7, b: 12)) // Output: 42
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Use the GCD to calculate the multiplication factor
let multiplicationFactor = greatestCommonDivisor(a: a, b: b)
// Return the least common multiple using the multiplication factor
return a * b / multiplicationFactor
}
```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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Use the GCD to calculate the multiplication factor
let multiplicationFactor = greatestCommonDivisor(a: a, b: b)
// Return the least common multiple using the multiplication factor
return a * b / multiplicationFactor
}
// Test the function
print(greatestCommonDivisor(a: 3, b: 5)) // Output: 1
print(greatestCommonDivisor(a: 25, b: 15)) // Output: 5
print(leastCommonMultiple(a: 3, b: 5)) // Output: 15
print(leastCommonMultiple(a: 7, b: 12)) // Output: 42
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Test the function
print(greatestCommonDivisor(a: 3, b: 5)) // Output: 1
print(greatestCommonDivisor(a: 25, b: 15)) // Output: 5
```
The `greatestCommonDivisor` function takes two integer parameters `a` and `b` and returns their greatest common divisor. The base case checks if one of the numbers is 0, and returns the other number as the GCD. The recursive case calculates the remainder of `a` divided by `b` using the modulo operator `%`, and recursively calls the function with the updated values of `a` and `b`.
The `print` function is used to output the results of the `greatestCommonDivisor` function.
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
return greatestCommonDivisor(a: b % a, b: a)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
return a * b / greatestCommonDivisor(a: a, b: b)
}
func sumOfNumbers(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumOfNumbers(n: n - 1)
}
func sumOfEvenNumbers(n: Int) -> Int {
if n == 1 {
return 0
}
if n % 2 == 0 {
return n + sumOfEvenNumbers(n: n - 1)
} else {
return sumOfEvenNumbers(n: n - 1)
}
}
func sumOfOddNumbers(n: Int) -> Int {
if n == 1 {
return 1
}
if n % 2 == 1 {
return n + sumOfOddNumbers(n: n - 1)
} else {
return sumOfOddNumbers(n: n - 1)
}
}
func sumOfNumbersDivisibleBy(n: Int) -> Int {
if n == 1 {
return 0
}
if n % 3 == 0 && n % 2 == 0 {
return n + sumOfNumbersDivisibleBy(n: n - 1)
} else {
return sumOfNumbersDivisibleBy(n: n - 1)
}
}
func sumOfPrimes(n: Int) -> Int {
if n == 1 {
return 0
}
if isPrime(n: n) {
return n + sumOfPrimes(n: n - 1)
} else {
return sumOfPrimes(n: n - 1)
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func sumOfFibonacciNumbers(n: Int) -> Int {
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return sumOfFibonacciNumbers(n: n - 1) + sumOfFibonacciNumbers(n: n - 2)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
return greatestCommonDivisor(a: b % a, b: a)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
return a * b / greatestCommonDivisor(a: a, b: b)
}
// Return the sum of all numbers between 1 and n
// sumOfNumbers(n: 5) == 15
// sumOfNumbers(n: 10) == 55
func sumOfNumbers(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumOfNumbers(n: n - 1)
}
// Return the sum of all even numbers between 1 and n
// sumOfEvenNumbers(n: 5) == 0
// sumOfEvenNumbers(n: 10) == 30
func sumOfEvenNumbers(n: Int) -> Int {
if n == 1 {
return 0
}
if n % 2 == 0 {
return n + sumOfEvenNumbers(n: n - 1)
} else {
return sumOfEvenNumbers(n: n - 1)
}
}
// Return the sum of all odd numbers between 1 and n
// sumOfOddNumbers(n: 5) == 5
// sumOfOddNumbers(n: 10) == 25
func sumOfOddNumbers(n: Int) -> Int {
if n == 1 {
return 1
}
if n % 2 == 1 {
return n + sumOfOddNumbers(n: n - 1)
} else {
return sumOfOddNumbers(n: n - 1)
}
}
// Return the sum of all numbers between 1 and n that are divisible by either 2 or 3
// sumOfNumbersDivisibleBy(n: 5) == 3
// sumOfNumbersDivisibleBy(n: 10) == 23
func sumOfNumbersDivisibleBy(n: Int) -> Int {
if n == 1 {
return 0
}
if n % 3 == 0 && n % 2 == 0 {
return n + sumOfNumbersDivisibleBy(n: n - 1)
} else {
return sumOfNumbersDivisibleBy(n: n - 1)
}
}
// Return the sum of all prime numbers between 1 and n
// sumOfPrimes(n: 5) == 2
// sumOfPrimes(n: 10) == 7
func sumOfPrimes(n: Int) -> Int {
if n == 1 {
return 0
}
if isPrime(n: n) {
return n + sumOfPrimes(n: n - 1)
} else {
return sumOfPrimes(n: n - 1)
}
}
// Return true if n is prime, false otherwise
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the sum of all Fibonacci numbers between 1 and n
// sumOfFibonacciNumbers(n: 5) == 5
// sumOfFibonacciNumbers(n: 10) == 12
func sumOfFibonacciNumbers(n: Int) -> Int {
if n == 1 {
return 0
}
if n == 2 {
return 1
}
return sumOfFibonacciNumbers(n: n - 1) + sumOfFibonacciNumbers(n: n - 2)
}
// Return the sum of all palindromic numbers between 1 and n
// sumOfPalindromicNumbers(n: 5) == 0
// sumOfPalindromicNumbers(n: 10) == 36
func sumOfPalindromicNumbers(n: Int) -> Int {
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if b is 0, the answer is a
if b == 0 {
return a
}
// Recursive case: compute the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Compute the GCD
let gcd = greatestCommonDivisor(a: a, b: b)
// Return the LCM using the formula LCM * GCD = a * b
return a / gcd * b
}
func leastCommonMultiple(of numbers: [Int]) -> Int {
// Base case: if the array contains only one number, return that number
if numbers.count == 1 {
return numbers[0]
}
// Recursive case:
// Divide the array into two halves
let mid = numbers.count / 2
let leftHalf = Array(numbers[0..<mid])
let rightHalf = Array(numbers[mid..<numbers.count])
// Find the LCM of the two halves
let lcmOfLeftHalf = leastCommonMultiple(of: leftHalf)
let lcmOfRightHalf = leastCommonMultiple(of: rightHalf)
// Find the LCM of the two halves combined
let lcmOfBoth = leastCommonMultiple(a: lcmOfLeftHalf, b: lcmOfRightHalf)
// Return the LCM of the original array and the LCM of the two halves combined
return leastCommonMultiple(a: numbers[0], b: lcmOfBoth)
}
```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 {
// Base case: if b is 0, the answer is a
if b == 0 {
return a
}
// Recursive case: compute the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Return the least common multiple of two integers a and b
// leastCommonMultiple(a: 3, b: 5) == 15
// leastCommonMultiple(a: 7, b: 12) == 42
func leastCommonMultiple(a: Int, b: Int) -> Int {
// Compute the GCD
let gcd = greatestCommonDivisor(a: a, b: b)
// Return the LCM using the formula LCM * GCD = a * b
return a / gcd * b
}
// Return the least common multiple of an array of integers
// leastCommonMultiple(of: [2, 3, 4, 5]) == 60
func leastCommonMultiple(of numbers: [Int]) -> Int {
// Base case: if the array contains only one number, return that number
if numbers.count == 1 {
return numbers[0]
}
// Recursive case:
// Divide the array into two halves
let mid = numbers.count / 2
let leftHalf = Array(numbers[0..<mid])
let rightHalf = Array(numbers[mid..<numbers.count])
// Find the LCM of the two halves
let lcmOfLeftHalf = leastCommonMultiple(of: leftHalf)
let lcmOfRightHalf = leastCommonMultiple(of: rightHalf)
// Find the LCM of the two halves combined
let lcmOfBoth = leastCommonMultiple(a: lcmOfLeftHalf, b: lcmOfRightHalf)
// Return the LCM of the original array and the LCM of the two halves combined
return leastCommonMultiple(a: numbers[0], b: lcmOfBoth)
}
// Example usage
print(greatestCommonDivisor(a: 36, b: 48)) // Output: 12
print(leastCommonMultiple(a: 3, b: 5)) // Output: 15
print(leastCommonMultiple(of: [2, 3, 4, 5])) // Output: 60
func greatestCommonDivisor(a: Int, b: Int) -> Int {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
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 {
// Base case: if one of the numbers is 0, the other number is the GCD
if a == 0 {
return b
}
if b == 0 {
return a
}
// Recursive case: calculate the GCD using the Euclidean algorithm
return greatestCommonDivisor(a: b, b: a % b)
}
// Test the function
print(greatestCommonDivisor(a: 3, b: 5)) // Output: 1
print(greatestCommonDivisor(a: 25, b: 15)) // Output: 5
```
The `greatestCommonDivisor` function takes two integer parameters `a` and `b` and returns their greatest common divisor. The base case checks if one of the numbers is 0, and returns the other number as the GCD. The recursive case calculates the remainder of `a` divided by `b` using the modulo operator `%`, and recursively calls the function with `b` and the remainder as the input parameters. The returned value from the recursive call is then used as the input parameter for the next recursive call.
The `greatestCommonDivisor` function is called with the test cases from the provided code, and the output is printed to the console.
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
substrings.append(suffix)
}
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if!substrings.contains(suffix) {
substrings.append(suffix)
}
}
}
return substrings
}
func longestPalindrome(string: String) -> String {
var longest = ""
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if suffix == String(suffix.reversed()) && suffix.count > longest.count {
longest = suffix
}
}
}
return longest
}
```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]()
var prefix = ""
for char in string {
prefix.append(char)
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]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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 index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
substrings.append(suffix)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if!substrings.contains(suffix) {
substrings.append(suffix)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if!substrings.contains(suffix) {
substrings.append(suffix)
}
}
}
return substrings
}
// Return the longest palindrome substring of the input string
// longestPalindrome(string: "abracadabraanamadamalayalamradar") == "anamadamalayalam"
func longestPalindrome(string: String) -> String {
var longest = ""
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if suffix == String(suffix.reversed()) && suffix.count > longest.count {
longest = suffix
}
}
}
return longest
}
// Return the longest palindrome substring of the input string
// longestPalindrome(string: "abracadabraanamadamalayalamradar") == "anamadamalayalam"
func longestPalindrome(string: String) -> String {
var longest = ""
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if suffix == String(suffix.reversed()) && suffix.count > longest.count {
longest = suffix
}
}
}
return longest
}
// Return the longest palindrome substring of the input string
// longestPalindrome(string: "abracadabraanamadamalayalamradar") == "anamadamalayalam"
func longestPalindrome(string: String) -> String {
var longest = ""
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if suffix == String(suffix.reversed()) && suffix.count > longest.count {
longest = suffix
}
}
}
return longest
}
// Return the longest palindrome substring of the input string
// longestPalindrome(string: "abracadabraanamadamalayalamradar") == "anamadamalayalam"
if!substrings.contains(suffix) { // expected expression, var, or let in 'if' condition
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for prefix in allPrefixes(string: string) {
for suffix in allSuffixes(string: string) {
substrings.append(prefix + suffix)
}
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for prefix in allPrefixes(string: string) {
for suffix in allSuffixes(string: string) {
if Set(suffix).count == suffix.count {
substrings.append(prefix + suffix)
}
}
}
return substrings
}
func allUniqueSubstrings2(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
for char in string {
suffixes.append(String(char))
for suffix in suffixes {
if Set(suffix).count == suffix.count {
substrings.append(suffix)
}
}
}
return substrings
}
func allUniqueSubstrings3(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
var lastChar = Character("")
for char in string {
if char!= lastChar {
suffixes.append(String(char))
for suffix in suffixes {
if Set(suffix).count == suffix.count {
substrings.append(suffix)
}
}
}
lastChar = char
}
return substrings
}
func allUniqueSubstrings4(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
var lastChar = Character("")
for char in string {
if char!= lastChar {
suffixes.append(String(char))
for suffix in suffixes {
if Set(suffix).count == suffix.count {
substrings.append(suffix)
}
}
}
lastChar = char
}
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]()
var prefix = ""
for char in string {
prefix.append(char)
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]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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 prefix in allPrefixes(string: string) {
for suffix in allSuffixes(string: string) {
substrings.append(prefix + suffix)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for prefix in allPrefixes(string: string) {
for suffix in allSuffixes(string: string) {
if Set(suffix).count == suffix.count {
substrings.append(prefix + suffix)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings2(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
for char in string {
suffixes.append(String(char))
for suffix in suffixes {
if Set(suffix).count == suffix.count {
substrings.append(suffix)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings3(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
var lastChar = Character("")
for char in string {
if char!= lastChar {
suffixes.append(String(char))
for suffix in suffixes {
if Set(suffix).count == suffix.count {
substrings.append(suffix)
}
}
}
lastChar = char
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings4(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
var lastChar = Character("")
for char in string {
if char!= lastChar {
suffixes.append(String(char))
for suffix in suffixes {
if Set(suffix).count == suffix.count {
substrings.append(suffix)
}
}
}
lastChar = char
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings5(string: String) -> [String] {
var substrings = [String]()
var suffixes = [String]()
var lastChar = Character("")
for char in string {
if char!= lastChar {
suffixes.append(String(char))
for suffix in suffixes {
substrings.append(
if char!= lastChar { // use of '=' in a boolean context, did you mean '=='?
if char!= lastChar { // '=' must have consistent whitespace on both sides
if char!= lastChar { // cannot force unwrap value of non-optional type 'Character'
if char!= lastChar { // '=' must have consistent whitespace on both sides
if char!= lastChar { // cannot force unwrap value of non-optional type 'Character'
if char!= lastChar { // use of '=' in a boolean context, did you mean '=='?
func allPrefixes(string: String) -> [String] {
if string.count == 0 {
return []
}
var prefixes = [String]()
for i in 1...string.count {
prefixes.append(string.prefix(i))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
if string.count == 0 {
return []
}
var suffixes = [String]()
for i in 1...string.count {
suffixes.append(string.suffix(i))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
substrings.append(string.substring(with: NSMakeRange(i, j-i)))
}
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = string.substring(with: NSMakeRange(i, j-i))
if substring.count == Set(substring).count {
substrings.append(substring)
}
}
}
return substrings
}
func allUniqueIncreasingSubstrings(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = string.substring(with: NSMakeRange(i, j-i))
if substring.count == Set(substring).count && substring > substrings.last {
substrings.append(substring)
}
}
}
return substrings
}
func allUniqueIncreasingSubstrings2(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = string.substring(with: NSMakeRange(i, j-i))
if substring.count == Set(substring).count && isIncreasing(string: substring) {
substrings.append(substring)
}
}
}
return substrings
}
func isIncreasing(string: String) -> Bool {
for i in 0...string.count-2 {
if string[string.index(string.startIndex, offsetBy: i)] > string[string.index(string.startIndex, offsetBy: i+1)] {
return false
}
}
return true
}
```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] {
if string.count == 0 {
return []
}
var prefixes = [String]()
for i in 1...string.count {
prefixes.append(string.prefix(i))
}
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] {
if string.count == 0 {
return []
}
var suffixes = [String]()
for i in 1...string.count {
suffixes.append(string.suffix(i))
}
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] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
substrings.append(string.substring(with: NSMakeRange(i, j-i)))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not have repeating characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = string.substring(with: NSMakeRange(i, j-i))
if substring.count == Set(substring).count {
substrings.append(substring)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not have repeating characters and are in lexicographically increasing order
// allUniqueIncreasingSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueIncreasingSubstrings(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = string.substring(with: NSMakeRange(i, j-i))
if substring.count == Set(substring).count && substring > substrings.last {
substrings.append(substring)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not have repeating characters and are in lexicographically increasing order
// allUniqueIncreasingSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueIncreasingSubstrings2(string: String) -> [String] {
if string.count == 0 {
return []
}
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = string.substring(with: NSMakeRange(i, j-i))
if substring.count == Set(substring).count && isIncreasing(string: substring) {
substrings.append(substring)
}
}
}
return substrings
}
func isIncreasing(string: String) -> Bool {
for i in 0...string.count-2 {
if string[string.index(string.startIndex, offsetBy: i)] > string[string.index(string.startIndex, offsetBy: i+1)] {
return false
}
}
return true
}
// Return array of all substrings from shortest to longest of the input string
// that do not have repeating characters and are in lexicographically increasing order
// allUniqueIncreasingSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueIncreasingSubstrings
prefixes.append(string.prefix(i)) // no exact matches in call to instance method 'append'
suffixes.append(string.suffix(i)) // no exact matches in call to instance method 'append'
substrings.append(string.substring(with: NSMakeRange(i, j-i))) // cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range<String.Index>'
let substring = string.substring(with: NSMakeRange(i, j-i)) // cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range<String.Index>'
let substring = string.substring(with: NSMakeRange(i, j-i)) // cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range<String.Index>'
if substring.count == Set(substring).count && substring > substrings.last { // value of optional type 'String?' must be unwrapped to a value of type 'String'
let substring = string.substring(with: NSMakeRange(i, j-i)) // cannot convert value of type 'NSRange' (aka '_NSRange') to expected argument type 'Range<String.Index>'
func allPrefixes(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
var prefix = ""
for char in string {
prefix.append(char)
result.append(prefix)
}
return result
}
func allSuffixes(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
result.append(suffix)
}
return result
}
func allSubstrings(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
result.append(substring)
}
}
return result
}
func allSubstringsWithVowels(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if substring.contains(where: Character.isVowel) {
result.append(substring)
}
}
}
return result
}
func allUniqueSubstrings(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if Set(substring).count == substring.count {
result.append(substring)
}
}
}
return result
}
func allUniqueSubstringsWithVowels(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if Set(substring).count == substring.count && substring.contains(where: Character.isVowel) {
result.append(substring)
}
}
}
return result
}
func allUniqueSubstringsWithVowelsStartEnd(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if substring.starts(with: Character.isVowel) && substring.ends(with: Character.isVowel) {
result.append(substring)
}
}
}
return result
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
var prefix = ""
for char in string {
prefix.append(char)
result.append(prefix)
}
return result
}
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "abc"]
func allSuffixes(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
result.append(suffix)
}
return result
}
// 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] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
result.append(substring)
}
}
return result
}
// Return array of all substrings from shortest to longest of the input string
// that contain at least one vowel
// allSubstringsWithVowels(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allSubstringsWithVowels(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if substring.contains(where: Character.isVowel) {
result.append(substring)
}
}
}
return result
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain any repeated characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if Set(substring).count == substring.count {
result.append(substring)
}
}
}
return result
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain any repeated characters
// and have at least one vowel
// allUniqueSubstringsWithVowels(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstringsWithVowels(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if Set(substring).count == substring.count && substring.contains(where: Character.isVowel) {
result.append(substring)
}
}
}
return result
}
// Return array of all substrings from shortest to longest of the input string
// that start and end with a vowel
// allUniqueSubstringsWithVowels(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstringsWithVowelsStartEnd(string: String) -> [String] {
guard!string.isEmpty else { return [] }
var result = [String]()
for index in 0...string.count {
for substring in string.prefix(index).suffix(string.count - index) {
if substring.starts(with: Character.isVowel) && substring.ends(with: Character.isVowel) {
result.append(substring)
}
}
}
return result
}
// Return array of all substrings from shortest to longest of the input string
// that start and end with a vowel
// and have
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
result.append(substring) // cannot convert value of type 'Substring.Element' (aka 'Character') to expected argument type 'String'
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
if substring.contains(where: Character.isVowel) { // value of type 'Substring.Element' (aka 'Character') has no member 'contains'
if substring.contains(where: Character.isVowel) { // type 'Character' has no member 'isVowel'
result.append(substring) // cannot convert value of type 'Substring.Element' (aka 'Character') to expected argument type 'String'
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
if Set(substring).count == substring.count { // value of type 'Substring.Element' (aka 'Character') has no member 'count'
if Set(substring).count == substring.count { // no exact matches in call to initializer
result.append(substring) // cannot convert value of type 'Substring.Element' (aka 'Character') to expected argument type 'String'
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
if Set(substring).count == substring.count && substring.contains(where: Character.isVowel) { // value of type 'Substring.Element' (aka 'Character') has no member 'contains'
if Set(substring).count == substring.count && substring.contains(where: Character.isVowel) { // missing argument label 'arrayLiteral:' in call
if Set(substring).count == substring.count && substring.contains(where: Character.isVowel) { // value of type 'Substring.Element' (aka 'Character') has no member 'count'
if Set(substring).count == substring.count && substring.contains(where: Character.isVowel) { // type 'Character' has no member 'isVowel'
result.append(substring) // cannot convert value of type 'Substring.Element' (aka 'Character') to expected argument type 'String'
guard!string.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
if substring.starts(with: Character.isVowel) && substring.ends(with: Character.isVowel) { // value of type 'Substring.Element' (aka 'Character') has no member 'starts'
if substring.starts(with: Character.isVowel) && substring.ends(with: Character.isVowel) { // value of type 'Substring.Element' (aka 'Character') has no member 'ends'
if substring.starts(with: Character.isVowel) && substring.ends(with: Character.isVowel) { // type 'Character' has no member 'isVowel'
if substring.starts(with: Character.isVowel) && substring.ends(with: Character.isVowel) { // type 'Character' has no member 'isVowel'
result.append(substring) // cannot convert value of type 'Substring.Element' (aka 'Character') to expected argument type 'String'
func allPrefixes(string: String) -> [String] {
var prefixes: [String] = []
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes: [String] = []
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings: [String] = []
var prefix = ""
for char in string {
prefix.append(char)
substrings.append(prefix)
}
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
substrings.append(suffix)
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
var substrings: [String] = []
var prefix = ""
var seen: Set<Character> = []
for char in string {
if seen.contains(char) {
continue
}
prefix.append(char)
substrings.append(prefix)
seen.insert(char)
}
var suffix = ""
for char in string.reversed() {
if seen.contains(char) {
continue
}
suffix.insert(char, at: suffix.startIndex)
substrings.append(suffix)
seen.insert(char)
}
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] = []
var prefix = ""
for char in string {
prefix.append(char)
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] = []
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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] = []
var prefix = ""
for char in string {
prefix.append(char)
substrings.append(prefix)
}
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
substrings.append(suffix)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings: [String] = []
var prefix = ""
var seen: Set<Character> = []
for char in string {
if seen.contains(char) {
continue
}
prefix.append(char)
substrings.append(prefix)
seen.insert(char)
}
var suffix = ""
for char in string.reversed() {
if seen.contains(char) {
continue
}
suffix.insert(char, at: suffix.startIndex)
substrings.append(suffix)
seen.insert(char)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings: [String] = []
var prefix = ""
var seen: Set<Character> = []
for char in string {
if seen.contains(char) {
continue
}
prefix.append(char)
substrings.append(prefix)
seen.insert(char)
}
var suffix = ""
for char in string.reversed() {
if seen.contains(char) {
continue
}
suffix.insert(char, at: suffix.startIndex)
substrings.append(suffix)
seen.insert(char)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings: [String] = []
var prefix = ""
var seen: Set<Character> = []
for char in string {
if seen.contains(char) {
continue
}
prefix.append(char)
substrings.append(prefix)
seen.insert(char)
}
var suffix = ""
for char in string.reversed() {
if seen.contains(char) {
continue
}
suffix.insert(char, at: suffix.startIndex)
substrings.append(suffix)
seen.insert(char)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings: [String] = []
var prefix = ""
var seen: Set<Character> = []
for char
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
var substring = ""
for char in string {
substring.append(char)
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]()
var prefix = ""
for char in string {
prefix.append(char)
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]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
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]()
var substring = ""
for char in string {
substring.append(char)
substrings.append(substring)
}
return substrings
}
// Return array of all substrings from
func allPrefixes(string: String) -> [String] {
guard string.count > 0 else { return [] }
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
guard string.count > 0 else { return [] }
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
guard string.count > 0 else { return [] }
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)]))
}
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)])
if!substrings.contains(substring) {
substrings.append(substring)
}
}
}
return substrings
}
func allUniqueSubstringsV2(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)])
if substring.count > 2 &&!substrings.contains(substring) {
substrings.append(substring)
}
}
}
return substrings
}
func allUniqueSubstringsV3(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = Set<String>()
for i in 0...string.count {
for j in i...string.count {
let substring = String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)])
if substring.count > 2 {
substrings.insert(substring)
}
}
}
return Array(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] {
guard string.count > 0 else { return [] }
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
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] {
guard string.count > 0 else { return [] }
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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] {
guard string.count > 0 else { return [] }
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)]))
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string, excluding any duplicate substrings
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)])
if!substrings.contains(substring) {
substrings.append(substring)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string, excluding any duplicate or substring of length 2 or less
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstringsV2(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = [String]()
for i in 0...string.count {
for j in i...string.count {
let substring = String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)])
if substring.count > 2 &&!substrings.contains(substring) {
substrings.append(substring)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string, excluding any duplicate or substring of length 2 or less
// allUniqueSubstringsV3(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstringsV3(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = Set<String>()
for i in 0...string.count {
for j in i...string.count {
let substring = String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)])
if substring.count > 2 {
substrings.insert(substring)
}
}
}
return Array(substrings)
}
// Return array of all substrings from shortest to longest of the input string, excluding any duplicate or substring of length 2 or less
// allUniqueSubstringsV4(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstringsV4(string: String) -> [String] {
guard string.count > 0 else { return [] }
var substrings = Set<String>()
for i
if!substrings.contains(substring) { // expected expression, var, or let in 'if' condition
if substring.count > 2 &&!substrings.contains(substring) { // expected '{' after 'if' condition
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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 {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return substrings
}
func allSubstrings2(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)]))
}
}
return substrings
}
func allSubstrings3(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)]))
}
}
return substrings
}
func allSubstrings4(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)]))
}
}
return substrings
}
func allSubstrings5(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)]))
}
}
return substrings
}
func allSubstrings6(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)]))
}
}
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]()
var prefix = ""
for char in string {
prefix.append(char)
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]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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 i...string.count {
substrings.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
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 allSubstrings2(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)]))
}
}
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 allSubstrings3(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)]))
}
}
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 allSubstrings4(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)]))
}
}
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 allSubstrings5(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)]))
}
}
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 allSubstrings6(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)]))
}
}
return substrings
}
// Return array of all substrings from short
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
var prefix = ""
for char in string {
prefix.append(char)
prefixes.append(prefix)
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
suffixes.append(suffix)
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
substrings.append(suffix)
}
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if!substrings.contains(suffix) {
substrings.append(suffix)
}
}
}
return substrings
}
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
var substring = ""
var characters = Set<Character>()
for char in string {
substring.append(char)
characters.insert(char)
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]()
var prefix = ""
for char in string {
prefix.append(char)
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]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
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 index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
substrings.append(suffix)
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
for index in 0...string.count {
for suffix in allSuffixes(string: String(string.suffix(index))) {
if!substrings.contains(suffix) {
substrings.append(suffix)
}
}
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
var substring = ""
var characters = Set<Character>()
for char in string {
substring.append(char)
characters.insert(char)
substrings.append(substring)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
var substring = ""
var characters = Set<Character>()
for char in string {
substring.append(char)
characters.insert(char)
substrings.append(substring)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
var substring = ""
var characters = Set<Character>()
for char in string {
substring.append(char)
characters.insert(char)
substrings.append(substring)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings = [String]()
var substring = ""
var characters = Set<Character>()
for char in string {
substring.append(char)
characters.insert(char)
substrings.append(substring)
}
return substrings
}
// Return array of all substrings from shortest to longest of the input string
// that do not contain duplicate characters
// allUniqueSubstrings(string: "abc") == ["a", "ab", "abc", "b", "bc", "c"]
func allUniqueSubstrings(string: String) -> [String] {
var substrings =
if!substrings.contains(suffix) { // expected expression, var, or let in 'if' condition
func allUniqueSubstrings(string: String) -> [String] { // invalid redeclaration of 'allUniqueSubstrings(string:)'
func allPrefixes(string: String) -> [String] {
var result = [String]()
var prefix = ""
for char in string {
prefix.append(char)
result.append(prefix)
}
return result
}
func allSuffixes(string: String) -> [String] {
var result = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
result.append(suffix)
}
return result
}
func allSubstrings(string: String) -> [String] {
var result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var result = [String]()
var prefix = ""
for char in string {
prefix.append(char)
result.append(prefix)
}
return result
}
// 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 result = [String]()
var suffix = ""
for char in string.reversed() {
suffix.insert(char, at: suffix.startIndex)
result.append(suffix)
}
return result
}
// 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 result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
// 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 result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
// 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 result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
// 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 result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
// 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 result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
// 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 result = [String]()
for i in 0...string.count {
for j in i...string.count {
result.append(String(string[string.index(string.startIndex, offsetBy: i)...string.index(string.startIndex, offsetBy: j)]))
}
}
return result
}
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "ab", "abc",
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func sumOfSquares(_ numbers: [Int]) -> Int {
var result = 0
for number in numbers {
if number % 2 == 0 {
result += number * number
}
}
return result
}
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
```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
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
var result = 0
for number in numbers {
if number % 2 == 0 {
result += number * number
}
}
return result
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2, 3, 4, 5]) == 55
// sumOfSquares([10, 11, 12, 13, 14]) == 114
func sumOfSquares(_ numbers: [Int]) -> Int {
return numbers.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)
}
// Return the sum of the squares of even numbers in the given array.
// sumOfSquares([1, 2
func sumOfSquares(_ numbers: [Int]) -> Int { // invalid redeclaration of 'sumOfSquares'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result.append("\(i) ")
}
return result
}
func sumOfCubes(_ arr: [Int]) -> Int {
var result = 0
for i in arr {
if i % 2 == 0 {
result += i * i * i
}
}
return result
}
func sumOfArray(_ arr: [Int]) -> Int {
var result = 0
for i in arr {
result += i
}
return result
}
func sumOfUniqueElements(_ arr: [Int]) -> Int {
var result = 0
var unique = Set<Int>()
for i in arr {
if!unique.contains(i) {
unique.insert(i)
result += i
}
}
return result
}
func productOfOddCubes(_ arr: [Int]) -> Int {
var result = 1
for i in arr {
if i % 2 == 1 {
result *= i * i * i
}
}
return result
}
func productOfArray(_ arr: [Int]) -> Int {
var result = 1
for i in arr {
result *= i
}
return result
}
func productOfUniqueElements(_ arr: [Int]) -> Int {
var result = 1
var unique = Set<Int>()
for i in arr {
if!unique.contains(i) {
unique.insert(i)
result *= i
}
}
return result
}
func differenceBetweenSumOfSquares(_ arr: [Int]) -> Int {
var even = 0
var odd = 0
for i in arr {
if i % 2 == 0 {
even += i * i
} else {
odd += i * i
}
}
return even - odd
}
```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.append("\(i) ")
}
return result
}
// Return the sum of the cubes of all the even numbers in the given array.
// sumOfCubes([1, 2, 3, 4, 5]) == 56
// sumOfCubes([1, 3, 5]) == 19
func sumOfCubes(_ arr: [Int]) -> Int {
var result = 0
for i in arr {
if i % 2 == 0 {
result += i * i * i
}
}
return result
}
// Return the sum of all the numbers in the given array.
// sumOfArray([1, 2, 3, 4, 5]) == 15
// sumOfArray([1, -2, 3, -4, 5]) == 3
func sumOfArray(_ arr: [Int]) -> Int {
var result = 0
for i in arr {
result += i
}
return result
}
// Return the sum of all the unique positive numbers in the given array.
// sumOfUniqueElements([1, 2, 3, 4, 5]) == 15
// sumOfUniqueElements([1, -2, 3, -4, 5]) == 9
func sumOfUniqueElements(_ arr: [Int]) -> Int {
var result = 0
var unique = Set<Int>()
for i in arr {
if!unique.contains(i) {
unique.insert(i)
result += i
}
}
return result
}
// Return the product of the cubes of all the odd numbers in the given array.
// productOfOddCubes([1, 2, 3, 4, 5]) == 1056
// productOfOddCubes([2, 3, 9]) == 572
func productOfOddCubes(_ arr: [Int]) -> Int {
var result = 1
for i in arr {
if i % 2 == 1 {
result *= i * i * i
}
}
return result
}
// Return the product of all the numbers in the given array.
// productOfArray([1, 2, 3, 4, 5]) == 120
// productOfArray([1, -2, 3, -4, 5]) == -60
func productOfArray(_ arr: [Int]) -> Int {
var result = 1
for i in arr {
result *= i
}
return result
}
// Return the product of all the unique positive numbers in the given array.
// productOfUniqueElements([1, 2, 3, 4, 5]) == 60
// productOfUniqueElements([1, -2, 3, -4, 5]) == -60
func productOfUniqueElements(_ arr: [Int]) -> Int {
var result = 1
var unique = Set<Int>()
for i in arr {
if!unique.contains(i) {
unique.insert(i)
result *= i
}
}
return result
}
// Return the difference between the sum of the squares of even and odd numbers in the given array.
// differenceBetweenSumOfSquares([1, 2, 3, 4, 5]) == 26
// differenceBetweenSumOfSquares([2, 8, 7, 5, 4]) == 17
func differenceBetweenSumOfSquares(_ arr: [Int]) -> Int {
var even = 0
var odd = 0
for i in arr {
if i % 2 == 0 {
even += i * i
} else {
odd += i * i
}
}
return even - odd
}
// Return the difference between the sum of the squares of even and odd numbers in the given array.
// differenceBetweenSumOfSquares([1, 2, 3, 4, 5]) == 26
// differenceBetweenSumOfSquares([2, 8, 7, 5, 4]) == 17
func differenceBetweenSumOfSquares(_ arr: [Int]) -> Int {
var even = 0
var odd = 0
for i in arr {
if i % 2 == 0 {
even += i * i
} else {
odd += i *
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
func fibonacciSumCubes(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
func fibonacciSum(n: Int = 100) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
func fibonacciSumCubes(n: Int = 100) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
func fibonacciSum(n: Int = 100) -> (Int, Int) {
var a = 0
var b = 1
var sumEven = 0
var sumOdd = 0
for _ in 0...n {
if b % 2 == 0 {
sumEven += b
} else {
sumOdd += b
}
let temp = b
b = a + b
a = temp
}
return (sumEven, sumOdd)
}
```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
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// fibonacciSum(1) == 0
// fibonacciSum(5) == 2
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
// Return the sum of the cubes of odd numbers in the Fibonacci sequence.
// fibonacciSumCubes(1) == 0
// fibonacciSumCubes(5) == 7
func fibonacciSumCubes(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// fibonacciSum(n: 10) == 24157817
func fibonacciSum(n: Int = 100) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
// Return the sum of the cubes of odd numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// fibonacciSumCubes(n: 10) == 79892
func fibonacciSumCubes(n: Int = 100) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = b
b = a + b
a = temp
}
return sum
}
// Return the sum of the squares of even fibonacci numbers and the sum of the cubes of odd fibonacci numbers.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// fibonacciSum(n: 10) == (24157817, 79892)
func fibonacciSum(n: Int = 100) -> (Int, Int) {
var a = 0
var b = 1
var sumEven = 0
var sumOdd = 0
for _ in 0...n {
if b % 2 == 0 {
sumEven += b
} else {
sumOdd += b
}
let temp = b
b = a + b
a = temp
}
return (sumEven, sumOdd)
}
// Return the sum of the squares of even fibonacci numbers and the sum of the cubes of odd fibonacci numbers.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// fibonacciSum(n: 10) == (24157817, 79892)
func fibonacciSum(n: Int = 100) -> (Int, Int) {
var a = 0
var b = 1
var sumEven = 0
var sumOdd = 0
for _ in 0...n {
if b % 2 == 0 {
sumEven += b
} else {
sumOdd += b
}
let temp = b
b = a + b
a = temp
}
return (sumEven, sumOdd)
}
// Return the sum of the squares of even fibonacci numbers and the sum of the cubes of odd
func fibonacciSum(n: Int = 100) -> Int { // invalid redeclaration of 'fibonacciSum(n:)'
func fibonacciSumCubes(n: Int = 100) -> Int { // invalid redeclaration of 'fibonacciSumCubes(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func arraySequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
func generatorSequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
func recursiveSequence(n: Int) -> [Int] {
if n == 0 {
return [0]
} else {
return [n] + recursiveSequence(n: n - 1)
}
}
func tailRecursiveSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return tailRecursiveSequence(n: n - 1, result: [n] + result)
}
}
func recursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return recursiveRange(n: n - 1, result: [n] + result)
}
}
func tailRecursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
func appendToResult(n: Int, result: [Int]) -> [Int] {
if n == 0 {
return result
} else {
return appendToResult(n: n - 1, result: [n] + result)
}
}
return appendToResult(n: n, result: result)
}
func whileLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
var i = n
var result = result
while i > 0 {
result.append(i)
i -= 1
}
return result
}
func forLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
for i in 0...n {
result.append(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
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func arraySequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func generatorSequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func recursiveSequence(n: Int) -> [Int] {
if n == 0 {
return [0]
} else {
return [n] + recursiveSequence(n: n - 1)
}
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func tailRecursiveSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return tailRecursiveSequence(n: n - 1, result: [n] + result)
}
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func recursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return recursiveRange(n: n - 1, result: [n] + result)
}
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func tailRecursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
func appendToResult(n: Int, result: [Int]) -> [Int] {
if n == 0 {
return result
} else {
return appendToResult(n: n - 1, result: [n] + result)
}
}
return appendToResult(n: n, result: result)
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func whileLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
var i = n
var result = result
while i > 0 {
result.append(i)
i -= 1
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func forLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
for i in 0...n {
result.append(i)
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n incl
result.append(i) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func stringSequence(n: Int) -> String {
return ""
}
func fibonacciSum(n: Int) -> Int {
return 0
}
func fibonacciSum(n: Int = 100) -> Int {
return 0
}
func fibonacciSumAndCount(n: Int = 100) -> (Int, Int) {
return (0, 0)
}
func fibonacciSumAndCount(n: Int = 100) -> (Int, Int, Double) {
return (0, 0, 0.0)
}
func fibonacciSumAndCount(n: Int = 100) -> (Int, Int, Double, Int) {
return (0, 0, 0.0, 0)
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
return ""
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// fibonacciSum(n: 0) == 0
// fibonacciSum(n: 6) == 12
func fibonacciSum(n: Int) -> Int {
return 0
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// The function handles the case when the input n is negative by returning 0.
// fibonacciSum(n: 10) == 33
// fibonacciSum(n: -5) == 0
func fibonacciSum(n: Int = 100) -> Int {
return 0
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// The function handles the case when the input n is negative by returning 0.
// The function also calculates and returns the sum of the squares of even numbers in the Fibonacci sequence.
// The function returns a tuple containing the Fibonacci sum and the number of even numbers in the sequence.
// fibonacciSumAndCount(n: 10) == (33, 5)
// fibonacciSumAndCount(n: -5) == (0, 0)
func fibonacciSumAndCount(n: Int = 100) -> (Int, Int) {
return (0, 0)
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// The function handles the case when the input n is negative by returning 0.
// The function also calculates and returns the sum of the squares of even numbers in the Fibonacci sequence.
// The function returns a tuple containing the Fibonacci sum, the number of even numbers in the sequence,
// and the average value of the squares of even numbers in the sequence.
// fibonacciSumAndCount(n: 10) == (33, 5, 16.666666666666667)
// fibonacciSumAndCount(n: -5) == (0, 0, 0.0)
func fibonacciSumAndCount(n: Int = 100) -> (Int, Int, Double) {
return (0, 0, 0.0)
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// The function handles the case when the input n is negative by returning 0.
// The function also calculates and returns the sum of the squares of even numbers in the Fibonacci sequence.
// The function returns a tuple containing the Fibonacci sum, the number of even numbers in the sequence,
// the average value of the squares of even numbers in the sequence, and the largest value of the squares of even numbers in the sequence.
// fibonacciSumAndCount(n: 10) == (33, 5, 16.666666666666667, 16)
// fibonacciSumAndCount(n: -5) == (0, 0, 0.0, 0)
func fibonacciSumAndCount(n: Int = 100) -> (Int, Int, Double, Int) {
return (0, 0, 0.0, 0)
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The function takes an optional argument to specify the maximum value of n.
// If n is not provided, the default value is 100.
// The function handles the case when the input
func fibonacciSum(n: Int = 100) -> Int { // invalid redeclaration of 'fibonacciSum(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func fibonacciSum(n: Int) -> Int {
if n < 2 {
return 0
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum += b
(a, b) = (b, a + b)
}
return sum
}
```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
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones.
// The first two numbers in the sequence are 0 and 1.
// The function should return 0 if the input is less than 2.
// Examples:
// fibonacciSum(1) == 0
// fibonacciSum(2) == 2
// fibonacciSum(5) == 2 + 8 + 34 + 55 + 89 = 165
func fibonacciSum(n: Int) -> Int {
if n < 2 {
return 0
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum += b
(a, b) = (b, a + b)
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones.
// The first two numbers in the sequence are 0 and 1.
// The function should return 0 if the input is less than 2.
// Examples:
// fibonacciSum(1) == 0
// fibonacciSum(2) == 2
// fibonacciSum(5) == 2 + 8 + 34 + 55 + 89 = 165
func fibonacciSum(n: Int) -> Int {
if n < 2 {
return 0
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum += b
(a, b) = (b, a + b)
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones.
// The first two numbers in the sequence are 0 and 1.
// The function should return 0 if the input is less than 2.
// Examples:
// fibonacciSum(1) == 0
// fibonacciSum(2) == 2
// fibonacciSum(5) == 2 + 8 + 34 + 55 + 89 = 165
func fibonacciSum(n: Int) -> Int {
if n < 2 {
return 0
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum += b
(a, b) = (b, a + b)
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones.
// The first two numbers in the sequence are 0 and 1.
// The function should return 0 if the input is less than 2.
// Examples:
// fibonacciSum(1) == 0
// fibonacciSum(2) == 2
// fibonacciSum(5) == 2 + 8 + 34 + 55 + 89 = 165
func fibonacciSum(n: Int) -> Int {
if n < 2 {
return 0
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum += b
(a, b) = (b, a + b)
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding ones.
// The first two numbers in the sequence are 0 and
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result.append(String(i) + " ")
}
return result
}
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = a + b
a = b
b = temp
}
return sum
}
```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.append(String(i) + " ")
}
return result
}
// Return the sum of the squares of even numbers in the Fibonacci sequence up to n.
// The Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.
// The first two numbers in the sequence are 0 and 1.
// The function should have a time complexity of O(n) and should not use any built-in Swift functions or libraries for calculating the Fibonacci sequence or the squares.
// f(0) = 0
// f(1) = 1
// f(n) = f(n-1) + f(n-2)
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = a + b
a = b
b = temp
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence up to n.
// The Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.
// The first two numbers in the sequence are 0 and 1.
// The function should have a time complexity of O(n) and should not use any built-in Swift functions or libraries for calculating the Fibonacci sequence or the squares.
// f(0) = 0
// f(1) = 1
// f(n) = f(n-1) + f(n-2)
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = a + b
a = b
b = temp
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence up to n.
// The Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.
// The first two numbers in the sequence are 0 and 1.
// The function should have a time complexity of O(n) and should not use any built-in Swift functions or libraries for calculating the Fibonacci sequence or the squares.
// f(0) = 0
// f(1) = 1
// f(n) = f(n-1) + f(n-2)
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = a + b
a = b
b = temp
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence up to n.
// The Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.
// The first two numbers in the sequence are 0 and 1.
// The function should have a time complexity of O(n) and should not use any built-in Swift functions or libraries for calculating the Fibonacci sequence or the squares.
// f(0) = 0
// f(1) = 1
// f(n) = f(n-1) + f(n-2)
func fibonacciSum(n: Int) -> Int {
var a = 0
var b = 1
var sum = 0
for _ in 0...n {
sum += b
let temp = a + b
a = b
b = temp
}
return sum
}
// Return the sum of the squares of even numbers in the Fibonacci sequence up to n.
// The Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.
// The first two numbers in the sequence are 0 and 1.
// The function should have a time complexity of O(n) and should not use any built-in Swift functions or libraries for calculating the Fibonacci sequence or the squares.
// f(0) = 0
// f(1) = 1
// f(n) = f(
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func arraySequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
func generatorSequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
func recursiveSequence(n: Int) -> [Int] {
if n == 0 {
return [0]
} else {
return [n] + recursiveSequence(n: n - 1)
}
}
func tailRecursiveSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return tailRecursiveSequence(n: n - 1, result: [n] + result)
}
}
func recursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return recursiveRange(n: n - 1, result: [n] + result)
}
}
func tailRecursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
func range(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return range(n: n - 1, result: [n] + result)
}
}
return range(n: n, result: result)
}
func whileLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
var i = n
var result = result
while i > 0 {
result.append(i)
i -= 1
}
return result
}
func forLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
var result = result
for i in 0...n {
result.append(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
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func arraySequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func generatorSequence(n: Int) -> [Int] {
var result = [Int]()
for i in 0...n {
result.append(i)
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func recursiveSequence(n: Int) -> [Int] {
if n == 0 {
return [0]
} else {
return [n] + recursiveSequence(n: n - 1)
}
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func tailRecursiveSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return tailRecursiveSequence(n: n - 1, result: [n] + result)
}
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func recursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return recursiveRange(n: n - 1, result: [n] + result)
}
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func tailRecursiveRange(n: Int, result: [Int] = [Int]()) -> [Int] {
func range(n: Int, result: [Int] = [Int]()) -> [Int] {
if n == 0 {
return result
} else {
return range(n: n - 1, result: [n] + result)
}
}
return range(n: n, result: result)
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func whileLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
var i = n
var result = result
while i > 0 {
result.append(i)
i -= 1
}
return result
}
// Return an array of integers containing numbers starting from 0 upto n inclusive.
// arraySequence(n: 0) == [0]
// arraySequence(n: 5) == [0, 1, 2, 3, 4, 5]
func forLoopSequence(n: Int, result: [Int] = [Int]()) -> [Int] {
var result = result
for i in 0...n {
result.append(i)
}
return result
}
// Return an array of integers containing numbers starting from 0
// XCTAssertTrue failed
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
} else {
return stringSequence(n: n-1) + " " + String(n)
}
}
func sumOfSquaresOfEvenFibonacci(n: Int) -> Int {
var fib = [0, 1]
var sum = 0
for i in 2...n {
fib.append(fib[i-1] + fib[i-2])
if fib[i] % 2 == 0 {
sum += fib[i] * fib[i]
}
}
return sum
}
func printFibonacciSequence(n: Int) {
var fib = [0, 1]
print(fib[0])
print(fib[1])
for i in 2...n {
fib.append(fib[i-1] + fib[i-2])
print(fib[i])
}
}
func fibonacciSequenceAndSumOfSquaresOfEvenNumbers(n: Int) {
var fib = [0, 1]
var sum = 0
print("Fibonacci Sequence:")
print(fib[0])
print(fib[1])
for i in 2...n {
fib.append(fib[i-1] + fib[i-2])
print(fib[i])
if fib[i] % 2 == 0 {
sum += fib[i] * fib[i]
}
}
print("Sum of Squares of Even Numbers:", sum)
}
```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 {
if n == 0 {
return "0"
} else {
return stringSequence(n: n-1) + " " + String(n)
}
}
// Return the sum of the squares of even numbers in the Fibonacci sequence.
// The Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.
// The first two numbers in the sequence are 0 and 1.
// The function should have a time complexity of O(n) and should not use any built-in functions or libraries for calculating the Fibonacci sequence or finding the squares of even numbers.
func sumOfSquaresOfEvenFibonacci(n: Int) -> Int {
var fib = [0, 1]
var sum = 0
for i in 2...n {
fib.append(fib[i-1] + fib[i-2])
if fib[i] % 2 == 0 {
sum += fib[i] * fib[i]
}
}
return sum
}
// Print the string representation of the Fibonacci sequence up to the nth term.
// The function should have a time complexity of O(n) and should not use any built-in functions or libraries for calculating the Fibonacci sequence or creating the string representation.
func printFibonacciSequence(n: Int) {
var fib = [0, 1]
print(fib[0])
print(fib[1])
for i in 2...n {
fib.append(fib[i-1] + fib[i-2])
print(fib[i])
}
}
// Calculate the sum of the squares of even numbers in the Fibonacci sequence up to the nth term and print the string representation of the Fibonacci sequence up to the nth term.
// The function should have a time complexity of O(n) and should not use any built-in functions or libraries for calculating the Fibonacci sequence, finding the squares of even numbers, or creating the string representation.
func fibonacciSequenceAndSumOfSquaresOfEvenNumbers(n: Int) {
var fib = [0, 1]
var sum = 0
print("Fibonacci Sequence:")
print(fib[0])
print(fib[1])
for i in 2...n {
fib.append(fib[i-1] + fib[i-2])
print(fib[i])
if fib[i] % 2 == 0 {
sum += fib[i] * fib[i]
}
}
print("Sum of Squares of Even Numbers:", sum)
}
// Test the implementation
print(stringSequence(n: 5)) // Output: "0 1 2 3 4 5"
print(sumOfSquaresOfEvenFibonacci(n: 10)) // Output: 105
printFibonacciSequence(n: 10) // Output: 0 1 1 2 3 5 8 13 21 34
fibonacciSequenceAndSumOfSquaresOfEvenNumbers(n: 10) // Output: Fibonacci Sequence: 0 1 1 2 3 5 8 13 21 34 Sum of Squares of Even Numbers: 105
```
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func sumFromString(_ string: String) -> Int {
var result = 0
let numbers = string.components(separatedBy: " ").map { Int($0)! }
for number in numbers {
result += number
}
return result
}
func sumFromString2(_ string: String) -> Int {
var result = 0
let numbers = string.components(separatedBy: " ")
for number in numbers {
result += Int(number)!
}
return result
}
func sumFromString3(_ string: String) -> Int {
return string.components(separatedBy: " ").map { Int($0)! }.reduce(0, +)
}
func sumFromString4(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.reduce(0, +)
}
func sumFromString5(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.reduce(0, +)
}
func sumFromString6(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.compactMap { $0 }
.reduce(0, +)
}
func sumFromString7(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.compactMap { $0 }
.compactMap { $0 }
.reduce(0, +)
}
func sumFromString8(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.compactMap { $0 }
.compactMap { $0 }
.compactMap { $0 }
.reduce(0, +)
}
```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
}
// Return the sum of all the numbers in the string.
// sumFromString("0") == 0
// sumFromString("1 2 3 4 5") == 15
func sumFromString(_ string: String) -> Int {
var result = 0
let numbers = string.components(separatedBy: " ").map { Int($0)! }
for number in numbers {
result += number
}
return result
}
// Return the sum of all the numbers in the string, using a for-in loop.
// sumFromString2("0") == 0
// sumFromString2("1 2 3 4 5") == 15
func sumFromString2(_ string: String) -> Int {
var result = 0
let numbers = string.components(separatedBy: " ")
for number in numbers {
result += Int(number)!
}
return result
}
// Return the sum of all the numbers in the string, using map and reduce.
// sumFromString3("0") == 0
// sumFromString3("1 2 3 4 5") == 15
func sumFromString3(_ string: String) -> Int {
return string.components(separatedBy: " ").map { Int($0)! }.reduce(0, +)
}
// Return the sum of all the numbers in the string, using map, compactMap, and reduce.
// sumFromString4("0") == 0
// sumFromString4("1 2 3 4 5") == 15
func sumFromString4(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.reduce(0, +)
}
// Return the sum of all the numbers in the string, using map, compactMap, compactMap, and reduce.
// sumFromString5("0") == 0
// sumFromString5("1 2 3 4 5") == 15
func sumFromString5(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.reduce(0, +)
}
// Return the sum of all the numbers in the string, using map, compactMap, compactMap, compactMap, and reduce.
// sumFromString6("0") == 0
// sumFromString6("1 2 3 4 5") == 15
func sumFromString6(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.compactMap { $0 }
.reduce(0, +)
}
// Return the sum of all the numbers in the string, using map, compactMap, compactMap, compactMap, compactMap, and reduce.
// sumFromString7("0") == 0
// sumFromString7("1 2 3 4 5") == 15
func sumFromString7(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.compactMap { $0 }
.compactMap { $0 }
.reduce(0, +)
}
// Return the sum of all the numbers in the string, using map, compactMap, compactMap, compactMap, compactMap, compactMap, and reduce.
// sumFromString8("0") == 0
// sumFromString8("1 2 3 4 5") == 15
func sumFromString8(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
.compactMap { $0 }
.compactMap { $0 }
.compactMap { $0 }
.compactMap { $0 }
.reduce(0, +)
}
// Return the sum of all the numbers in the string, using map, compactMap, compactMap, compactMap, compactMap, compactMap, compactMap, and reduce.
// sumFromString9("0") == 0
// sumFromString9("1 2 3 4 5") == 15
func sumFromString9(_ string: String) -> Int {
return string.components(separatedBy: " ")
.compactMap { Int($0) }
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var characters = Set<Character>()
for character in string {
characters.insert(character)
}
return characters.count
}
func getCharacterWhichAppearsMostTimes(string: String) -> Character {
var characters = [Character: Int]()
for character in string {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
var maxCount = 0
var maxCharacter: Character = " "
for (character, count) in characters {
if count > maxCount {
maxCount = count
maxCharacter = character
}
}
return maxCharacter
}
func getCharacterWhichAppearsMostTimesWithoutWhitespaces(string: String) -> Character {
var characters = [Character: Int]()
var stringWithoutWhitespaces = ""
for character in string {
if character!= " " {
stringWithoutWhitespaces.append(character)
}
}
for character in stringWithoutWhitespaces {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
var maxCount = 0
var maxCharacter: Character = " "
for (character, count) in characters {
if count > maxCount {
maxCount = count
maxCharacter = character
}
}
return maxCharacter
}
func getLongestSubstringOfUniqueCharacters(string: String) -> Int {
var characters = Set<Character>()
var start = 0
var end = 0
var maxLength = 0
while end < string.count {
if!characters.contains(string[String.Index(encodedOffset: end)]) {
characters.insert(string[String.Index(encodedOffset: end)])
end += 1
maxLength = max(maxLength, characters.count)
} else {
characters.remove(string[String.Index(encodedOffset: start)])
start += 1
}
}
return maxLength
}
func getLongestSubstringOfUniqueCharactersWithoutDataStructures(string: String) -> Int {
var maxLength = 0
var characters = [Character: Int]()
var start = 0
var end = 0
while end < string.count {
if let index = characters[string[String.Index(encodedOffset: end)]] {
start = max(start, index + 1)
}
characters[string[String.Index(encodedOffset: end)]] = end
end += 1
maxLength = max(maxLength, end - start)
}
return maxLength
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var characters = Set<Character>()
for character in string {
characters.insert(character)
}
return characters.count
}
// Given a string, return the character that appears the most times in it
// getCharacterWhichAppearsMostTimes(string: "abcaabdef") == "a"
// getCharacterWhichAppearsMostTimes(string: "apple") == "a"
func getCharacterWhichAppearsMostTimes(string: String) -> Character {
var characters = [Character: Int]()
for character in string {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
var maxCount = 0
var maxCharacter: Character = " "
for (character, count) in characters {
if count > maxCount {
maxCount = count
maxCharacter = character
}
}
return maxCharacter
}
// Given a string, return the character that appears the most times in it, but ignore any whitespace characters
// getCharacterWhichAppearsMostTimesWithoutWhitespaces(string: "abca abdef") == "a"
// getCharacterWhichAppearsMostTimesWithoutWhitespaces(string: "apple") == "a"
func getCharacterWhichAppearsMostTimesWithoutWhitespaces(string: String) -> Character {
var characters = [Character: Int]()
var stringWithoutWhitespaces = ""
for character in string {
if character!= " " {
stringWithoutWhitespaces.append(character)
}
}
for character in stringWithoutWhitespaces {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
var maxCount = 0
var maxCharacter: Character = " "
for (character, count) in characters {
if count > maxCount {
maxCount = count
maxCharacter = character
}
}
return maxCharacter
}
// Given a string, return the length of the longest substring of unique characters
// getLongestSubstringOfUniqueCharacters(string: "abcabcbb") == 3
// getLongestSubstringOfUniqueCharacters(string: "abcdefg") == 7
func getLongestSubstringOfUniqueCharacters(string: String) -> Int {
var characters = Set<Character>()
var start = 0
var end = 0
var maxLength = 0
while end < string.count {
if!characters.contains(string[String.Index(encodedOffset: end)]) {
characters.insert(string[String.Index(encodedOffset: end)])
end += 1
maxLength = max(maxLength, characters.count)
} else {
characters.remove(string[String.Index(encodedOffset: start)])
start += 1
}
}
return maxLength
}
// Given a string, return the length of the longest substring of unique characters, but without using any built-in
// functions or data structures
// getLongestSubstringOfUniqueCharactersWithoutDataStructures(string: "abcabcbb") == 3
// getLongestSubstringOfUniqueCharactersWithoutDataStructures(string: "abcdefg") == 7
func getLongestSubstringOfUniqueCharactersWithoutDataStructures(string: String) -> Int {
var maxLength = 0
var characters = [Character: Int]()
var start = 0
var end = 0
while end < string.count {
if let index = characters[string[String.Index(encodedOffset: end)]] {
start = max(start, index + 1)
}
characters[string[String.Index(encodedOffset: end)]] = end
end += 1
maxLength = max(maxLength, end - start)
}
return maxLength
}
// Given two strings, write a method to decide if one is a permutation of the other
// isPermutation(string1: "abc", string2: "bac") == true
// isPermutation(string1: "abc", string2: "bca") == false
func isPermutation(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var characters = [Character: Int]()
for character in string1 {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
if character!= " " { // '=' must have consistent whitespace on both sides
if character!= " " { // use of '=' in a boolean context, did you mean '=='?
if character!= " " { // cannot force unwrap value of non-optional type 'Character'
if!characters.contains(string[String.Index(encodedOffset: end)]) { // expected expression, var, or let in 'if' condition
if let index = characters[string[String.Index(encodedOffset: end)]] { // 'init(encodedOffset:)' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use String.Index(utf16Offset:in:) to achieve the same behavior.
characters[string[String.Index(encodedOffset: end)]] = end // 'init(encodedOffset:)' is deprecated: encodedOffset has been deprecated as most common usage is incorrect. Use String.Index(utf16Offset:in:) to achieve the same behavior.
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
func removeDuplicates(string: String) -> String {
var distinctCharacters = Set<Character>()
var result = ""
for character in string {
if!distinctCharacters.contains(character) {
distinctCharacters.insert(character)
result.append(character)
}
}
return result
}
func isAnagram(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
if let count = charCounts[character] {
charCounts[character] = count + 1
} else {
charCounts[character] = 1
}
}
for character in string2 {
if let count = charCounts[character] {
charCounts[character] = count - 1
} else {
return false
}
}
return true
}
func isAnagramAlternative(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
charCounts[character, default: 0] += 1
}
for character in string2 {
charCounts[character, default: 0] -= 1
}
return charCounts.values.allSatisfy { $0 == 0 }
}
func firstNonRecurringCharacter(string: String) -> Character? {
var charCounts = [Character: Int]()
for character in string {
charCounts[character, default: 0] += 1
if charCounts[character] == 2 {
return character
}
}
return nil
}
func firstNonRecurringCharacterAlternative(string: String) -> Character? {
var charSet = CharacterSet()
for character in string {
if charSet.contains(character) {
return character
} else {
charSet.insert(character)
}
}
return nil
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// Given a string, remove all duplicate characters (regardless of case)
// removeDuplicates(string: "xyzXYZ") == "XYZ"
// removeDuplicates(string: "JERRY") == "JERRY"
func removeDuplicates(string: String) -> String {
var distinctCharacters = Set<Character>()
var result = ""
for character in string {
if!distinctCharacters.contains(character) {
distinctCharacters.insert(character)
result.append(character)
}
}
return result
}
// Given two strings, check if they are anagrams. An anagram is a word or phrase formed by
// rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
// isAnagram(string1: "Restful", string2: "fluster") == true
// isAnagram(string1: "tap", string2: "pat") == true
// isAnagram(string1: "a man", string2: "a mn a") == true
// isAnagram(string1: "hello", string2: "world") == false
func isAnagram(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
if let count = charCounts[character] {
charCounts[character] = count + 1
} else {
charCounts[character] = 1
}
}
for character in string2 {
if let count = charCounts[character] {
charCounts[character] = count - 1
} else {
return false
}
}
return true
}
// Given two strings, check if they are anagrams. An anagram is a word or phrase formed by
// rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
// isAnagramAlternative(string1: "Restful", string2: "fluster") == true
// isAnagramAlternative(string1: "tap", string2: "pat") == true
// isAnagramAlternative(string1: "a man", string2: "a mn a") == true
// isAnagramAlternative(string1: "hello", string2: "world") == false
func isAnagramAlternative(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
charCounts[character, default: 0] += 1
}
for character in string2 {
charCounts[character, default: 0] -= 1
}
return charCounts.values.allSatisfy { $0 == 0 }
}
// Given a string, return the first recurring character that does not exist in the string.
// firstNonRecurringCharacter(string: "xyzXYZ") == nil
// firstNonRecurringCharacter(string: "Jerry") == "r"
// firstNonRecurringCharacter(string: "abcABCdef123") == "1"
func firstNonRecurringCharacter(string: String) -> Character? {
var charCounts = [Character: Int]()
for character in string {
charCounts[character, default: 0] += 1
if charCounts[character] == 2 {
return character
}
}
return nil
}
// Given a string, return the first recurring character that does not exist in the string.
// firstNonRecurringCharacterAlternative(string: "xyzXYZ") == nil
// firstNonRecurringCharacterAlternative(string: "Jerry") == "r"
// firstNonRecurringCharacterAlternative(string: "abcABCdef123") == "1"
func firstNonRecurringCharacterAlternative(string: String) -> Character? {
var charSet = CharacterSet()
for character in string {
if charSet.contains(character) {
return character
} else {
charSet.insert(character)
}
}
return nil
}
// Given a string, return the first recurring character that does not exist in the string.
// firstNonRecurringCharacterAlternative(string: "xyzXYZ") == nil
// firstNonRecurringCharacterAlternative(string
if!distinctCharacters.contains(character) { // expected expression, var, or let in 'if' condition
if string1.count!= string2.count { // use of '=' in a boolean context, did you mean '=='?
if string1.count!= string2.count { // cannot force unwrap value of non-optional type 'Int'
if string1.count!= string2.count { // '=' must have consistent whitespace on both sides
if string1.count!= string2.count { // '=' must have consistent whitespace on both sides
if string1.count!= string2.count { // cannot force unwrap value of non-optional type 'Int'
if string1.count!= string2.count { // use of '=' in a boolean context, did you mean '=='?
if charSet.contains(character) { // cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'
charSet.insert(character) // cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
func swapCharacters(string: String, i: Int, j: Int) -> String {
let stringArray = Array(string)
if stringArray[i]!= stringArray[j] {
var swappedArray = stringArray
swappedArray[i] = stringArray[j]
swappedArray[j] = stringArray[i]
return String(swappedArray)
}
return ""
}
func longestSubstringWithoutRepeatingCharacters(string: String) -> Int {
var longestSubstring = ""
var currentSubstring = ""
for character in string {
if!currentSubstring.contains(character) {
currentSubstring.append(character)
} else {
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
currentSubstring = String(character)
}
}
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
return longestSubstring.count
}
func longestSubstringWithKDistinctCharacters(string: String, k: Int) -> Int {
var longestSubstring = ""
var currentSubstring = ""
var distinctLetterCount = 0
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
distinctLetterCount += 1
}
currentSubstring.append(character)
while distinctLetterCount > k {
let firstCharacter = currentSubstring.first!
if let count = characterCount[firstCharacter] {
characterCount[firstCharacter] = count - 1
if characterCount[firstCharacter] == 0 {
characterCount[firstCharacter] = nil
distinctLetterCount -= 1
}
}
currentSubstring.removeFirst()
}
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
}
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
return longestSubstring.count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// Given a string, return a new string with the characters at index i and j swapped,
// if the characters are different. If the characters are the same, return an empty string.
// swapCharacters(string: "hello", i: 1, j: 2) == "helo"
// swapCharacters(string: "hello", i: 1, j: 2) == "hllo"
// swapCharacters(string: "hello", i: 1, j: 1) == "hello"
// swapCharacters(string: "hello", i: 0, j: 0) == "hello"
func swapCharacters(string: String, i: Int, j: Int) -> String {
let stringArray = Array(string)
if stringArray[i]!= stringArray[j] {
var swappedArray = stringArray
swappedArray[i] = stringArray[j]
swappedArray[j] = stringArray[i]
return String(swappedArray)
}
return ""
}
// Given a string, return the length of the longest substring without repeating characters.
// longestSubstringWithoutRepeatingCharacters(string: "abcabcbb") == 3
// longestSubstringWithoutRepeatingCharacters(string: "bbbbbb") == 1
// longestSubstringWithoutRepeatingCharacters(string: "pwwkew") == 3
func longestSubstringWithoutRepeatingCharacters(string: String) -> Int {
var longestSubstring = ""
var currentSubstring = ""
for character in string {
if!currentSubstring.contains(character) {
currentSubstring.append(character)
} else {
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
currentSubstring = String(character)
}
}
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
return longestSubstring.count
}
// Given a string, return the length of the longest substring that has the same distinct,
// lowercase letters, as the given string.
// longestSubstringWithKDistinctCharacters(string: "abacabadabacaba") == 5
// longestSubstringWithKDistinctCharacters(string: "baaaa") == 2
// longestSubstringWithKDistinctCharacters(string: "abcdefg") == 7
func longestSubstringWithKDistinctCharacters(string: String, k: Int) -> Int {
var longestSubstring = ""
var currentSubstring = ""
var distinctLetterCount = 0
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
distinctLetterCount += 1
}
currentSubstring.append(character)
while distinctLetterCount > k {
let firstCharacter = currentSubstring.first!
if let count = characterCount[firstCharacter] {
characterCount[firstCharacter] = count - 1
if characterCount[firstCharacter] == 0 {
characterCount[firstCharacter] = nil
distinctLetterCount -= 1
}
}
currentSubstring.removeFirst()
}
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
}
if currentSubstring.count > longestSubstring.count {
longestSubstring = currentSubstring
}
return longestSubstring.count
}
// Given a string, return the length of the longest substring that starts and ends with the same
// character and has at least one vowel.
// longestVowelSubString(string: "aei") == 2
// longestVowelSubString(string: "rithmschool") == 5
// longestVowelSubString(string: "apple") == 0
func longestVowelSubString(string: String) -> Int {
var longestSubstring = ""
var currentSubstring = ""
var vowelCount = 0
var characterCount = [Character: Int]()
for character in string {
if isVowel(character: character) {
vowelCount += 1
}
characterCount[character] = (characterCount[character]?? 0) + 1
currentSubstring.append(character)
if v
if stringArray[i]!= stringArray[j] { // use of '=' in a boolean context, did you mean '=='?
if stringArray[i]!= stringArray[j] { // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
if stringArray[i]!= stringArray[j] { // '=' must have consistent whitespace on both sides
if!currentSubstring.contains(character) { // expected expression, var, or let in 'if' condition
func countDistinctCharacters(string: String) -> Int {
var count = 0
var charSet = Set<Character>()
for char in string {
if!charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
func getProductsOfAllOtherElements(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for i in 0..<input.count {
products[i] = leftProduct
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
products[i] *= rightProduct
rightProduct *= input[i]
}
return products
}
func getProductsOfAllOtherElementsConstantSpace(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for i in 0..<input.count {
products[i] = leftProduct
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
products[i] *= rightProduct
rightProduct *= input[i]
}
return products
}
func getProductsOfAllOtherElementsConstantSpaceV2(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for i in 0..<input.count {
products[i] = leftProduct
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
products[i] *= rightProduct
rightProduct *= input[i]
}
return products
}
```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 {
if!charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherElements(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for i in 0..<input.count {
products[i] = leftProduct
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
products[i] *= rightProduct
rightProduct *= input[i]
}
return products
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherElementsConstantSpace(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for i in 0..<input.count {
products[i] = leftProduct
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
products[i] *= rightProduct
rightProduct *= input[i]
}
return products
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherElementsConstantSpaceV2(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for i in 0..<input.count {
products[i] = leftProduct
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
products[i] *= rightProduct
rightProduct *= input[i]
}
return products
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherElementsConstantSpaceV3(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
if!charSet.contains(char) { // expected expression, var, or let in 'if' condition
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
func removeDuplicates(string: String) -> String {
var distinctCharacters = Set<Character>()
var result = ""
for character in string {
if!distinctCharacters.contains(character) {
distinctCharacters.insert(character)
result.append(character)
}
}
return result
}
func isPermutation(string1: String, string2: String) -> Bool {
guard string1.count == string2.count else {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
charCounts[character, default: 0] += 1
}
for character in string2 {
charCounts[character, default: 0] -= 1
if charCounts[character] == 0 {
charCounts[character] = nil
} else {
return false
}
}
return true
}
func isPermutationCaseInsensitive(string1: String, string2: String) -> Bool {
guard string1.count == string2.count else {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
charCounts[character.lowercased(), default: 0] += 1
}
for character in string2 {
charCounts[character.lowercased(), default: 0] -= 1
if charCounts[character.lowercased()] == 0 {
charCounts[character.lowercased()] = nil
} else {
return false
}
}
return true
}
func isPalindrome(string: String) -> Bool {
guard string.count > 1 else {
return true
}
var leftIndex = 0
var rightIndex = string.count - 1
while leftIndex < rightIndex {
if string[leftIndex]!= string[rightIndex] {
return false
}
leftIndex += 1
rightIndex -= 1
}
return true
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// Given a string, remove all duplicate characters (regardless of case)
// removeDuplicates(string: "xyzXYZ") == "XYZ"
// removeDuplicates(string: "JERRY") == "JERRY"
func removeDuplicates(string: String) -> String {
var distinctCharacters = Set<Character>()
var result = ""
for character in string {
if!distinctCharacters.contains(character) {
distinctCharacters.insert(character)
result.append(character)
}
}
return result
}
// Given two strings, check if one string is a permutation of the other
// isPermutation(string1: "abc", string2: "bac") == true
// isPermutation(string1: "abc", string2: "a b c") == true
// isPermutation(string1: "abc", string2: "ab-c") == true
// isPermutation(string1: "abc", string2: "abcd") == false
func isPermutation(string1: String, string2: String) -> Bool {
guard string1.count == string2.count else {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
charCounts[character, default: 0] += 1
}
for character in string2 {
charCounts[character, default: 0] -= 1
if charCounts[character] == 0 {
charCounts[character] = nil
} else {
return false
}
}
return true
}
// Given two strings, check if one string is a permutation of the other ignoring case
// isPermutationCaseInsensitive(string1: "abc", string2: "bac") == true
// isPermutationCaseInsensitive(string1: "abc", string2: "a b c") == true
// isPermutationCaseInsensitive(string1: "abc", string2: "ab-c") == true
// isPermutationCaseInsensitive(string1: "abc", string2: "abcd") == false
func isPermutationCaseInsensitive(string1: String, string2: String) -> Bool {
guard string1.count == string2.count else {
return false
}
var charCounts = [Character: Int]()
for character in string1 {
charCounts[character.lowercased(), default: 0] += 1
}
for character in string2 {
charCounts[character.lowercased(), default: 0] -= 1
if charCounts[character.lowercased()] == 0 {
charCounts[character.lowercased()] = nil
} else {
return false
}
}
return true
}
// Given a string, check if it is a palindrome
// isPalindrome(string: "abcba") == true
// isPalindrome(string: "abacdfgdcaba") == true
// isPalindrome(string: "abacdfgdcabba") == true
// isPalindrome(string: "abacdfgdcaba") == false
func isPalindrome(string: String) -> Bool {
guard string.count > 1 else {
return true
}
var leftIndex = 0
var rightIndex = string.count - 1
while leftIndex < rightIndex {
if string[leftIndex]!= string[rightIndex] {
return false
}
leftIndex += 1
rightIndex -= 1
}
return true
}
// Given a string, check if it is a palindrome ignoring non-alphanumeric characters
// isPalindromeAllowingSpecialCharacters(string: "abcba") == true
// isPalindromeAllowingSpecialCharacters(string: "abacdfgdcaba") == true
// isPalindromeAllowingSpecialCharacters(string: "abacdfgdcabba") == true
// isPalindromeAllowingSpecialCharacters(string: "abacdfgdcaba") == false
func isPalindromeAllowingSpecialCharacters(string: String) -> Bool {
guard string.count > 1 else {
return true
}
var leftIndex = 0
var rightIndex = string.count - 1
while leftIndex < rightIndex {
if!CharacterSet.alphanumerics.contains(string[leftIndex]) {
leftIndex
if!distinctCharacters.contains(character) { // expected expression, var, or let in 'if' condition
charCounts[character.lowercased(), default: 0] += 1 // cannot convert value of type 'String' to expected argument type 'Character'
charCounts[character.lowercased(), default: 0] -= 1 // cannot convert value of type 'String' to expected argument type 'Character'
if charCounts[character.lowercased()] == 0 { // cannot convert value of type 'String' to expected argument type 'Character'
charCounts[character.lowercased()] = nil // cannot convert value of type 'String' to expected argument type 'Character'
if string[leftIndex]!= string[rightIndex] { // '=' must have consistent whitespace on both sides
if string[leftIndex]!= string[rightIndex] { // cannot force unwrap value of non-optional type 'Character'
if string[leftIndex]!= string[rightIndex] { // use of '=' in a boolean context, did you mean '=='?
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
func swapCharacters(string: String, i: Int, j: Int) -> String {
let stringArray = Array(string)
if stringArray[i]!= stringArray[j] {
var swappedArray = stringArray
swappedArray[i] = stringArray[j]
swappedArray[j] = stringArray[i]
return String(swappedArray)
} else {
return string
}
}
func isPermutationOfPalindrome(string: String) -> Bool {
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
}
}
var isOddCount = false
for (_, count) in characterCount {
if count % 2!= 0 {
if isOddCount {
return false
}
isOddCount = true
}
}
return true
}
func isRotation(string1: String, string2: String) -> Bool {
if string1.count == string2.count {
let string1PlusString1 = string1 + string1
return string1PlusString1.contains(string2)
} else {
return false
}
}
func isPermutationOfPalindrome2(string: String) -> Bool {
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
}
}
var isOddCount = false
for (_, count) in characterCount {
if count % 2!= 0 {
if isOddCount {
return false
}
isOddCount = true
}
}
return true
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// Given a string, return a new string with the characters at index i and j swapped,
// if the characters are different. If the characters are the same, return the string unchanged.
// swapCharacters(string: "hello", i: 1, j: 3) == "helo"
// swapCharacters(string: "hello", i: 1, j: 2) == "hello"
func swapCharacters(string: String, i: Int, j: Int) -> String {
let stringArray = Array(string)
if stringArray[i]!= stringArray[j] {
var swappedArray = stringArray
swappedArray[i] = stringArray[j]
swappedArray[j] = stringArray[i]
return String(swappedArray)
} else {
return string
}
}
// Given a string, return true if it is a permutation of a palindrome, and false otherwise.
// Note: a palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
// isPermutationOfPalindrome(string: "Tact Coa") == true
// isPermutationOfPalindrome(string: "hello") == false
func isPermutationOfPalindrome(string: String) -> Bool {
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
}
}
var isOddCount = false
for (_, count) in characterCount {
if count % 2!= 0 {
if isOddCount {
return false
}
isOddCount = true
}
}
return true
}
// Given two strings, return true if the second string is a rotation of the first string.
// Note: A rotation is when you cut out a section of the original string and concatenate it to the end.
// isRotation(string1: "waterbottle", string2: "erbottlewat") == true
// isRotation(string1: "hello", string2: "lohel") == true
// isRotation(string1: "hello", string2: "lohe") == false
func isRotation(string1: String, string2: String) -> Bool {
if string1.count == string2.count {
let string1PlusString1 = string1 + string1
return string1PlusString1.contains(string2)
} else {
return false
}
}
// Given a string, return true if it is a permutation of a palindrome, and false otherwise.
// Note: a palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
// isPermutationOfPalindrome(string: "Tact Coa") == true
// isPermutationOfPalindrome(string: "hello") == false
func isPermutationOfPalindrome2(string: String) -> Bool {
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
}
}
var isOddCount = false
for (_, count) in characterCount {
if count % 2!= 0 {
if isOddCount {
return false
}
isOddCount = true
}
}
return true
}
// Given a string, return true if it is a permutation of a palindrome, and false otherwise.
// Note: a palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward.
// isPermutationOfPalindrome(string: "Tact Coa") == true
// isPermutationOfPalindrome(string: "hello") == false
func isPermutationOfPalindrome3(string: String) -> Bool {
var characterCount = [Character: Int]()
for character in string {
if let count = characterCount[character] {
characterCount[character] = count + 1
} else {
characterCount[character] = 1
}
}
var isOddCount = false
for (_, count) in characterCount {
if count % 2!=
if stringArray[i]!= stringArray[j] { // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
if stringArray[i]!= stringArray[j] { // use of '=' in a boolean context, did you mean '=='?
if stringArray[i]!= stringArray[j] { // '=' must have consistent whitespace on both sides
if count % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if count % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if count % 2!= 0 { // '=' must have consistent whitespace on both sides
if count % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if count % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if count % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if count % 2!= 0 { // '=' must have consistent whitespace on both sides
if count % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
func countDistinctCharacters(string: String) -> Int {
var count = 0
var visited: [Character: Bool] = [:]
for char in string {
if visited[char] == nil {
count += 1
visited[char] = true
}
}
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 visited: [Character: Bool] = [:]
for char in string {
if visited[char] == nil {
count += 1
visited[char] = true
}
}
return count
}
countDistinctCharacters(string: "xyzXYZ") == 3
countDistinctCharacters(string: "Jerry") == 4
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
func getFirstNonRepeatingCharacter(string: String) -> Character? {
var characters = [Character: Int]()
for character in string {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string {
if characters[character] == 1 {
return character
}
}
return nil
}
func getFirstNonRepeatingCharacter(string: String, startingAfter: Character) -> Character? {
var characters = [Character: Int]()
var seen = Set<Character>()
for character in string {
if character == startingAfter {
continue
}
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string {
if character == startingAfter || seen.contains(character) {
continue
}
if characters[character] == 1 {
return character
}
seen.insert(character)
}
return nil
}
func getLastNonRepeatingCharacter(string: String) -> Character? {
var characters = [Character: Int]()
for character in string {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string.reversed() {
if characters[character] == 1 {
return character
}
}
return nil
}
func getLastNonRepeatingCharacter(string: String, startingBefore: Character) -> Character? {
var characters = [Character: Int]()
var seen = Set<Character>()
for character in string.reversed() {
if character == startingBefore {
continue
}
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string.reversed() {
if character == startingBefore || seen.contains(character) {
continue
}
if characters[character] == 1 {
return character
}
seen.insert(character)
}
return nil
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// Given a string, return the first non-repeating character. If there is no such character, return nil.
// getFirstNonRepeatingCharacter(string: "abcdb") == "d"
// getFirstNonRepeatingCharacter(string: "Jerry") == "J"
// getFirstNonRepeatingCharacter(string: "abcaab") == nil
func getFirstNonRepeatingCharacter(string: String) -> Character? {
var characters = [Character: Int]()
for character in string {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string {
if characters[character] == 1 {
return character
}
}
return nil
}
// Given a string, return the first non-repeating character that appears after a specific character.
// If there is no such character, return nil.
// getFirstNonRepeatingCharacter(string: "abcdb", startingAfter: "b") == "c"
// getFirstNonRepeatingCharacter(string: "Jerry", startingAfter: "J") == nil
// getFirstNonRepeatingCharacter(string: "abcaab", startingAfter: "b") == nil
func getFirstNonRepeatingCharacter(string: String, startingAfter: Character) -> Character? {
var characters = [Character: Int]()
var seen = Set<Character>()
for character in string {
if character == startingAfter {
continue
}
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string {
if character == startingAfter || seen.contains(character) {
continue
}
if characters[character] == 1 {
return character
}
seen.insert(character)
}
return nil
}
// Given a string, return the last non-repeating character. If there is no such character, return nil.
// getLastNonRepeatingCharacter(string: "abcdb") == "b"
// getLastNonRepeatingCharacter(string: "Jerry") == "J"
// getLastNonRepeatingCharacter(string: "abcaab") == nil
func getLastNonRepeatingCharacter(string: String) -> Character? {
var characters = [Character: Int]()
for character in string {
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string.reversed() {
if characters[character] == 1 {
return character
}
}
return nil
}
// Given a string, return the last non-repeating character that appears before a specific character.
// If there is no such character, return nil.
// getLastNonRepeatingCharacter(string: "abcdb", startingBefore: "b") == "a"
// getLastNonRepeatingCharacter(string: "Jerry", startingBefore: "J") == nil
// getLastNonRepeatingCharacter(string: "abcaab", startingBefore: "b") == nil
func getLastNonRepeatingCharacter(string: String, startingBefore: Character) -> Character? {
var characters = [Character: Int]()
var seen = Set<Character>()
for character in string.reversed() {
if character == startingBefore {
continue
}
if let count = characters[character] {
characters[character] = count + 1
} else {
characters[character] = 1
}
}
for character in string.reversed() {
if character == startingBefore || seen.contains(character) {
continue
}
if characters[character] == 1 {
return character
}
seen.insert(character)
}
return nil
}
// Given a string, return the longest substring that does not contain repeating characters.
// getLongestSubstringWithoutRepeatingCharacters(string: "abcdb") == "abc"
// getLongestSubstringWithoutRepeatingCharacters(string: "Jerry") == "Jer"
// getLongestSubstringWithoutRepeatingCharacters(string: "abcaab") == "abca"
func getLongestSubstringWithoutRepeatingCharacters
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var characters = Set<Character>()
for character in string {
characters.insert(character)
}
return characters.count
}
func getProductsOfAllOtherNumbers(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *= input[index]
}
var rightProduct = 1
for index in (0..<input.count).reversed() {
products[index] *= rightProduct
rightProduct *= input[index]
}
return products
}
func getProductsOfAllOtherNumbersConstantSpace(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *= input[index]
}
var rightProduct = 1
for index in (0..<input.count).reversed() {
products[index] *= rightProduct
rightProduct *= input[index]
}
return products
}
func getProductsOfAllOtherNumbersConstantSpaceV2(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *= input[index]
}
var rightProduct = 1
for index in (0..<input.count).reversed() {
products[index] *= rightProduct
rightProduct *= input[index]
}
return products
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var characters = Set<Character>()
for character in string {
characters.insert(character)
}
return characters.count
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherNumbers(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *= input[index]
}
var rightProduct = 1
for index in (0..<input.count).reversed() {
products[index] *= rightProduct
rightProduct *= input[index]
}
return products
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherNumbersConstantSpace(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *= input[index]
}
var rightProduct = 1
for index in (0..<input.count).reversed() {
products[index] *= rightProduct
rightProduct *= input[index]
}
return products
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherNumbersConstantSpaceV2(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *= input[index]
}
var rightProduct = 1
for index in (0..<input.count).reversed() {
products[index] *= rightProduct
rightProduct *= input[index]
}
return products
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherNumbersConstantSpaceV3(input: [Int]) -> [Int] {
var products = [Int](repeating: 1, count: input.count)
var leftProduct = 1
for index in 0..<input.count {
products[index] = leftProduct
leftProduct *=
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
func getProductsOfAllOtherElements(input: [Int]) -> [Int] {
var products = [1]
for i in 1..<input.count {
products.append(products[i - 1] * input[i - 1])
}
var rightProduct = 1
var output = [Int]()
for i in (0..<input.count).reversed() {
output.append(rightProduct)
rightProduct *= input[i]
if i > 0 {
output[i] *= products[i - 1]
}
}
return output
}
func checkPermutation(s1: String, s2: String) -> Bool {
guard s1.count == s2.count else {
return false
}
var charCounts = [Character: Int]()
for character in s1 {
charCounts[character, default: 0] += 1
}
for character in s2 {
charCounts[character, default: 0] -= 1
if charCounts[character] == -1 {
return false
}
}
return true
}
func checkPermutation2(s1: String, s2: String) -> Bool {
guard s1.count == s2.count else {
return false
}
var charCounts = [Character: Int]()
for (i, character) in s1.enumerated() {
charCounts[character, default: 0] += 1
if charCounts[character] == 2 {
charCounts[character] = 0
} else {
charCounts[character] = 1
}
}
for (i, character) in s2.enumerated() {
charCounts[character, default: 0] -= 1
if charCounts[character] == -2 {
charCounts[character] = 0
} else {
charCounts[character] = -1
}
if charCounts[character] == 1 {
return false
}
}
return true
}
func checkPermutation3(s1: String, s2: String) -> Bool {
guard s1.count == s2.count else {
return false
}
var charCounts = [Character: Int]()
for character in s1 {
charCounts[character, default: 0] += 1
}
for character in s2 {
charCounts[character, default: 0] -= 1
if charCounts[character] == 0 {
charCounts[character] = -1
} else if charCounts[character] == -1 {
return false
}
}
return true
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var distinctCharacters = Set<Character>()
for character in string {
distinctCharacters.insert(character)
}
return distinctCharacters.count
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Note: You will not solve this problem without using division.
// Example:
// Input: [1, 2, 3, 4, 5]
// Output: [120, 60, 40, 30, 24]
// Follow-up: Can you solve it with constant space complexity? (Note: The output array does not count as extra space for space complexity analysis.)
func getProductsOfAllOtherElements(input: [Int]) -> [Int] {
var products = [1]
for i in 1..<input.count {
products.append(products[i - 1] * input[i - 1])
}
var rightProduct = 1
var output = [Int]()
for i in (0..<input.count).reversed() {
output.append(rightProduct)
rightProduct *= input[i]
if i > 0 {
output[i] *= products[i - 1]
}
}
return output
}
// Given two strings, write a method to decide if one is a permutation of the other.
// Example:
// s1 = "abcd"
// s2 = "dcab"
// Return true.
// s1 = "abcd"
// s2 = "dabc"
// Return false.
func checkPermutation(s1: String, s2: String) -> Bool {
guard s1.count == s2.count else {
return false
}
var charCounts = [Character: Int]()
for character in s1 {
charCounts[character, default: 0] += 1
}
for character in s2 {
charCounts[character, default: 0] -= 1
if charCounts[character] == -1 {
return false
}
}
return true
}
// Given two strings, write a method to decide if one is a permutation of the other.
// Example:
// s1 = "abcd"
// s2 = "dcab"
// Return true.
// s1 = "abcd"
// s2 = "dabc"
// Return false.
func checkPermutation2(s1: String, s2: String) -> Bool {
guard s1.count == s2.count else {
return false
}
var charCounts = [Character: Int]()
for (i, character) in s1.enumerated() {
charCounts[character, default: 0] += 1
if charCounts[character] == 2 {
charCounts[character] = 0
} else {
charCounts[character] = 1
}
}
for (i, character) in s2.enumerated() {
charCounts[character, default: 0] -= 1
if charCounts[character] == -2 {
charCounts[character] = 0
} else {
charCounts[character] = -1
}
if charCounts[character] == 1 {
return false
}
}
return true
}
// Given two strings, write a method to decide if one is a permutation of the other.
// Example:
// s1 = "abcd"
// s2 = "dcab"
// Return true.
// s1 = "abcd"
// s2 = "dabc"
// Return false.
func checkPermutation3(s1: String, s2: String) -> Bool {
guard s1.count == s2.count else {
return false
}
var charCounts = [Character: Int]()
for character in s1 {
charCounts[character, default: 0] += 1
}
for character in s2 {
charCounts[character, default: 0] -= 1
if charCounts[character] == 0 {
charCounts[character] = -1
} else if charCounts[character] == -1 {
return false
}
}
return true
}
// Given two strings, write a method to decide if one is a permutation of the other.
// Example:
// s1 = "abcd"
// s2 = "dcab"
// Return true.
//
for (i, character) in s1.enumerated() { // immutable value 'i' was never used; consider replacing with '_' or removing it
for (i, character) in s2.enumerated() { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
result.append(currentBeat)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o|.| o| o|.|.|.|.| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
break
}
result.append(currentBeat)
}
return result
}
// Example usage
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats)
// Output: [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
let musicString2 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats2 = parseMusic(musicString: musicString2)
print(beats2)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString3 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var beatCount = 0
for char in musicString {
if char == "o" {
beatCount += 4
} else if char == "o|" {
beatCount += 2
} else if char == "." {
beatCount += 1
}
result.append(beatCount)
}
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 beatCount = 0
for char in musicString {
if char == "o" {
beatCount += 4
} else if char == "o|" {
beatCount += 2
} else if char == "." {
beatCount += 1
}
result.append(beatCount)
}
return result
}
// Tests
assert(parseMusic(musicString: "o o|.| o| o|.|.|.|.| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4])
assert(parseMusic(musicString: "o. o| o. o| o. o| o. o| o. o| o. o| o. o| o. o") == [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4])
assert(parseMusic(musicString: "o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o| o o") == [4, 4, 4, 4, 4, 4, 4,
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for char in musicString {
if char == "o" {
currentBeat += 4
} else if char == "o|" {
currentBeat += 2
} else if char == "." {
currentBeat += 1
}
result.append(currentBeat)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o|.| o| o|.|.|.|.| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for char in musicString {
if char == "o" {
currentBeat += 4
} else if char == "o|" {
currentBeat += 2
} else if char == "." {
currentBeat += 1
}
result.append(currentBeat)
}
return result
}
// Example usage
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats)
// Additional edge case tests
let edgeCase1 = "o o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o|
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var beats = [Int]()
var beat = 0
for char in musicString {
switch char {
case "o":
beat += 4
case "o|":
beat += 2
case ".|":
beat += 1
default:
break
}
beats.append(beat)
}
return beats
}
func parseMusic(musicArray: [Int]) -> String {
var musicString = ""
for beat in musicArray {
switch beat {
case 4:
musicString += "o"
case 2:
musicString += "o|"
case 1:
musicString += ".|"
default:
break
}
}
return musicString
}
func countTotalBeats(musicString: String) -> Int {
var totalBeats = 0
for char in musicString {
switch char {
case "o":
totalBeats += 4
case "o|":
totalBeats += 2
case ".|":
totalBeats += 1
default:
break
}
}
return totalBeats
}
func countTotalBeats(musicArray: [Int]) -> Int {
var totalBeats = 0
for beat in musicArray {
totalBeats += beat
}
return totalBeats
}
func countQuarterNotes(musicString: String) -> Int {
var quarterNotes = 0
for char in musicString {
switch char {
case ".|":
quarterNotes += 1
default:
break
}
}
return quarterNotes
}
```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]()
var beat = 0
for char in musicString {
switch char {
case "o":
beat += 4
case "o|":
beat += 2
case ".|":
beat += 1
default:
break
}
beats.append(beat)
}
return beats
}
// Input to this function is an array of integers representing musical notes in a special ASCII format.
// Your task is to parse this array and return string representing the same notes in a special format,
// but now with the length of each note represented in beats.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicArray: [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]) == "o o|.| o| o|.|.|.|.| o o"
func parseMusic(musicArray: [Int]) -> String {
var musicString = ""
for beat in musicArray {
switch beat {
case 4:
musicString += "o"
case 2:
musicString += "o|"
case 1:
musicString += ".|"
default:
break
}
}
return musicString
}
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return the total number of beats in the song.
// 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") == 32
func countTotalBeats(musicString: String) -> Int {
var totalBeats = 0
for char in musicString {
switch char {
case "o":
totalBeats += 4
case "o|":
totalBeats += 2
case ".|":
totalBeats += 1
default:
break
}
}
return totalBeats
}
// Input to this function is an array of integers representing musical notes in a special ASCII format.
// Your task is to parse this array and return the total number of beats in the song.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// countTotalBeats(musicArray: [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]) == 32
func countTotalBeats(musicArray: [Int]) -> Int {
var totalBeats = 0
for beat in musicArray {
totalBeats += beat
}
return totalBeats
}
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return the total number of quater notes in the song.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// countQuarterNotes(musicString: "o o|.| o| o|.|.|.|.| o o") == 8
func countQuarterNotes(musicString: String) -> Int {
var quarterNotes = 0
for char in musicString {
switch char {
case ".|":
quarterNotes += 1
default:
break
}
}
return quarterNotes
}
// Input to this function is an array of integers representing musical notes in a special ASCII format.
// Your task is to parse this array and return the total number of quater notes in the song.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// countQuarterNotes(musicArray: [
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var beats = [Int]()
var beat = 0
for char in musicString {
switch char {
case "o":
beat += 4
case "o|":
beat += 2
case ".|":
beat += 1
default:
break
}
beats.append(beat)
}
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]()
var beat = 0
for char in musicString {
switch char {
case "o":
beat += 4
case "o|":
beat += 2
case ".|":
beat += 1
default:
break
}
beats.append(beat)
}
return beats
}
// Example usage:
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats) // [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
```
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var beatCount = 0
for char in musicString {
switch char {
case "o":
beatCount += 4
case "o|":
beatCount += 2
case ".|":
beatCount += 1
default:
break
}
result.append(beatCount)
}
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 beatCount = 0
for char in musicString {
switch char {
case "o":
beatCount += 4
case "o|":
beatCount += 2
case ".|":
beatCount += 1
default:
break
}
result.append(beatCount)
}
return result
}
// Example usage
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats)
// Output: [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
let musicString2 = "o o o| o o o| o o o| o o o| o o o| o o o"
let beats2 = parseMusic(musicString: musicString2)
print(beats2)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString3 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats3 = parseMusic(musicString: musicString3)
print(beats3)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString4 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats4 = parseMusic(musicString: musicString4)
print(beats4)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString5 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats5 = parseMusic(musicString: musicString5)
print(beats5)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString6 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats6 = parseMusic(musicString: musicString6)
print(beats6)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString7 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats7 = parseMusic(musicString: musicString7)
print(beats7)
// Output: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4]
let musicString8 = "o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o| o o o"
let beats8 = parseMusic(musicString
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
continue
}
result.append(currentBeat)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o|.| o| o|.|.|.|.| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var currentBeat = 0
for char in musicString {
switch char {
case "o":
currentBeat += 4
case "o|":
currentBeat += 2
case ".|":
currentBeat += 1
default:
continue
}
result.append(currentBeat)
}
return result
}
// Example usage
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats) // [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
// Additional test cases
let test1 = "o o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var beatCount = 0
for char in musicString {
switch char {
case "o":
beatCount += 4
case "o|":
beatCount += 2
case ".|":
beatCount += 1
default:
break
}
result.append(beatCount)
}
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 beatCount = 0
for char in musicString {
switch char {
case "o":
beatCount += 4
case "o|":
beatCount += 2
case ".|":
beatCount += 1
default:
break
}
result.append(beatCount)
}
return result
}
// Example usage
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats)
// Output: [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
// Another example usage
let anotherMusicString = "o o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o| o|
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
case ".|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
var result = [Int]()
var beatCount = 0
for char in musicString {
if char == "o" {
beatCount += 4
} else if char == "o|" {
beatCount += 2
} else if char == "." {
beatCount += 1
}
result.append(beatCount)
}
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 beatCount = 0
for char in musicString {
if char == "o" {
beatCount += 4
} else if char == "o|" {
beatCount += 2
} else if char == "." {
beatCount += 1
}
result.append(beatCount)
}
return result
}
// Tests
assert(parseMusic(musicString: "o o|.| o| o|.|.|.|.| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1])
assert(parseMusic(musicString: "o o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o| o. o. o") == [4, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2,
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func parseMusic(musicString: String) -> [Int] {
var result: [Int] = []
var beatCount = 0
for char in musicString {
if char == "o" {
beatCount += 4
} else if char == "o|" {
beatCount += 2
} else if char == "." {
beatCount += 1
}
result.append(beatCount)
}
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 beatCount = 0
for char in musicString {
if char == "o" {
beatCount += 4
} else if char == "o|" {
beatCount += 2
} else if char == "." {
beatCount += 1
}
result.append(beatCount)
}
return result
}
// Example usage
let musicString = "o o|.| o| o|.|.|.|.| o o"
let beats = parseMusic(musicString: musicString)
print(beats) // [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
```
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'Character' and 'String'
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
if string[i] == substring[0] {
var isMatch = true
for j in 1..<substring.count {
if string[i + j]!= substring[j] {
isMatch = false
break
}
}
if isMatch {
count += 1
}
}
}
return count
}
func longestNonDuplicateSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string[i..<j])
if substring.count > longest.count && isUnique(string: substring) {
longest = substring
}
}
}
return longest
}
func isUnique(string: String) -> Bool {
var chars = [Character: Bool]()
for char in string {
if chars[char] == nil {
chars[char] = true
} else {
return false
}
}
return true
}
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
func isPalindrome(string: String) -> Bool {
return reverse(string: string) == string
}
func removeDuplicates(string: String) -> String {
var result = ""
var chars = [Character: Bool]()
for char in string {
if chars[char] == nil {
chars[char] = true
result += "\(char)"
}
}
return result
}
func removeSpaces(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
func isValidNumber(string: String) -> Bool {
return string.range(of: "^[0-9]+$", options:.regularExpression)!= nil
}
func isValidEmail(string: String) -> Bool {
return string.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}", options:.regularExpression)!= nil
}
```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 {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
if string[i] == substring[0] {
var isMatch = true
for j in 1..<substring.count {
if string[i + j]!= substring[j] {
isMatch = false
break
}
}
if isMatch {
count += 1
}
}
}
return count
}
// Find the longest substring in a given string that does not contain duplicate characters.
// longestNonDuplicateSubstring(string: "abcabcbb") == "abc"
// longestNonDuplicateSubstring(string: "bbbbb") == "b"
// longestNonDuplicateSubstring(string: "pwwkew") == "wke"
func longestNonDuplicateSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
for j in i..<string.count {
let substring = String(string[i..<j])
if substring.count > longest.count && isUnique(string: substring) {
longest = substring
}
}
}
return longest
}
// Check if a given string contains only unique characters.
// isUnique(string: "abc") == true
// isUnique(string: "aaa") == false
// isUnique(string: "aabc") == false
func isUnique(string: String) -> Bool {
var chars = [Character: Bool]()
for char in string {
if chars[char] == nil {
chars[char] = true
} else {
return false
}
}
return true
}
// Reverse a given string.
// reverse(string: "Hello, World!") == "!dlroW,olleH"
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
// Check if a given string is a palindrome.
// isPalindrome(string: "racecar") == true
// isPalindrome(string: "hello") == false
func isPalindrome(string: String) -> Bool {
return reverse(string: string) == string
}
// Remove duplicate characters from a given string.
// removeDuplicates(string: "abcdcba") == "abcda"
// removeDuplicates(string: "aabbcc") == "abc"
func removeDuplicates(string: String) -> String {
var result = ""
var chars = [Character: Bool]()
for char in string {
if chars[char] == nil {
chars[char] = true
result += "\(char)"
}
}
return result
}
// Remove spaces from a given string.
// removeSpaces(string: "Hello, World!") == "HelloWorld"
// removeSpaces(string: " Hello, World! ") == "HelloWorld"
func removeSpaces(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
// Check if a given string is a valid number.
// isValidNumber(string: "123") == true
// isValidNumber(string: "12a3") == false
// isValidNumber(string: "12 3") == false
func isValidNumber(string: String) -> Bool {
return string.range(of: "^[0-9]+$", options:.regularExpression)!= nil
}
// Check if a given string is a valid email address.
// isValidEmail(string: "[email protected]") == true
// isValidEmail(string: "example@example") == false
// isValidEmail(string: "[email protected]") == false
func isValidEmail(string: String) -> Bool {
return string.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}", options:.regularExpression)!= nil
}
// Check if a given string is a valid phone number.
// isValidPhoneNumber(string: "555-555-5555") == true
// isValidPhoneNumber
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
let substring = String(string[i..<j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
return string.range(of: "^[0-9]+$", options:.regularExpression)!= nil // '=' must have consistent whitespace on both sides
return string.range(of: "^[0-9]+$", options:.regularExpression)!= nil // cannot assign through '!': function call returns immutable value
return string.range(of: "^[0-9]+$", options:.regularExpression)!= nil // use of '=' in a boolean context, did you mean '=='?
return string.range(of: "^[0-9]+$", options:.regularExpression)!= nil // 'nil' cannot be assigned to type 'Range<String.Index>'
return string.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}", options:.regularExpression)!= nil // cannot assign through '!': function call returns immutable value
return string.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}", options:.regularExpression)!= nil // '=' must have consistent whitespace on both sides
return string.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}", options:.regularExpression)!= nil // use of '=' in a boolean context, did you mean '=='?
return string.range(of: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}", options:.regularExpression)!= nil // 'nil' cannot be assigned to type 'Range<String.Index>'
func howManyTimes(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(index!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.firstIndex(of: substring.first!, range: index!.range(of: substring))
}
return count
}
func howManyTimes2(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(index!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.index(of: substring.first!, range: index!.range(of: substring))
}
return count
}
func howManyTimes3(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(of: substring.first!, range: index!.range(of: substring))
}
return count
}
func howManyTimes4(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.index(of: substring.first!, range: index!.range(of: substring))
}
return count
}
func howManyTimes5(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: index!)
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(index!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.firstIndex(of: substring.first!, range: index!.range(of: substring))
}
return count
}
// 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 howManyTimes2(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(index!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.index(of: substring.first!, range: index!.range(of: substring))
}
return count
}
// 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 howManyTimes3(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(of: substring.first!, range: index!.range(of: substring))
}
return count
}
// 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 howManyTimes4(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.index(of: substring.first!, range: index!.range(of: substring))
}
return count
}
// 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 howManyTimes5(string: String, substring: String) -> Int {
guard!string.isEmpty &&!substring.isEmpty else { return 0 }
var count = 0
var index = string.firstIndex(of: substring.first!)
while index!= nil {
count += 1
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: string.endIndex)
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: index!)
}
return count
}
// 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 howManyTimes6(string: String, substring: String
guard!string.isEmpty &&!substring.isEmpty else { return 0 } // expected expression, var, let or case in 'guard' condition
while index!= nil { // use of '=' in a boolean context, did you mean '=='?
while index!= nil { // 'nil' cannot be assigned to type 'String.Index'
while index!= nil { // '=' must have consistent whitespace on both sides
index = string.firstIndex(of: substring.first!, range: index!.range(of: substring)) // value of type 'String.Index' has no member 'range'
index = string.firstIndex(of: substring.first!, range: index!.range(of: substring)) // extra argument 'range' in call
guard!string.isEmpty &&!substring.isEmpty else { return 0 } // expected expression, var, let or case in 'guard' condition
while index!= nil { // use of '=' in a boolean context, did you mean '=='?
while index!= nil { // 'nil' cannot be assigned to type 'String.Index'
while index!= nil { // '=' must have consistent whitespace on both sides
index = string.index(of: substring.first!, range: index!.range(of: substring)) // value of type 'String.Index' has no member 'range'
index = string.index(of: substring.first!, range: index!.range(of: substring)) // extra argument 'range' in call
guard!string.isEmpty &&!substring.isEmpty else { return 0 } // expected expression, var, let or case in 'guard' condition
while index!= nil { // 'nil' cannot be assigned to type 'String.Index'
while index!= nil { // '=' must have consistent whitespace on both sides
while index!= nil { // use of '=' in a boolean context, did you mean '=='?
index = string.index(of: substring.first!, range: index!.range(of: substring)) // value of type 'String.Index' has no member 'range'
index = string.index(of: substring.first!, range: index!.range(of: substring)) // extra argument 'range' in call
guard!string.isEmpty &&!substring.isEmpty else { return 0 } // expected expression, var, let or case in 'guard' condition
while index!= nil { // 'nil' cannot be assigned to type 'String.Index'
while index!= nil { // '=' must have consistent whitespace on both sides
while index!= nil { // use of '=' in a boolean context, did you mean '=='?
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: string.endIndex) // no exact matches in call to instance method 'index'
index = string.index(of: substring.first!, range: index!.range(of: substring)) // value of type 'String.Index' has no member 'range'
index = string.index(of: substring.first!, range: index!.range(of: substring)) // extra argument 'range' in call
guard!string.isEmpty &&!substring.isEmpty else { return 0 } // expected expression, var, let or case in 'guard' condition
while index!= nil { // use of '=' in a boolean context, did you mean '=='?
while index!= nil { // 'nil' cannot be assigned to type 'String.Index'
while index!= nil { // '=' must have consistent whitespace on both sides
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: string.endIndex) // no exact matches in call to instance method 'index'
index = string.index(of: substring.first!, offsetBy: substring.count, limitedBy: index!) // no exact matches in call to instance method 'index'
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var match = true
for j in 0..<substring.count {
if string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
}
}
return count
}
func longestUniqueSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
var current = ""
var seen = [Character: Int]()
for char in string {
if let lastIndex = seen[char] {
if current.count > longest.count {
longest = current
}
current = String(Array(string)[lastIndex...])
}
current += String(char)
seen[char] = current.count - 1
}
if current.count > longest.count {
longest = current
}
return longest
}
func longestPalindrome(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
let odd = longestPalindromeFrom(i, i, string)
let even = longestPalindromeFrom(i, i + 1, string)
let candidate = odd.count > even.count? odd : even
if candidate.count > longest.count {
longest = candidate
}
}
return longest
}
func longestPalindromeFrom(_ left: Int, _ right: Int, _ string: String) -> String {
var longest = ""
while left >= 0 && right < string.count && string[left] == string[right] {
let candidate = String(Array(string)[left...right])
if candidate.count > longest.count {
longest = candidate
}
left -= 1
right += 1
}
return longest
}
func smallestSubstring(string: String, characters: String) -> String {
guard string.count > 0 && characters.count > 0 else { return "" }
var smallest = ""
for i in 0...string.count - characters.count {
var match = true
for j in 0..<characters.count {
if string[i + j]!= characters[j] {
match = false
break
}
}
if match {
if smallest.count == 0 || smallest.count > i + characters.count {
smallest = String(Array(string)[i...i + characters.count - 1])
}
}
}
return smallest
}
```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 {
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var match = true
for j in 0..<substring.count {
if string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
}
}
return count
}
// Find the longest substring of a given string that only contains unique characters.
// longestUniqueSubstring(string: "abcabcbb") == "abc"
// longestUniqueSubstring(string: "bbbbb") == "b"
// longestUniqueSubstring(string: "pwwkew") == "wke"
func longestUniqueSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
var current = ""
var seen = [Character: Int]()
for char in string {
if let lastIndex = seen[char] {
if current.count > longest.count {
longest = current
}
current = String(Array(string)[lastIndex...])
}
current += String(char)
seen[char] = current.count - 1
}
if current.count > longest.count {
longest = current
}
return longest
}
// Find the longest palindrome in a given string.
// longestPalindrome(string: "babad") == "bab"
// longestPalindrome(string: "cbbd") == "bb"
// longestPalindrome(string: "a") == "a"
// longestPalindrome(string: "ac") == "a"
func longestPalindrome(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
let odd = longestPalindromeFrom(i, i, string)
let even = longestPalindromeFrom(i, i + 1, string)
let candidate = odd.count > even.count? odd : even
if candidate.count > longest.count {
longest = candidate
}
}
return longest
}
func longestPalindromeFrom(_ left: Int, _ right: Int, _ string: String) -> String {
var longest = ""
while left >= 0 && right < string.count && string[left] == string[right] {
let candidate = String(Array(string)[left...right])
if candidate.count > longest.count {
longest = candidate
}
left -= 1
right += 1
}
return longest
}
// Find the smallest substring of a given string that contains all the characters of a second string.
// smallestSubstring(string: "abcdabcdefg", characters: "bcd") == "bcd"
// smallestSubstring(string: "abcdabcdefg", characters: "z") == ""
// smallestSubstring(string: "abcdefg", characters: "abcdefg") == "abcdefg"
func smallestSubstring(string: String, characters: String) -> String {
guard string.count > 0 && characters.count > 0 else { return "" }
var smallest = ""
for i in 0...string.count - characters.count {
var match = true
for j in 0..<characters.count {
if string[i + j]!= characters[j] {
match = false
break
}
}
if match {
if smallest.count == 0 || smallest.count > i + characters.count {
smallest = String(Array(string)[i...i + characters.count - 1])
}
}
}
return smallest
}
// Find the longest common substring between two strings.
// longestCommonSubstring(string1: "abcdxyz", string2: "xyzabcd") == "xyz"
// longestCommonSubstring(string1: "abcd", string2: "xyz") == ""
// longestCommonSubstring(string1: "abcde", string2: "acfgh") == "acfgh"
func longestCommonSubstring(string1: String, string2: String) -> String {
guard string1.count > 0 && string2.count > 0 else { return "" }
var longest = ""
for i in 0...string1.count - 1
if string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
let candidate = odd.count > even.count? odd : even // expected expression
let candidate = odd.count > even.count? odd : even // consecutive statements on a line must be separated by ';'
let candidate = odd.count > even.count? odd : even // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let candidate = odd.count > even.count? odd : even // expression of type 'String' is unused
let candidate = odd.count > even.count? odd : even // cannot use optional chaining on non-optional value of type 'Int'
let candidate = odd.count > even.count? odd : even // consecutive statements on a line must be separated by ';'
while left >= 0 && right < string.count && string[left] == string[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while left >= 0 && right < string.count && string[left] == string[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
left -= 1 // left side of mutating operator isn't mutable: 'left' is a 'let' constant
right += 1 // left side of mutating operator isn't mutable: 'right' is a 'let' constant
if string[i + j]!= characters[j] { // use of '=' in a boolean context, did you mean '=='?
if string[i + j]!= characters[j] { // '=' must have consistent whitespace on both sides
if string[i + j]!= characters[j] { // cannot force unwrap value of non-optional type 'Character'
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0...(string.count - substring.count) {
if string[i..<i+substring.count] == substring {
count += 1
}
}
return count
}
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0...a.count {
for j in 0...b.count {
if i + j > longest.count {
let substring = a[i..<i+j]
if howManyTimes(string: b, substring: substring) > 0 {
longest = substring
}
}
}
}
return longest
}
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0...a.count {
for j in 0...b.count {
if i + j > longest.count {
let substring = a[i..<i+j]
if howManyTimes(string: b, substring: substring) == 1 {
longest = substring
}
}
}
}
return longest
}
func shortestCommonSupersequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var shortest = ""
for i in 0...a.count {
for j in 0...b.count {
if i + j < shortest.count {
let substring = a[i..<i+j]
if howManyTimes(string: b, substring: substring) == 1 {
shortest = substring
}
}
}
}
return shortest
}
func longestPalindromeSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0...string.count {
for j in 0...i {
let substring = string[i-j..<i]
if substring == String(substring.reversed()) && substring.count > longest.count {
longest = substring
}
}
}
return longest
}
```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 {
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0...(string.count - substring.count) {
if string[i..<i+substring.count] == substring {
count += 1
}
}
return count
}
// Find the longest common substring between two strings.
// longestCommonSubstring(a: "abcba", b: "abccba") == "bcb"
// longestCommonSubstring(a: "abcd", b: "efgh") == ""
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0...a.count {
for j in 0...b.count {
if i + j > longest.count {
let substring = a[i..<i+j]
if howManyTimes(string: b, substring: substring) > 0 {
longest = substring
}
}
}
}
return longest
}
// Find the longest common subsequence between two strings.
// longestCommonSubsequence(a: "abc", b: "def") == "def"
// longestCommonSubsequence(a: "abc", b: "defg") == "defg"
// longestCommonSubsequence(a: "abc", b: "abef") == "abef"
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0...a.count {
for j in 0...b.count {
if i + j > longest.count {
let substring = a[i..<i+j]
if howManyTimes(string: b, substring: substring) == 1 {
longest = substring
}
}
}
}
return longest
}
// Find the shortest common supersequence between two strings.
// shortestCommonSupersequence(a: "abcd", b: "efgh") == "abcdefgh"
// shortestCommonSupersequence(a: "abc", b: "defg") == "abcdefg"
// shortestCommonSupersequence(a: "abc", b: "abef") == "abcdef"
func shortestCommonSupersequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var shortest = ""
for i in 0...a.count {
for j in 0...b.count {
if i + j < shortest.count {
let substring = a[i..<i+j]
if howManyTimes(string: b, substring: substring) == 1 {
shortest = substring
}
}
}
}
return shortest
}
// Find the longest palindrome substring in a string.
// longestPalindromeSubstring(string: "babad") == "bab"
// longestPalindromeSubstring(string: "cbbd") == "bb"
func longestPalindromeSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0...string.count {
for j in 0...i {
let substring = string[i-j..<i]
if substring == String(substring.reversed()) && substring.count > longest.count {
longest = substring
}
}
}
return longest
}
// Find the longest palindrome subsequence in a string.
// longestPalindromeSubsequence(string: "babad") == "bab"
// longestPalindromeSubsequence(string: "cbbd") == "bb"
func longestPalindromeSubsequence(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0...string.count {
for j in 0...i {
let substring = string[i-j..<i]
if substring == String(substring.reversed()) && substring.count > longest.count {
longest = substring
}
}
}
return
if string[i..<i+substring.count] == substring { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let substring = a[i..<i+j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let substring = a[i..<i+j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let substring = a[i..<i+j] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let substring = string[i-j..<i] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
if string[i..<i + substring.count] == substring {
count += 1
}
}
return count
}
func longestUniqueSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
var current = ""
var seen = [Character: Int]()
for char in string {
if let seenIndex = seen[char] {
if current.count > longest.count {
longest = current
}
current = String(Array(string)[seenIndex...])
}
current.append(char)
seen[char] = current.count
}
if current.count > longest.count {
longest = current
}
return longest
}
func longestCommonPrefix(_ strings: [String]) -> String {
guard strings.count > 0 else { return "" }
var prefix = strings[0]
for i in 1..<strings.count {
while!strings[i].hasPrefix(prefix) {
prefix = String(prefix.dropLast())
if prefix.isEmpty {
return ""
}
}
}
return prefix
}
func squared(_ numbers: [Int]) -> [Int] {
var squared = [Int]()
for number in numbers {
squared.append(number * number)
}
return squared
}
func cubed(_ numbers: [Int]) -> [Int] {
var cubed = [Int]()
for number in numbers {
cubed.append(number * number * number)
}
return cubed
}
func incrementedByOne(_ numbers: [Int]) -> [Int] {
var incremented = [Int]()
for number in numbers {
incremented.append(number + 1)
}
return incremented
}
func decrementedByOne(_ numbers: [Int]) -> [Int] {
var decremented = [Int]()
for number in numbers {
decremented.append(number - 1)
}
return decremented
}
```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 {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
if string[i..<i + substring.count] == substring {
count += 1
}
}
return count
}
// Find the longest substring of a given string that only contains unique characters.
// longestUniqueSubstring(string: "abcabcbb") == "abc"
// longestUniqueSubstring(string: "bbbbb") == "b"
// longestUniqueSubstring(string: "pwwkew") == "wke"
func longestUniqueSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
var current = ""
var seen = [Character: Int]()
for char in string {
if let seenIndex = seen[char] {
if current.count > longest.count {
longest = current
}
current = String(Array(string)[seenIndex...])
}
current.append(char)
seen[char] = current.count
}
if current.count > longest.count {
longest = current
}
return longest
}
// Find the longest common prefix in an array of strings.
// longestCommonPrefix(["flower", "flow", "flight", "fleet"]) == "fl"
// longestCommonPrefix(["dog", "racecar", "car"]) == ""
func longestCommonPrefix(_ strings: [String]) -> String {
guard strings.count > 0 else { return "" }
var prefix = strings[0]
for i in 1..<strings.count {
while!strings[i].hasPrefix(prefix) {
prefix = String(prefix.dropLast())
if prefix.isEmpty {
return ""
}
}
}
return prefix
}
// Given an array of integers, return a new array of the same length that contains the original values squared.
// Example:
// squared([-1, 2, 3]) == [1, 4, 9]
// squared([0, 1, 5]) == [0, 1, 25]
func squared(_ numbers: [Int]) -> [Int] {
var squared = [Int]()
for number in numbers {
squared.append(number * number)
}
return squared
}
// Given an array of integers, return a new array of the same length that contains the original values cubed.
// Example:
// cubed([-1, 2, 3]) == [-1, 8, 27]
// cubed([0, 1, 5]) == [0, 1, 125]
func cubed(_ numbers: [Int]) -> [Int] {
var cubed = [Int]()
for number in numbers {
cubed.append(number * number * number)
}
return cubed
}
// Given an array of integers, return a new array of the same length that contains the original values incremented by 1.
// incrementedByOne([-1, 2, 3]) == [0, 3, 4]
// incrementedByOne([0, 1, 5]) == [1, 2, 6]
func incrementedByOne(_ numbers: [Int]) -> [Int] {
var incremented = [Int]()
for number in numbers {
incremented.append(number + 1)
}
return incremented
}
// Given an array of integers, return a new array of the same length that contains the original values decremented by 1.
// decrementedByOne([-1, 2, 3]) == [-2, 1, 2]
// decrementedByOne([0, 1, 5]) == [-1, 0, 4]
func decrementedByOne(_ numbers: [Int]) -> [Int] {
var decremented = [Int]()
for number in numbers {
decremented.append(number - 1)
}
return decremented
}
// Given an array of integers, return a new array of the same length that contains the original values multiplied by 2.
// multipliedByTwo([-1, 2, 3]) == [-2,
if string[i..<i + substring.count] == substring { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
while!strings[i].hasPrefix(prefix) { // expected expression, var, or let in 'while' condition
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var isFound = true
for j in 0..<substring.count {
if string[i + j]!= substring[j] {
isFound = false
break
}
}
if isFound {
count += 1
}
}
return count
}
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var isFound = true
while isFound && i + k < a.count && j + k < b.count {
if a[i + k]!= b[j + k] {
isFound = false
}
k += 1
}
if isFound && k > longest.count {
longest = String(a[i..<i + k])
}
}
}
}
return longest
}
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var isFound = true
while isFound && i + k < a.count && j + k < b.count {
if a[i + k]!= b[j + k] {
isFound = false
}
k += 1
}
if isFound && k > longest.count {
longest = String(a[i..<i + k])
}
}
}
}
return longest
}
func shortestCommonSupersequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var shortest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var isFound = true
while isFound && i + k < a.count && j + k < b.count {
if a[i + k]!= b[j + k] {
isFound = false
}
k += 1
}
if isFound && k < shortest.count {
shortest = String(a[i..<i + k])
}
}
}
}
if shortest.count == 0 {
shortest = a + b
}
return shortest
}
```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 {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var isFound = true
for j in 0..<substring.count {
if string[i + j]!= substring[j] {
isFound = false
break
}
}
if isFound {
count += 1
}
}
return count
}
// Find the longest common substring between two strings.
// longestCommonSubstring(a: "abcba", b: "abccba") == "bcb"
// longestCommonSubstring(a: "abcba", b: "dcba") == "a"
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var isFound = true
while isFound && i + k < a.count && j + k < b.count {
if a[i + k]!= b[j + k] {
isFound = false
}
k += 1
}
if isFound && k > longest.count {
longest = String(a[i..<i + k])
}
}
}
}
return longest
}
// Find the longest common subsequence between two strings.
// longestCommonSubsequence(a: "abcba", b: "abccba") == "bcb"
// longestCommonSubsequence(a: "abcba", b: "dcba") == "abcba"
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var isFound = true
while isFound && i + k < a.count && j + k < b.count {
if a[i + k]!= b[j + k] {
isFound = false
}
k += 1
}
if isFound && k > longest.count {
longest = String(a[i..<i + k])
}
}
}
}
return longest
}
// Find the shortest common supersequence between two strings.
// shortestCommonSupersequence(a: "abcba", b: "abccba") == "abcbacbccba"
// shortestCommonSupersequence(a: "abcba", b: "dcba") == "adbcabcba"
func shortestCommonSupersequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var shortest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var isFound = true
while isFound && i + k < a.count && j + k < b.count {
if a[i + k]!= b[j + k] {
isFound = false
}
k += 1
}
if isFound && k < shortest.count {
shortest = String(a[i..<i + k])
}
}
}
}
if shortest.count == 0 {
shortest = a + b
}
return shortest
}
// Find the longest palindrome substring in a given string.
// longestPalindromeSubstring(string: "abracadabraanamadamalayalamradar") == "anamadamalayalam"
func longestPalindromeSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
for j in 0..<string.count {
var k = 0
var isFound = true
while is
if string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
if string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i + k]!= b[j + k] { // cannot force unwrap value of non-optional type 'Character'
if a[i + k]!= b[j + k] { // use of '=' in a boolean context, did you mean '=='?
if a[i + k]!= b[j + k] { // '=' must have consistent whitespace on both sides
longest = String(a[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i + k]!= b[j + k] { // '=' must have consistent whitespace on both sides
if a[i + k]!= b[j + k] { // use of '=' in a boolean context, did you mean '=='?
if a[i + k]!= b[j + k] { // cannot force unwrap value of non-optional type 'Character'
longest = String(a[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i + k]!= b[j + k] { // use of '=' in a boolean context, did you mean '=='?
if a[i + k]!= b[j + k] { // cannot force unwrap value of non-optional type 'Character'
if a[i + k]!= b[j + k] { // '=' must have consistent whitespace on both sides
shortest = String(a[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
if string[i..<i+substring.count] == substring {
count += 1
}
}
return count
}
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var substring = ""
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] {
substring = String(a[i+k])
k += 1
}
if k > longest.count {
longest = substring
}
}
}
}
return longest
}
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var subsequence = ""
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] {
subsequence = String(a[i+k])
k += 1
}
if k > longest.count {
longest = subsequence
}
}
}
}
return longest
}
```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 {
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
if string[i..<i+substring.count] == substring {
count += 1
}
}
return count
}
// Find the longest common substring between two strings.
// longestCommonSubstring(a: "", b: "") == ""
// longestCommonSubstring(a: "a", b: "b") == ""
// longestCommonSubstring(a: "abc", b: "def") == ""
// longestCommonSubstring(a: "hello", b: "world") == "o"
// longestCommonSubstring(a: "cat", b: "dog") == ""
// longestCommonSubstring(a: "hello", b: "world") == "o"
// longestCommonSubstring(a: "hello", b: "earth") == "el"
// longestCommonSubstring(a: "cat", b: "dog") == ""
// longestCommonSubstring(a: "cat", b: "tac") == "at"
// longestCommonSubstring(a: "hello", b: "yellow") == "ello"
// longestCommonSubstring(a: "abcdefg", b: "acfgh") == "acf"
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var substring = ""
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] {
substring = String(a[i+k])
k += 1
}
if k > longest.count {
longest = substring
}
}
}
}
return longest
}
// Find the longest common subsequence between two strings.
// longestCommonSubsequence(a: "", b: "") == ""
// longestCommonSubsequence(a: "a", b: "b") == ""
// longestCommonSubsequence(a: "abc", b: "def") == ""
// longestCommonSubsequence(a: "hello", b: "world") == "helo"
// longestCommonSubsequence(a: "cat", b: "dog") == "a"
// longestCommonSubsequence(a: "hello", b: "earth") == "hleo"
// longestCommonSubsequence(a: "cat", b: "dog") == "a"
// longestCommonSubsequence(a: "cat", b: "tac") == "at"
// longestCommonSubsequence(a: "hello", b: "yellow") == "hll"
// longestCommonSubsequence(a: "abcdefg", b: "acfgh") == "acfgh"
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 1
var subsequence = ""
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] {
subsequence = String(a[i+k])
k += 1
}
if k > longest.count {
longest = subsequence
}
}
}
}
return longest
}
// Find the shortest common supersequence between two strings.
// shortestCommonSupersequence(a: "", b: "") == ""
// shortestCommonSupersequence(a: "a", b: "b") == "ab"
// shortestCommonSupersequence(a: "abc", b: "def") == "abcdef"
// shortestCommonSupersequence(a: "hello", b: "world") == "helloworld"
// shortestCommonSupersequence(a: "cat", b: "dog") == "catdog"
// shortestCommonSupersequence(a: "hello", b: "
if string[i..<i+substring.count] == substring { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
substring = String(a[i+k]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while i + k < a.count && j + k < b.count && a[i+k] == b[j+k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
subsequence = String(a[i+k]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var index = 0
while index < string.count {
if string[index] == substring[0] {
var subIndex = 1
while subIndex < substring.count && index + subIndex < string.count {
if string[index + subIndex]!= substring[subIndex] {
break
}
subIndex += 1
}
if subIndex == substring.count {
count += 1
}
}
index += 1
}
return count
}
func longestCommonPrefix(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b }
var index = 0
var result = ""
while index < a.count && index < b.count {
if a[index] == b[index] {
result.append(a[index])
} else {
break
}
index += 1
}
return result
}
func longestCommonPrefix(strings: [String]) -> String {
guard strings.count > 0 else { return "" }
guard strings.count > 1 else { return strings[0] }
var result = strings[0]
for i in 1..<strings.count {
result = longestCommonPrefix(a: result, b: strings[i])
if result.count == 0 {
break
}
}
return result
}
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b }
var result = ""
var maxLength = 0
for i in 0..<a.count {
for j in 0..<b.count {
var subIndex = 0
while i + subIndex < a.count && j + subIndex < b.count {
if a[i + subIndex] == b[j + subIndex] {
subIndex += 1
} else {
break
}
}
if subIndex > maxLength {
maxLength = subIndex
result = String(a[i..<i+subIndex])
}
}
}
return result
}
func longestCommonSubstring(strings: [String]) -> String {
guard strings.count > 0 else { return "" }
guard strings.count > 1 else { return strings[0] }
var result = strings[0]
for i in 1..<strings.count {
result = longestCommonSubstring(a: result, b: strings[i])
if result.count == 0 {
break
}
}
return result
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var index = 0
while index < string.count {
if string[index] == substring[0] {
var subIndex = 1
while subIndex < substring.count && index + subIndex < string.count {
if string[index + subIndex]!= substring[subIndex] {
break
}
subIndex += 1
}
if subIndex == substring.count {
count += 1
}
}
index += 1
}
return count
}
// Find the longest common prefix of two strings.
// longestCommonPrefix(a: "", b: "") == ""
// longestCommonPrefix(a: "abc", b: "abc") == "abc"
// longestCommonPrefix(a: "abc", b: "abcd") == "ab"
func longestCommonPrefix(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b }
var index = 0
var result = ""
while index < a.count && index < b.count {
if a[index] == b[index] {
result.append(a[index])
} else {
break
}
index += 1
}
return result
}
// Find the longest common prefix of an array of strings.
// longestCommonPrefix(strings: []) == ""
// longestCommonPrefix(strings: ["abc", "abc"]) == "abc"
// longestCommonPrefix(strings: ["abc", "abcd", "abdc"]) == "ab"
func longestCommonPrefix(strings: [String]) -> String {
guard strings.count > 0 else { return "" }
guard strings.count > 1 else { return strings[0] }
var result = strings[0]
for i in 1..<strings.count {
result = longestCommonPrefix(a: result, b: strings[i])
if result.count == 0 {
break
}
}
return result
}
// Find the longest common substring of two strings.
// longestCommonSubstring(a: "", b: "") == ""
// longestCommonSubstring(a: "abc", b: "abc") == "abc"
// longestCommonSubstring(a: "abc", b: "abcd") == "ab"
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b }
var result = ""
var maxLength = 0
for i in 0..<a.count {
for j in 0..<b.count {
var subIndex = 0
while i + subIndex < a.count && j + subIndex < b.count {
if a[i + subIndex] == b[j + subIndex] {
subIndex += 1
} else {
break
}
}
if subIndex > maxLength {
maxLength = subIndex
result = String(a[i..<i+subIndex])
}
}
}
return result
}
// Find the longest common substring of an array of strings.
// longestCommonSubstring(strings: []) == ""
// longestCommonSubstring(strings: ["abc", "abc"]) == "abc"
// longestCommonSubstring(strings: ["abc", "abcd", "abdc"]) == "ab"
func longestCommonSubstring(strings: [String]) -> String {
guard strings.count > 0 else { return "" }
guard strings.count > 1 else { return strings[0] }
var result = strings[0]
for i in 1..<strings.count {
result = longestCommonSubstring(a: result, b: strings[i])
if result.count == 0 {
break
}
}
return result
}
// Find the longest common subsequence of two strings.
// longestCommonSubsequence(a: "", b: "") == ""
// longestCommonSubsequence(a: "abc", b: "abc
if string[index] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[index] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[index + subIndex]!= substring[subIndex] { // '=' must have consistent whitespace on both sides
if string[index + subIndex]!= substring[subIndex] { // use of '=' in a boolean context, did you mean '=='?
if string[index + subIndex]!= substring[subIndex] { // cannot force unwrap value of non-optional type 'Character'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // consecutive statements on a line must be separated by ';'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // cannot convert return expression of type 'Bool' to return type 'String'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // expected expression
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // cannot use optional chaining on non-optional value of type 'Int'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // expression of type 'String' is unused
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // consecutive statements on a line must be separated by ';'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
if a[index] == b[index] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[index] == b[index] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result.append(a[index]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // cannot use optional chaining on non-optional value of type 'Int'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // expression of type 'String' is unused
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // expected expression
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // consecutive statements on a line must be separated by ';'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // cannot convert return expression of type 'Bool' to return type 'String'
guard a.count > 0 && b.count > 0 else { return a.count > b.count? a : b } // consecutive statements on a line must be separated by ';'
if a[i + subIndex] == b[j + subIndex] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i + subIndex] == b[j + subIndex] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
result = String(a[i..<i+subIndex]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var j = 0
while j < substring.count {
if string[i + j]!= substring[j] {
break
}
j += 1
}
if j == substring.count {
count += 1
}
}
return count
}
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
var k = 0
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] {
k += 1
}
if k > longest.count {
longest = String(a[i..<i + k])
}
}
}
return longest
}
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 0
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] {
k += 1
}
if k > longest.count {
longest = String(a[i..<i + k])
}
}
}
}
return longest
}
func shortestCommonSupersequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var shortest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 0
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] {
k += 1
}
if k < shortest.count {
shortest = String(a[i..<i + k])
}
}
}
}
if shortest.count == 0 {
shortest = a + b
}
return shortest
}
func longestPalindromeSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
for j in 0..<string.count {
var k = 0
while k < string.count - i && k < string.count - j && string[i + k] == string[j + k] {
k += 1
}
if k > longest.count {
longest = String(string[i..<i + k])
}
}
}
return longest
}
```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 {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var j = 0
while j < substring.count {
if string[i + j]!= substring[j] {
break
}
j += 1
}
if j == substring.count {
count += 1
}
}
return count
}
// Find the longest common substring between two strings.
// longestCommonSubstring(a: "abc", b: "bc") == "bc"
// longestCommonSubstring(a: "abc", b: "def") == ""
func longestCommonSubstring(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
var k = 0
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] {
k += 1
}
if k > longest.count {
longest = String(a[i..<i + k])
}
}
}
return longest
}
// Find the longest common subsequence between two strings.
// longestCommonSubsequence(a: "abc", b: "bc") == "b"
// longestCommonSubsequence(a: "abc", b: "def") == ""
func longestCommonSubsequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var longest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 0
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] {
k += 1
}
if k > longest.count {
longest = String(a[i..<i + k])
}
}
}
}
return longest
}
// Find the shortest common supersequence between two strings.
// shortestCommonSupersequence(a: "abc", b: "bc") == "abc"
// shortestCommonSupersequence(a: "abc", b: "def") == "abcdef"
func shortestCommonSupersequence(a: String, b: String) -> String {
guard a.count > 0 && b.count > 0 else { return "" }
var shortest = ""
for i in 0..<a.count {
for j in 0..<b.count {
if a[i] == b[j] {
var k = 0
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] {
k += 1
}
if k < shortest.count {
shortest = String(a[i..<i + k])
}
}
}
}
if shortest.count == 0 {
shortest = a + b
}
return shortest
}
// Find the longest palindrome substring in a given string.
// longestPalindromeSubstring(string: "abracadabraanamadamalayalamradar") == "anamadamalayalam"
func longestPalindromeSubstring(string: String) -> String {
guard string.count > 0 else { return "" }
var longest = ""
for i in 0..<string.count {
for j in 0..<string.count {
var k = 0
while k < string.count - i && k < string.count - j && string[i + k] == string[j + k] {
k += 1
}
if k > longest.count {
longest = String(string[i..<i + k])
}
}
}
return longest
}
// Find the longest palindrome subsequence in a given string.
// longestPalindromeSubsequence(string: "abracadabraanamadamalayalamradar") == "an
if string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
if string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
longest = String(a[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
longest = String(a[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if a[i] == b[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while k < a.count - i && k < b.count - j && a[i + k] == b[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
shortest = String(a[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
while k < string.count - i && k < string.count - j && string[i + k] == string[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while k < string.count - i && k < string.count - j && string[i + k] == string[j + k] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
longest = String(string[i..<i + k]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var match = true
for j in 0..<substring.count {
if string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
}
}
return count
}
func howManyTimes2(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var i = 0
while i < string.count {
var match = true
for j in 0..<substring.count {
if i + j >= string.count || string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
i += substring.count
} else {
i += 1
}
}
return count
}
func howManyTimes3(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var i = 0
while i < string.count {
if string[i] == substring[0] {
var match = true
for j in 1..<substring.count {
if i + j >= string.count || string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
i += substring.count
} else {
i += 1
}
} else {
i += 1
}
}
return count
}
func howManyTimes4(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var i = 0
while i < string.count {
if string[i] == substring[0] {
var match = true
for j in 1..<substring.count {
if i + j >= string.count || string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
i += substring.count
} else {
i += 1
}
} else {
i += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
for i in 0..<string.count - substring.count + 1 {
var match = true
for j in 0..<substring.count {
if string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
}
}
return count
}
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes2(string: "", substring: "a") == 0
// howManyTimes2(string: "aaa", substring: "a") == 3
// howManyTimes2(string: "aaaa", substring: "aa") == 3
func howManyTimes2(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var i = 0
while i < string.count {
var match = true
for j in 0..<substring.count {
if i + j >= string.count || string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
i += substring.count
} else {
i += 1
}
}
return count
}
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes3(string: "", substring: "a") == 0
// howManyTimes3(string: "aaa", substring: "a") == 3
// howManyTimes3(string: "aaaa", substring: "aa") == 3
func howManyTimes3(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var i = 0
while i < string.count {
if string[i] == substring[0] {
var match = true
for j in 1..<substring.count {
if i + j >= string.count || string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
i += substring.count
} else {
i += 1
}
} else {
i += 1
}
}
return count
}
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes4(string: "", substring: "a") == 0
// howManyTimes4(string: "aaa", substring: "a") == 3
// howManyTimes4(string: "aaaa", substring: "aa") == 3
func howManyTimes4(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
var i = 0
while i < string.count {
if string[i] == substring[0] {
var match = true
for j in 1..<substring.count {
if i + j >= string.count || string[i + j]!= substring[j] {
match = false
break
}
}
if match {
count += 1
i += substring.count
} else {
i += 1
}
} else {
i += 1
}
}
return count
}
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes5(string: "", substring: "a") == 0
// howManyTimes5(string: "aaa", substring: "a") == 3
// howManyTimes5(string: "aaaa", substring: "aa") == 3
func howManyTimes5(string: String, substring: String) -> Int {
guard substring.count > 0 else { return 0 }
guard substring.count <= string.count else { return 0 }
var count = 0
if string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
if string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if i + j >= string.count || string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if i + j >= string.count || string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
if i + j >= string.count || string[i + j]!= substring[j] { // expression is not assignable: '||' returns immutable value
if i + j >= string.count || string[i + j]!= substring[j] { // cannot convert value of type 'Character' to expected argument type 'Bool'
if i + j >= string.count || string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i + j >= string.count || string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if i + j >= string.count || string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
if i + j >= string.count || string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if i + j >= string.count || string[i + j]!= substring[j] { // cannot convert value of type 'Character' to expected argument type 'Bool'
if i + j >= string.count || string[i + j]!= substring[j] { // expression is not assignable: '||' returns immutable value
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] == substring[0] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i + j >= string.count || string[i + j]!= substring[j] { // expression is not assignable: '||' returns immutable value
if i + j >= string.count || string[i + j]!= substring[j] { // '=' must have consistent whitespace on both sides
if i + j >= string.count || string[i + j]!= substring[j] { // cannot force unwrap value of non-optional type 'Character'
if i + j >= string.count || string[i + j]!= substring[j] { // use of '=' in a boolean context, did you mean '=='?
if i + j >= string.count || string[i + j]!= substring[j] { // cannot convert value of type 'Character' to expected argument type 'Bool'
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0 > $1 }
return sortedWords.joined(separator: " ")
}
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 < $1 }
return sortedWords.joined(separator: " ")
}
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted in reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and alphabetically
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 < $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separatedBy:.whitespaces)
var sortedWords = words.sorted { $0.count > $1.count || $0 > $1 }
return sortedWords.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length and reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let words = words.components(separated
var sortedNumbers = numbers.sorted() // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedWords = words.sorted { $0 > $1 } // variable 'sortedWords' was never mutated; consider changing to 'let' constant
func sortWords(words: String) -> String { // invalid redeclaration of 'sortWords(words:)'
func sortWords(words: String) -> String { // invalid redeclaration of 'sortWords(words:)'
func sortNumbers(numbers: String) -> String {
var sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort()
return sortedNumbers.joined(separator: " ")
}
func sortNumbersDescending(numbers: String) -> String {
var sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort(by: >)
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
var sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort()
return sortedNumbers.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
var sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort(by: >)
return sortedNumbers.joined(separator: " ")
}
// 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 sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort()
return sortedNumbers.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
var sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort(by: >)
return sortedNumbers.joined(separator: " ")
}
// 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 sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort()
return sortedNumbers.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
var sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort(by: >)
return sortedNumbers.joined(separator: " ")
}
// 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 sortedNumbers = numbers.components(separatedBy:.whitespaces)
sortedNumbers.sort()
return sortedNumbers.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
var sortedNumbers = numbers.components(separated
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: >)
return sortedNumbers.joined(separator: " ")
}
func sortNumbersAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: <)
return sortedNumbers.joined(separator: " ")
}
func sortNumbersWithDuplicates(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: <)
return sortedNumbers.joined(separator: " ")
}
func sortNumbersWithDuplicatesDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: >)
return sortedNumbers.joined(separator: " ")
}
func sortNumbersWithDuplicatesAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: <)
return sortedNumbers.joined(separator: " ")
}
func sortNumbersWithDuplicatesAndNegative(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: >)
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted()
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: >)
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: <)
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersWithDuplicates(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: <)
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersWithDuplicatesDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: >)
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersWithDuplicatesAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: <)
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersWithDuplicatesAndNegative(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted(by: >)
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers
var sortedNumbers = numbers.sorted() // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted(by: >) // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted(by: <) // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted(by: <) // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted(by: >) // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted(by: <) // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted(by: >) // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! < Int($1)!
}
return sortedArray.joined(separator: " ")
}
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! > Int($1)!
}
return sortedArray.joined(separator: " ")
}
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! < Int($1)!
}
return sortedArray.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! < Int($1)!
}
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! > Int($1)!
}
return sortedArray.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! < Int($1)!
}
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! > Int($1)!
}
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! < Int($1)!
}
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! > Int($1)!
}
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted {
Int($0)! < Int($1)!
}
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string
var sortedArray = numberArray.sorted { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
func sortWords(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
func sortWordsByLength(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: { $0.count > $1.count })
return sortedArray.joined(separator: " ")
}
func sortWordsByLengthAndContent(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count > $1.count
}
})
return sortedArray.joined(separator: " ")
}
func sortWordsByLengthAndContentReverse(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count < $1.count
}
})
return sortedArray.joined(separator: " ")
}
func sortWordsByLengthAndContentAlphabetical(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 < $1
} else {
return $0.count > $1.count
}
})
return sortedArray.joined(separator: " ")
}
func sortWordsByLengthAndContentAlphabeticalReverse(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count < $1.count
}
})
return sortedArray.joined(separator: " ")
}
func sortWordsByLengthAndContentReverseAlphabetical(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count < $1.count
}
})
return sortedArray.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted in reverse alphabetical order.
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length in descending order.
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWordsByLength(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: { $0.count > $1.count })
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length in descending order.
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWordsByLengthAndContent(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count > $1.count
}
})
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length in descending order.
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWordsByLengthAndContentReverse(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count < $1.count
}
})
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length in descending order.
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWordsByLengthAndContentAlphabetical(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 < $1
} else {
return $0.count > $1.count
}
})
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length in descending order.
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWordsByLengthAndContentAlphabeticalReverse(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count < $1.count
}
})
return sortedArray.joined(separator: " ")
}
// Input is a space-delimited string of words.
// Return the string with words sorted by length in descending order.
// sortWords(words: "cat dog tie") == "cat dog tie"
func sortWordsByLengthAndContentReverseAlphabetical(words: String) -> String {
let wordArray = words.components(separatedBy:.whitespaces)
var sortedArray = wordArray.sorted(by: {
if $0.count == $1.count {
return $0 > $1
} else {
return $0.count < $1.count
}
})
return sortedArray.joined(separator: " ")
}
// Input is a space
var sortedArray = numberArray.sorted() // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: >) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: { $0.count > $1.count }) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = wordArray.sorted(by: { // variable 'sortedArray' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = [Int]()
for number in numberArray {
if let number = Int(number) {
sortedArray.append(number)
}
}
sortedArray.sort()
var sortedNumbers = ""
for number in sortedArray {
sortedNumbers += String(number) + " "
}
return sortedNumbers
}
func sortLetters(letters: String) -> String {
let letterArray = letters.components(separatedBy: " ")
var sortedArray = [String]()
for letter in letterArray {
sortedArray.append(letter)
}
sortedArray.sort()
var sortedLetters = ""
for letter in sortedArray {
sortedLetters += letter + " "
}
return sortedLetters
}
func sortWords(words: String) -> String {
let wordArray = words.components(separatedBy: " ")
var sortedArray = [String]()
for word in wordArray {
sortedArray.append(word)
}
sortedArray.sort()
sortedArray.reverse()
var sortedWords = ""
for word in sortedArray {
sortedWords += word + " "
}
return sortedWords
}
func sortNumbersAndLetters(numbersAndLetters: String) -> String {
let numberAndLetterArray = numbersAndLetters.components(separatedBy: " ")
var sortedArray = [String]()
for numberAndLetter in numberAndLetterArray {
if let number = Int(numberAndLetter) {
sortedArray.append(String(number))
} else {
sortedArray.append(numberAndLetter)
}
}
sortedArray.sort()
var sortedNumbersAndLetters = ""
for numberOrLetter in sortedArray {
if let number = Int(numberOrLetter) {
sortedNumbersAndLetters += String(number) + " "
} else {
sortedNumbersAndLetters += numberOrLetter + " "
}
}
return sortedNumbersAndLetters
}
func sortNumbersAndLettersReverse(numbersAndLetters: String) -> String {
let numberAndLetterArray = numbersAndLetters.components(separatedBy: " ")
var sortedArray = [String]()
for numberAndLetter in numberAndLetterArray {
if let number = Int(numberAndLetter) {
sortedArray.append(String(number))
} else {
sortedArray.append(numberAndLetter)
}
}
sortedArray.sort()
sortedArray.reverse()
var sortedNumbersAndLetters = ""
for numberOrLetter in sortedArray {
if let number = Int(numberOrLetter) {
sortedNumbersAndLetters += String(number) + " "
} else {
sortedNumbersAndLetters += numberOrLetter + " "
}
}
return sortedNumbersAndLetters
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = [Int]()
for number in numberArray {
if let number = Int(number) {
sortedArray.append(number)
}
}
sortedArray.sort()
var sortedNumbers = ""
for number in sortedArray {
sortedNumbers += String(number) + " "
}
return sortedNumbers
}
// Input is a space-delimited string of letters from 'a' to 'z'.
// Return the string with letters sorted in alphabetical order
// sortLetters(letters: "cat dog tie") == "cat dog tie"
func sortLetters(letters: String) -> String {
let letterArray = letters.components(separatedBy: " ")
var sortedArray = [String]()
for letter in letterArray {
sortedArray.append(letter)
}
sortedArray.sort()
var sortedLetters = ""
for letter in sortedArray {
sortedLetters += letter + " "
}
return sortedLetters
}
// Input is a space-delimited string of words.
// Return the string with words sorted in reverse alphabetical order
// sortWords(words: "cat dog tie") == "tie dog cat"
func sortWords(words: String) -> String {
let wordArray = words.components(separatedBy: " ")
var sortedArray = [String]()
for word in wordArray {
sortedArray.append(word)
}
sortedArray.sort()
sortedArray.reverse()
var sortedWords = ""
for word in sortedArray {
sortedWords += word + " "
}
return sortedWords
}
// Input is a space-delimited string of numbers and letters from 'a' to 'z'.
// Return the string with numbers sorted from smallest to largest and letters sorted in reverse alphabetical order
// sortNumbersAndLetters(numbersAndLetters: "cat 1 dog 8 tie 3") == "cat 8 dog 3 tie 1"
func sortNumbersAndLetters(numbersAndLetters: String) -> String {
let numberAndLetterArray = numbersAndLetters.components(separatedBy: " ")
var sortedArray = [String]()
for numberAndLetter in numberAndLetterArray {
if let number = Int(numberAndLetter) {
sortedArray.append(String(number))
} else {
sortedArray.append(numberAndLetter)
}
}
sortedArray.sort()
var sortedNumbersAndLetters = ""
for numberOrLetter in sortedArray {
if let number = Int(numberOrLetter) {
sortedNumbersAndLetters += String(number) + " "
} else {
sortedNumbersAndLetters += numberOrLetter + " "
}
}
return sortedNumbersAndLetters
}
// Input is a space-delimited string of numbers and letters from 'a' to 'z'.
// Return the string with numbers sorted from smallest to largest and letters sorted in alphabetical order
// sortNumbersAndLetters(numbersAndLetters: "cat 1 dog 8 tie 3") == "cat 1 dog 3 tie 8"
func sortNumbersAndLettersReverse(numbersAndLetters: String) -> String {
let numberAndLetterArray = numbersAndLetters.components(separatedBy: " ")
var sortedArray = [String]()
for numberAndLetter in numberAndLetterArray {
if let number = Int(numberAndLetter) {
sortedArray.append(String(number))
} else {
sortedArray.append(numberAndLetter)
}
}
sortedArray.sort()
sortedArray.reverse()
var sortedNumbersAndLetters = ""
for numberOrLetter in sortedArray {
if let number = Int(numberOrLetter) {
sortedNumbersAndLetters += String(number) + " "
} else {
sortedNumbersAndLetters += numberOrLetter + " "
}
}
return sortedNumbersAndLetters
}
// Input is a space-delimited string of numbers and letters from 'a' to 'z'.
// Return the string with letters sorted in alphabetical order and numbers sorted from smallest to largest
// sortLettersAndNumbers(lettersAndNumbers: "cat 1 dog 8 tie 3") == "cat 3 dog 8 tie 1"
func sortLettersAndNumbers(lettersAndNumbers: String) -> String {
let numberAndLetterArray = lettersAndNumbers.components(separatedBy: " ")
var sortedArray = [String]()
for numberAndLetter in number
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted(by: <)
return sortedArray.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted(by: <)
return sortedArray.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersAscending(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted(by: <)
return sortedArray.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy:.whitespaces)
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five")
var sortedArray = numberArray.sorted() // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: >) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: <) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
func reverseSortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
func reverseSortNumbers2(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 > $1 })
return sortedArray.joined(separator: " ")
}
func reverseSortNumbers3(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
func reverseSortNumbers4(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 > $1 })
return sortedArray.joined(separator: " ")
}
func sortNumbers2(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 < $1 })
return sortedArray.joined(separator: " ")
}
func sortNumbers3(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 < $1 })
return sortedArray.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted()
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func reverseSortNumbers(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func reverseSortNumbers2(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 > $1 })
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func reverseSortNumbers3(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: >)
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func reverseSortNumbers4(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 > $1 })
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbers2(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 < $1 })
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbers3(numbers: String) -> String {
let numberArray = numbers.components(separatedBy: " ")
var sortedArray = numberArray.sorted(by: { $0 < $1 })
return sortedArray.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers:
var sortedArray = numberArray.sorted() // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: >) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: { $0 > $1 }) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: >) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: { $0 > $1 }) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: { $0 < $1 }) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
var sortedArray = numberArray.sorted(by: { $0 < $1 }) // variable 'sortedArray' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! > Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! > Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbersAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! > Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! > Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersAscending(numbers: String) -> String {
let numbers = numbers.components(separatedBy: " ")
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven',
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int($0)! > Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersByDigitCount(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
$0.count > $1.count
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersByDigitCountDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
$0.count < $1.count
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersByDigitSum(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int(String($0))! + Int(String($1))! > Int(String($1))! + Int(String($0))!
}
return sortedNumbers.joined(separator: " ")
}
func sortNumbersByDigitSumDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int(String($0))! + Int(String($1))! < Int(String($1))! + Int(String($0))!
}
return sortedNumbers.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five','six','seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int($0)! < Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 largest to smallest
// sortNumbers(numbers: "three one five") == "five three one"
func sortNumbersDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int($0)! > Int($1)!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order based on the number of digits
// sortNumbers(numbers: "three one five") == "three five one"
func sortNumbersByDigitCount(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
$0.count > $1.count
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order based on the number of digits
// sortNumbers(numbers: "three one five") == "five one three"
func sortNumbersByDigitCountDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
$0.count < $1.count
}
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order based on the number of digits
// sortNumbers(numbers: "three one five") == "three five one"
func sortNumbersByDigitSum(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int(String($0))! + Int(String($1))! > Int(String($1))! + Int(String($0))!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in descending order based on the number of digits
// sortNumbers(numbers: "three one five") == "five one three"
func sortNumbersByDigitSumDescending(numbers: String) -> String {
let numbers = numbers.components(separatedBy:.whitespaces)
var sortedNumbers = numbers.sorted {
Int(String($0))! + Int(String($1))! < Int(String($1))! + Int(String($0))!
}
return sortedNumbers.joined(separator: " ")
}
// 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 in ascending order based on the number of digits
// sortNumbers(numbers: "three one five") == "three five one"
func sortNumbersByDigitSumAndDigitCount(
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
var sortedNumbers = numbers.sorted { // variable 'sortedNumbers' was never mutated; consider changing to 'let' constant
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[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) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// 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.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// 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: [0.0, 1.0, 2.0]) == (0.0, 1.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[1])
}
// 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]) == (1.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[1])
}
// 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, 4.0, 5.0, 3.0]) == (3.0, 4.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// 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.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// 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,
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("Array must contain at least two numbers")
}
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("Array must contain at least two numbers")
}
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
//: [Next](@next)
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[1])
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[0])
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (0.0, 0.0)
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[2])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// 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.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// 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: [0.0, 1.0, 2.0]) == (0.0, 1.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[1])
}
// 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]) == (1.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[1])
}
// 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]) == (1.0, 1.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[0])
}
// 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: []) == (0.0, 0.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (0.0, 0.0)
}
// 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, 5.0, 10.0]) == (1.0, 10.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
return (numbers[0], numbers[2])
}
// 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, 5.0, 10.0, 100.0]) == (1.0, 100
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var numbers = numbers
numbers.sort()
let smallest = numbers[0]
let largest = numbers[numbers.count - 1]
var smallestDifference = largest - smallest
var result: (Double, Double) = (smallest, largest)
for i in 0..<numbers.count {
let difference = numbers[i] - smallest
if difference < smallestDifference {
smallestDifference = difference
result = (smallest, numbers[i])
}
}
return result
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
var numbers = numbers
numbers.sort()
let smallest = numbers[0]
let middle = numbers[numbers.count / 2]
let largest = numbers[numbers.count - 1]
var smallestDifference = largest - smallest
var middleDifference = largest - middle
var result: (Double, Double, Double) = (smallest, middle, largest)
for i in 0..<numbers.count {
let difference = numbers[i] - smallest
if difference < smallestDifference {
smallestDifference = difference
result = (smallest, numbers[i], largest)
}
let difference2 = numbers[i] - middle
if difference2 < middleDifference {
middleDifference = difference2
result = (smallest, middle, numbers[i])
}
}
return result
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
var numbers = numbers
numbers.sort()
let smallest = numbers[0]
let middle1 = numbers[numbers.count / 2 - 1]
let middle2 = numbers[numbers.count / 2]
let largest = numbers[numbers.count - 1]
var smallestDifference = largest - smallest
var middleDifference1 = largest - middle1
var middleDifference2 = largest - middle2
var result: (Double, Double, Double, Double) = (smallest, middle1, middle2, largest)
for i in 0..<numbers.count {
let difference = numbers[i] - smallest
if difference < smallestDifference {
smallestDifference = difference
result = (smallest, numbers[i], middle1, largest)
}
let difference2 = numbers[i] - middle1
if difference2 < middleDifference1 {
middleDifference1 = difference2
result = (smallest, middle1, numbers[i], largest)
}
let difference3 = numbers[i] - middle2
if difference3 < middleDifference2 {
middleDifference2 = difference3
result = (smallest, middle1, middle2, numbers[i])
}
}
return result
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var numbers = numbers
numbers.sort()
let smallest = numbers[0]
let largest = numbers[numbers.count - 1]
var smallestDifference = largest - smallest
var result: (Double, Double) = (smallest, largest)
for i in 0..<numbers.count {
let difference = numbers[i] - smallest
if difference < smallestDifference {
smallestDifference = difference
result = (smallest, numbers[i])
}
}
return result
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
// From a supplied array of numbers (of length at least three) select and return three that are the closest to each
// other and return them in order (smallest number, middle number, largest number).
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 3.0, 5.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
var numbers = numbers
numbers.sort()
let smallest = numbers[0]
let middle = numbers[numbers.count / 2]
let largest = numbers[numbers.count - 1]
var smallestDifference = largest - smallest
var middleDifference = largest - middle
var result: (Double, Double, Double) = (smallest, middle, largest)
for i in 0..<numbers.count {
let difference = numbers[i] - smallest
if difference < smallestDifference {
smallestDifference = difference
result = (smallest, numbers[i], largest)
}
let difference2 = numbers[i] - middle
if difference2 < middleDifference {
middleDifference = difference2
result = (smallest, middle, numbers[i])
}
}
return result
}
findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0])
// From a supplied array of numbers (of length at least four) select and return four that are the closest to each
// other and return them in order (smallest number, middle number, middle number, largest number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 5.0]) == (2.0, 2.5, 3.0, 5.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
var numbers = numbers
numbers.sort()
let smallest = numbers[0]
let middle1 = numbers[numbers.count / 2 - 1]
let middle2 = numbers[numbers.count / 2]
let largest = numbers[numbers.count - 1]
var smallestDifference = largest - smallest
var middleDifference1 = largest - middle1
var middleDifference2 = largest - middle2
var result: (Double, Double, Double, Double) = (smallest, middle1, middle2, largest)
for i in 0..<numbers.count {
let difference = numbers[i] - smallest
if difference < smallestDifference {
smallestDifference = difference
result = (smallest, numbers[i], middle1, largest)
}
let difference2 = numbers[i] - middle1
if difference2 < middleDifference1 {
middleDifference1 = difference2
result = (smallest, middle1, numbers[i], largest)
}
let difference3 = numbers[i] - middle2
if difference3 < middleDifference2 {
middleDifference2 = difference3
result = (smallest, middle1, middle2, numbers[i])
}
}
return result
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 5.0])
// From a supplied array of numbers (of length at least four) select and return four that are the closest to each
// other and return them in order (smallest number, middle number, middle number, largest number).
// findClosestElements
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("There must be at least two numbers")
}
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("There must be at least two numbers")
}
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// Test cases
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0))
// Negative numbers
assert(findClosestElements(numbers: [-1.0, -2.8, -3.0, -4.0, -5.0, -2.0]) == (-2.8, -2.0))
// Edge cases
assert(findClosestElements(numbers: [1.0]) == (1.0, 1.0))
assert(findClosestElements(numbers: [1.0, 2.0]) == (1.0, 2.0))
assert(findClosestElements(numbers: [2.0, 1.0]) == (1.0, 2.0))
assert(findClosestElements(numbers: [2.0, 1.0, 3.0]) == (1.0, 2.0))
assert(findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8))
// Additional edge cases
assert(findClosestElements(numbers: [1.0, 1.0, 1.0]) == (1.0, 1.0))
assert(findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0, 2.0]) == (2.0, 2.8))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8]) == (2.0, 2.8))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2, 2.8]) == (2.0, 2.8))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.0, 2.8]) == (2.0, 2.8))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2, 2.0, 2.8]) == (2.0, 2.8))
// Additional test cases
assert(findClosestElements(numbers: [1.0, 1.0, 1.0, 1.0]) == (1.0, 1.0))
assert(findClosestElements(numbers: [1.0, 1.8, 2.0, 2.0, 2.0, 2.0]) == (1.8, 2.0))
assert(findClosestElements(numbers: [1.0, 1.8, 2.0, 2.2, 2.0, 2.0]) == (1.8, 2.0))
assert(findClosestElements(numbers: [1.0, 1.8, 2.0, 2.2, 2.0, 2.0, 3.0]) == (1.8, 2.0))
assert(findClosestElements(numbers: [1.0, 1.8, 2.0, 2.2, 2.0, 2.0,
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("Array must contain at least two elements")
}
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
guard numbers.count >= 3 else {
fatalError("Array must contain at least three elements")
}
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
guard numbers.count >= 4 else {
fatalError("Array must contain at least four elements")
}
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[right])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("Array must contain at least two elements")
}
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// From a supplied array of numbers (of length at least three) select and return three that are the closest to each
// other and return them in order (smaller number, middle number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 3.0, 4.0)
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8, 3.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
guard numbers.count >= 3 else {
fatalError("Array must contain at least three elements")
}
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[right])
}
// From a supplied array of numbers (of length at least four) select and return four that are the closest to each
// other and return them in order (smaller number, middle number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 3.0, 4.0, 5.0)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 10.0, 5.0, 2.0]) == (2.0, 3.0, 4.0, 5.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
guard numbers.count >= 4 else {
fatalError("Array must contain at least four elements")
}
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[right])
}
// From a supplied array of numbers (of length at least five) select and return five that are the closest to each
// other and return them in order (smaller number, middle number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 3.0, 4.0, 5.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 10.0, 5.0, 2.0]) == (2.0, 3.0, 4.0, 5.0, 10.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double, Double) {
guard numbers.count >= 5 else {
fatalError("Array must contain at
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("Array must contain at least two elements")
}
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else {
fatalError("Array must contain at least two elements")
}
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
//: [Next](@next)
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 3 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[right])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2])
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0])
// From a supplied array of numbers (of length at least three) select and return three that are closest to each other
// and return them in order (smallest number, middle number, largest number).
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 3.0, 4.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 1 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[right])
}
findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0])
// From a supplied array of numbers (of length at least four) select and return four that are closest to each other
// and return them in order (smallest number, middle number, middle number, largest number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 5.0]) == (2.0, 2.5, 3.0, 5.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 3 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[right])
}
findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 5.0])
// From a supplied array of numbers (of length at least four) select and return four that are closest to each other
// and return them in order (smallest number, middle number, middle number, largest number).
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0, 2.0]) == (2.0, 2.5, 3.0, 5.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
var left = 0
var right = numbers.count - 1
var minDiff = abs(numbers[left] - numbers[right])
while right - left > 3 {
let mid = (left + right) / 2
let diff = abs(numbers[mid] - numbers[mid - 1])
if diff < minDiff {
minDiff = diff
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left +
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
guard numbers.count >= 3 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 2 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
guard numbers.count >= 4 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 3 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[right])
}
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double, Double) {
guard numbers.count >= 5 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 4 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[left + 3], numbers[right])
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 1 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[right])
}
// From a supplied array of numbers (of length at least three) select and return three that are the closest to each
// other and return them in order (smaller number, middle number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 3.0, 4.0)
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8, 3.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double) {
guard numbers.count >= 3 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 2 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[right])
}
// From a supplied array of numbers (of length at least four) select and return four that are the closest to each
// other and return them in order (smaller number, middle number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 3.0, 4.0, 5.0)
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8, 3.0, 4.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double) {
guard numbers.count >= 4 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 3 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[right])
}
// From a supplied array of numbers (of length at least five) select and return five that are the closest to each
// other and return them in order (smaller number, middle number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 3.0, 4.0, 5.0, 2.2)
// findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8, 3.0, 4.0, 5.0)
func findClosestElements(numbers: [Double]) -> (Double, Double, Double, Double, Double) {
guard numbers.count >= 5 else { fatalError("not enough numbers") }
var left = 0
var right = numbers.count - 1
while right - left > 4 {
let mid = (left + right) / 2
if numbers[mid] > numbers[left] {
left = mid
} else {
right = mid
}
}
return (numbers[left], numbers[left + 1], numbers[left + 2], numbers[left + 3], numbers[right])
}
// From a supplied array of numbers (of length at least six) select and return six that are the closest to each
// other and return them in order
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var numbers = numbers
numbers.sort()
let first = numbers[0]
let last = numbers[numbers.count - 1]
var firstIndex = 0
var lastIndex = numbers.count - 1
while lastIndex - firstIndex >= 1 {
let midIndex = (firstIndex + lastIndex) / 2
let mid = numbers[midIndex]
if mid == first {
return (first, last)
} else if mid == last {
return (last, first)
} else if mid > first {
firstIndex = midIndex
} else {
lastIndex = midIndex
}
}
return (numbers[firstIndex], numbers[lastIndex])
}
```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) {
guard numbers.count >= 2 else { fatalError("Array must contain at least two elements") }
var numbers = numbers
numbers.sort()
let first = numbers[0]
let last = numbers[numbers.count - 1]
var firstIndex = 0
var lastIndex = numbers.count - 1
while lastIndex - firstIndex >= 1 {
let midIndex = (firstIndex + lastIndex) / 2
let mid = numbers[midIndex]
if mid == first {
return (first, last)
} else if mid == last {
return (last, first)
} else if mid > first {
firstIndex = midIndex
} else {
lastIndex = midIndex
}
}
return (numbers[firstIndex], numbers[lastIndex])
}
// Tests
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2))
assert(findClosestElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.8))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.2]) == (2.0, 2.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4]) == (2.0, 2.8))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6]) == (2.0, 3.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6, 3.5]) == (2.0, 3.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6, 3.5, 3.7]) == (2.0, 3.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6, 3.5, 3.7, 3.4]) == (2.0, 3.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6, 3.5, 3.7, 3.4, 3.3]) == (2.0, 3.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6, 3.5, 3.7, 3.4, 3.3, 3.8]) == (2.0, 3.2))
assert(findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0, 2.8, 2.4, 3.2, 3.1, 3.6, 3.5, 3.7, 3.4, 3.3, 3.8, 3.
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescale
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: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { ($0 - min) / range }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($0 - min) / range }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($0 - min) / range }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($0 - min) / range }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($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: [Float]) -> [Float] {
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: [Int]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($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: [Int8]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($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: [Int16]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($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: [Int32]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($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: [Int64]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = Double(max - min)
return numbers.map { Double($0 - min) /
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [UInt]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [UInt8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [UInt]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [UInt8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
func rescaleToUnit(numbers: [Int64]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
// 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: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int64]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { Double($0 - min) / Double(max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int64]) -> [Double] {
// XCTAssertTrue failed
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = max - min
return numbers.map { ($0 - min) / diff }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
```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 diff = max - min
return numbers.map { ($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let diff = Double(max - min)
return numbers.map { Double($0 - min) / diff }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [UInt]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [UInt]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Float' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int8' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'UInt' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int16' and 'Double'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
// 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, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Float]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [CGFloat]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescale
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Float' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int8' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int16' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int32' and 'Double'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
func rescaleToUnit(numbers: [Int64]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
// 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: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { ($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.75, 1]
func rescaleToUnit(numbers: [Int64]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1, 2, 3, 4, 5]) == [0, 0.25, 0.5, 0.
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int8' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int16' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int32' and 'Double'
return numbers.map { Double($0 - min) / (max - min) } // binary operator '-' cannot be applied to operands of type 'Int64' and 'Double'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - Float(min) }
.map { $0 / (Float(max) - Float(min)) }
}
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - min }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Float]) -> [Float] {
let min = numbers.min()!
let max = numbers.max()!
return numbers.map { $0 - Float(min) }
.map { $0 / (Float(max) - Float(min)) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int8]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int16]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int32]) -> [Double] {
let min = Double(numbers.min()!)
let max = Double(numbers.max()!)
return numbers.map { Double($0 - min) }
.map { $0 / (max - min) }
}
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Int64]) -> [Double] {
let min = Double(numbers
return numbers.map { Double($0 - min) } // binary operator '-' cannot be applied to operands of type 'Int' and 'Double'
return numbers.map { Double($0 - min) } // binary operator '-' cannot be applied to operands of type 'Int8' and 'Double'
return numbers.map { Double($0 - min) } // binary operator '-' cannot be applied to operands of type 'Int16' and 'Double'
return numbers.map { Double($0 - min) } // binary operator '-' cannot be applied to operands of type 'Int32' and 'Double'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
}
return nil
}
}
func filterDictionaries(values: [AnyHashable]) -> [AnyHashable : AnyHashable] {
return values.compactMap { value in
if let dictionaryValue = value as? [AnyHashable : AnyHashable] {
return dictionaryValue
}
return nil
}
}
func filterArrays(values: [AnyHashable]) -> [Any] {
return values.compactMap { value in
if let arrayValue = value as? [Any] {
return arrayValue
}
return nil
}
}
func filterSets(values: [AnyHashable]) -> Set<AnyHashable> {
return values.compactMap { value in
return value
}
}
func filterTuples(values: [AnyHashable]) -> [(AnyHashable, AnyHashable)] {
return values.compactMap { value in
if let tupleValue = value as? (AnyHashable, AnyHashable) {
return tupleValue
}
return nil
}
}
func filterOptionalValues(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { value in
return value
}
}
enum Color: String, Hashable {
case Red, Green, Blue
}
func filterEnums(values: [AnyHashable]) -> [Color] {
return values.compactMap { value in
if let enumValue = value as? Color {
return enumValue
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// Filter given array of any swiftthon values only for strings
// filterStrings(values: ["a", 3.14, 5]) == ["a", "3.14"]
// filterStrings(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
}
return nil
}
}
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: ["a", 3.14, 5]) == []
// filterDictionaries(values: [1, 2, 3, "abc", [:], []]) == [:] as [AnyHashable : AnyHashable]
func filterDictionaries(values: [AnyHashable]) -> [AnyHashable : AnyHashable] {
return values.compactMap { value in
if let dictionaryValue = value as? [AnyHashable : AnyHashable] {
return dictionaryValue
}
return nil
}
}
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: ["a", 3.14, 5]) == []
// filterArrays(values: [1, 2, 3, "abc", [:], []]) == []
func filterArrays(values: [AnyHashable]) -> [Any] {
return values.compactMap { value in
if let arrayValue = value as? [Any] {
return arrayValue
}
return nil
}
}
// Filter given array of any swiftthon values only for sets
// filterSets(values: ["a", 3.14, 5]) == []
// filterSets(values: [1, 2, 3, "abc", [:], []]) == []
func filterSets(values: [AnyHashable]) -> Set<AnyHashable> {
return values.compactMap { value in
return value
}
}
// Filter given array of any swiftthon values only for tuples
// filterTuples(values: ["a", 3.14, 5]) == []
// filterTuples(values: [1, 2, 3, "abc", [:], []]) == []
func filterTuples(values: [AnyHashable]) -> [(AnyHashable, AnyHashable)] {
return values.compactMap { value in
if let tupleValue = value as? (AnyHashable, AnyHashable) {
return tupleValue
}
return nil
}
}
// Filter given array of any swiftthon values only for optional values
// filterOptionalValues(values: ["a", 3.14, 5]) == ["a", 3.14, 5]
// filterOptionalValues(values: [1, 2, 3, "abc", [:], nil]) == [1, 2, 3, "abc", [:]]
func filterOptionalValues(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { value in
return value
}
}
// Filter given array of any swiftthon values only for enums
// filterEnums(values: ["a", 3.14, 5]) == []
// filterEnums(values: [1, 2, 3, "abc", [:], nil]) == []
// filterEnums(values: [Red, Green, Blue]) == [Red, Green, Blue]
enum Color: String, Hashable {
case Red, Green, Blue
}
func filterEnums(values: [AnyHashable]) -> [Color] {
return values.compactMap { value in
if let enumValue = value as? Color {
return enumValue
}
return nil
}
}
// Filter given array of any swiftthon values only for functions
// filterFunctions(values: ["a", 3.14, 5]) == []
// filterFunctions(values: [1, 2,
return values.compactMap { value in // cannot convert return expression of type '[[AnyHashable : AnyHashable]]' to return type '[AnyHashable : AnyHashable]'
return values.compactMap { value in // cannot convert return expression of type '[AnyHashable]' to return type 'Set<AnyHashable>'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if
// XCTAssertTrue failed
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
}
return nil
}
}
func filterDictionaries(values: [AnyHashable]) -> [AnyDictionary] {
return values.compactMap { value in
if let dictionaryValue = value as? AnyDictionary {
return dictionaryValue
}
return nil
}
}
func filterArrays(values: [AnyHashable]) -> [AnyArray] {
return values.compactMap { value in
if let arrayValue = value as? AnyArray {
return arrayValue
}
return nil
}
}
func filterSets(values: [AnyHashable]) -> [AnySet] {
return values.compactMap { value in
if let setValue = value as? AnySet {
return setValue
}
return nil
}
}
func filterTuples(values: [AnyHashable]) -> [AnyTuple] {
return values.compactMap { value in
if let tupleValue = value as? AnyTuple {
return tupleValue
}
return nil
}
}
func filterEnums(values: [AnyHashable]) -> [AnyEnum] {
return values.compactMap { value in
if let enumValue = value as? AnyEnum {
return enumValue
}
return nil
}
}
func filterClasses(values: [AnyHashable]) -> [AnyClass] {
return values.compactMap { value in
if let classValue = value as? AnyClass {
return classValue
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
if let intValue = Int(stringValue) {
return intValue
}
}
return nil
}
}
// Filter given array of any swiftthon values only for strings
// filterStrings(values: ["a", 3.14, 5]) == ["a", "3.14"]
// filterStrings(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
}
return nil
}
}
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: ["a", 3.14, 5]) == []
// filterDictionaries(values: [1, 2, 3, "abc", [:], []]) == [[:]]
func filterDictionaries(values: [AnyHashable]) -> [AnyDictionary] {
return values.compactMap { value in
if let dictionaryValue = value as? AnyDictionary {
return dictionaryValue
}
return nil
}
}
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: ["a", 3.14, 5]) == []
// filterArrays(values: [1, 2, 3, "abc", [:], []]) == [[]]
func filterArrays(values: [AnyHashable]) -> [AnyArray] {
return values.compactMap { value in
if let arrayValue = value as? AnyArray {
return arrayValue
}
return nil
}
}
// Filter given array of any swiftthon values only for sets
// filterSets(values: ["a", 3.14, 5]) == []
// filterSets(values: [1, 2, 3, "abc", [:], []]) == [[:]]
func filterSets(values: [AnyHashable]) -> [AnySet] {
return values.compactMap { value in
if let setValue = value as? AnySet {
return setValue
}
return nil
}
}
// Filter given array of any swiftthon values only for tuples
// filterTuples(values: ["a", 3.14, 5]) == []
// filterTuples(values: [1, 2, 3, "abc", [:], []]) == []
func filterTuples(values: [AnyHashable]) -> [AnyTuple] {
return values.compactMap { value in
if let tupleValue = value as? AnyTuple {
return tupleValue
}
return nil
}
}
// Filter given array of any swiftthon values only for enums
// filterEnums(values: ["a", 3.14, 5]) == []
// filterEnums(values: [1, 2, 3, "abc", [:], []]) == []
func filterEnums(values: [AnyHashable]) -> [AnyEnum] {
return values.compactMap { value in
if let enumValue = value as? AnyEnum {
return enumValue
}
return nil
}
}
// Filter given array of any swiftthon values only for classes
// filterClasses(values: ["a", 3.14, 5]) == []
// filterClasses(values: [1, 2, 3, "abc", [:], []]) == []
func filterClasses(values: [AnyHashable]) -> [AnyClass] {
return values.compactMap { value in
if let classValue = value as? AnyClass {
return classValue
}
return nil
}
}
// Filter given array of any swiftthon values only for functions
// filterFunctions(values: ["a", 3.14, 5]) == []
// filterFunctions(values: [1, 2, 3, "abc", [:], []]) == []
func filterFunctions(values: [AnyHashable]) -> [AnyFunction] {
return values.compactMap { value in
if let functionValue = value as? AnyFunction {
return functionValue
}
return nil
}
func filterDictionaries(values: [AnyHashable]) -> [AnyDictionary] { // cannot find type 'AnyDictionary' in scope
func filterArrays(values: [AnyHashable]) -> [AnyArray] { // cannot find type 'AnyArray' in scope
func filterSets(values: [AnyHashable]) -> [AnySet] { // cannot find type 'AnySet' in scope
func filterTuples(values: [AnyHashable]) -> [AnyTuple] { // cannot find type 'AnyTuple' in scope
func filterEnums(values: [AnyHashable]) -> [AnyEnum] { // cannot find type 'AnyEnum' in scope
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
func filterIntegers(values: [Any]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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: [Any]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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: [Any]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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: [Any]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// 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: [Any]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// Filter given
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
return Int(stringValue)
} else if let arrayValue = value as? [AnyHashable] {
return filterIntegers(values: arrayValue)
} else if let dictValue = value as? [AnyHashable : AnyHashable] {
return filterIntegers(values: Array(dictValue.values))
}
return nil
}
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
} else if let arrayValue = value as? [AnyHashable] {
return filterStrings(values: arrayValue)
} else if let dictValue = value as? [AnyHashable : AnyHashable] {
return filterStrings(values: Array(dictValue.values))
}
return nil
}
}
func filterDictionaries(values: [AnyHashable]) -> [AnyHashable : AnyHashable] {
return values.compactMap { value in
if let dictValue = value as? [AnyHashable : AnyHashable] {
return dictValue
} else if let arrayValue = value as? [AnyHashable] {
return filterDictionaries(values: arrayValue)
}
return nil
}
}
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap { value in
if let arrayValue = value as? [AnyHashable] {
return arrayValue
} else if let dictValue = value as? [AnyHashable : AnyHashable] {
return filterArrays(values: Array(dictValue.values))
}
return nil
}
}
func flatten(values: [AnyHashable]) -> [AnyHashable] {
var result: [AnyHashable] = []
for value in values {
if let arrayValue = value as? [AnyHashable] {
result += flatten(values: arrayValue)
} else {
result.append(value)
}
}
return result
}
func array(values: [AnyHashable]) -> [AnyHashable] {
return values
}
```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 { value in
if let intValue = value as? Int {
return intValue
} else if let doubleValue = value as? Double {
return Int(doubleValue)
} else if let stringValue = value as? String {
return Int(stringValue)
} else if let arrayValue = value as? [AnyHashable] {
return filterIntegers(values: arrayValue)
} else if let dictValue = value as? [AnyHashable : AnyHashable] {
return filterIntegers(values: Array(dictValue.values))
}
return nil
}
}
// Filter given array of any swiftthon values only for strings
// filterStrings(values: ["a", 3.14, 5]) == ["a", "3.14"]
// filterStrings(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
} else if let arrayValue = value as? [AnyHashable] {
return filterStrings(values: arrayValue)
} else if let dictValue = value as? [AnyHashable : AnyHashable] {
return filterStrings(values: Array(dictValue.values))
}
return nil
}
}
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: ["a", 3.14, 5]) == []
// filterDictionaries(values: [1, 2, 3, "abc", [:], []]) == [[:]]
func filterDictionaries(values: [AnyHashable]) -> [AnyHashable : AnyHashable] {
return values.compactMap { value in
if let dictValue = value as? [AnyHashable : AnyHashable] {
return dictValue
} else if let arrayValue = value as? [AnyHashable] {
return filterDictionaries(values: arrayValue)
}
return nil
}
}
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: ["a", 3.14, 5]) == []
// filterArrays(values: [1, 2, 3, "abc", [:], []]) == [[], [1, 2, 3, "abc", [:], []]]
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap { value in
if let arrayValue = value as? [AnyHashable] {
return arrayValue
} else if let dictValue = value as? [AnyHashable : AnyHashable] {
return filterArrays(values: Array(dictValue.values))
}
return nil
}
}
// Flatten given array of any swiftthon values
// flatten(values: ["a", 3.14, 5, [1, 2, 3, "abc", [:], []]]) == ["a", 3.14, 5, 1, 2, 3, "abc", [:], []]
func flatten(values: [AnyHashable]) -> [AnyHashable] {
var result: [AnyHashable] = []
for value in values {
if let arrayValue = value as? [AnyHashable] {
result += flatten(values: arrayValue)
} else {
result.append(value)
}
}
return result
}
// Return a new array of given array of any swiftthon values
// array(values: ["a", 3.14, 5]) == ["a", 3.14, 5]
// array(values: [1, 2, 3, "abc", [:], []]) == [1, 2, 3, "abc", [:], []]
func array(values: [AnyHashable]) -> [AnyHashable] {
return values
}
// Return a new dictionary of given array of any swiftthon values
// dictionary(values: ["a", 3.14, 5]) == [:a: 3.14, :b: 5]
// dictionary(values: [1, 2, 3, "abc", [:], []]) == [:0: 1, :1: 2, :2: 3, :3:
return Int(stringValue) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return filterStrings(values: arrayValue) // cannot convert value of type '[String]' to closure result type 'String'
return values.compactMap { value in // cannot convert return expression of type '[[AnyHashable : AnyHashable]]' to return type '[AnyHashable : AnyHashable]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
}
return nil
}
}
func filterDictionaries(values: [AnyHashable]) -> [AnyHashable : AnyHashable] {
return values.compactMap { value in
if let dictionaryValue = value as? [AnyHashable : AnyHashable] {
return dictionaryValue
}
return nil
}
}
func filterArrays(values: [AnyHashable]) -> [Any] {
return values.compactMap { value in
if let arrayValue = value as? [Any] {
return arrayValue
}
return nil
}
}
func filterNumbers(values: [AnyHashable]) -> [Double] {
return values.compactMap { value in
if let numberValue = value as? Double {
return numberValue
}
return nil
}
}
func filterBooleans(values: [AnyHashable]) -> [Bool] {
return values.compactMap { value in
if let booleanValue = value as? Bool {
return booleanValue
}
return nil
}
}
func filterData(values: [AnyHashable]) -> [Data] {
return values.compactMap { value in
if let dataValue = value as? Data {
return dataValue
}
return nil
}
}
func filterOptionalValues(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { value in
return value
}
}
```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 { value in
if let intValue = value as? Int {
return intValue
}
return nil
}
}
// Filter given array of any swiftthon values only for strings
// filterStrings(values: ["a", 3.14, 5]) == ["a"]
// filterStrings(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { value in
if let stringValue = value as? String {
return stringValue
}
return nil
}
}
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: ["a", 3.14, 5]) == []
// filterDictionaries(values: [1, 2, 3, "abc", [:], []]) == [:] as [AnyHashable : AnyHashable]
func filterDictionaries(values: [AnyHashable]) -> [AnyHashable : AnyHashable] {
return values.compactMap { value in
if let dictionaryValue = value as? [AnyHashable : AnyHashable] {
return dictionaryValue
}
return nil
}
}
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: ["a", 3.14, 5]) == []
// filterArrays(values: [1, 2, 3, "abc", [:], []]) == []
func filterArrays(values: [AnyHashable]) -> [Any] {
return values.compactMap { value in
if let arrayValue = value as? [Any] {
return arrayValue
}
return nil
}
}
// Filter given array of any swiftthon values only for numbers
// filterNumbers(values: ["a", 3.14, 5]) == [3.14]
// filterNumbers(values: [1, 2, 3, "abc", [:], []]) == []
func filterNumbers(values: [AnyHashable]) -> [Double] {
return values.compactMap { value in
if let numberValue = value as? Double {
return numberValue
}
return nil
}
}
// Filter given array of any swiftthon values only for booleans
// filterBooleans(values: ["a", 3.14, 5]) == []
// filterBooleans(values: [true, false, true]) == [true, false]
func filterBooleans(values: [AnyHashable]) -> [Bool] {
return values.compactMap { value in
if let booleanValue = value as? Bool {
return booleanValue
}
return nil
}
}
// Filter given array of any swiftthon values only for data
// filterData(values: ["a", 3.14, 5]) == []
// filterData(values: [Data(bytes: [0x01, 0x02, 0x03])]) == [Data(bytes: [0x01, 0x02, 0x03])]
func filterData(values: [AnyHashable]) -> [Data] {
return values.compactMap { value in
if let dataValue = value as? Data {
return dataValue
}
return nil
}
}
// Filter given array of any swiftthon values only for optional values
// filterOptionalValues(values: ["a", 3.14, 5]) == ["a", 3.14, 5]
// filterOptionalValues(values: [1, 2, 3, "abc", [:], nil]) == [1, 2, 3, "abc", [:]]
func filterOptionalValues(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { value in
return value
}
}
// Filter given array of any swiftthon values only for enums
// filterEnums(values: ["a", 3.14, 5]) == []
// filterEnums(values: [1, 2, 3, "abc", [:], nil]) == []
// filterEnums(values: [TestEnum.one, TestEnum.two, TestEnum.three]) == [TestEnum.one, TestEnum.two, TestEnum.three]
enum TestEnum: Int, Hashable {
return values.compactMap { value in // cannot convert return expression of type '[[AnyHashable : AnyHashable]]' to return type '[AnyHashable : AnyHashable]'
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let value = value as? Int {
return value
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// 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 { value in
if let value = value as? Int {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
} else if let value = $0 as? String, Int(value)!= nil {
return Int(value)!
} else {
return nil
}
}
}
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let
} else if let value = $0 as? String, Int(value)!= nil { // use of '=' in a boolean context, did you mean '=='?
} else if let value = $0 as? String, Int(value)!= nil { // 'nil' cannot be assigned to type 'Int'
} else if let value = $0 as? String, Int(value)!= nil { // cannot assign through '!': function call returns immutable value
} else if let value = $0 as? String, Int(value)!= nil { // '=' must have consistent whitespace on both sides
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
}
return nil
}
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap {
if let value = $0 as? String {
return value
}
return nil
}
}
func filterDictionaries(values: [AnyHashable]) -> [Dictionary<AnyHashable, AnyHashable>] {
return values.compactMap {
if let value = $0 as? Dictionary<AnyHashable, AnyHashable> {
return value
}
return nil
}
}
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap {
if let value = $0 as? [AnyHashable] {
return value
}
return nil
}
}
func filterSets(values: [AnyHashable]) -> [Set<AnyHashable>] {
return values.compactMap {
if let value = $0 as? Set<AnyHashable> {
return value
}
return nil
}
}
func filterTuples(values: [AnyHashable]) -> [(AnyHashable, AnyHashable)] {
return values.compactMap {
if let value = $0 as? (AnyHashable, AnyHashable) {
return value
}
return nil
}
}
func filterOptionalValues(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap {
return $0
}
}
enum Color: String, Hashable {
case Red, Green, Blue
}
func filterEnums(values: [AnyHashable]) -> [Color] {
return values.compactMap {
if let value = $0 as? Color {
return value
}
return nil
}
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap {
if let value = $0 as? Int {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for strings
// filterStrings(values: ["a", 3.14, 5]) == ["a"]
// filterStrings(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap {
if let value = $0 as? String {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: ["a", 3.14, 5]) == []
// filterDictionaries(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [:]]) == [[:]]
func filterDictionaries(values: [AnyHashable]) -> [Dictionary<AnyHashable, AnyHashable>] {
return values.compactMap {
if let value = $0 as? Dictionary<AnyHashable, AnyHashable> {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: ["a", 3.14, 5]) == []
// filterArrays(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [[], []]
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap {
if let value = $0 as? [AnyHashable] {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for sets
// filterSets(values: ["a", 3.14, 5]) == []
// filterSets(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [[:]]
func filterSets(values: [AnyHashable]) -> [Set<AnyHashable>] {
return values.compactMap {
if let value = $0 as? Set<AnyHashable> {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for tuples
// filterTuples(values: ["a", 3.14, 5]) == []
// filterTuples(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterTuples(values: [AnyHashable]) -> [(AnyHashable, AnyHashable)] {
return values.compactMap {
if let value = $0 as? (AnyHashable, AnyHashable) {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for optional values
// filterOptionalValues(values: ["a", 3.14, 5]) == ["a", 3.14, 5]
// filterOptionalValues(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3, "abc", [:], []]
func filterOptionalValues(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap {
return $0
}
}
// Filter given array of any swiftthon values only for enums
// filterEnums(values: ["a", 3.14, 5]) == []
// filterEnums(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
// filterEnums(values: [Red, Green, Blue]) == [Red, Green, Blue]
enum Color: String, Hashable {
case Red, Green, Blue
}
func filterEnums(values: [AnyHashable]) -> [Color] {
return values.compactMap {
if let value = $0 as? Color {
return value
}
return nil
}
}
// Filter given array of any swiftthon values only for
func strlen(string: String) -> Int {
if string.isEmpty {
return 0
} else {
return 1 + strlen(string: string.dropFirst())
}
}
func sumArray(array: [Int]) -> Int {
if array.isEmpty {
return 0
} else {
return array.first! + sumArray(array: Array(array.dropFirst()))
}
}
func factorial(number: Int) -> Int {
if number == 0 {
return 1
} else {
return number * factorial(number: number - 1)
}
}
func fibonacci(number: Int) -> Int {
if number == 0 {
return 0
} else if number == 1 {
return 1
} else {
return fibonacci(number: number - 1) + fibonacci(number: number - 2)
}
}
func sumFibs(number: Int) -> Int {
if number <= 2 {
return number
} else {
return fibonacci(number: number - 1) + sumFibs(number: number - 2)
}
}
func sumMult3Or5(number: Int) -> Int {
if number <= 0 {
return 0
} else if number % 3 == 0 && number % 5 == 0 {
return number + sumMult3Or5(number: number - 1)
} else if number % 3 == 0 {
return number + sumMult3Or5(number: number - 1)
} else if number % 5 == 0 {
return number + sumMult3Or5(number: number - 1)
} else {
return sumMult3Or5(number: number - 1)
}
}
func fibonacciRecursion(number: Int) -> Int {
if number <= 1 {
return number
} else {
return fibonacciRecursion(number: number - 1) + fibonacciRecursion(number: number - 2)
}
}
func sumFibsRecursion(number: Int) -> Int {
if number <= 2 {
return number
} else {
return fibonacciRecursion(number: number - 1) + sumFibsRecursion(number: number - 2)
}
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
if string.isEmpty {
return 0
} else {
return 1 + strlen(string: string.dropFirst())
}
}
// Return the sum of all the integers in the given array
// sumArray([1, 2, 3]) == 6
// sumArray([1, 2, 3, 4, 5]) == 15
func sumArray(array: [Int]) -> Int {
if array.isEmpty {
return 0
} else {
return array.first! + sumArray(array: Array(array.dropFirst()))
}
}
// Return the factorial of the given integer
// factorial(0) == 1
// factorial(5) == 120
func factorial(number: Int) -> Int {
if number == 0 {
return 1
} else {
return number * factorial(number: number - 1)
}
}
// Return the nth fibonacci number
// fibonacci(0) == 0
// fibonacci(1) == 1
// fibonacci(5) == 5
func fibonacci(number: Int) -> Int {
if number == 0 {
return 0
} else if number == 1 {
return 1
} else {
return fibonacci(number: number - 1) + fibonacci(number: number - 2)
}
}
// Return the sum of all the even fibonacci numbers less than or equal to the given integer
// sumFibs(10) == 10
// sumFibs(14) == 14
func sumFibs(number: Int) -> Int {
if number <= 2 {
return number
} else {
return fibonacci(number: number - 1) + sumFibs(number: number - 2)
}
}
// Return the sum of all the multiples of 3 or 5 below the given integer
// sumMult3Or5(10) == 23
// sumMult3Or5(1000) == 233168
func sumMult3Or5(number: Int) -> Int {
if number <= 0 {
return 0
} else if number % 3 == 0 && number % 5 == 0 {
return number + sumMult3Or5(number: number - 1)
} else if number % 3 == 0 {
return number + sumMult3Or5(number: number - 1)
} else if number % 5 == 0 {
return number + sumMult3Or5(number: number - 1)
} else {
return sumMult3Or5(number: number - 1)
}
}
// Return the nth Fibonacci number using recursion
// fibonacciRecursion(0) == 0
// fibonacciRecursion(1) == 1
// fibonacciRecursion(5) == 5
func fibonacciRecursion(number: Int) -> Int {
if number <= 1 {
return number
} else {
return fibonacciRecursion(number: number - 1) + fibonacciRecursion(number: number - 2)
}
}
// Return the sum of all the even fibonacci numbers less than or equal to the given integer
// using recursion
// sumFibsRecursion(10) == 10
// sumFibsRecursion(14) == 14
func sumFibsRecursion(number: Int) -> Int {
if number <= 2 {
return number
} else {
return fibonacciRecursion(number: number - 1) + sumFibsRecursion(number: number - 2)
}
}
// Return the sum of all the multiples of 3 or 5 below the given integer
// using recursion
// sumMult3Or5Recursion(10) == 23
// sumMult3Or5Recursion(1000) == 233168
func sumMult3Or5Recursion(number: Int) -> Int {
if number <= 0 {
return 0
} else if number % 3 == 0 && number % 5 == 0 {
return number + sumMult3Or5Recursion(number: number - 1)
} else if number %
return 1 + strlen(string: string.dropFirst()) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
func ucfirst(string: String) -> String {
guard!string.isEmpty else { return "" }
return string.prefix(1).uppercased() + string.dropFirst()
}
func nospace(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
func nopunc(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.punctuationCharacters)
}
func lowercase(string: String) -> String {
return string.lowercased()
}
func uppercase(string: String) -> String {
return string.uppercased()
}
func reversewords(string: String) -> String {
return string.components(separatedBy: " ").map(String.init).reversed().joined(separator: " ")
}
func ucwords(string: String) -> String {
return string.components(separatedBy: " ").map(ucfirst).joined(separator: " ")
}
func nochars(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
}
func printable(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(CharacterSet.controlCharacters))
}
func ascii(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.nonASCIICharacters)
}
```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 reversed string
// reverse(string: "") == ""
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
// Return string with first character as upper case
// ucfirst(string: "") == ""
// ucfirst(string: "abc") == "Abc"
func ucfirst(string: String) -> String {
guard!string.isEmpty else { return "" }
return string.prefix(1).uppercased() + string.dropFirst()
}
// Return string with all spaces removed
// nospace(string: "abc def") == "abcdef"
// nospace(string: "abc def") == "abcdef"
// nospace(string: "abc\tdef") == "abcdef"
// nospace(string: "abc\ndef") == "abcdef"
func nospace(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
// Return string with all punctuation marks removed
// nopunc(string: "Hello, world!") == "Hello world"
// nopunc(string: "Hello world") == "Hello world"
// nopunc(string: "Hello-world") == "Hello-world"
func nopunc(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.punctuationCharacters)
}
// Return string with all letters converted to lowercase
// lowercase(string: "Hello World") == "hello world"
func lowercase(string: String) -> String {
return string.lowercased()
}
// Return string with all letters converted to uppercase
// uppercase(string: "Hello World") == "HELLO WORLD"
func uppercase(string: String) -> String {
return string.uppercased()
}
// Return string with words reversed
// reversewords(string: "Hello World") == "World Hello"
// reversewords(string: "Hello World") == "World Hello"
// reversewords(string: "Hello\nWorld") == "World Hello"
func reversewords(string: String) -> String {
return string.components(separatedBy: " ").map(String.init).reversed().joined(separator: " ")
}
// Return string with first character of each word upper cased
// ucwords(string: "hello world") == "Hello World"
// ucwords(string: "hello world") == "Hello World"
func ucwords(string: String) -> String {
return string.components(separatedBy: " ").map(ucfirst).joined(separator: " ")
}
// Return string with all special characters removed
// nochars(string: "Hello, world!") == "Hello world"
// nochars(string: "Hello world") == "Hello world"
// nochars(string: "Hello-world") == "Hello-world"
func nochars(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
}
// Return string with all non-printable characters removed
// printable(string: "\n\tHello, world!\n\t") == "Hello, world!"
// printable(string: "Hello, world!") == "Hello, world!"
// printable(string: "\n\t") == ""
func printable(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(CharacterSet.controlCharacters))
}
// Return string with all non-ASCII characters removed
// ascii(string: "Hello, world!") == "Hello, world!"
// ascii(string: "Hello, 世界!") == "Hello, 世界!"
func ascii(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.nonASCIICharacters)
}
// Return string with all HTML tags removed
// html(string: "<b>Hello, world!</b>") == "Hello, world!"
// html(string: "Hello, <b>world!</b>") == "Hello, world!"
func html(string: String) -> String {
return string.replacingOccurrences(of: "<[^>]*
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
return string.components(separatedBy: " ").map(String.init).reversed().joined(separator: " ") // ambiguous use of 'init'
return string.trimmingCharacters(in: CharacterSet.nonASCIICharacters) // type 'CharacterSet' has no member 'nonASCIICharacters'
func strlen(string: String) -> Int {
return 0
}
func sum(array: [Int]) -> Int {
return 0
}
func uniqueValues(array: [Int]) -> Int {
return 0
}
func reverse(string: String) -> String {
return ""
}
func permutations(string: String) -> [String] {
return []
}
func combinations(array: [Int]) -> [[Int]] {
return []
}
func isSorted(array: [Int]) -> Bool {
return true
}
func containsDuplicates(array: [Int]) -> Bool {
return false
}
func pairs(array: [Int], sum: Int) -> [(Int, Int)] {
return []
}
func zeroSumPairs(array: [Int]) -> [(Int, Int)] {
return []
}
func subarrays(array: [Int]) -> [[Int]] {
return []
}
func isPalindrome(array: [Int]) -> Bool {
return true
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return 0
}
// Return sum of all numbers in given array
// sum(array: []) == 0
// sum(array: [1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return 0
}
// Return count of all unique values in given array
// uniqueValues(array: []) == 0
// uniqueValues(array: [1, 2, 3, 1, 2, 3]) == 3
func uniqueValues(array: [Int]) -> Int {
return 0
}
// Return reversed string
// reverse(string: "") == ""
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
return ""
}
// Return array of all permutations of given string
// permutations(string: "") == [""]
// permutations(string: "abc") == ["abc", "acb", "bac", "bca", "cab", "cba"]
func permutations(string: String) -> [String] {
return []
}
// Return array of all combinations of given array
// combinations(array: []) == [[]]
// combinations(array: [1, 2, 3]) == [[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
func combinations(array: [Int]) -> [[Int]] {
return []
}
// Return true if given array is sorted in ascending order
// isSorted(array: []) == true
// isSorted(array: [1]) == true
// isSorted(array: [1, 2, 3]) == true
// isSorted(array: [3, 2, 1]) == false
func isSorted(array: [Int]) -> Bool {
return true
}
// Return true if given array contains duplicates
// containsDuplicates(array: []) == false
// containsDuplicates(array: [1]) == false
// containsDuplicates(array: [1, 2, 3]) == false
// containsDuplicates(array: [1, 2, 2, 3]) == true
func containsDuplicates(array: [Int]) -> Bool {
return false
}
// Return array of all pairs of elements that sum to given value
// pairs(array: [], sum: 10) == []
// pairs(array: [1, 2, 3, 4], sum: 6) == [(1, 5), (2, 4)]
// pairs(array: [1, 2, 3, 4], sum: 7) == [(1, 6), (2, 5), (3, 4)]
func pairs(array: [Int], sum: Int) -> [(Int, Int)] {
return []
}
// Return array of all pairs of elements that sum to zero from given array
// zeroSumPairs(array: []) == []
// zeroSumPairs(array: [1, 2, 3, 4]) == [(1, 4), (2, 3)]
// zeroSumPairs(array: [1, 2, 3, 4, 5]) == [(1, 5), (2, 4), (3, 3)]
func zeroSumPairs(array: [Int]) -> [(Int, Int)] {
return []
}
// Return array of all subarrays of given array
// subarrays(array: []) == [[]]
// subarrays(array: [1]) == [[1]]
// subarrays(array: [1, 2, 3]) == [[1], [2], [3], [1, 2], [2, 3], [1, 2, 3]]
func subarrays(array: [Int]) -> [[Int]] {
return []
}
// Return true if given array is a palindrome
// isPalindrome(array: []) == true
// isPalindrome(array: [1]) == true
// isPalindrome(array: [1, 2, 3, 2, 1]) == true
// isPalindrome(array: [1, 2, 3, 4, 5]) == false
func isPalindrome(array: [Int]) -> Bool {
return true
}
// Return true if given array is a permutation of a palind
// XCTAssertTrue failed
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
func ucfirst(string: String) -> String {
guard!string.isEmpty else { return "" }
return string.prefix(1).uppercased() + string.dropFirst()
}
func nospace(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
func nonalpha(string: String) -> String {
return string.filter {!Character.isLetter($0) }
}
func nondigit(string: String) -> String {
return string.filter {!Character.isNumber($0) }
}
func nonalnum(string: String) -> String {
return string.filter {!Character.isLetterOrDigit($0) }
}
func compact(string: String) -> String {
return string.trimmingCharacters(in:.whitespacesAndNewlines)
}
func compact(string: String, preserveNewlines: Bool) -> String {
if preserveNewlines {
return string.trimmingCharacters(in:.whitespacesAndNewlines)
} else {
return string.trimmingCharacters(in:.whitespaces)
}
}
func remove(string: String, character: Character) -> String {
var result = ""
for char in string {
if char!= character {
result.append(char)
}
}
return result
}
func whitelist(string: String, whitelist: String) -> String {
var result = ""
for char in string {
if whitelist.contains(char) {
result.append(char)
}
}
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 reversed string
// reverse(string: "") == ""
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
// Return string with first character as upper case
// ucfirst(string: "") == ""
// ucfirst(string: "abc") == "Abc"
func ucfirst(string: String) -> String {
guard!string.isEmpty else { return "" }
return string.prefix(1).uppercased() + string.dropFirst()
}
// Return string with all spaces removed
// nospace(string: "abc def") == "abcdef"
// nospace(string: "abc def") == "abcdef"
// nospace(string: "abc\tdef") == "abcdef"
func nospace(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
// Return string with all characters except alphabets removed
// nonalpha(string: "abc def") == " def"
// nonalpha(string: "abc123 def") == "123 def"
// nonalpha(string: "abc!@#$% def") == "!@#$% def"
func nonalpha(string: String) -> String {
return string.filter {!Character.isLetter($0) }
}
// Return string with all characters except digits removed
// nondigit(string: "abc123 def") == "abc def"
// nondigit(string: "abc!@#$% def") == "abc!@#$% def"
func nondigit(string: String) -> String {
return string.filter {!Character.isNumber($0) }
}
// Return string with all characters except alphabets and digits removed
// nonalnum(string: "abc123 def") == " def"
// nonalnum(string: "abc!@#$% def") == "!@#$% def"
func nonalnum(string: String) -> String {
return string.filter {!Character.isLetterOrDigit($0) }
}
// Return string with all consecutive spaces removed
// compact(string: "abc def") == "abc def"
// compact(string: "abc def") == "abc def"
// compact(string: "abc\t def") == "abc def"
func compact(string: String) -> String {
return string.trimmingCharacters(in:.whitespacesAndNewlines)
}
// Return string with all consecutive spaces and newlines removed
// compact(string: "abc\n def\n\n") == "abc def"
func compact(string: String, preserveNewlines: Bool) -> String {
if preserveNewlines {
return string.trimmingCharacters(in:.whitespacesAndNewlines)
} else {
return string.trimmingCharacters(in:.whitespaces)
}
}
// Return string with all occurrences of character c removed
// remove(string: "abc def", character: "d") == "abc def"
// remove(string: "abc def", character: "e") == "abc d"
func remove(string: String, character: Character) -> String {
var result = ""
for char in string {
if char!= character {
result.append(char)
}
}
return result
}
// Return string with all characters except those in the whitelist removed
// whitelist(string: "abc def", whitelist: "abc") == "def"
// whitelist(string: "abc def", whitelist: "abc def") == "abc def"
// whitelist(string: "abc def", whitelist: "abc", " ") == " def"
func whitelist(string: String, whitelist: String) -> String {
var result = ""
for char in string {
if whitelist.contains(char) {
result.append(char)
}
}
return result
}
// Return string with all characters in the whitelist replaced by the corresponding character in the map
// whitelist(string: "abc def", whitelist: "abc", map: ["d": "x", "e": "x"])
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
return string.filter {!Character.isLetter($0) } // cannot call value of non-function type 'Bool'
return string.filter {!Character.isLetter($0) } // instance member 'isLetter' cannot be used on type 'Character'; did you mean to use a value of this type instead?
return string.filter {!Character.isNumber($0) } // cannot call value of non-function type 'Bool'
return string.filter {!Character.isNumber($0) } // instance member 'isNumber' cannot be used on type 'Character'; did you mean to use a value of this type instead?
return string.filter {!Character.isLetterOrDigit($0) } // type 'Character' has no member 'isLetterOrDigit'
if char!= character { // '=' must have consistent whitespace on both sides
if char!= character { // cannot force unwrap value of non-optional type 'Character'
if char!= character { // use of '=' in a boolean context, did you mean '=='?
func strlen(string: String) -> Int {
if string.isEmpty {
return 0
} else {
return 1 + strlen(string: string.dropFirst())
}
}
func sum(n: Int) -> Int {
if n == 0 {
return 0
} else {
return n + sum(n: n - 1)
}
}
func factorial(n: Int) -> Int {
if n == 0 {
return 1
} else {
return n * factorial(n: n - 1)
}
}
func fibonacci(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fibonacci(n: n - 1) + fibonacci(n: n - 2)
}
}
func prime(n: Int) -> Int {
if n == 0 {
return 2
} else {
var i = 3
while i < 100000 {
if isPrime(i) {
n += 1
if n == 1 {
return i
}
}
i += 2
}
}
return 0
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
} else {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
}
func reverse(_ string: String) -> String {
if string.isEmpty {
return ""
} else {
return reverse(string.dropLast()) + string.first!
}
}
func fibonacciDynamic(_ n: Int) -> Int {
var fib = [Int]()
fib.append(0)
fib.append(1)
for i in 2...n {
fib.append(fib[i - 1] + fib[i - 2])
}
return fib[n]
}
func primeDynamic(_ n: Int) -> Int {
var prime = [Int]()
prime.append(2)
var i = 3
while prime.count < n {
if isPrime(i) {
prime.append(i)
}
i += 2
}
return prime[n - 1]
}
func isPalindrome(_ n: Int) -> Bool {
return String(n) == String(String(n).reversed())
}
func sumSquares(_ n: Int) -> Int {
if n == 0 {
return 0
} else {
return n * (n + 1) * (2 * n + 1) / 6
}
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
if string.isEmpty {
return 0
} else {
return 1 + strlen(string: string.dropFirst())
}
}
// Return sum of first n natural numbers
// sum(n: 0) == 0
// sum(n: 1) == 1
// sum(n: 5) == 15
func sum(n: Int) -> Int {
if n == 0 {
return 0
} else {
return n + sum(n: n - 1)
}
}
// Return the factorial of a given number
// factorial(0) == 1
// factorial(5) == 120
func factorial(n: Int) -> Int {
if n == 0 {
return 1
} else {
return n * factorial(n: n - 1)
}
}
// Return the nth fibonacci number
// fibonacci(0) == 0
// fibonacci(1) == 1
// fibonacci(5) == 5
func fibonacci(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fibonacci(n: n - 1) + fibonacci(n: n - 2)
}
}
// Return the nth prime number
// prime(0) == 2
// prime(1) == 3
// prime(5) == 11
func prime(n: Int) -> Int {
if n == 0 {
return 2
} else {
var i = 3
while i < 100000 {
if isPrime(i) {
n += 1
if n == 1 {
return i
}
}
i += 2
}
}
return 0
}
// Check if a given number is prime
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
} else {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
}
// Reverse a given string
// reverse("") == ""
// reverse("abc") == "cba"
func reverse(_ string: String) -> String {
if string.isEmpty {
return ""
} else {
return reverse(string.dropLast()) + string.first!
}
}
// Return the nth Fibonacci number using dynamic programming
// fibonacciDynamic(0) == 0
// fibonacciDynamic(1) == 1
// fibonacciDynamic(5) == 5
func fibonacciDynamic(_ n: Int) -> Int {
var fib = [Int]()
fib.append(0)
fib.append(1)
for i in 2...n {
fib.append(fib[i - 1] + fib[i - 2])
}
return fib[n]
}
// Return the nth prime number using dynamic programming
// primeDynamic(0) == 2
// primeDynamic(1) == 3
// primeDynamic(5) == 11
func primeDynamic(_ n: Int) -> Int {
var prime = [Int]()
prime.append(2)
var i = 3
while prime.count < n {
if isPrime(i) {
prime.append(i)
}
i += 2
}
return prime[n - 1]
}
// Check if a given number is palindrome
// isPalindrome(121) == true
// isPalindrome(123) == false
func isPalindrome(_ n: Int) -> Bool {
return String(n) == String(String(n).reversed())
}
// Return the sum of squares of first n natural numbers
// sumSquares(0) == 0
// sumSquares(3) == 14
func sumSquares(_ n: Int) -> Int {
if n == 0 {
return 0
} else {
return n * (n + 1) * (2 * n + 1) / 6
}
}
// Return the sum of cubes of first n natural numbers
// sumCubes(0) == 0
//
return 1 + strlen(string: string.dropFirst()) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
n += 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
return reverse(string.dropLast()) + string.first! // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
return reverse(string.dropLast()) + string.first! // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
func isPalindrome(string: String) -> Bool {
if string == "" {
return true
}
if string.count == 1 {
return true
}
if string.count == 2 {
return string[0] == string[1]
}
if string[0] == string.last! {
return isPalindrome(string: String(string.suffix(from: 1)))
}
return false
}
func upper(string: String) -> String {
var upperString = ""
for char in string {
upperString += "\(char.uppercased())"
}
return upperString
}
func lower(string: String) -> String {
var lowerString = ""
for char in string {
lowerString += "\(char.lowercased())"
}
return lowerString
}
func capitalize(string: String) -> String {
var capitalizedString = ""
for (index, char) in string.enumerated() {
if index == 0 {
capitalizedString += "\(char.uppercased())"
} else {
capitalizedString += "\(char.lowercased())"
}
}
return capitalizedString
}
func dropFirst(string: String) -> String {
return String(string.suffix(from: 1))
}
func dropLast(string: String) -> String {
return String(string.prefix(upTo: string.count - 1))
}
func chop(string: String) -> String {
return String(string.suffix(from: 1).prefix(upTo: string.count - 2))
}
func chomp(string: String) -> String {
if string.hasSuffix("\n") {
return String(string.suffix(from: 1).prefix(upTo: string.count - 2))
} else {
return String(string.suffix(from: 1))
}
}
```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 reversed string
// reverse(string: "") == ""
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
// Return true if string is palindrome
// isPalindrome(string: "") == true
// isPalindrome(string: "a") == true
// isPalindrome(string: "ab") == false
// isPalindrome(string: "abc") == true
// isPalindrome(string: "abcba") == true
// isPalindrome(string: "abacdfgdcaba") == true
func isPalindrome(string: String) -> Bool {
if string == "" {
return true
}
if string.count == 1 {
return true
}
if string.count == 2 {
return string[0] == string[1]
}
if string[0] == string.last! {
return isPalindrome(string: String(string.suffix(from: 1)))
}
return false
}
// Return uppercase string
// upper(string: "") == ""
// upper(string: "abc") == "ABC"
// upper(string: "abc def") == "ABC DEF"
func upper(string: String) -> String {
var upperString = ""
for char in string {
upperString += "\(char.uppercased())"
}
return upperString
}
// Return lowercase string
// lower(string: "") == ""
// lower(string: "ABC") == "abc"
// lower(string: "ABC DEF") == "abc def"
func lower(string: String) -> String {
var lowerString = ""
for char in string {
lowerString += "\(char.lowercased())"
}
return lowerString
}
// Return string with first character capitalized
// capitalize(string: "") == ""
// capitalize(string: "abc") == "Abc"
// capitalize(string: "abc def") == "Abc def"
func capitalize(string: String) -> String {
var capitalizedString = ""
for (index, char) in string.enumerated() {
if index == 0 {
capitalizedString += "\(char.uppercased())"
} else {
capitalizedString += "\(char.lowercased())"
}
}
return capitalizedString
}
// Return string with all characters but first removed
// dropFirst(string: "") == ""
// dropFirst(string: "abc") == "bc"
// dropFirst(string: "abc def") == " def"
func dropFirst(string: String) -> String {
return String(string.suffix(from: 1))
}
// Return string with all characters but last removed
// dropLast(string: "") == ""
// dropLast(string: "abc") == "abc"
// dropLast(string: "abc def") == "abc "
func dropLast(string: String) -> String {
return String(string.prefix(upTo: string.count - 1))
}
// Return string with all characters but first and last removed
// chop(string: "") == ""
// chop(string: "abc") == "bc"
// chop(string: "abc def") == " def"
func chop(string: String) -> String {
return String(string.suffix(from: 1).prefix(upTo: string.count - 2))
}
// Return string with all characters but first and last removed
// chomp(string: "") == ""
// chomp(string: "abc") == "abc"
// chomp(string: "abc\n") == "abc"
// chomp(string: "abc\n\n") == "abc\n"
func chomp(string: String) -> String {
if string.hasSuffix("\n") {
return String(string.suffix(from: 1).prefix(upTo: string.count - 2))
} else {
return String(string.suffix(from: 1))
}
}
// Return string with all characters but first and last removed
// chomp(string: "") == ""
// chomp(string: "abc") == "
return string[0] == string[1] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return string[0] == string[1] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[0] == string.last! { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return isPalindrome(string: String(string.suffix(from: 1))) // cannot convert value of type 'Int' to expected argument type 'String.Index'
return String(string.suffix(from: 1)) // cannot convert value of type 'Int' to expected argument type 'String.Index'
return String(string.prefix(upTo: string.count - 1)) // cannot convert value of type 'Int' to expected argument type 'String.Index'
return String(string.suffix(from: 1).prefix(upTo: string.count - 2)) // cannot convert value of type 'Int' to expected argument type 'String.Index'
return String(string.suffix(from: 1).prefix(upTo: string.count - 2)) // cannot convert value of type 'Int' to expected argument type 'Substring.Index' (aka 'String.Index')
return String(string.suffix(from: 1).prefix(upTo: string.count - 2)) // cannot convert value of type 'Int' to expected argument type 'String.Index'
return String(string.suffix(from: 1).prefix(upTo: string.count - 2)) // cannot convert value of type 'Int' to expected argument type 'Substring.Index' (aka 'String.Index')
return String(string.suffix(from: 1)) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
func upper(string: String) -> String {
var upperString = ""
for char in string {
upperString += "\(char.uppercased())"
}
return upperString
}
func lower(string: String) -> String {
var lowerString = ""
for char in string {
lowerString += "\(char.lowercased())"
}
return lowerString
}
func ucfirst(string: String) -> String {
var firstChar = ""
for char in string {
firstChar = "\(char)"
break
}
return firstChar.uppercased() + lower(string: string.dropFirst())
}
func substring(string: String, start: Int, end: Int) -> String {
var substring = ""
var count = 0
for char in string {
if count >= start && count <= end {
substring += "\(char)"
}
count += 1
}
return substring
}
func after(string: String, character: Character) -> String {
var afterString = ""
var found = false
for char in string {
if char == character &&!found {
found = true
} else if found {
afterString += "\(char)"
}
}
return afterString
}
func before(string: String, character: Character) -> String {
var beforeString = ""
var found = false
for char in string {
if char == character &&!found {
found = true
} else {
beforeString += "\(char)"
}
}
return beforeString
}
func between(string: String, start: Character, end: Character) -> String {
var betweenString = ""
var foundStart = false
var foundEnd = false
for char in string {
if char == start &&!foundStart {
foundStart = true
} else if char == end && foundStart &&!foundEnd {
foundEnd = true
} else if foundStart &&!foundEnd {
betweenString += "\(char)"
}
}
return betweenString
}
```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 reversed string
// reverse(string: "") == ""
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
// Return uppercase string
// upper(string: "") == ""
// upper(string: "abc") == "ABC"
func upper(string: String) -> String {
var upperString = ""
for char in string {
upperString += "\(char.uppercased())"
}
return upperString
}
// Return lowercase string
// lower(string: "") == ""
// lower(string: "ABC") == "abc"
func lower(string: String) -> String {
var lowerString = ""
for char in string {
lowerString += "\(char.lowercased())"
}
return lowerString
}
// Return string with first character as upper case
// ucfirst(string: "") == ""
// ucfirst(string: "abc") == "Abc"
func ucfirst(string: String) -> String {
var firstChar = ""
for char in string {
firstChar = "\(char)"
break
}
return firstChar.uppercased() + lower(string: string.dropFirst())
}
// Return substring from start to end (inclusive)
// substring(string: "", start: 0, end: 0) == ""
// substring(string: "abc", start: 0, end: 0) == ""
// substring(string: "abc", start: 0, end: 1) == "a"
// substring(string: "abc", start: 0, end: 2) == "ab"
// substring(string: "abc", start: 1, end: 2) == "bc"
func substring(string: String, start: Int, end: Int) -> String {
var substring = ""
var count = 0
for char in string {
if count >= start && count <= end {
substring += "\(char)"
}
count += 1
}
return substring
}
// Return substring after first occurrence of character
// after(string: "", character: "") == ""
// after(string: "abc", character: "a") == "bc"
// after(string: "abc", character: "b") == ""
func after(string: String, character: Character) -> String {
var afterString = ""
var found = false
for char in string {
if char == character &&!found {
found = true
} else if found {
afterString += "\(char)"
}
}
return afterString
}
// Return substring before first occurrence of character
// before(string: "", character: "") == ""
// before(string: "abc", character: "c") == "ab"
// before(string: "abc", character: "b") == "a"
func before(string: String, character: Character) -> String {
var beforeString = ""
var found = false
for char in string {
if char == character &&!found {
found = true
} else {
beforeString += "\(char)"
}
}
return beforeString
}
// Return substring between two characters
// between(string: "", start: "", end: "") == ""
// between(string: "abc", start: "a", end: "c") == "b"
// between(string: "abc", start: "b", end: "a") == ""
func between(string: String, start: Character, end: Character) -> String {
var betweenString = ""
var foundStart = false
var foundEnd = false
for char in string {
if char == start &&!foundStart {
foundStart = true
} else if char == end && foundStart &&!foundEnd {
foundEnd = true
} else if foundStart &&!foundEnd {
betweenString += "\(char)"
}
}
return betweenString
}
// Return string with all special characters removed
// noSpecial(string: "") == ""
// noSpecial(string: "abc123") == "abc123"
// noSpecial(string: "abc!@#$%") == "abc123"
func noSpecial(string: String
return firstChar.uppercased() + lower(string: string.dropFirst()) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
if char == character &&!found { // expected '{' after 'if' condition
var found = false // variable 'found' was written to, but never read
if char == character &&!found { // expected '{' after 'if' condition
var foundEnd = false // variable 'foundEnd' was written to, but never read
if char == start &&!foundStart { // expected '{' after 'if' condition
} else if char == end && foundStart &&!foundEnd { // expected '{' after 'if' condition
} else if foundStart &&!foundEnd { // expected '{' after 'if' condition
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
func sumascii(string: String) -> Int {
var sum = 0
for char in string {
sum += Int(char.asciiValue!)
}
return sum
}
func sumasciiexcludingvowels(string: String) -> Int {
var sum = 0
for char in string {
if!"aeiouAEIOU".contains(char) {
sum += Int(char.asciiValue!)
}
}
return sum
}
func sumofascii(string: String) -> (Int, Int) {
var evenSum = 0
var oddSum = 0
for (index, char) in string.characters.enumerate() {
if index % 2 == 0 {
evenSum += Int(char.asciiValue!)
} else {
oddSum += Int(char.asciiValue!)
}
}
return (evenSum, oddSum)
}
func concat(str1: String, str2: String) -> String {
return str1 + str2
}
func firstcharremoved(string: String) -> String {
return String(string.characters.dropFirst())
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
// Return the sum of the ASCII values of all characters in the given string
// sumascii(string: "") == 0
// sumascii(string: "abc") == 97 + 98 + 99 = 306
func sumascii(string: String) -> Int {
var sum = 0
for char in string {
sum += Int(char.asciiValue!)
}
return sum
}
// Return the sum of the ASCII values of all characters in the given string, excluding any vowels
// sumasciiexcludingvowels(string: "") == 0
// sumasciiexcludingvowels(string: "abc") == 97 + 98 + 99 = 306
// sumasciiexcludingvowels(string: "aeiou") == 0
// sumasciiexcludingvowels(string: "bcdef") == 98 + 99 + 100 = 306
func sumasciiexcludingvowels(string: String) -> Int {
var sum = 0
for char in string {
if!"aeiouAEIOU".contains(char) {
sum += Int(char.asciiValue!)
}
}
return sum
}
// Return the sum of the ASCII values of all even-indexed characters in the given string,
// and the sum of the ASCII values of all odd-indexed characters in the given string.
// The input string will always contain a minimum of 1 character, and a maximum of 50 characters.
// sumofascii(string: "") == (0, 0)
// sumofascii(string: "abc") == (97, 98, 99)
// sumofascii(string: "abcdef") == (97, 98, 99, 100, 101)
func sumofascii(string: String) -> (Int, Int) {
var evenSum = 0
var oddSum = 0
for (index, char) in string.characters.enumerate() {
if index % 2 == 0 {
evenSum += Int(char.asciiValue!)
} else {
oddSum += Int(char.asciiValue!)
}
}
return (evenSum, oddSum)
}
// Return the concatenation of the first string with the second string,
// the first string and the second string concatenated together,
// and the length of the first string concatenated with the length of the second string.
// concat(str1: "", str2: "") == ""
// concat(str1: "a", str2: "") == "a"
// concat(str1: "ab", str2: "cd") == "abcd"
// concat(str1: "abc", str2: "def") == "abcdef"
// concat(str1: "ab", str2: "cd") == "abcd"
// concat(str1: "abc", str2: "def") == "abcdef"
// concat(str1: "abc", str2: "def") == "abcdef"
// concat(str1: "abc", str2: "def") == "abcdef"
// concat(str1: "abcdef", str2: "ghijklmnop") == "abcdefghijklmnop"
// concat(str1: "abc", str2: "defghijklmnop") == "abcdefghijklmnop"
// concat(str1: "abcdefghijklmnop", str2: "qrstuvwxyz") == "abcdefghijklmnopqrstuvwxyz"
func concat(str1: String, str2: String) -> String {
return str1 + str2
}
// Return the string with the first character removed
// firstcharremoved(string: "") == ""
// firstcharremoved(string: "a") == ""
// firstcharremoved(string: "abc") == "bc"
// firstcharremoved(string: "abcdef") == "def"
func firstcharremoved(string: String) -> String {
return String(string.characters.dropFirst())
}
// Return the string with the last character removed
// lastcharremoved(string: "") == ""
// lastcharremoved(string: "a") == ""
// lastcharremoved(string: "abc") == "ab"
// lastcharremoved(string: "
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
for (index, char) in string.characters.enumerate() { // value of type 'String' has no member 'enumerate'
return String(string.characters.dropFirst()) // 'characters' is unavailable: Please use String directly
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
func ucfirst(string: String) -> String {
guard!string.isEmpty else { return "" }
return string.prefix(1).uppercased() + string.dropFirst()
}
func nospace(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
func nopunc(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.punctuationCharacters)
}
func reversewords(string: String) -> String {
return string.components(separatedBy: " ").map(reverse).joined(separator: " ")
}
func isalpha(string: String) -> Bool {
for char in string {
if!CharacterSet.alphabetic.contains(char) {
return false
}
}
return true
}
func isalnum(string: String) -> Bool {
for char in string {
if!CharacterSet.alphanumerics.contains(char) {
return false
}
}
return true
}
func isdigit(string: String) -> Bool {
for char in string {
if!CharacterSet.decimalDigits.contains(char) {
return false
}
}
return true
}
func isxdigit(string: String) -> Bool {
for char in string {
if!CharacterSet.hexadecimalDigits.contains(char) {
return false
}
}
return true
}
func isupper(string: String) -> Bool {
for char in string {
if!CharacterSet.uppercaseLetters.contains(char) {
return false
}
}
return true
}
```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 reversed string
// reverse(string: "") == ""
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
var reversed = ""
for char in string {
reversed = "\(char)" + reversed
}
return reversed
}
// Return string with first character as upper case
// ucfirst(string: "") == ""
// ucfirst(string: "abc") == "Abc"
func ucfirst(string: String) -> String {
guard!string.isEmpty else { return "" }
return string.prefix(1).uppercased() + string.dropFirst()
}
// Return string with all spaces removed
// nospace(string: "abc def") == "abcdef"
// nospace(string: "abc def") == "abcdef"
// nospace(string: "abc\tdef") == "abcdef"
func nospace(string: String) -> String {
return string.replacingOccurrences(of: " ", with: "")
}
// Return string with all punctuation marks removed
// nopunc(string: "Hello, world!") == "Hello world"
// nopunc(string: "Hello world") == "Hello world"
// nopunc(string: "Hello-world") == "Hello-world"
func nopunc(string: String) -> String {
return string.trimmingCharacters(in: CharacterSet.punctuationCharacters)
}
// Return string with words reversed
// reversewords(string: "Hello world") == "dlrow olleH"
// reversewords(string: "Hello") == "olleH"
// reversewords(string: "Hello world, how are you?") == "you? are how world Hello"
func reversewords(string: String) -> String {
return string.components(separatedBy: " ").map(reverse).joined(separator: " ")
}
// Return true if string contains only alphabetic characters
// isalpha(string: "abc") == true
// isalpha(string: "abc123") == false
func isalpha(string: String) -> Bool {
for char in string {
if!CharacterSet.alphabetic.contains(char) {
return false
}
}
return true
}
// Return true if string contains only alphanumeric characters
// isalnum(string: "abc123") == true
// isalnum(string: "abc123!") == false
func isalnum(string: String) -> Bool {
for char in string {
if!CharacterSet.alphanumerics.contains(char) {
return false
}
}
return true
}
// Return true if string contains only digits
// isdigit(string: "123") == true
// isdigit(string: "abc123") == false
func isdigit(string: String) -> Bool {
for char in string {
if!CharacterSet.decimalDigits.contains(char) {
return false
}
}
return true
}
// Return true if string contains only hexadecimal characters
// isxdigit(string: "abc123") == false
// isxdigit(string: "abcdef") == false
// isxdigit(string: "ABC123") == false
// isxdigit(string: "ABCDEF") == false
// isxdigit(string: "abcdefABCDEF0123") == true
func isxdigit(string: String) -> Bool {
for char in string {
if!CharacterSet.hexadecimalDigits.contains(char) {
return false
}
}
return true
}
// Return true if string contains only uppercase alphabetic characters
// isupper(string: "ABC") == true
// isupper(string: "abc") == false
func isupper(string: String) -> Bool {
for char in string {
if!CharacterSet.uppercaseLetters.contains(char) {
return false
}
}
return true
}
// Return true if string contains only lowercase alphabetic characters
// islower(string: "abc") == true
// islower(string: "ABC") == false
func islower(string: String) -> Bool {
for char in string {
if!CharacterSet.lowercaseLetters.contains(char) {
return false
}
}
return true
guard!string.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
if!CharacterSet.alphabetic.contains(char) { // expected expression, var, or let in 'if' condition
if!CharacterSet.alphanumerics.contains(char) { // expected expression, var, or let in 'if' condition
if!CharacterSet.decimalDigits.contains(char) { // expected expression, var, or let in 'if' condition
if!CharacterSet.hexadecimalDigits.contains(char) { // expected expression, var, or let in 'if' condition
if!CharacterSet.uppercaseLetters.contains(char) { // expected expression, var, or let in 'if' condition
func strlen(string: String) -> Int {
if string.isEmpty {
return 0
} else {
return 1 + strlen(string: string.dropFirst())
}
}
func sum(n: Int) -> Int {
if n == 0 {
return 0
} else {
return n + sum(n: n - 1)
}
}
func factorial(n: Int) -> Int {
if n == 0 {
return 1
} else {
return n * factorial(n: n - 1)
}
}
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 product(string: String) -> String {
if string.count == 1 {
return string
} else {
return string.prefix(1) + product(string: string.dropFirst())
}
}
func sum_of_squares(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n * n + sum_of_squares(n: n - 1)
}
}
func square_of_sum(n: Int) -> Int {
return sum(n: n) * sum(n: n)
}
func difference(n: Int) -> Int {
return square_of_sum(n: n) - sum_of_squares(n: n)
}
func is_palindrome(number: Int) -> Bool {
if number < 10 {
return true
} else {
let lastDigit = number % 10
let firstDigit = number / 10
return lastDigit == firstDigit && is_palindrome(number: number / 10)
}
}
func digits(number: Int) -> Int {
if number < 10 {
return 1
} else {
return 1 + digits(number: number / 10)
}
}
func cubes_sum(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n * n * n + cubes_sum(n: n - 1)
}
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
if string.isEmpty {
return 0
} else {
return 1 + strlen(string: string.dropFirst())
}
}
// Return the sum of the first n integers
// sum(n: 0) == 0
// sum(n: 1) == 1
// sum(n: 5) == 15
func sum(n: Int) -> Int {
if n == 0 {
return 0
} else {
return n + sum(n: n - 1)
}
}
// Return the factorial of a given number
// factorial(0) == 1
// factorial(5) == 120
func factorial(n: Int) -> Int {
if n == 0 {
return 1
} else {
return n * factorial(n: n - 1)
}
}
// Return the nth fibonacci number
// fib(0) == 0
// fib(1) == 1
// fib(5) == 5
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)
}
}
// Return the product of a given string
// product("abc") == "a"
// product("abcd") == "ab"
// product("abcde") == "abcde"
func product(string: String) -> String {
if string.count == 1 {
return string
} else {
return string.prefix(1) + product(string: string.dropFirst())
}
}
// Return the sum of squares of first n natural numbers
// sum_of_squares(1) == 1
// sum_of_squares(5) == 55
func sum_of_squares(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n * n + sum_of_squares(n: n - 1)
}
}
// Return the square of sum of first n natural numbers
// square_of_sum(1) == 1
// square_of_sum(5) == 225
func square_of_sum(n: Int) -> Int {
return sum(n: n) * sum(n: n)
}
// Return the difference between sum_of_squares and square_of_sum of first n natural numbers
// difference(1) == 0
// difference(5) == 2640
func difference(n: Int) -> Int {
return square_of_sum(n: n) - sum_of_squares(n: n)
}
// Return true if a given number is a palindrome
// is_palindrome(121) == true
// is_palindrome(123) == false
func is_palindrome(number: Int) -> Bool {
if number < 10 {
return true
} else {
let lastDigit = number % 10
let firstDigit = number / 10
return lastDigit == firstDigit && is_palindrome(number: number / 10)
}
}
// Return the number of digits in a given number
// digits(1234) == 4
// digits(123) == 3
func digits(number: Int) -> Int {
if number < 10 {
return 1
} else {
return 1 + digits(number: number / 10)
}
}
// Return the sum of the cubes of all positive integers from 1 to n
// cubes_sum(1) == 1
// cubes_sum(5) == 125
func cubes_sum(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n * n * n + cubes_sum(n: n - 1)
}
}
// Return the sum of the squares of all positive integers from 1 to n
// squares_sum(1) == 1
// squares_sum(5) == 55
func squares_sum(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n * n
return 1 + strlen(string: string.dropFirst()) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
return string.prefix(1) + product(string: string.dropFirst()) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return i
}
func smallestMultiple(n: Int) -> Int {
var i = 2
var multiple = 1
while i <= n {
multiple *= i
i += 1
}
return multiple
}
func fibonacciSum(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func fibonacciSum2(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func fibonacciSum3(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func fibonacciSum4(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func fibonacciSum5(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func fibonacciSum6(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func fibonacciSum7(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return i
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestMultiple(n: 10) == 2520
func smallestMultiple(n: Int) -> Int {
var i = 2
var multiple = 1
while i <= n {
multiple *= i
i += 1
}
return multiple
}
// Find the sum of all even Fibonacci numbers less than or equal to 1000
// fibonacciSum(1000) == 1433455
func fibonacciSum(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the sum of all even Fibonacci numbers less than or equal to 4 million
// fibonacciSum(4000000) == 4613732
func fibonacciSum2(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the sum of all even Fibonacci numbers less than or equal to 4 million
// fibonacciSum(4000000) == 4613732
func fibonacciSum3(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the sum of all even Fibonacci numbers less than or equal to 4 million
// fibonacciSum(4000000) == 4613732
func fibonacciSum4(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the sum of all even Fibonacci numbers less than or equal to 4 million
// fibonacciSum(4000000) == 4613732
func fibonacciSum5(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the sum of all even Fibonacci numbers less than or equal to 4 million
// fibonacciSum(4000000) == 4613732
func fibonacciSum6(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the sum of all even Fibonacci numbers less than or equal to 4 million
// fibonacciSum(4000000) == 4613732
func fibonacciSum7(limit: Int) -> Int {
var a = 1
var b = 2
var sum = 2
while b < limit {
let temp = b
b = a + b
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
n = n / i // cannot assign to value: 'n' is a 'let' constant
func largestDivisor(n: Int) -> Int {
var largest = 1
while largest * largest <= n {
if n % largest == 0 {
return largest
}
largest += 1
}
return n
}
func smallestCommons(_ arr: [Int]) -> Int {
let sortedArr = arr.sorted()
var largest = sortedArr[sortedArr.count - 1]
var smallestCommons = largest
while true {
var isDivisible = true
for i in 0..<sortedArr.count - 1 {
if smallestCommons % sortedArr[i]!= 0 {
isDivisible = false
break
}
}
if isDivisible {
return smallestCommons
}
smallestCommons += largest
}
}
func nextSmallestCommons(_ n: Int) -> Int {
var i = n + 1
while true {
var isDivisible = true
for j in 2...i {
if i % j!= 0 {
isDivisible = false
break
}
}
if isDivisible {
return i
}
i += 1
}
}
func nextLargestCommons(_ n: Int) -> Int {
var i = n + 1
while true {
var isDivisible = true
for j in 2...i {
if i % j!= 0 {
isDivisible = false
break
}
}
if isDivisible {
return i
}
i += 1
}
}
func numDivisors(_ n: Int) -> Int {
var count = 0
for i in 1...n {
if n % i == 0 {
count += 1
}
}
return count
}
func sumDivisors(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 {
sum += i
}
}
return sum
}
func sumDivisorsExcludingPrime(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 &&!isPrime(i) {
sum += i
}
}
return sum
}
func sumDivisorsExcludingPerfectSquare(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 &&!isPerfectSquare(i) {
sum += i
}
}
return sum
}
func sumDivisorsExcludingMultipleOf3And5(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) {
sum += i
}
}
return sum
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var largest = 1
while largest * largest <= n {
if n % largest == 0 {
return largest
}
largest += 1
}
return n
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestCommons([1, 2, 3, 4, 5]) == 60
func smallestCommons(_ arr: [Int]) -> Int {
let sortedArr = arr.sorted()
var largest = sortedArr[sortedArr.count - 1]
var smallestCommons = largest
while true {
var isDivisible = true
for i in 0..<sortedArr.count - 1 {
if smallestCommons % sortedArr[i]!= 0 {
isDivisible = false
break
}
}
if isDivisible {
return smallestCommons
}
smallestCommons += largest
}
}
// For a given number n, find the next smallest number that is evenly divisible by all numbers from 1 to n
// nextSmallestCommons(15) == 30
func nextSmallestCommons(_ n: Int) -> Int {
var i = n + 1
while true {
var isDivisible = true
for j in 2...i {
if i % j!= 0 {
isDivisible = false
break
}
}
if isDivisible {
return i
}
i += 1
}
}
// For a given number n, find the next largest number that is evenly divisible by all numbers from 1 to n
// nextLargestCommons(15) == 60
func nextLargestCommons(_ n: Int) -> Int {
var i = n + 1
while true {
var isDivisible = true
for j in 2...i {
if i % j!= 0 {
isDivisible = false
break
}
}
if isDivisible {
return i
}
i += 1
}
}
// For a given number n, find the number of divisors that n has
// numDivisors(12) == 3
func numDivisors(_ n: Int) -> Int {
var count = 0
for i in 1...n {
if n % i == 0 {
count += 1
}
}
return count
}
// Find the sum of all the divisors that n has
// sumDivisors(12) == 16
func sumDivisors(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 {
sum += i
}
}
return sum
}
// Find the sum of all the divisors that n has, excluding prime numbers
// sumDivisorsExcludingPrime(12) == 15
func sumDivisorsExcludingPrime(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 &&!isPrime(i) {
sum += i
}
}
return sum
}
// Find the sum of all the divisors that n has, excluding perfect squares
// sumDivisorsExcludingPerfectSquare(12) == 10
func sumDivisorsExcludingPerfectSquare(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 &&!isPerfectSquare(i) {
sum += i
}
}
return sum
}
// Find the sum of all the divisors that n has, excluding numbers that are divisible by both 3 and 5
// sumDivisorsExcludingMultipleOf3And5(12) == 8
func sumDivisorsExcludingMultipleOf3And5(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) {
sum += i
}
}
return sum
}
// Find the sum of all the divisors that n has, excluding numbers that are divisible by 7 and 11
// sumDivisorsExcludingMultipleOf7And11(12) ==
if smallestCommons % sortedArr[i]!= 0 { // use of '=' in a boolean context, did you mean '=='?
if smallestCommons % sortedArr[i]!= 0 { // cannot force unwrap value of non-optional type 'Int'
if smallestCommons % sortedArr[i]!= 0 { // '=' must have consistent whitespace on both sides
if smallestCommons % sortedArr[i]!= 0 { // expression is not assignable: binary operator returns immutable value
if i % j!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % j!= 0 { // '=' must have consistent whitespace on both sides
if i % j!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % j!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % j!= 0 { // '=' must have consistent whitespace on both sides
if i % j!= 0 { // use of '=' in a boolean context, did you mean '=='?
if n % i == 0 &&!isPrime(i) { // expected '{' after 'if' condition
if n % i == 0 &&!isPerfectSquare(i) { // expected '{' after 'if' condition
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // cannot force unwrap value of non-optional type 'Int'
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // use of '=' in a boolean context, did you mean '=='?
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // expression is not assignable: '||' returns immutable value
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // expression is not assignable: binary operator returns immutable value
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // '=' must have consistent whitespace on both sides
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // cannot force unwrap value of non-optional type 'Int'
if n % i == 0 && (i % 3!= 0 || i % 5!= 0) { // '=' must have consistent whitespace on both sides
func largestDivisor(n: Int) -> Int {
var largest = 1
while largest * largest <= n {
if n % largest == 0 {
return largest
}
largest += 1
}
return n
}
func smallestCommons(_ arr: [Int]) -> Int {
let sortedArr = arr.sorted()
var largest = sortedArr[sortedArr.count - 1]
var smallest = sortedArr[0]
var commons = largest
while true {
for i in 1...sortedArr.count - 1 {
if commons % sortedArr[i]!= 0 {
break
} else if i == sortedArr.count - 1 {
return commons
}
}
commons += largest
}
}
```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 largest = 1
while largest * largest <= n {
if n % largest == 0 {
return largest
}
largest += 1
}
return n
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestCommons([1, 5]) == 60
func smallestCommons(_ arr: [Int]) -> Int {
let sortedArr = arr.sorted()
var largest = sortedArr[sortedArr.count - 1]
var smallest = sortedArr[0]
var commons = largest
while true {
for i in 1...sortedArr.count - 1 {
if commons % sortedArr[i]!= 0 {
break
} else if i == sortedArr.count - 1 {
return commons
}
}
commons += largest
}
}
print(largestDivisor(n: 15))
print(smallestCommons([1, 5]))
if commons % sortedArr[i]!= 0 { // use of '=' in a boolean context, did you mean '=='?
if commons % sortedArr[i]!= 0 { // cannot force unwrap value of non-optional type 'Int'
if commons % sortedArr[i]!= 0 { // '=' must have consistent whitespace on both sides
if commons % sortedArr[i]!= 0 { // expression is not assignable: binary operator returns immutable value
func largestDivisor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output, including the time and space complexity analysis
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 {
// TODO: Implement the function according to the suggested steps in the output, including the time and space complexity analysis
return 0
}
// Examples:
assert(largestDivisor(n: 15) == 5)
assert(largestDivisor(n: 6) == 3)
assert(largestDivisor(n: 24) == 6)
assert(largestDivisor(n: 7) == 7)
assert(largestDivisor(n: 21) == 7)
assert(largestDivisor(n: 999) == 333)
assert(largestDivisor(n: 1000) == 333)
assert(largestDivisor(n: 10000) == 3333)
assert(largestDivisor(n: 100000) == 33333)
assert(largestDivisor(n: 1000000) == 333333)
assert(largestDivisor(n: 10000000) == 3333333)
assert(largestDivisor(n: 100000000) == 33333333)
assert(largestDivisor(n: 1000000000) == 333333333)
```
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func smallestMult(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= largestDivisor(n: i)
}
return result
}
func nextPrime(n: Int) -> Int {
var i = n + 1
while true {
if isPrime(n: i) {
return i
}
i += 1
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func primeFactors(n: Int) -> [Int: Int] {
var result = [Int: Int]()
var i = 2
while i <= n {
if n % i == 0 {
if result[i] == nil {
result[i] = 1
} else {
result[i]! += 1
}
n /= i
} else {
i += 1
}
}
return result
}
func primeFactorization(n: Int) -> [Int: Int] {
var result = [Int: Int]()
var i = 2
while i <= n {
if n % i == 0 {
if result[i] == nil {
result[i] = 1
} else {
result[i]! += 1
}
n /= i
} else {
i += 1
}
}
return result
}
func gcd(a: Int, _ b: Int) -> Int {
var a = abs(a)
var b = abs(b)
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
func lcm(a: Int, _ b: Int) -> Int {
return abs(a * b) / gcd(a: a, b: b)
}
func lcm(array: [Int]) -> Int {
var result = array[0]
for i in 1..<array.count {
result = lcm(a: result, b: array[i])
}
return result
}
func digits(n: Int) -> Int {
return String(n).count
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestMult(n: 15) == 60
func smallestMult(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= largestDivisor(n: i)
}
return result
}
// For a given number n, find the next prime number after n
// nextPrime(n: 15) == 17
func nextPrime(n: Int) -> Int {
var i = n + 1
while true {
if isPrime(n: i) {
return i
}
i += 1
}
}
// For a given number n, determine if it is prime
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// For a given number n, determine the prime factors of n
// primeFactors(n: 15) == [3: 2, 5: 1]
func primeFactors(n: Int) -> [Int: Int] {
var result = [Int: Int]()
var i = 2
while i <= n {
if n % i == 0 {
if result[i] == nil {
result[i] = 1
} else {
result[i]! += 1
}
n /= i
} else {
i += 1
}
}
return result
}
// For a given number n, determine the prime factors and their exponents
// primeFactorization(n: 15) == [3: 2, 5: 1]
func primeFactorization(n: Int) -> [Int: Int] {
var result = [Int: Int]()
var i = 2
while i <= n {
if n % i == 0 {
if result[i] == nil {
result[i] = 1
} else {
result[i]! += 1
}
n /= i
} else {
i += 1
}
}
return result
}
// For a given number n, determine the prime factors and their exponents
// primeFactorization(n: 15) == [3: 2, 5: 1]
func primeFactorization(n: Int) -> [Int: Int] {
var result = [Int: Int]()
var i = 2
while i <= n {
if n % i == 0 {
if result[i] == nil {
result[i] = 1
} else {
result[i]! += 1
}
n /= i
} else {
i += 1
}
}
return result
}
// Find the greatest common divisor of two numbers
// gcd(10, 15) == 5
func gcd(a: Int, _ b: Int) -> Int {
var a = abs(a)
var b = abs(b)
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
// Find the least common multiple of two numbers
// lcm(10, 15) == 60
func lcm(a: Int, _ b: Int) -> Int {
return abs(a * b) / gcd(a: a, b: b)
}
// Find the least common multiple of an array of numbers
// lcm([10, 15, 20]) == 600
func lcm(array: [Int]) -> Int {
var result = array[0]
for i in 1..<array.count {
result = lcm(a: result, b: array[i])
}
return result
}
// Find the number of digits in a number
// digits(1234) == 4
func digits(n: Int) -> Int {
return String(n).count
}
// Find the number of digits in a number
//
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
return abs(a * b) / gcd(a: a, b: b) // extraneous argument label 'b:' in call
result = lcm(a: result, b: array[i]) // extraneous argument label 'b:' in call
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func smallestCommons(_ arr: [Int]) -> Int {
let range = arr.sorted()
var i = range[0]
while true {
let isDivisible = arr.filter { i % $0 == 0 }.count == arr.count
if isDivisible {
return i
}
i += range[1] - range[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 = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestCommons([1, 5]) == 60
func smallestCommons(_ arr: [Int]) -> Int {
let range = arr.sorted()
var i = range[0]
while true {
let isDivisible = arr.filter { i % $0 == 0 }.count == arr.count
if isDivisible {
return i
}
i += range[1] - range[0]
}
}
print(largestDivisor(n: 15))
print(smallestCommons([1, 5]))
// XCTAssertTrue failed
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return i
}
func smallestCommons(_ arr: [Int]) -> Int {
var max = arr.max()!
var min = arr.min()!
var range = max - min + 1
var result = 1
for i in 1...range {
result *= i
}
for i in 1...max {
if!isDivisible(result, i) {
result = lcm(result, i)
}
}
return result
}
func isDivisible(_ num: Int, _ divisor: Int) -> Bool {
return num % divisor == 0
}
func gcd(_ a: Int, _ b: Int) -> Int {
if b == 0 {
return a
}
return gcd(b, a % b)
}
func lcm(_ a: Int, _ b: Int) -> Int {
return a * b / gcd(a, b)
}
```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 = 2
while i < n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return i
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestCommons([1, 3, 5]) == 60
func smallestCommons(_ arr: [Int]) -> Int {
var max = arr.max()!
var min = arr.min()!
var range = max - min + 1
var result = 1
for i in 1...range {
result *= i
}
for i in 1...max {
if!isDivisible(result, i) {
result = lcm(result, i)
}
}
return result
}
func isDivisible(_ num: Int, _ divisor: Int) -> Bool {
return num % divisor == 0
}
func gcd(_ a: Int, _ b: Int) -> Int {
if b == 0 {
return a
}
return gcd(b, a % b)
}
func lcm(_ a: Int, _ b: Int) -> Int {
return a * b / gcd(a, b)
}
smallestCommons([1, 5])
n = n / i // cannot assign to value: 'n' is a 'let' constant
if!isDivisible(result, i) { // expected expression, var, or let in 'if' condition
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return i
}
func smallestMult(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sumMultiples(limit: Int) -> Int {
var result = 0
for i in 1...limit {
if i % 3 == 0 || i % 5 == 0 {
result += i
}
}
return result
}
func sumFibs(limit: Int) -> Int {
var result = 2
var current = 1
var previous = 1
while current < limit {
let next = current + previous
previous = current
current = next
if current % 2 == 0 {
result += current
}
}
return result
}
func greatestProduct(input: Int) -> Int {
var result = 0
let str = String(input)
for i in 100...str.count - 3 {
for j in 100...str.count - 3 {
let first = Int(String(str[i...i+2]))!
let second = Int(String(str[j...j+2]))!
if first * second > result {
result = first * second
}
}
}
return result
}
func sumAmicable(limit: Int) -> Int {
var result = 0
for i in 2...limit {
var sum1 = 0
var j = 1
while j < i {
if i % j == 0 {
sum1 += j
}
j += 1
}
var sum2 = 0
var k = 1
while k < sum1 {
if sum1 % k == 0 {
sum2 += k
}
k += 1
}
if sum2 == i && i!= sum1 {
result += i
}
}
return result
}
func sumAbundant(limit: Int) -> Int {
var result = 0
for i in 1...limit {
if isAbundant(i) {
result += i
}
}
return result
}
func sumPowDigs(limit: Int) -> Int {
var result = 0
for i in 1...limit {
if isPowDig(i) {
result += i
}
}
return result
}
func sumTo2020(limit: Int) -> Int {
var result = 0
for i in 1...limit {
for j in 1...limit {
if i + j == 2020 {
result += 1
}
}
}
return result
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return i
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestMult(n: 10) == 2520
func smallestMult(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
// Find the sum of all the multiples of 3 or 5 below 1000
// sumMultiples(limit: 1000) == 233168
func sumMultiples(limit: Int) -> Int {
var result = 0
for i in 1...limit {
if i % 3 == 0 || i % 5 == 0 {
result += i
}
}
return result
}
// Find the sum of all the even Fibonacci numbers below 4 million
// sumFibs(limit: 4_000_000) == 4613732
func sumFibs(limit: Int) -> Int {
var result = 2
var current = 1
var previous = 1
while current < limit {
let next = current + previous
previous = current
current = next
if current % 2 == 0 {
result += current
}
}
return result
}
// Find the greatest product of two three-digit numbers in the 1000-digit number
// greatestProduct(input: 130_000) == 23514624000
func greatestProduct(input: Int) -> Int {
var result = 0
let str = String(input)
for i in 100...str.count - 3 {
for j in 100...str.count - 3 {
let first = Int(String(str[i...i+2]))!
let second = Int(String(str[j...j+2]))!
if first * second > result {
result = first * second
}
}
}
return result
}
// Find the sum of all the amicable numbers under 10000
// sumAmicable(limit: 10_000) == 31626
func sumAmicable(limit: Int) -> Int {
var result = 0
for i in 2...limit {
var sum1 = 0
var j = 1
while j < i {
if i % j == 0 {
sum1 += j
}
j += 1
}
var sum2 = 0
var k = 1
while k < sum1 {
if sum1 % k == 0 {
sum2 += k
}
k += 1
}
if sum2 == i && i!= sum1 {
result += i
}
}
return result
}
// Find the sum of all the abundant numbers under 28123
// sumAbundant(limit: 28123) == 4179871
func sumAbundant(limit: Int) -> Int {
var result = 0
for i in 1...limit {
if isAbundant(i) {
result += i
}
}
return result
}
// Find the sum of all the numbers which can be written as the sum of fifth powers of their digits
// sumPowDigs(limit: 10000) == 37328
func sumPowDigs(limit: Int) -> Int {
var result = 0
for i in 1...limit {
if isPowDig(i) {
result += i
}
}
return result
}
// Find the number of numbers between 1 and 1000 that add up to 2020
// sumTo2020(limit: 1000) == 241
func sumTo2020(limit: Int) -> Int {
var result = 0
for i in 1...limit {
for j in 1...limit {
if i + j == 2020 {
result += 1
}
}
}
return result
}
//
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
let first = Int(String(str[i...i+2]))! // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
let second = Int(String(str[j...j+2]))! // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if sum2 == i && i!= sum1 { // cannot force unwrap value of non-optional type 'Int'
if sum2 == i && i!= sum1 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if sum2 == i && i!= sum1 { // use of '=' in a boolean context, did you mean '=='?
if sum2 == i && i!= sum1 { // '=' must have consistent whitespace on both sides
if isAbundant(i) { // cannot find 'isAbundant' in scope
if isPowDig(i) { // cannot find 'isPowDig' in scope
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func smallestMult(n: Int) -> Int {
var i = 1
while true {
var isDiv = true
for j in 2...n {
if i % j!= 0 {
isDiv = false
break
}
}
if isDiv {
return i
}
i *= 2
}
}
func sumMultiples() -> Int {
var sum = 0
for i in 1...999 {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
func sumFibs() -> Int {
var sum = 2
var a = 1
var b = 2
while b < 4_000_000 {
let temp = b
b += a
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
func largestProduct() -> Int {
var max = 0
let numString = getInputString()
for i in 0...numString.count - 3 {
for j in i+1...numString.count - 2 {
let first = Int(String(numString[i...j]))!
for k in j+1...numString.count - 1 {
let second = Int(String(numString[j+1...k]))!
let product = first * second
if product > max {
max = product
}
}
}
}
return max
}
func sumAmicable() -> Int {
var sum = 0
for i in 2...10_000 {
if isSumOfProperDivisors(i) && isSumOfProperDivisors(i, sum: i) {
sum += i
}
}
return sum
}
func sumAbundant() -> Int {
var sum = 0
for i in 12...28123 {
if isAbundant(i) {
sum += i
}
}
return sum
}
func smallestMult() -> Int {
var num = 1
for i in 2...20 {
num *= smallestMult(i)
}
return num
}
func numDigits(n: Int) -> Int {
var num = n
var count = 0
while num > 0 {
num /= 10
count += 1
}
return count
}
func largestPalindrome() -> Int {
var max = 0
for i in 100...999 {
for j in 100...999 {
let product = i * j
if product > max && isPalindrome(product) {
max = product
}
}
}
return max
}
```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 = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
// For a given number n, find the smallest number that is evenly divisible from 1 to n
// smallestMult(n: 15) == 60
func smallestMult(n: Int) -> Int {
var i = 1
while true {
var isDiv = true
for j in 2...n {
if i % j!= 0 {
isDiv = false
break
}
}
if isDiv {
return i
}
i *= 2
}
}
// Find the sum of all the multiples of 3 or 5 below 1000
// sumMultiples() == 233168
func sumMultiples() -> Int {
var sum = 0
for i in 1...999 {
if i % 3 == 0 || i % 5 == 0 {
sum += i
}
}
return sum
}
// Find the sum of all the even Fibonacci numbers below 4 million
// sumFibs() == 4613732
func sumFibs() -> Int {
var sum = 2
var a = 1
var b = 2
while b < 4_000_000 {
let temp = b
b += a
a = temp
if b % 2 == 0 {
sum += b
}
}
return sum
}
// Find the greatest product of two three-digit numbers in the 1000-digit number
// largestProduct() == 906609
func largestProduct() -> Int {
var max = 0
let numString = getInputString()
for i in 0...numString.count - 3 {
for j in i+1...numString.count - 2 {
let first = Int(String(numString[i...j]))!
for k in j+1...numString.count - 1 {
let second = Int(String(numString[j+1...k]))!
let product = first * second
if product > max {
max = product
}
}
}
}
return max
}
// Find the sum of all the amicable numbers under 10000
// sumAmicable() == 31626
func sumAmicable() -> Int {
var sum = 0
for i in 2...10_000 {
if isSumOfProperDivisors(i) && isSumOfProperDivisors(i, sum: i) {
sum += i
}
}
return sum
}
// Find the sum of all the abundant numbers under 28123
// sumAbundant() == 4179871
func sumAbundant() -> Int {
var sum = 0
for i in 12...28123 {
if isAbundant(i) {
sum += i
}
}
return sum
}
// Find the smallest number divisible by all integers from 1 to 20
// smallestMult() == 232792560
func smallestMult() -> Int {
var num = 1
for i in 2...20 {
num *= smallestMult(i)
}
return num
}
// Find the number of digits in the number 100!
// numDigits(100!) == 20
func numDigits(n: Int) -> Int {
var num = n
var count = 0
while num > 0 {
num /= 10
count += 1
}
return count
}
// Find the greatest palindrome made from the product of two 3-digit numbers
// largestPalindrome() == 906609
func largestPalindrome() -> Int {
var max = 0
for i in 100...999 {
for j in 100...999 {
let product = i * j
if product > max && isPalindrome(product) {
max = product
}
}
}
return max
}
// Find the sum of all the amicable numbers under 10000
// sumDeficient() == 31
if i % j!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % j!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % j!= 0 { // '=' must have consistent whitespace on both sides
let numString = getInputString() // cannot find 'getInputString' in scope
if isSumOfProperDivisors(i) && isSumOfProperDivisors(i, sum: i) { // cannot find 'isSumOfProperDivisors' in scope
if isSumOfProperDivisors(i) && isSumOfProperDivisors(i, sum: i) { // cannot find 'isSumOfProperDivisors' in scope
if isAbundant(i) { // cannot find 'isAbundant' in scope
num *= smallestMult(i) // missing argument label 'n:' in call
if product > max && isPalindrome(product) { // cannot find 'isPalindrome' in scope
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func smallestCommons(_ arr: [Int]) -> Int {
let max = arr.max()!
var i = 1
while true {
let divisible = arr.filter { i % $0 == 0 }
if divisible.count == arr.count {
return i
}
i += max
}
}
func sumMultiples() -> Int {
var sum = 0
for i in 1...1000 {
if i % 7 == 0 || i % 13 == 0 {
sum += i
}
}
return sum
}
func sumAmicable() -> Int {
var sum = 0
for i in 2...10000 {
let sumOfDivisors = divisors(i).reduce(0, +)
let sumOfDivisorsOfSumOfDivisors = divisors(sumOfDivisors).reduce(0, +)
if sumOfDivisors == i && sumOfDivisors!= sumOfDivisorsOfSumOfDivisors {
sum += i
}
}
return sum
}
func sumOfAbundant() -> Int {
var sum = 0
for i in 12...28123 {
if isAbundant(i) {
sum += i
}
}
return sum
}
func sumOfDigitFifthPowers() -> Int {
var sum = 0
for i in 10...999 {
let digits = Array(String(i))
if digits.reduce(0, +).power(5) == i {
sum += i
}
}
return sum
}
func sumOfPerfectSquares() -> Int {
var sum = 0
for i in 1...1000 {
if isPerfectSquare(i) {
sum += i
}
}
return sum
}
func sumOfDeficientSquares() -> Int {
var sum = 0
for i in 1...1000 {
if isDeficientSquare(i) {
sum += i
}
}
return sum
}
func sumOfAbundantSquares() -> Int {
var sum = 0
for i in 1...1000 {
if isAbundantSquare(i) {
sum += i
}
}
return sum
}
func sumOfSquares() -> Int {
var sum = 0
for i in 1...100 {
sum += i * i
}
return sum
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
// For a given number n, find the smallest number that is evenly divisible by all numbers from 1 to n
// smallestCommons([1, 3, 5]) == 60
func smallestCommons(_ arr: [Int]) -> Int {
let max = arr.max()!
var i = 1
while true {
let divisible = arr.filter { i % $0 == 0 }
if divisible.count == arr.count {
return i
}
i += max
}
}
// Find the sum of all the multiples of 7 or 13 below 1000
// sumMultiples() == 233168
func sumMultiples() -> Int {
var sum = 0
for i in 1...1000 {
if i % 7 == 0 || i % 13 == 0 {
sum += i
}
}
return sum
}
// Find the sum of all the amicable numbers under 10000
// sumAmicable() == 31626
func sumAmicable() -> Int {
var sum = 0
for i in 2...10000 {
let sumOfDivisors = divisors(i).reduce(0, +)
let sumOfDivisorsOfSumOfDivisors = divisors(sumOfDivisors).reduce(0, +)
if sumOfDivisors == i && sumOfDivisors!= sumOfDivisorsOfSumOfDivisors {
sum += i
}
}
return sum
}
// Find the sum of all the abundant numbers under 28123
// sumOfAbundant() == 4179871
func sumOfAbundant() -> Int {
var sum = 0
for i in 12...28123 {
if isAbundant(i) {
sum += i
}
}
return sum
}
// Find the sum of all the numbers which can be written as the sum of fifth powers of their digits
// sumOfDigitFifthPowers() == 373092176
func sumOfDigitFifthPowers() -> Int {
var sum = 0
for i in 10...999 {
let digits = Array(String(i))
if digits.reduce(0, +).power(5) == i {
sum += i
}
}
return sum
}
// Find the sum of all the amicable numbers under 10000
// sumOfPerfectSquares() == 87218
func sumOfPerfectSquares() -> Int {
var sum = 0
for i in 1...1000 {
if isPerfectSquare(i) {
sum += i
}
}
return sum
}
// Find the sum of all the amicable numbers under 10000
// sumOfPerfectSquares() == 87218
func sumOfDeficientSquares() -> Int {
var sum = 0
for i in 1...1000 {
if isDeficientSquare(i) {
sum += i
}
}
return sum
}
// Find the sum of all the amicable numbers under 10000
// sumOfPerfectSquares() == 87218
func sumOfAbundantSquares() -> Int {
var sum = 0
for i in 1...1000 {
if isAbundantSquare(i) {
sum += i
}
}
return sum
}
// Find the sum of all the amicable numbers under 10000
// sumOfPerfectSquares() == 87218
func sumOfSquares() -> Int {
var sum = 0
for i in 1...100 {
sum += i * i
}
return sum
}
// Find the sum of all the amicable numbers under 10000
// sumOfPerfectSquares() == 87218
func sumOfCubes() -> Int {
var sum = 0
for i in 1...100 {
sum
let sumOfDivisors = divisors(i).reduce(0, +) // cannot find 'divisors' in scope
let sumOfDivisorsOfSumOfDivisors = divisors(sumOfDivisors).reduce(0, +) // cannot find 'divisors' in scope
if sumOfDivisors == i && sumOfDivisors!= sumOfDivisorsOfSumOfDivisors { // use of '=' in a boolean context, did you mean '=='?
if sumOfDivisors == i && sumOfDivisors!= sumOfDivisorsOfSumOfDivisors { // '=' must have consistent whitespace on both sides
if isAbundant(i) { // cannot find 'isAbundant' in scope
if digits.reduce(0, +).power(5) == i { // cannot convert value of type '(Int) -> Int' to expected argument type '(Int, String.Element) throws -> Int' (aka '(Int, Character) throws -> Int')
if digits.reduce(0, +).power(5) == i { // value of type 'Int' has no member 'power'
if isPerfectSquare(i) { // cannot find 'isPerfectSquare' in scope
if isDeficientSquare(i) { // cannot find 'isDeficientSquare' in scope
if isAbundantSquare(i) { // cannot find 'isAbundantSquare' in scope
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var divisor = 2
while divisor <= n {
if n % divisor == 0 {
factors.append(divisor)
n /= divisor
} else {
divisor += 1
}
}
return factors
}
func sumOfDigits(n: Int) -> Int {
var n = n
var sum = 0
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func sumOfDigits2(n: Int) -> Int {
return String(n).reduce(0, +)
}
func sumOfDigits3(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits4(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits5(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits6(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits7(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits8(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits9(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
func sumOfDigits10(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
```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 divisor = 2
while divisor <= n {
if n % divisor == 0 {
factors.append(divisor)
n /= divisor
} else {
divisor += 1
}
}
return factors
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits(n: Int) -> Int {
var n = n
var sum = 0
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits2(n: Int) -> Int {
return String(n).reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits3(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits4(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits5(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits6(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits7(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits8(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits9(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOfDigits10(n: Int) -> Int {
return String(n).map { Int(String($0))! }.reduce(0, +)
}
// Return the sum of all digits in the given integer.
// Input: 12345
// Output: 15
// Input: 987654321
// Output: 45
func sumOf
n /= divisor // left side of mutating operator isn't mutable: 'n' is a 'let' constant
return String(n).reduce(0, +) // cannot convert value of type '(Int) -> Int' to expected argument type '(Int, String.Element) throws -> Int' (aka '(Int, Character) throws -> Int')
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 sumDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
func productDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
func sumDigitsExceptThree(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
let digit = number % 10
if digit % 3!= 0 {
sum += digit
}
number /= 10
}
return sum
}
func productDigitsExceptThree(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 3!= 0 {
product *= digit
}
number /= 10
}
return product
}
func sumDigitsExceptTwoFive(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
let digit = number % 10
if digit % 2!= 0 && digit % 5!= 0 {
sum += digit
}
number /= 10
}
return sum
}
func productDigitsExceptTwoFive(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2!= 0 && digit % 5!= 0 {
product *= digit
}
number /= 10
}
return product
}
```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
}
// Return the sum of all digits in the given integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
// sumDigits(n: 1010) == 11
func sumDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the product of all digits in the given integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 210
// productDigits(n: 1010) == 100
func productDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the sum of all digits in the given integer, excluding any digits that are divisible by 3
// sumDigitsExceptThree(n: 123) == 3
// sumDigitsExceptThree(n: 456) == 6
// sumDigitsExceptThree(n: 1010) == 2
func sumDigitsExceptThree(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
let digit = number % 10
if digit % 3!= 0 {
sum += digit
}
number /= 10
}
return sum
}
// Return the product of all digits in the given integer, excluding any digits that are divisible by 3
// productDigitsExceptThree(n: 123) == 1
// productDigitsExceptThree(n: 456) == 120
// productDigitsExceptThree(n: 1010) == 10
func productDigitsExceptThree(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 3!= 0 {
product *= digit
}
number /= 10
}
return product
}
// Return the sum of all digits in the given integer, excluding any digits that are divisible by 2 or 5
// sumDigitsExceptTwoFive(n: 123) == 3
// sumDigitsExceptTwoFive(n: 456) == 6
// sumDigitsExceptTwoFive(n: 1010) == 1
func sumDigitsExceptTwoFive(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
let digit = number % 10
if digit % 2!= 0 && digit % 5!= 0 {
sum += digit
}
number /= 10
}
return sum
}
// Return the product of all digits in the given integer, excluding any digits that are divisible by 2 or 5
// productDigitsExceptTwoFive(n: 123) == 1
// productDigitsExceptTwoFive(n: 456) == 120
// productDigitsExceptTwoFive(n: 1010) == 10
func productDigitsExceptTwoFive(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
let digit = number % 10
if digit % 2!= 0 && digit % 5!= 0 {
product *= digit
}
number /= 10
}
return product
}
// Return the sum of all digits in the given integer, excluding any digits that are divisible by 7
// sumDigitsExceptSeven(n: 123) == 6
// sumDigitsExceptSeven(n: 456) == 15
// sumDigitsExceptSeven(n: 1010)
if digit % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 3!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 3!= 0 { // '=' must have consistent whitespace on both sides
if digit % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 3!= 0 { // '=' must have consistent whitespace on both sides
if digit % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 3!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 2!= 0 && digit % 5!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 2!= 0 && digit % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 2!= 0 && digit % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if digit % 2!= 0 && digit % 5!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if digit % 2!= 0 && digit % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if digit % 2!= 0 && digit % 5!= 0 { // '=' must have consistent whitespace on both sides
if digit % 2!= 0 && digit % 5!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 2!= 0 && digit % 5!= 0 { // '=' must have consistent whitespace on both sides
if digit % 2!= 0 && digit % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 2!= 0 && digit % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 2!= 0 && digit % 5!= 0 { // '=' must have consistent whitespace on both sides
if digit % 2!= 0 && digit % 5!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if digit % 2!= 0 && digit % 5!= 0 { // '=' must have consistent whitespace on both sides
if digit % 2!= 0 && digit % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if digit % 2!= 0 && digit % 5!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 2!= 0 && digit % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if digit % 2!= 0 && digit % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 2!= 0 && digit % 5!= 0 { // use of '=' in a boolean context, did you mean '=='?
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var number = n
for i in 2...n {
var count = 0
while number % i == 0 {
number /= i
count += 1
}
if count > 0 {
factors.append(i)
factors.append(count)
}
}
return factors
}
func greatestCommonDivisors(a: Int, b: Int) -> [Int] {
var a = a
var b = b
var result: [Int] = []
while b!= 0 {
let remainder = a % b
a = b
b = remainder
}
let gcd = a
var number = a <= b? a : b
while number > 1 {
if number % gcd == 0 {
result.append(number)
}
number -= 1
}
return result
}
func sumArray(_ array: [Int]) -> Int {
var result = 0
for number in array {
result += number
}
return result
}
func productArray(_ array: [Int]) -> Int {
var result = 1
for number in array {
result *= number
}
return result
}
func difference(_ array: [Int]) -> Int {
var min = array[0]
var max = array[0]
for number in array {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
func countElements(_ array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
let average = sum / array.count
var count = 0
for number in array {
if number > average {
count += 1
}
}
return count
}
```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
for i in 2...n {
var count = 0
while number % i == 0 {
number /= i
count += 1
}
if count > 0 {
factors.append(i)
factors.append(count)
}
}
return factors
}
// Return array of all numbers between 2 given numbers that have a greatest common divisor (GCD) equal to 1.
// The array should be sorted in ascending order.
// Input numbers should be positive integers and 2 <= n <= 100
// Example:
// greatestCommonDivisors(a: 2, b: 16) == [1, 2, 4, 8, 16]
// greatestCommonDivisors(a: 7, b: 15) == [1, 7]
func greatestCommonDivisors(a: Int, b: Int) -> [Int] {
var a = a
var b = b
var result: [Int] = []
while b!= 0 {
let remainder = a % b
a = b
b = remainder
}
let gcd = a
var number = a <= b? a : b
while number > 1 {
if number % gcd == 0 {
result.append(number)
}
number -= 1
}
return result
}
// Return the sum of all elements in the array.
// The array may contain negative numbers and duplicates
// Example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([-1, 0, 1]) == 0
func sumArray(_ array: [Int]) -> Int {
var result = 0
for number in array {
result += number
}
return result
}
// Return the product of all elements in the array.
// The array may contain negative numbers and duplicates
// Example:
// productArray([1, 2, 3, 4, 5]) == 120
// productArray([-1, 0, 1]) == 0
func productArray(_ array: [Int]) -> Int {
var result = 1
for number in array {
result *= number
}
return result
}
// Return the difference between the largest and smallest elements in the array.
// The array may contain duplicate numbers
// Example:
// difference([1, 5, 2, 10, 3]) == 9
// difference([-1, 0, 1]) == 2
func difference(_ array: [Int]) -> Int {
var min = array[0]
var max = array[0]
for number in array {
if number > max {
max = number
}
if number < min {
min = number
}
}
return max - min
}
// Return the number (count) of elements that are greater than the average value of the array.
// The array may contain negative numbers and duplicates
// Example:
// countElements([1, 2, 3, 4, 5]) == 3
// countElements([1, 1, 1, 4, 5]) == 4
// countElements([-1, 0, 1]) == 0
func countElements(_ array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
let average = sum / array.count
var count = 0
for number in array {
if number > average {
count += 1
}
}
return count
}
// Return the number (count) of elements that are greater than the average value of the array.
// The array may contain negative numbers and duplicates
// Example:
// countElements([1, 2, 3, 4, 5]) == 3
// countElements([1, 1, 1, 4, 5]) == 4
// countElements([-1, 0, 1]) == 0
func countElements(_ array: [Int]) -> Int {
var sum = 0
for number in array {
sum += number
}
let average = sum / array.count
var count = 0
for number in array {
if number > average {
count += 1
}
}
return count
}
// Return the number (count) of elements that are greater than the
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
var number = a <= b? a : b // expected expression
var number = a <= b? a : b // consecutive statements on a line must be separated by ';'
var number = a <= b? a : b // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
var number = a <= b? a : b // variable is unused
var number = a <= b? a : b // consecutive statements on a line must be separated by ';'
var number = a <= b? a : b // cannot use optional chaining on non-optional value of type 'Int'
func factorize(n: Int) -> [Int] {
var factors: [Int: Int] = [:]
var number = n
for i in 2...n {
while number % i == 0 {
if factors[i] == nil {
factors[i] = 1
} else {
factors[i]! += 1
}
number /= i
}
}
return Array(factors.values)
}
func divideNumbers(dividend: Int, divisor: Int) -> [Int] {
var numbers: [Int] = []
var number = dividend
while number >= divisor {
numbers.append(number)
number -= divisor
}
return numbers
}
func sumDivisibleNumbers(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
func sumDivisibleNumbers2(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
func sumDivisibleNumbers3(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
func sumDivisibleNumbers4(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
func sumDivisibleNumbers5(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
func sumDivisibleNumbers6(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
func sumDivisibleNumbers7(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
```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: Int] = [:]
var number = n
for i in 2...n {
while number % i == 0 {
if factors[i] == nil {
factors[i] = 1
} else {
factors[i]! += 1
}
number /= i
}
}
return Array(factors.values)
}
// Return array of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// The numbers in the array should be sorted in ascending order.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: [3, 6]
func divideNumbers(dividend: Int, divisor: Int) -> [Int] {
var numbers: [Int] = []
var number = dividend
while number >= divisor {
numbers.append(number)
number -= divisor
}
return numbers
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers2(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers3(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers4(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers5(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers6(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given divisor.
// Inputs:
// - dividend: 2
// - divisor: 3
// - Output: 3 + 6 = 9
func sumDivisibleNumbers7(dividend: Int, divisor: Int) -> Int {
return divideNumbers(dividend: dividend, divisor: divisor).reduce(0, +)
}
// Return the sum of all numbers between 2 given numbers (inclusive) which are divisible by given div
// XCTAssertTrue failed
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var divisor = 2
while divisor <= n {
if n % divisor == 0 {
factors.append(divisor)
n /= divisor
} else {
divisor += 1
}
}
return factors
}
func sumDigits(n: Int) -> Int {
var sum = 0
var n = n
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func sumDivisibleDigits(n: Int) -> Int {
var sum = 0
var n = n
while n > 0 {
let digit = n % 10
if digit % 3!= 0 {
sum += digit
}
n /= 10
}
return sum
}
func productDigits(n: Int) -> Int {
var product = 1
var n = n
while n > 0 {
product *= n % 10
n /= 10
}
return product
}
func productDivisibleDigits(n: Int) -> Int {
var product = 1
var n = n
while n > 0 {
let digit = n % 10
if digit % 3!= 0 {
product *= digit
}
n /= 10
}
return product
}
func digitsCount(n: Int) -> Int {
var count = 0
var n = n
while n > 0 {
count += 1
n /= 10
}
return count
}
func sumDivisibleDigitsNotDivisibleBy3And2(n: Int) -> Int {
var sum = 0
var n = n
while n > 0 {
let digit = n % 10
if digit % 3!= 0 && digit % 2!= 0 {
sum += digit
}
n /= 10
}
return sum
}
```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 divisor = 2
while divisor <= n {
if n % divisor == 0 {
factors.append(divisor)
n /= divisor
} else {
divisor += 1
}
}
return factors
}
// Return the sum of all digits in the given integer.
// Input number should be positive
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
// sumDigits(n: 789) == 24
func sumDigits(n: Int) -> Int {
var sum = 0
var n = n
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
// Return the sum of all digits in the given integer, excluding any digits that are divisible by 3.
// Input number should be positive
// sumDivisibleDigits(n: 123) == 6
// sumDivisibleDigits(n: 456) == 15
// sumDivisibleDigits(n: 789) == 24
func sumDivisibleDigits(n: Int) -> Int {
var sum = 0
var n = n
while n > 0 {
let digit = n % 10
if digit % 3!= 0 {
sum += digit
}
n /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number should be positive
// productDigits(n: 123) == 6
// productDigits(n: 456) == 216
// productDigits(n: 789) == 576
func productDigits(n: Int) -> Int {
var product = 1
var n = n
while n > 0 {
product *= n % 10
n /= 10
}
return product
}
// Return the product of all digits in the given integer, excluding any digits that are divisible by 3.
// Input number should be positive
// productDivisibleDigits(n: 123) == 6
// productDivisibleDigits(n: 456) == 216
// productDivisibleDigits(n: 789) == 576
func productDivisibleDigits(n: Int) -> Int {
var product = 1
var n = n
while n > 0 {
let digit = n % 10
if digit % 3!= 0 {
product *= digit
}
n /= 10
}
return product
}
// Return the number of digits in the given integer.
// Input number should be positive
// digitsCount(n: 123) == 3
// digitsCount(n: 456) == 3
// digitsCount(n: 789) == 3
func digitsCount(n: Int) -> Int {
var count = 0
var n = n
while n > 0 {
count += 1
n /= 10
}
return count
}
// Return the sum of all digits in the given integer, excluding any digits that are divisible by 3 and are also
// divisible by 2.
// Input number should be positive
// sumDivisibleDigitsNotDivisibleBy3And2(n: 123) == 6
// sumDivisibleDigitsNotDivisibleBy3And2(n: 456) == 15
// sumDivisibleDigitsNotDivisibleBy3And2(n: 789) == 24
func sumDivisibleDigitsNotDivisibleBy3And2(n: Int) -> Int {
var sum = 0
var n = n
while n > 0 {
let digit = n % 10
if digit % 3!= 0 && digit % 2!= 0 {
sum += digit
}
n /= 10
}
return sum
}
// Return the product of all digits in the given integer, excluding any digits that are divisible by 3 and are also
// divisible by 2.
// Input number should be positive
// productDivisibleDigitsNotDivisibleBy3And2(n: 123) ==
n /= divisor // left side of mutating operator isn't mutable: 'n' is a 'let' constant
if digit % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 3!= 0 { // '=' must have consistent whitespace on both sides
if digit % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 3!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 3!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 3!= 0 { // '=' must have consistent whitespace on both sides
if digit % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 3!= 0 && digit % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if digit % 3!= 0 && digit % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if digit % 3!= 0 && digit % 2!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if digit % 3!= 0 && digit % 2!= 0 { // '=' must have consistent whitespace on both sides
if digit % 3!= 0 && digit % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if digit % 3!= 0 && digit % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 3!= 0 && digit % 2!= 0 { // '=' must have consistent whitespace on both sides
if digit % 3!= 0 && digit % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if digit % 3!= 0 && digit % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
func factorize(n: Int) -> [Int] {
var factors: [Int: Int] = [:]
var num = n
for i in 2...n {
while num % i == 0 {
num /= i
if factors[i] == nil {
factors[i] = 1
} else {
factors[i]! += 1
}
}
}
return Array(factors.values)
}
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
```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: Int] = [:]
var num = n
for i in 2...n {
while num % i == 0 {
num /= i
if factors[i] == nil {
factors[i] = 1
} else {
factors[i]! += 1
}
}
}
return Array(factors.values)
}
// Return the sum of all digits in the given integer.
// Input number should be positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
// sumDigits(n: 789) == 24
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number should be positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 210
// productDigits(n: 789) == 700
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number should be positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
// sumDigits(n: 789) == 24
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number should be positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 210
// productDigits(n: 789) == 700
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number should be positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
// sumDigits(n: 789) == 24
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number should be positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 210
// productDigits(n: 789) == 700
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number should be positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
// sumDigits(n: 789) == 24
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number should be positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 210
// productDigits(n: 789) == 700
func productDigits(n: Int) -> Int {
var product = 1
var num
// XCTAssertTrue failed
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var number = n
for i in 2...n {
while number % i == 0 {
factors.append(i)
number /= i
}
}
return factors
}
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
func numberOfDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
number /= 10
digits += 1
}
return digits
}
```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
for i in 2...n {
while number % i == 0 {
factors.append(i)
number /= i
}
}
return factors
}
// Return the sum of all digits in the given integer.
// Input: 1234 -> Output: 10
// Input: 9876 -> Output: 36
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input: 1234 -> Output: 120
// Input: 9876 -> Output: 720
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the number of digits in the given integer.
// Input: 1234 -> Output: 4
// Input: 9876 -> Output: 4
func numberOfDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
number /= 10
digits += 1
}
return digits
}
// Return the sum of all digits in the given integer.
// Input: 1234 -> Output: 10
// Input: 9876 -> Output: 36
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input: 1234 -> Output: 120
// Input: 9876 -> Output: 720
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the number of digits in the given integer.
// Input: 1234 -> Output: 4
// Input: 9876 -> Output: 4
func numberOfDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
number /= 10
digits += 1
}
return digits
}
// Return the sum of all digits in the given integer.
// Input: 1234 -> Output: 10
// Input: 9876 -> Output: 36
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input: 1234 -> Output: 120
// Input: 9876 -> Output: 720
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the number of digits in the given integer.
// Input: 1234 -> Output: 4
// Input: 9876 -> Output: 4
func numberOfDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
number /= 10
digits += 1
}
return digits
}
// Return the sum of all digits in the given integer.
// Input: 1234 -> Output: 10
// Input: 9876 -> Output: 36
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input: 1234 -> Output:
func factorize(n: Int) -> [Int] {
var factors: [Int: Int] = [:]
var number = n
var factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors[factor, default: 0] += 1
number /= factor
} else {
factor += 1
}
}
factors[number, default: 0] += 1
return Array(factors.map { $0.key ** $0.value })
}
func findPrimes(in range: ClosedRange<Int>) -> [Int] {
var primes: [Int] = []
for number in range {
if isPrime(number) {
primes.append(number)
}
}
return primes
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for factor in 2...number {
if number % factor == 0 {
return false
}
}
return true
}
func sum(in range: ClosedRange<Int>) -> Int {
return range.reduce(0, +)
}
func sumOfPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).reduce(0, +)
}
func sumOfEvenPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2 == 0 }.reduce(0, +)
}
func sumOfOddPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(0, +)
}
func productOfPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).reduce(1, *)
}
func productOfEvenPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2 == 0 }.reduce(1, *)
}
func productOfOddPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(1, *)
}
func sumOfNumbersDivisibleBy3(in range: ClosedRange<Int>) -> Int {
return range.filter { $0 % 3 == 0 }.reduce(0, +)
}
```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: Int] = [:]
var number = n
var factor = 2
while factor * factor <= number {
if number % factor == 0 {
factors[factor, default: 0] += 1
number /= factor
} else {
factor += 1
}
}
factors[number, default: 0] += 1
return Array(factors.map { $0.key ** $0.value })
}
// Return array of all prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: [2, 3, 5, 7]
func findPrimes(in range: ClosedRange<Int>) -> [Int] {
var primes: [Int] = []
for number in range {
if isPrime(number) {
primes.append(number)
}
}
return primes
}
// Return true if the given number is prime, false otherwise.
// A number is prime if it is greater than 1 and its only factors are 1 and itself.
// Input: 2
// Output: true
// Input: 4
// Output: false
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for factor in 2...number {
if number % factor == 0 {
return false
}
}
return true
}
// Return the sum of all numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 55
func sum(in range: ClosedRange<Int>) -> Int {
return range.reduce(0, +)
}
// Return the sum of all prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 17
func sumOfPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).reduce(0, +)
}
// Return the sum of all even prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 10
func sumOfEvenPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2 == 0 }.reduce(0, +)
}
// Return the sum of all odd prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 17
func sumOfOddPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(0, +)
}
// Return the product of all prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 3134
func productOfPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).reduce(1, *)
}
// Return the product of all even prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 32
func productOfEvenPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2 == 0 }.reduce(1, *)
}
// Return the product of all odd prime numbers in the given range.
// The range is inclusive.
// Input range: 1...10
// Output: 929
func productOfOddPrimes(in range: ClosedRange<Int>) -> Int {
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(1, *)
}
// Return the sum of all numbers divisible by 3 in the given range.
// The range is inclusive.
// Input range: 1...100
// Output: 66
func sumOfNumbersDivisibleBy3(in range: ClosedRange<Int>) -> Int {
return range.filter { $0 % 3 == 0 }.reduce(0, +)
}
// Return the sum of all squares of even prime numbers in the given range.
//
return Array(factors.map { $0.key ** $0.value }) // no operator '**' is defined; did you mean 'pow(_:_:)'?
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(0, +) // cannot convert value of type '()' to closure result type 'Bool'
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(0, +) // '=' must have consistent whitespace on both sides
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(0, +) // cannot force unwrap value of non-optional type 'Int'
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(0, +) // expression is not assignable: binary operator returns immutable value
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(1, *) // '=' must have consistent whitespace on both sides
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(1, *) // cannot convert value of type '()' to closure result type 'Bool'
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(1, *) // expression is not assignable: binary operator returns immutable value
return findPrimes(in: range).filter { $0 % 2!= 0 }.reduce(1, *) // cannot force unwrap value of non-optional type 'Int'
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var number = n
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
func countDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
digits += 1
number /= 10
}
return digits
}
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var number = n
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
factors.append(divisor)
number /= divisor
} else {
divisor += 1
}
}
return factors
}
// Return the sum of all digits in the given integer.
// Input number: 12345
// Output: 15
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the number of digits in the given integer.
// Input number: 12345
// Output: 5
func countDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
digits += 1
number /= 10
}
return digits
}
// Return the product of all digits in the given integer.
// Input number: 12345
// Output: 120
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number: 12345
// Output: 15
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the number of digits in the given integer.
// Input number: 12345
// Output: 5
func countDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
digits += 1
number /= 10
}
return digits
}
// Return the product of all digits in the given integer.
// Input number: 12345
// Output: 120
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number: 12345
// Output: 15
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the number of digits in the given integer.
// Input number: 12345
// Output: 5
func countDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
digits += 1
number /= 10
}
return digits
}
// Return the product of all digits in the given integer.
// Input number: 12345
// Output: 120
func productOfDigits(n: Int) -> Int {
var product = 1
var number = n
while number > 0 {
product *= number % 10
number /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number: 12345
// Output: 15
func sumOfDigits(n: Int) -> Int {
var sum = 0
var number = n
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
// Return the number of digits in the given integer.
// Input number: 12345
// Output: 5
func countDigits(n: Int) -> Int {
var number = n
var digits = 0
while number > 0 {
digits += 1
number /= 10
}
return digits
}
// Return the product of all digits in the given integer.
// Input number: 12345
// Output: 120
func productOfDigits(n: Int) -> Int {
var product =
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var num = n
var i = 2
while i <= num {
if num % i == 0 {
factors.append(i)
num /= i
i = 1
} else {
i += 1
}
}
return factors
}
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
```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 num = n
var i = 2
while i <= num {
if num % i == 0 {
factors.append(i)
num /= i
i = 1
} else {
i += 1
}
}
return factors
}
// Return the sum of all digits in the given integer.
// Input number is positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number is positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 100
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number is positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number is positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 100
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number is positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number is positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 100
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number is positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number is positive integer
// productDigits(n: 123) == 6
// productDigits(n: 456) == 100
func productDigits(n: Int) -> Int {
var product = 1
var num = n
while num > 0 {
product *= num % 10
num /= 10
}
return product
}
// Return the sum of all digits in the given integer.
// Input number is positive integer
// sumDigits(n: 123) == 6
// sumDigits(n: 456) == 15
func sumDigits(n: Int) -> Int {
var sum = 0
var num = n
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
// Return the product of all digits in the given integer.
// Input number is positive integer
// product
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if seen.contains(number) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if seen.contains(number) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than twice.
// Remove duplicates in place.
// removeDuplicatesInPlace(numbers: &numbers)
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicatesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeDuplicatesInPlace2(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeDuplicatesInPlace3(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeDuplicatesInPlace4(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeDuplicatesInPlace5(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeDuplicatesInPlace6(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace2(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace3(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace4(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace5(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace6(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the input array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace7(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i])
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicatesAndSort(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted()
}
func removeDuplicatesAndSortDescending(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted(by: >)
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than once.
// Sort the elements in the result in ascending order.
// removeDuplicatesAndSort(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesAndSort(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted()
}
// From an array of integers, remove all elements that occur more than once.
// Sort the elements in the result in descending order.
// removeDuplicatesAndSortDescending(numbers: [1, 2, 3, 2, 4]) == [4, 3, 2, 1]
func removeDuplicatesAndSortDescending(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted(by: >)
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicates and sort in ascending order.
// removeDuplicatesAndSort(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesAndSort(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted()
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicates and sort in descending order.
// removeDuplicatesAndSortDescending(numbers: [1, 2, 3, 2, 4]) == [4, 3, 2, 1]
func removeDuplicatesAndSortDescending(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted(by: >)
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicates and sort in descending order.
// removeDuplicatesAndSortDescending(numbers: [1, 2, 3, 2, 4]) == [4, 3, 2, 1]
func removeDuplicatesAndSortDescending(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted(by: >)
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicates and sort in descending order.
// removeDuplicatesAndSortDescending(numbers: [1, 2, 3, 2, 4]) == [4, 3, 2, 1]
func removeDuplicatesAndSortDescending(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result.sorted(by: >)
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicates and sort in descending order.
// removeDuplicatesAndSortDescending(numbers: [1, 2, 3, 2, 4]) == [4, 3, 2, 1]
func removeDuplicatesAndSortDescending(numbers: [Int])
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if seen.contains(number) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
func removeDuplicatesInPlace2(numbers: inout [Int]) {
var i = 0
while i < numbers.count {
var j = i + 1
while j < numbers.count {
if numbers[i] == numbers[j] {
numbers.remove(at: j)
} else {
j += 1
}
}
i += 1
}
}
func removeDuplicatesInPlace3(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
func removeDuplicatesInPlace4(numbers: inout [Int]) {
var i = 0
while i < numbers.count {
var j = i + 1
while j < numbers.count {
if numbers[i] == numbers[j] {
numbers.remove(at: j)
} else {
j += 1
}
}
i += 1
}
}
func removeDuplicatesInPlace5(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if seen.contains(number) {
continue
}
seen.insert(number)
result.append(number)
}
return result
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicate elements in place.
// removeDuplicatesInPlace([1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesInPlace(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicate elements in place.
// removeDuplicatesInPlace([1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesInPlace2(numbers: inout [Int]) {
var i = 0
while i < numbers.count {
var j = i + 1
while j < numbers.count {
if numbers[i] == numbers[j] {
numbers.remove(at: j)
} else {
j += 1
}
}
i += 1
}
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicate elements in place.
// removeDuplicatesInPlace([1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesInPlace3(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicate elements in place.
// removeDuplicatesInPlace([1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesInPlace4(numbers: inout [Int]) {
var i = 0
while i < numbers.count {
var j = i + 1
while j < numbers.count {
if numbers[i] == numbers[j] {
numbers.remove(at: j)
} else {
j += 1
}
}
i += 1
}
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicate elements in place.
// removeDuplicatesInPlace([1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesInPlace5(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
}
// From an array of integers, remove all elements that occur more than once.
// Remove duplicate elements in place.
// removeDuplicatesInPlace([1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicatesInPlace6(numbers: inout [Int]) {
var seen = Set<Int>()
var i = 0
while i < numbers.
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicatesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeSingles(numbers: [Int]) -> [Int] {
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
}
}
return Array(seen)
}
func removeSinglesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func multiplyByTwo(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number * 2)
}
return result
}
func multiplyByTwoInPlace(numbers: inout [Int]) -> [Int] {
for i in 0..<numbers.count {
numbers[i] *= 2
}
return numbers
}
func divideByTwo(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number / 2)
}
return result
}
func divideByTwoInPlace(numbers: inout [Int]) -> [Int] {
for i in 0..<numbers.count {
numbers[i] /= 2
}
return numbers
}
func square(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number * number)
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the original array.
// removeDuplicatesInPlace(numbers: &numbers) == [1, 3, 4]
func removeDuplicatesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur only once.
// Return a new array with the elements that occur only once.
// removeSingles(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeSingles(numbers: [Int]) -> [Int] {
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
}
}
return Array(seen)
}
// From an array of integers, remove all elements that occur only once.
// Remove elements in-place, modifying the original array.
// removeSinglesInPlace(numbers: &numbers) == [1, 2, 3, 4]
func removeSinglesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// Given an array of integers, return a new array with all values
// multiplied by 2.
// multiplyByTwo(numbers: [1, 2, 3, 4]) == [2, 4, 6, 8]
func multiplyByTwo(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number * 2)
}
return result
}
// Given an array of integers, multiply each value in the array by 2.
// multiplyByTwoInPlace(numbers: &numbers) == [2, 4, 6, 8]
func multiplyByTwoInPlace(numbers: inout [Int]) -> [Int] {
for i in 0..<numbers.count {
numbers[i] *= 2
}
return numbers
}
// Given an array of integers, return a new array with all values
// divided by 2.
// divideByTwo(numbers: [1, 2, 3, 4]) == [0, 1, 1, 0]
func divideByTwo(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number / 2)
}
return result
}
// Given an array of integers, divide each value in the array by 2.
// divideByTwoInPlace(numbers: &numbers) == [0, 1, 1, 0]
func divideByTwoInPlace(numbers: inout [Int]) -> [Int] {
for i in 0..<numbers.count {
numbers[i] /= 2
}
return numbers
}
// Given an array of integers, return a new array with all values
// squared.
// square(numbers: [1, 2, 3, 4]) == [1, 4, 9, 16]
func square(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number * number)
}
return result
}
// Given an array of integers, square each value in the array.
// squareInPlace(numbers: &numbers) == [1, 4, 9, 16]
func squareInPlace(numbers: inout [Int]) -> [Int] {
for i in 0..<numbers.count
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicatesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeSingles(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
} else if result.last == number {
result.removeLast()
}
}
return result
}
func removeSinglesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
func removeTriples(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var last = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
last = number
} else if number == last + 1 {
result.append(last)
last = number
}
}
result.append(last)
return result
}
func removeTriplesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than once.
// Remove elements in-place, modifying the original array.
// removeDuplicatesInPlace(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicatesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur only once.
// Keep order of elements left the same as in the input.
// removeSingles(numbers: [1, 2, 3, 2, 4]) == [2, 2, 4]
func removeSingles(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
} else if result.last == number {
result.removeLast()
}
}
return result
}
// From an array of integers, remove all elements that occur only once.
// Remove elements in-place, modifying the original array.
// removeSinglesInPlace(numbers: [1, 2, 3, 2, 4]) == [2, 4]
func removeSinglesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur
// more than twice, but only if they are consecutive.
// Keep order of elements left the same as in the input.
// removeTriples(numbers: [1, 2, 3, 2, 4, 2, 5]) == [1, 2, 3, 4, 5]
func removeTriples(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var last = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
last = number
} else if number == last + 1 {
result.append(last)
last = number
}
}
result.append(last)
return result
}
// From an array of integers, remove all elements that occur
// more than twice, but only if they are consecutive.
// Remove elements in-place, modifying the original array.
// removeTriplesInPlace(numbers: [1, 2, 3, 2, 4, 2, 5]) == [1, 2, 3, 4, 5]
func removeTriplesInPlace(numbers: inout [Int]) -> [Int] {
var seen = Set<Int>()
var i = 0
while i < numbers.count {
if seen.contains(numbers[i]) {
numbers.remove(at: i)
} else {
seen.insert(numbers[i])
i += 1
}
}
return numbers
}
// From an array of integers, remove all elements that occur
// more than twice, but only if they are consecutive.
// Remove elements in-place, modifying the original array.
// removeTriplesInPlace(numbers: [1, 2, 3, 2, 4, 2, 5]) == [1, 2, 3, 4, 5]
func removeTriplesInPlace2(numbers: inout [Int]) -> [Int] {
var i = 0
while i < numbers.count {
if i + 2 < numbers.count && numbers[i] == numbers[i + 2] {
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicates2(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates3(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates4(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
func removeDuplicates5(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else if count == 2 {
count += 1
result.removeLast()
}
}
return result
}
func removeDuplicates6(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else if count == 2 {
count += 1
result.removeLast()
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates2(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates3(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates4(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates5(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else if count == 2 {
count += 1
result.removeLast()
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates6(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else if count == 2 {
count += 1
result.removeLast()
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates7(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 3 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 4 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 5 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 6 {
count += 1
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than three times.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 3 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than four times.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 4 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than five times.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 5 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than six times.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 6 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than seven times.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count =
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicates2(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates3(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates4(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
func removeDuplicates5(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else {
count -= 1
}
}
return result
}
func removeDuplicates6(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else {
count -= 1
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates2(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates3(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates4(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates5(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else {
count -= 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates6(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
} else {
count -= 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 2, 3, 4]
func removeDuplicates7(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
func removeDuplicates2(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates3(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
result.append(number)
}
}
return result
}
func removeDuplicates4(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
func removeDuplicates5(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
func removeDuplicates6(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates2(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count < 2 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates3(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
result.append(number)
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates4(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates5(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates6(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count += 1
}
}
return result
}
// From an array of integers, remove all elements that occur more than twice.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates7(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
var count = 0
for number in numbers {
if!seen.contains(number) {
seen.insert(number)
count = 1
result.append(number)
} else if count == 1 {
count +=
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
if!seen.contains(number) { // expected expression, var, or let in 'if' condition
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
// Test the function
let inputString = "Hello World!"
let outputString = flipCase(string: inputString)
print(outputString)
```
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
// Test the function
let inputString = "Hello World!"
let outputString = flipCase(string: inputString)
print(outputString)
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
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 {
var newString = ""
for char in string {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
// Test Cases
assert(flipCase(string: "Hello") == "hELLO")
assert(flipCase(string: "World") == "wORLD")
assert(flipCase(string: "1234") == "1234")
assert(flipCase(string: "!@#$%") == "!@#$%")
assert(flipCase(string: "Hello World") == "hELLO wORLD")
assert(flipCase(string: "1234!@#$%") == "1234!@#$%")
assert(flipCase(string: "!@#$% World") == "!@#$% wORLD")
```
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char).lowercased()
} else {
flippedString += String(char).uppercased()
}
}
return flippedString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char).lowercased()
} else {
flippedString += String(char).uppercased()
}
}
return flippedString
}
// Test the function
let inputString = "Hello World!"
let outputString = flipCase(string: inputString)
print(outputString)
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
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 {
var newString = ""
for char in string {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
// Test the function
let inputString = "Hello World!"
let outputString = flipCase(string: inputString)
print(outputString)
```
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
// Test the function
let inputString = "Hello World!"
let outputString = flipCase(string: inputString)
print(outputString)
```
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char.lowercased())
} else {
flippedString += String(char.uppercased())
}
}
return flippedString
}
// Test Cases
flipCase(string: "Hello") // "hELLO"
flipCase(string: "World") // "wORLD"
flipCase(string: "Python Programming") // "pYTHON pROGRAMMING"
flipCase(string: "1234") // "1234"
flipCase(string: "!@#$%") // "!@#$%"
```
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char).lowercased()
} else {
flippedString += String(char).uppercased()
}
}
return flippedString
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var flippedString = ""
for char in string {
if char.isUppercase {
flippedString += String(char).lowercased()
} else {
flippedString += String(char).uppercased()
}
}
return flippedString
}
// Test Cases
assert(flipCase(string: "Hello") == "hELLO")
assert(flipCase(string: "World") == "wORLD")
assert(flipCase(string: "Hello World") == "hELLO wORLD")
assert(flipCase(string: "1234") == "1234")
assert(flipCase(string: "!@#$%") == "!@#$%")
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
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 {
var newString = ""
for char in string {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
// Test the function
let inputString = "Hello World"
let outputString = flipCase(string: inputString)
print(outputString)
```
func flipCase(string: String) -> String {
var newString = ""
for char in string {
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 {
var newString = ""
for char in string {
if char.isUppercase {
newString += String(char).lowercased()
} else {
newString += String(char).uppercased()
}
}
return newString
}
// Test the function
let inputString = "Hello World!"
let outputString = flipCase(string: inputString)
print(outputString)
```
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func allUniqueCharacters(string: String) -> Bool {
return Set(string).count == string.count
}
func reverse(string: String) -> String {
return String(string.reversed())
}
func removeDuplicates(string: String) -> String {
var characters = Set<Character>()
var result = ""
for character in string {
if!characters.contains(character) {
characters.insert(character)
result.append(character)
}
}
return result
}
func areAnagrams(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var characters = [Character: Int]()
for character in string1 {
characters[character, default: 0] += 1
}
for character in string2 {
if let count = characters[character] {
characters[character] = count - 1
if characters[character] == 0 {
characters[character] = nil
}
} else {
return false
}
}
return true
}
func isPalindrome(string: String) -> Bool {
if string.count == 0 || string.count == 1 {
return true
}
if string.count == 2 {
return string[string.startIndex] == string[string.index(after: string.startIndex)]
}
let middleIndex = string.index(string.startIndex, offsetBy: Int(string.count / 2))
let firstHalf = String(string[string.startIndex...middleIndex])
let secondHalf = String(string[string.index(after: middleIndex)...string.endIndex])
return firstHalf == String(secondHalf.reversed())
}
func removeSpecialCharacters(string: String) -> String {
var result = ""
for character in string {
if character.isLetter || character.isNumber {
result.append(character)
}
}
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 {
return strings.joined()
}
// Determine if a string contains only unique characters
// allUniqueCharacters(string: "") == true
// allUniqueCharacters(string: "abc") == true
// allUniqueCharacters(string: "abcabc") == false
func allUniqueCharacters(string: String) -> Bool {
return Set(string).count == string.count
}
// Reverse a string
// reverse(string: "") == ""
// reverse(string: "a") == "a"
// reverse(string: "ab") == "ba"
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
return String(string.reversed())
}
// Remove duplicate characters from a string
// removeDuplicates(string: "") == ""
// removeDuplicates(string: "a") == "a"
// removeDuplicates(string: "ab") == "ab"
// removeDuplicates(string: "abc") == "abc"
// removeDuplicates(string: "abbc") == "abc"
func removeDuplicates(string: String) -> String {
var characters = Set<Character>()
var result = ""
for character in string {
if!characters.contains(character) {
characters.insert(character)
result.append(character)
}
}
return result
}
// Check if two strings are anagrams
// areAnagrams(string1: "", string2: "") == true
// areAnagrams(string1: "a", string2: "a") == true
// areAnagrams(string1: "ab", string2: "ba") == true
// areAnagrams(string1: "abc", string2: "cba") == true
// areAnagrams(string1: "abbc", string2: "cba") == false
func areAnagrams(string1: String, string2: String) -> Bool {
if string1.count!= string2.count {
return false
}
var characters = [Character: Int]()
for character in string1 {
characters[character, default: 0] += 1
}
for character in string2 {
if let count = characters[character] {
characters[character] = count - 1
if characters[character] == 0 {
characters[character] = nil
}
} else {
return false
}
}
return true
}
// Determine if a string is a palindrome
// isPalindrome(string: "") == true
// isPalindrome(string: "a") == true
// isPalindrome(string: "ab") == false
// isPalindrome(string: "abc") == false
// isPalindrome(string: "abba") == true
// isPalindrome(string: "abcba") == true
func isPalindrome(string: String) -> Bool {
if string.count == 0 || string.count == 1 {
return true
}
if string.count == 2 {
return string[string.startIndex] == string[string.index(after: string.startIndex)]
}
let middleIndex = string.index(string.startIndex, offsetBy: Int(string.count / 2))
let firstHalf = String(string[string.startIndex...middleIndex])
let secondHalf = String(string[string.index(after: middleIndex)...string.endIndex])
return firstHalf == String(secondHalf.reversed())
}
// Remove all whitespace, punctuation, and special characters from a string
// removeSpecialCharacters(string: "") == ""
// removeSpecialCharacters(string: "a") == "a"
// removeSpecialCharacters(string: "abc") == "abc"
// removeSpecialCharacters(string: "ab,c") == "abc"
// removeSpecialCharacters(string: "a!bc") == "abc"
// removeSpecialCharacters(string: "a!bc 123") == "abc123"
func removeSpecialCharacters(string: String) -> String {
var result = ""
for character in string {
if character.isLetter || character.isNumber {
result.append(character)
}
}
return result
}
// Check if a string is a palindrome with special characters and whitespace removed
// isPalindromeWithoutSpecialCharacters(string: "") == true
// isPalindromeWithoutSpecialCharacters(string: "a") == true
// isPalindromeWithoutSpecialCharacters(string: "ab
if!characters.contains(character) { // expected expression, var, or let in 'if' condition
if string1.count!= string2.count { // '=' must have consistent whitespace on both sides
if string1.count!= string2.count { // cannot force unwrap value of non-optional type 'Int'
if string1.count!= string2.count { // use of '=' in a boolean context, did you mean '=='?
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
func reverse(string: String) -> String {
var result = ""
for char in string {
result = "\(char)" + result
}
return result
}
func countOccurrences(in string: String, character: Character) -> Int {
var count = 0
for char in string {
if char == character {
count += 1
}
}
return count
}
func removeDuplicates(from string: String) -> String {
var result = ""
for char in string {
if!result.contains(char) {
result += "\(char)"
}
}
return result
}
func isPalindrome(string: String) -> Bool {
if string.count == 0 {
return true
}
if string.count == 1 {
return true
}
if string.count == 2 {
return string[string.startIndex] == string[string.index(after: string.startIndex)]
}
let first = string[string.startIndex]
let last = string[string.index(before: string.endIndex)]
if first == last {
return isPalindrome(string: String(string.suffix(from: string.index(after: string.startIndex) )))
} else {
return false
}
}
func removeWhitespace(string: String) -> String {
var result = ""
for char in string {
if char!= " " {
result += "\(char)"
}
}
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
}
// Reverse the characters in a string
// reverse(string: "") == ""
// reverse(string: "a") == "a"
// reverse(string: "ab") == "ba"
// reverse(string: "abc") == "cba"
func reverse(string: String) -> String {
var result = ""
for char in string {
result = "\(char)" + result
}
return result
}
// Count the number of occurrences of a character in a string
// countOccurrences(in: "", character: "") == 0
// countOccurrences(in: "a", character: "a") == 1
// countOccurrences(in: "ab", character: "a") == 1
// countOccurrences(in: "ab", character: "b") == 1
// countOccurrences(in: "abc", character: "a") == 1
// countOccurrences(in: "abc", character: "b") == 1
// countOccurrences(in: "abc", character: "c") == 1
// countOccurrences(in: "abc", character: "d") == 0
func countOccurrences(in string: String, character: Character) -> Int {
var count = 0
for char in string {
if char == character {
count += 1
}
}
return count
}
// Remove duplicate characters from a string
// removeDuplicates(from: "") == ""
// removeDuplicates(from: "a") == "a"
// removeDuplicates(from: "ab") == "ab"
// removeDuplicates(from: "aba") == "ab"
// removeDuplicates(from: "abc") == "abc"
// removeDuplicates(from: "abca") == "abc"
// removeDuplicates(from: "abcba") == "abc"
func removeDuplicates(from string: String) -> String {
var result = ""
for char in string {
if!result.contains(char) {
result += "\(char)"
}
}
return result
}
// Check if a string is a palindrome
// isPalindrome(string: "") == true
// isPalindrome(string: "a") == true
// isPalindrome(string: "ab") == true
// isPalindrome(string: "abc") == false
// isPalindrome(string: "abba") == true
// isPalindrome(string: "abcba") == true
// isPalindrome(string: "abcdba") == false
func isPalindrome(string: String) -> Bool {
if string.count == 0 {
return true
}
if string.count == 1 {
return true
}
if string.count == 2 {
return string[string.startIndex] == string[string.index(after: string.startIndex)]
}
let first = string[string.startIndex]
let last = string[string.index(before: string.endIndex)]
if first == last {
return isPalindrome(string: String(string.suffix(from: string.index(after: string.startIndex) )))
} else {
return false
}
}
// Remove all whitespace characters from a string
// removeWhitespace(string: "") == ""
// removeWhitespace(string: "a") == "a"
// removeWhitespace(string: "ab") == "ab"
// removeWhitespace(string: "a ") == "a"
// removeWhitespace(string: "a b") == "a b"
// removeWhitespace(string: "a b") == "a b"
// removeWhitespace(string: "a b ") == "a b"
func removeWhitespace(string: String) -> String {
var result = ""
for char in string {
if char!= " " {
result += "\(char)"
}
}
return result
}
// Split a string into an array of words
// splitIntoWords(string: "") == []
// splitIntoWords(string: "a") == ["a"]
// splitIntoWords(string: "ab") == ["ab"]
// splitIntoWords(string: "abc") == ["abc"]
// splitIntoWords(string: "a b c") == ["a", "b", "c"]
// splitIntoWords(string:
if!result.contains(char) { // expected expression, var, or let in 'if' condition
if char!= " " { // use of '=' in a boolean context, did you mean '=='?
if char!= " " { // cannot force unwrap value of non-optional type 'Character'
if char!= " " { // '=' must have consistent whitespace on both sides
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func firstNonEmpty(strings: [String]) -> String? {
for string in strings {
if!string.isEmpty {
return string
}
}
return nil
}
func longest(strings: [String]) -> String? {
var longest: String?
for string in strings {
if longest == nil || string.count > longest!.count {
longest = string
}
}
return longest
}
func vowelStrings(from strings: [String]) -> [String] {
var vowelStrings = [String]()
for string in strings {
if "aeiou".contains(string.prefix(1)) {
vowelStrings.append(string)
}
}
return vowelStrings
}
func substringStrings(from strings: [String], containing substring: String) -> [String] {
var substringStrings = [String]()
for string in strings {
if string.contains(substring) {
substringStrings.append(string)
}
}
return substringStrings
}
func lengthStrings(from strings: [String], withLength length: Int) -> [String] {
var lengthStrings = [String]()
for string in strings {
if string.count == length {
lengthStrings.append(string)
}
}
return lengthStrings
}
func vowelLengthStrings(from strings: [String], withLength length: Int) -> [String] {
var vowelLengthStrings = [String]()
for string in strings {
if "aeiou".contains(string.prefix(1)) && string.count == length {
vowelLengthStrings.append(string)
}
}
return vowelLengthStrings
}
func vowelLengthSubstringStrings(from strings: [String], containing substring: String, withLength length: Int) -> [String] {
var vowelLengthSubstringStrings = [String]()
for string in strings {
if "aeiou".contains(string.prefix(1)) && string.count == length && string.contains(substring) {
vowelLengthSubstringStrings.append(string)
}
}
return vowelLengthSubstringStrings
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Return the first non-empty string from an array of strings
// firstNonEmpty(strings: [] as [String]) == nil
// firstNonEmpty(strings: ["a", "b", "c"]) == "a"
func firstNonEmpty(strings: [String]) -> String? {
for string in strings {
if!string.isEmpty {
return string
}
}
return nil
}
// Return the longest string from an array of strings
// longest(strings: [] as [String]) == nil
// longest(strings: ["abc", "def", "ghij"]) == "ghij"
func longest(strings: [String]) -> String? {
var longest: String?
for string in strings {
if longest == nil || string.count > longest!.count {
longest = string
}
}
return longest
}
// Return an array of strings containing only the strings that begin with a vowel
// vowelStrings(from: []) == []
// vowelStrings(from: ["apple", "banana", "orange"]) == ["apple", "orange"]
func vowelStrings(from strings: [String]) -> [String] {
var vowelStrings = [String]()
for string in strings {
if "aeiou".contains(string.prefix(1)) {
vowelStrings.append(string)
}
}
return vowelStrings
}
// Return an array of strings containing only the strings that contain a specific substring
// substringStrings(from: [], containing: "") == []
// substringStrings(from: ["apple", "banana", "orange"], containing: "an") == ["banana", "orange"]
func substringStrings(from strings: [String], containing substring: String) -> [String] {
var substringStrings = [String]()
for string in strings {
if string.contains(substring) {
substringStrings.append(string)
}
}
return substringStrings
}
// Return an array of strings containing only the strings that have a specific length
// lengthStrings(from: [], withLength: 0) == []
// lengthStrings(from: ["apple", "banana", "orange"], withLength: 5) == ["apple", "banana"]
func lengthStrings(from strings: [String], withLength length: Int) -> [String] {
var lengthStrings = [String]()
for string in strings {
if string.count == length {
lengthStrings.append(string)
}
}
return lengthStrings
}
// Return an array of strings containing only the strings that start with a vowel and have a specific length
// vowelLengthStrings(from: [], withLength: 0) == []
// vowelLengthStrings(from: ["apple", "banana", "orange"], withLength: 5) == ["apple"]
func vowelLengthStrings(from strings: [String], withLength length: Int) -> [String] {
var vowelLengthStrings = [String]()
for string in strings {
if "aeiou".contains(string.prefix(1)) && string.count == length {
vowelLengthStrings.append(string)
}
}
return vowelLengthStrings
}
// Return an array of strings containing only the strings that start with a vowel, have a specific length,
// and contain a specific substring
// vowelLengthSubstringStrings(from: [], containing: "", withLength: 0) == []
// vowelLengthSubstringStrings(from: ["apple", "banana", "orange"], containing: "an", withLength: 5) == ["apple"]
func vowelLengthSubstringStrings(from strings: [String], containing substring: String, withLength length: Int) -> [String] {
var vowelLengthSubstringStrings = [String]()
for string in strings {
if "aeiou".contains(string.prefix(1)) && string.count == length && string.contains(substring) {
vowelLengthSubstringStrings.append(string)
}
}
return vowelLengthSubstringStrings
}
// Return an array of strings sorted in alphabetical order
// sortStrings(strings: []) == []
// sortStrings(strings: ["cat", "apple", "dog", "elephant", "orange"]) == ["apple", "cat", "dog", "elephant", "orange"]
func sortStrings(strings: [
if!string.isEmpty { // expected expression, var, or let in 'if' condition
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func longestLength(strings: [String]) -> Int {
return strings.map { $0.count }.max()?? 0
}
func longest(strings: [String]) -> String? {
return strings.max { $0.count < $1.count }
}
func shortest(strings: [String]) -> String? {
return strings.min { $0.count < $1.count }
}
func sort(strings: [String]) -> [String] {
return strings.sorted()
}
func reverseSort(strings: [String]) -> [String] {
return strings.sorted(by: >)
}
func unique(strings: [String]) -> [String] {
return Array(Set(strings))
}
func removePrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) == false }
}
func removeSuffix(strings: [String], suffix: String) -> [String] {
return strings.filter { $0.hasSuffix(suffix) == false }
}
func removeWhitespace(strings: [String]) -> [String] {
return strings.map { $0.trimmingCharacters(in:.whitespaces) }
}
func removePunctuation(strings: [String]) -> [String] {
return strings.map { $0.trimmingCharacters(in: CharacterSet.punctuationCharacters) }
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Return the length of the longest string in the array
// longestLength(strings: [] as [String]) == 0
// longestLength(strings: ["a", "ab", "abc"]) == 3
func longestLength(strings: [String]) -> Int {
return strings.map { $0.count }.max()?? 0
}
// Return the longest string in the array
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "ab", "abc"]) == "abc"
func longest(strings: [String]) -> String? {
return strings.max { $0.count < $1.count }
}
// Return the shortest string in the array
// shortest(strings: [] as [String]) == nil
// shortest(strings: ["a", "ab", "abc"]) == "a"
func shortest(strings: [String]) -> String? {
return strings.min { $0.count < $1.count }
}
// Return an array of strings sorted in alphabetical order
// sort(strings: [] as [String]) == []
// sort(strings: ["b", "a", "c"]) == ["a", "b", "c"]
func sort(strings: [String]) -> [String] {
return strings.sorted()
}
// Return an array of strings sorted in reverse alphabetical order
// reverseSort(strings: [] as [String]) == []
// reverseSort(strings: ["b", "a", "c"]) == ["c", "b", "a"]
func reverseSort(strings: [String]) -> [String] {
return strings.sorted(by: >)
}
// Return an array of strings with duplicates removed
// unique(strings: [] as [String]) == []
// unique(strings: ["a", "a", "b", "c", "b"]) == ["a", "b", "c"]
func unique(strings: [String]) -> [String] {
return Array(Set(strings))
}
// Return an array of strings with the given prefix removed
// removePrefix(strings: [] as [String], prefix: "") == []
// removePrefix(strings: ["apple", "banana", "cherry"], prefix: "ba") == ["apple", "cherry"]
func removePrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) == false }
}
// Return an array of strings with the given suffix removed
// removeSuffix(strings: [] as [String], suffix: "") == []
// removeSuffix(strings: ["apple", "banana", "cherry"], suffix: "e") == ["apple", "banana"]
func removeSuffix(strings: [String], suffix: String) -> [String] {
return strings.filter { $0.hasSuffix(suffix) == false }
}
// Return an array of strings with whitespace removed from each string
// removeWhitespace(strings: [] as [String]) == []
// removeWhitespace(strings: ["a", "b", "c"]) == ["a", "b", "c"]
// removeWhitespace(strings: ["a ", " b", " c "]) == ["a", "b", "c"]
func removeWhitespace(strings: [String]) -> [String] {
return strings.map { $0.trimmingCharacters(in:.whitespaces) }
}
// Return an array of strings with punctuation marks removed from each string
// removePunctuation(strings: [] as [String]) == []
// removePunctuation(strings: ["a.", "b!", "c?"]) == ["a", "b", "c"]
// removePunctuation(strings: ["a,", "b.", "c!"]) == ["a", "b", "c"]
func removePunctuation(strings: [String]) -> [String] {
return strings.map { $0.trimmingCharacters(in: CharacterSet.punctuationCharacters) }
}
// Return an array of strings with non-alphabetic characters removed from each string
// removeNonAlphabetic(strings: [] as [String]) == []
// removeNonAlphabetic(strings: ["a", "b2", "c"]) == ["a", "b2", "c"]
// removeNonAlphabetic(strings: ["a", "b", "c", " ", "2", "
return strings.map { $0.count }.max()?? 0 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return strings.map { $0.count }.max()?? 0 // cannot use optional chaining on non-optional value of type 'Int'
return strings.map { $0.count }.max()?? 0 // consecutive statements on a line must be separated by ';'
return strings.map { $0.count }.max()?? 0 // integer literal is unused
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
func concatenateFilter(strings: [String]) -> String {
var result = ""
for string in strings {
if string.count > 3 {
result += string
}
}
return result
}
func maxLength(strings: [String]) -> Int {
var max = 0
for string in strings {
if string.count > max {
max = string.count
}
}
return max
}
func filterByMinLength(strings: [String], minLength: Int) -> [String] {
var result = [String]()
for string in strings {
if string.count > minLength {
result.append(string)
}
}
return result
}
func sortStrings(strings: [String]) -> [String] {
return strings.sorted()
}
func reverseSortStrings(strings: [String]) -> [String] {
return strings.sorted(by: >)
}
func removeDuplicates(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
if!result.contains(string) {
result.append(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, but only include strings that are longer than 3 characters
// concatenateFilter(strings: [] as [String]) == ""
// concatenateFilter(strings: ["a", "b", "c"]) == "abc"
// concatenateFilter(strings: ["a", "bc", "def"]) == "abcdef"
func concatenateFilter(strings: [String]) -> String {
var result = ""
for string in strings {
if string.count > 3 {
result += string
}
}
return result
}
// Return the length of the longest string in an array of strings
// maxLength(strings: [] as [String]) == 0
// maxLength(strings: ["a", "b", "c"]) == 3
// maxLength(strings: ["a", "bc", "defg"]) == 6
func maxLength(strings: [String]) -> Int {
var max = 0
for string in strings {
if string.count > max {
max = string.count
}
}
return max
}
// Return the length of the longest string in an array of strings, but only consider strings that are longer than minLength
// filterByMinLength(strings: [] as [String], minLength: 5) == []
// filterByMinLength(strings: ["a", "b", "c"], minLength: 5) == ["a", "b", "c"]
// filterByMinLength(strings: ["a", "bc", "defg"], minLength: 5) == ["a", "bc", "defg"]
// filterByMinLength(strings: ["a", "bc", "defg"], minLength: 4) == ["a", "bc", "defg"]
func filterByMinLength(strings: [String], minLength: Int) -> [String] {
var result = [String]()
for string in strings {
if string.count > minLength {
result.append(string)
}
}
return result
}
// Return an array of strings sorted in alphabetical order
// sortStrings(strings: [] as [String]) == []
// sortStrings(strings: ["b", "a", "c"]) == ["a", "b", "c"]
// sortStrings(strings: ["b", "a", "C"]) == ["a", "b", "C"]
// sortStrings(strings: ["B", "a", "c", "A"]) == ["A", "a", "B", "c"]
func sortStrings(strings: [String]) -> [String] {
return strings.sorted()
}
// Return an array of strings sorted in reverse alphabetical order
// reverseSortStrings(strings: [] as [String]) == []
// reverseSortStrings(strings: ["b", "a", "c"]) == ["c", "b", "a"]
// reverseSortStrings(strings: ["b", "a", "C"]) == ["C", "b", "a"]
// reverseSortStrings(strings: ["B", "a", "c", "A"]) == ["A", "c", "B", "a"]
func reverseSortStrings(strings: [String]) -> [String] {
return strings.sorted(by: >)
}
// Return an array of strings with duplicates removed
// removeDuplicates(strings: [] as [String]) == []
// removeDuplicates(strings: ["a", "b", "c"]) == ["a", "b", "c"]
// removeDuplicates(strings: ["a", "b", "a", "c"]) == ["a", "b", "c"]
// removeDuplicates(strings: ["a", "b", "A", "a", "c", "C", "c"]) == ["a", "b", "A", "c"]
func removeDuplicates(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
if!result.contains(string) {
result.append(string)
}
}
return result
}
// Return an array of strings with duplicates removed, but only include strings that are at least minLength in length
// filterByMinLengthAndUnique(strings: [] as [String], minLength: 5) == []
// filterByMinLengthAndUnique(strings: ["a", "b", "c"], minLength: 5) == ["a", "b", "
if!result.contains(string) { // expected expression, var, or let in 'if' condition
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
func reverse(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
result.insert(string, at: 0)
}
return result
}
func firstThreeCharacters(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
if string.count > 3 {
result.append(string[0...2])
} else {
result.append(string)
}
}
return result
}
func removeWhitespace(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
var newString = ""
for char in string {
if!char.isWhitespace {
newString += String(char)
}
}
result.append(newString)
}
return result
}
func removePunctuation(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
var newString = ""
for char in string {
if!char.isPunctuation {
newString += String(char)
}
}
result.append(newString)
}
return result
}
func removeVowels(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
var newString = ""
for char in string {
if!"AEIOUYaeiouy".contains(char) {
newString += String(char)
}
}
result.append(newString)
}
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
}
// Reverse the order of an array of strings
// reverse(strings: [] as [String]) == []
// reverse(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverse(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
result.insert(string, at: 0)
}
return result
}
// Return an array of strings containing the first 3 characters of each string
// firstThreeCharacters(strings: [] as [String]) == []
// firstThreeCharacters(strings: ["a", "ab", "abc"]) == ["a", "ab", "abc"]
func firstThreeCharacters(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
if string.count > 3 {
result.append(string[0...2])
} else {
result.append(string)
}
}
return result
}
// Return an array of strings with all whitespace characters removed
// removeWhitespace(strings: [] as [String]) == []
// removeWhitespace(strings: ["a", "b", "c"]) == ["a", "b", "c"]
// removeWhitespace(strings: ["a", "b", "c", " "]) == ["a", "b", "c"]
// removeWhitespace(strings: ["a", "b", "c", " ", " "]) == ["a", "b", "c"]
// removeWhitespace(strings: ["a", "b", "c", " ", " ", " "]) == ["a", "b", "c"]
func removeWhitespace(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
var newString = ""
for char in string {
if!char.isWhitespace {
newString += String(char)
}
}
result.append(newString)
}
return result
}
// Return an array of strings with all punctuation marks and special characters removed
// removePunctuation(strings: [] as [String]) == []
// removePunctuation(strings: ["a", "b", "c"]) == ["a", "b", "c"]
// removePunctuation(strings: ["a", "b", "c", "!"]) == ["a", "b", "c", "!"]
// removePunctuation(strings: ["a", "b", "c", "!", "@"]) == ["a", "b", "c", "!"]
// removePunctuation(strings: ["a", "b", "c", "!", "@", "#"]) == ["a", "b", "c", "!"]
func removePunctuation(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
var newString = ""
for char in string {
if!char.isPunctuation {
newString += String(char)
}
}
result.append(newString)
}
return result
}
// Return an array of strings with all vowels removed
// removeVowels(strings: [] as [String]) == []
// removeVowels(strings: ["a", "b", "c"]) == ["b", "c"]
// removeVowels(strings: ["a", "e", "i", "o", "u", "y"]) == []
// removeVowels(strings: ["a", "e", "i", "o", "u", "y", "A", "E", "I", "O", "U", "Y"]) == []
func removeVowels(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
var newString = ""
for char in string {
if!"AEIOUYaeiouy".contains(char) {
newString += String(char)
}
}
result.append(newString)
}
return result
}
// Return an array of strings with duplicates removed
// removeDuplicates(strings: [] as [String]) == []
// removeDuplicates(strings: ["a", "b", "c"]) == ["a", "b", "c"]
// removeDuplicates(strings: ["a", "b", "c", "a"]) == ["a", "b", "c"]
// removeDuplicates(strings: ["a",
result.append(string[0...2]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if!char.isWhitespace { // expected expression, var, or let in 'if' condition
if!char.isPunctuation { // expected expression, var, or let in 'if' condition
if!"AEIOUYaeiouy".contains(char) { // expected expression, var, or let in 'if' condition
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
func first(strings: [String], n: Int) -> [String] {
return Array(strings.prefix(n))
}
func rest(strings: [String], n: Int) -> [String] {
return Array(strings.dropFirst(n))
}
func butLast(strings: [String], n: Int) -> [String] {
return Array(strings.dropLast(n))
}
func removeAt(strings: [String], indexes: [Int]) -> [String] {
var mutableStrings = strings
indexes.forEach { index in
mutableStrings.remove(at: index)
}
return mutableStrings
}
func remove(strings: [String], stringsToRemove: [String]) -> [String] {
var mutableStrings = strings
stringsToRemove.forEach { string in
mutableStrings.removeAll(where: { $0 == string })
}
return mutableStrings
}
func reverseInPlace(strings: [String]) -> [String] {
var mutableStrings = strings
mutableStrings.reverse()
return mutableStrings
}
func capitalizeInPlace(strings: [String]) -> [String] {
var mutableStrings = strings
mutableStrings.forEach { string in
mutableStrings[strings.firstIndex(of: string)!] = string.capitalized
}
return mutableStrings
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Reverse the order of an array of strings
// reverse(strings: [] as [String]) == []
// reverse(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
// Return an array of strings containing the first n strings
// first(strings: [] as [String], n: 0) == []
// first(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// first(strings: ["a", "b", "c"], n: 4) == ["a", "b", "c"]
func first(strings: [String], n: Int) -> [String] {
return Array(strings.prefix(n))
}
// Return an array of strings containing all but the first n strings
// rest(strings: [] as [String], n: 0) == []
// rest(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// rest(strings: ["a", "b", "c"], n: 3) == []
func rest(strings: [String], n: Int) -> [String] {
return Array(strings.dropFirst(n))
}
// Return an array of strings containing all but the last n strings
// butLast(strings: [] as [String], n: 0) == []
// butLast(strings: ["a", "b", "c"], n: 1) == ["a", "b"]
// butLast(strings: ["a", "b", "c"], n: 3) == []
func butLast(strings: [String], n: Int) -> [String] {
return Array(strings.dropLast(n))
}
// Return an array of strings containing all strings but the ones at the specified indexes
// removeAt(strings: [] as [String], indexes: []) == []
// removeAt(strings: ["a", "b", "c", "d", "e"], indexes: [0, 2, 4]) == ["b", "d"]
func removeAt(strings: [String], indexes: [Int]) -> [String] {
var mutableStrings = strings
indexes.forEach { index in
mutableStrings.remove(at: index)
}
return mutableStrings
}
// Return an array of strings containing all strings but the specified strings
// remove(strings: [] as [String], stringsToRemove: []) == []
// remove(strings: ["a", "b", "c", "d", "e"], stringsToRemove: ["a", "e"]) == ["b", "c", "d"]
func remove(strings: [String], stringsToRemove: [String]) -> [String] {
var mutableStrings = strings
stringsToRemove.forEach { string in
mutableStrings.removeAll(where: { $0 == string })
}
return mutableStrings
}
// Return an array of strings containing the original strings in reverse order
// reverseInPlace(strings: [] as [String]) == []
// reverseInPlace(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverseInPlace(strings: [String]) -> [String] {
var mutableStrings = strings
mutableStrings.reverse()
return mutableStrings
}
// Return an array of strings containing the original strings with each string capitalized
// capitalizeInPlace(strings: [] as [String]) == []
// capitalizeInPlace(strings: ["a", "b", "c"]) == ["A", "B", "C"]
func capitalizeInPlace(strings: [String]) -> [String] {
var mutableStrings = strings
mutableStrings.forEach { string in
mutableStrings[strings.firstIndex(of: string)!] = string.capitalized
}
return mutableStrings
}
// Return an array of strings containing the original strings with each string reversed and capitalized
// mapInPlace(strings: [] as [String], transform: (String) -> String) == []
// mapInPlace(strings: ["a", "b", "c"], transform: { string in string.capitalized + string.reversed() }) == ["Aa", "Bb", "Cc"]
func mapInPlace(strings: [String], transform: (String) -> String) -> [String] {
var mutableStrings = strings
mutableStrings.enumerated().forEach
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
func first(strings: [String], n: Int) -> [String] {
return Array(strings[0..<min(n, strings.count)])
}
func rest(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count])
}
func initial(strings: [String], n: Int) -> [String] {
return Array(strings[0..<max(0, strings.count - n)])
}
func withoutLast(strings: [String], n: Int) -> [String] {
return Array(strings[1..<max(1, strings.count - n)])
}
func withoutFirst(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count])
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Reverse the order of an array of strings
// reverse(strings: [] as [String]) == []
// reverse(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
// Return an array of strings containing the first n strings
// first(strings: [] as [String], n: 1) == []
// first(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// first(strings: ["a", "b", "c"], n: 3) == ["a", "b", "c"]
// first(strings: ["a", "b", "c"], n: 4) == ["a", "b", "c"]
func first(strings: [String], n: Int) -> [String] {
return Array(strings[0..<min(n, strings.count)])
}
// Return an array of strings containing all strings except the first n
// rest(strings: [] as [String], n: 1) == []
// rest(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// rest(strings: ["a", "b", "c"], n: 2) == ["c"]
// rest(strings: ["a", "b", "c"], n: 3) == []
func rest(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count])
}
// Return an array of strings containing all strings except the last n
// initial(strings: [] as [String], n: 1) == []
// initial(strings: ["a", "b", "c"], n: 1) == ["a", "b"]
// initial(strings: ["a", "b", "c"], n: 2) == ["a"]
// initial(strings: ["a", "b", "c"], n: 3) == []
func initial(strings: [String], n: Int) -> [String] {
return Array(strings[0..<max(0, strings.count - n)])
}
// Return an array of strings containing all strings except the first and last n
// withoutLast(strings: [] as [String], n: 1) == []
// withoutLast(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// withoutLast(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// withoutLast(strings: ["a", "b", "c"], n: 3) == ["a"]
func withoutLast(strings: [String], n: Int) -> [String] {
return Array(strings[1..<max(1, strings.count - n)])
}
// Return an array of strings containing all strings except the first and first n
// withoutFirst(strings: [] as [String], n: 1) == []
// withoutFirst(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// withoutFirst(strings: ["a", "b", "c"], n: 2) == ["c"]
// withoutFirst(strings: ["a", "b", "c"], n: 3) == []
func withoutFirst(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count])
}
// Return an array of strings containing all strings in reverse order
// reverse(strings: [] as [String]) == []
// reverse(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
// Return an array of strings containing all strings in reverse order,
// but without any duplicates
// unique(strings: [] as [String]) == []
// unique(strings: ["a", "b", "c"]) == ["c", "b", "a"]
// unique(strings: ["a", "b", "c", "a"]) == ["c", "b", "a"]
func unique(strings: [String]) -> [String] {
var uniqueStrings = [String]()
for string in strings {
if!uniqueStrings.contains(string)
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
func first(strings: [String], n: Int) -> [String] {
return Array(strings[0..<Swift.min(n, strings.count)])
}
func rest(strings: [String], n: Int) -> [String] {
return Array(strings[Swift.max(0, n)..<strings.count])
}
func initial(strings: [String], n: Int) -> [String] {
return Array(strings[0..<Swift.max(0, strings.count - n)])
}
func compact(strings: [String], n: Int) -> [String] {
return Array(strings[Swift.max(0, n)..<Swift.min(strings.count - n, strings.count)])
}
func filterLongStrings(strings: [String], minLength: Int) -> [String] {
return strings.filter { $0.count > minLength }
}
func filterShortStrings(strings: [String], maxLength: Int) -> [String] {
return strings.filter { $0.count < maxLength }
}
func unique(strings: [String]) -> [String] {
return Array(Set(strings))
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Reverse the order of an array of strings
// reverse(strings: [] as [String]) == []
// reverse(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
// Return an array of strings containing the first n strings
// first(strings: [] as [String], n: 0) == []
// first(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// first(strings: ["a", "b", "c"], n: 42) == ["a", "b", "c"]
func first(strings: [String], n: Int) -> [String] {
return Array(strings[0..<Swift.min(n, strings.count)])
}
// Return an array of strings containing all strings except the first n
// rest(strings: [] as [String], n: 0) == []
// rest(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// rest(strings: ["a", "b", "c"], n: 42) == []
func rest(strings: [String], n: Int) -> [String] {
return Array(strings[Swift.max(0, n)..<strings.count])
}
// Return an array of strings containing all strings except the last n
// initial(strings: [] as [String], n: 0) == []
// initial(strings: ["a", "b", "c"], n: 1) == ["a", "b"]
// initial(strings: ["a", "b", "c"], n: 42) == ["a", "b", "c"]
func initial(strings: [String], n: Int) -> [String] {
return Array(strings[0..<Swift.max(0, strings.count - n)])
}
// Return an array of strings containing all strings except the first and last n
// compact(strings: [] as [String], n: 0) == []
// compact(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// compact(strings: ["a", "b", "c"], n: 2) == ["a", "b", "c"]
func compact(strings: [String], n: Int) -> [String] {
return Array(strings[Swift.max(0, n)..<Swift.min(strings.count - n, strings.count)])
}
// Return an array of strings containing all strings longer than the given length
// filterLongStrings(strings: [] as [String], minLength: 0) == []
// filterLongStrings(strings: ["a", "ab", "abc"], minLength: 2) == ["ab", "abc"]
// filterLongStrings(strings: ["a", "ab", "abc"], minLength: 4) == ["ab", "abc"]
func filterLongStrings(strings: [String], minLength: Int) -> [String] {
return strings.filter { $0.count > minLength }
}
// Return an array of strings containing all strings shorter than the given length
// filterShortStrings(strings: [] as [String], maxLength: 0) == []
// filterShortStrings(strings: ["a", "ab", "abc"], maxLength: 2) == ["a"]
// filterShortStrings(strings: ["a", "ab", "abc"], maxLength: 4) == ["a", "ab"]
func filterShortStrings(strings: [String], maxLength: Int) -> [String] {
return strings.filter { $0.count < maxLength }
}
// Return an array of strings containing only strings with unique characters
// unique(strings: [] as [String]) == []
// unique(strings: ["a", "b", "c"]) == ["a", "b", "c"]
// unique(strings: ["a", "b", "ba", "c", "ca"]) == ["a", "b", "c", "ca"]
func unique(strings: [String]) -> [String] {
return Array(Set(strings))
}
// Return an array of strings containing only strings with unique characters,
// preserving order of original strings
// uniquePreservingOrder(strings: [] as [String]) == []
//
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
func first(strings: [String], n: Int) -> [String] {
return Array(strings[0..<min(n, strings.count)])
}
func rest(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count])
}
func initial(strings: [String], n: Int) -> [String] {
return Array(strings[0..<max(0, strings.count - n)])
}
func compact(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count-n])
}
func filterLongerThan(strings: [String], n: Int) -> [String] {
return strings.filter { $0.count > n }
}
func filterShorterThan(strings: [String], n: Int) -> [String] {
return strings.filter { $0.count < n }
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.reduce("", +)
}
// Reverse the order of an array of strings
// reverse(strings: [] as [String]) == []
// reverse(strings: ["a", "b", "c"]) == ["c", "b", "a"]
func reverse(strings: [String]) -> [String] {
return strings.reversed()
}
// Return an array of strings containing the first n strings
// first(strings: [] as [String], n: 1) == []
// first(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// first(strings: ["a", "b", "c"], n: 3) == ["a", "b", "c"]
// first(strings: ["a", "b", "c"], n: 4) == ["a", "b", "c"]
func first(strings: [String], n: Int) -> [String] {
return Array(strings[0..<min(n, strings.count)])
}
// Return an array of strings containing all strings except the first n
// rest(strings: [] as [String], n: 1) == []
// rest(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// rest(strings: ["a", "b", "c"], n: 2) == ["c"]
// rest(strings: ["a", "b", "c"], n: 3) == []
func rest(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count])
}
// Return an array of strings containing all strings except the last n
// initial(strings: [] as [String], n: 1) == []
// initial(strings: ["a", "b", "c"], n: 1) == ["a", "b"]
// initial(strings: ["a", "b", "c"], n: 2) == ["a"]
// initial(strings: ["a", "b", "c"], n: 3) == []
func initial(strings: [String], n: Int) -> [String] {
return Array(strings[0..<max(0, strings.count - n)])
}
// Return an array of strings containing all strings except the first and last n
// compact(strings: [] as [String], n: 1) == []
// compact(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// compact(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// compact(strings: ["a", "b", "c"], n: 3) == ["a"]
func compact(strings: [String], n: Int) -> [String] {
return Array(strings[n..<strings.count-n])
}
// Return an array of strings containing all strings longer than n characters
// filterLongerThan(strings: [] as [String], n: 1) == []
// filterLongerThan(strings: ["a", "b", "c"], n: 1) == ["b", "c"]
// filterLongerThan(strings: ["a", "b", "c"], n: 2) == ["b", "c"]
// filterLongerThan(strings: ["a", "b", "c"], n: 3) == ["a", "b", "c"]
func filterLongerThan(strings: [String], n: Int) -> [String] {
return strings.filter { $0.count > n }
}
// Return an array of strings containing all strings shorter than n characters
// filterShorterThan(strings: [] as [String], n: 1) == []
// filterShorterThan(strings: ["a", "b", "c"], n: 1) == ["a"]
// filterShorterThan(strings: ["a", "b", "c"], n: 2) == ["a", "b"]
// filterShorterThan(strings: ["a", "b", "c"], n: 3) == ["a", "b", "c"]
func filterShorterThan(strings: [String], n: Int) -> [String] {
return strings.filter { $0.count < n }
}
// Return an array of strings containing all strings with the given length
// filterByLength(strings: [] as [String
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByRegex(strings: [String], regex: String) -> [String] {
var result = [String]()
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
func filterByPrefixAndSuffixAndSubstring(strings: [String], prefix: String, suffix: String, substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByPrefixAndSuffixAndSubstringAndRegex(strings: [String], prefix: String, suffix: String, substring: String, regex: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) && string.range(of: regex, options:.regularExpression)!= nil {
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
}
// 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") == ["bcd", "cde"]
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
// 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", "bcd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that match a given regular expression.
// filterByRegex(strings: [] as [String], regex: "a") == [] as [String]
// filterByRegex(strings: ["abc", "bcd", "cde", "array"], regex: "[a-z]+") == ["abc", "bcd", "cde"]
func filterByRegex(strings: [String], regex: String) -> [String] {
var result = [String]()
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
// Filter an input array of strings by first removing all strings that do not start with a given prefix,
// then removing all strings that do not end with a given suffix, and finally removing all strings that do not contain
// a given substring.
// filterByPrefixAndSuffixAndSubstring(strings: [] as [String], prefix: "a", suffix: "a", substring: "a") == [] as [String]
// filterByPrefixAndSuffixAndSubstring(strings: ["abc", "bcd", "cde", "array"], prefix: "a", suffix: "a", substring: "a") == ["abc", "array"]
func filterByPrefixAndSuffixAndSubstring(strings: [String], prefix: String, suffix: String, substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings by first removing all strings that do not start with a given prefix,
// then removing all strings that do not end with a given suffix, and finally removing all strings that do not contain
// a given substring, while also removing any strings that do not match a given regular expression.
// filterByPrefixAndSuffixAndSubstringAndRegex(strings: [] as [String], prefix: "a", suffix: "a", substring: "a", regex: "[a-z]+") == [] as [String]
// filterByPrefixAndSuffixAndSubstringAndRegex(strings: ["abc", "bcd", "cde", "array"], prefix: "a", suffix: "a", substring: "a", regex: "[a-z]+") == ["abc", "array"]
func filterByPrefixAndSuffixAndSubstringAndRegex(strings: [String], prefix: String, suffix: String, substring: String, regex: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) && string.range(of: regex, options:.regularExpression)!= nil {
result.append(string)
}
}
return result
}
// Filter an input array of strings by first removing all strings that do not start with a given prefix,
// then removing all strings that do not end with a given suffix, and finally removing all strings that
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) && string.range(of: regex, options:.regularExpression)!= nil { // use of '=' in a boolean context, did you mean '=='?
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) && string.range(of: regex, options:.regularExpression)!= nil { // 'nil' cannot be assigned to type 'Bool'
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) && string.range(of: regex, options:.regularExpression)!= nil { // '=' must have consistent whitespace on both sides
if string.hasPrefix(prefix) && string.hasSuffix(suffix) && string.contains(substring) && string.range(of: regex, options:.regularExpression)!= nil { // cannot convert value of type 'Range<String.Index>' to expected argument type 'Bool'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterBySubstringInReverse(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.reversed().contains(substring) {
result.append(string)
}
}
return result
}
func filterByCharacter(strings: [String], character: Character) -> [String] {
var result = [String]()
for string in strings {
if string.contains(character) {
result.append(string)
}
}
return result
}
func filterByCharacterAtIndex(strings: [String], character: Character, index: Int) -> [String] {
var result = [String]()
for string in strings {
if string.indices.contains(index) && string[string.index(string.startIndex, offsetBy: index)] == character {
result.append(string)
}
}
return result
}
func filterByPrefixAndSubstring(strings: [String], prefix: String, substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByPrefixAndSubstringInReverse(strings: [String], prefix: String, substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.reversed().contains(substring) {
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
}
// 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", "bcd", "cde"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that contain a given substring in reverse.
// filterBySubstringInReverse(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringInReverse(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["cde", "array"]
func filterBySubstringInReverse(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.reversed().contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that contain a given character.
// filterByCharacter(strings: [] as [String], character: "a") == [] as [String]
// filterByCharacter(strings: ["abc", "bcd", "cde", "array"], character: "a") == ["abc", "bcd", "cde", "array"]
func filterByCharacter(strings: [String], character: Character) -> [String] {
var result = [String]()
for string in strings {
if string.contains(character) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that contain a given character at a given index.
// filterByCharacterAtIndex(strings: [] as [String], character: "a", index: 0) == [] as [String]
// filterByCharacterAtIndex(strings: ["abc", "bcd", "cde", "array"], character: "a", index: 0) == ["abc", "array"]
func filterByCharacterAtIndex(strings: [String], character: Character, index: Int) -> [String] {
var result = [String]()
for string in strings {
if string.indices.contains(index) && string[string.index(string.startIndex, offsetBy: index)] == character {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that start with a given prefix and contain a given substring.
// filterByPrefixAndSubstring(strings: [] as [String], prefix: "a", substring: "b") == [] as [String]
// filterByPrefixAndSubstring(strings: ["abc", "bcd", "cde", "array"], prefix: "a", substring: "b") == ["abc"]
func filterByPrefixAndSubstring(strings: [String], prefix: String, substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that start with a given prefix and contain a given substring in reverse.
// filterByPrefixAndSubstringInReverse(strings: [] as [String], prefix: "a", substring: "b") == [] as [String]
// filterByPrefixAndSubstringInReverse(strings: ["abc", "bcd", "cde", "array"], prefix: "a", substring: "b") == ["cde"]
func filterByPrefixAndSubstringInReverse(strings: [String], prefix: String, substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) && string.reversed().contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that start with a given prefix and contain a given character.
// filterByPrefixAndCharacter(
if string.indices.contains(index) && string[string.index(string.startIndex, offsetBy: index)] == character { // cannot convert value of type 'Int' to expected argument type 'DefaultIndices<String>.Element' (aka 'String.Index')
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, +)
}
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
func median(numbers: [Int]) -> Double? {
let sortedNumbers = numbers.sorted()
let count = sortedNumbers.count
if count % 2 == 0 {
let midIndex = count / 2
return Double(sortedNumbers[midIndex - 1] + sortedNumbers[midIndex]) / 2.0
} else {
let midIndex = count / 2
return Double(sortedNumbers[midIndex])
}
}
func product(numbers: [Int]) -> Int {
return numbers.reduce(1, *)
}
func mostCommon(numbers: [Int]) -> Int? {
return numbers.reduce(into: [:]) { counts, number in
counts[number, default: 0] += 1
}.max { $0.value < $1.value }?.key
}
func longest(strings: [String]) -> String? {
return strings.reduce(into: "") { currentLongest, string in
if currentLongest.count < string.count {
currentLongest = string
}
}
}
func shortest(strings: [String]) -> String? {
return strings.reduce(into: "") { currentShortest, string in
if currentShortest.count == 0 || string.count < currentShortest.count {
currentShortest = 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 integers only for ones that are divisible by a given divisor.
// filterByDivisor(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisor(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 2) == [2, 4, 6, 8, 10]
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Return the sum of all integers in an input array.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, +)
}
// Return the average of all integers in an input array.
// average(numbers: [] as [Int]) == 0.0
// average(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
// Return the median of all integers in an input array.
// median(numbers: [] as [Int]) == nil
// median(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5
func median(numbers: [Int]) -> Double? {
let sortedNumbers = numbers.sorted()
let count = sortedNumbers.count
if count % 2 == 0 {
let midIndex = count / 2
return Double(sortedNumbers[midIndex - 1] + sortedNumbers[midIndex]) / 2.0
} else {
let midIndex = count / 2
return Double(sortedNumbers[midIndex])
}
}
// Return the product of all integers in an input array.
// product(numbers: [] as [Int]) == 1
// product(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 3628800
func product(numbers: [Int]) -> Int {
return numbers.reduce(1, *)
}
// Return the most common element in an input array.
// mostCommon(numbers: [] as [Int]) == nil
// mostCommon(numbers: [1, 1, 2, 3, 4, 4, 4, 5, 5, 5, 5]) == 5
func mostCommon(numbers: [Int]) -> Int? {
return numbers.reduce(into: [:]) { counts, number in
counts[number, default: 0] += 1
}.max { $0.value < $1.value }?.key
}
// Return the longest string in an input array.
// longest(strings: [] as [String]) == nil
// longest(strings: ["abc", "bcd", "cde", "array"]) == "array"
func longest(strings: [String]) -> String? {
return strings.reduce(into: "") { currentLongest, string in
if currentLongest.count < string.count {
currentLongest = string
}
}
}
// Return the shortest string in an input array.
// shortest(strings: [] as [String]) == nil
// shortest(strings: ["abc", "bcd", "cde", "array"]) == "abc"
func shortest(strings: [String]) -> String? {
return strings.reduce(into: "") { currentShortest, string in
if currentShortest.count == 0 || string.count < currentShortest.count {
currentShortest = string
}
}
}
// Return the second longest string in an input array.
// secondLongest(strings: [] as [String]) == nil
// secondLongest(strings: ["abc", "bcd", "
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByRegex(strings: [String], regex: String) -> [String] {
var result = [String]()
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
func longestLength(strings: [String]) -> Int {
var longest = 0
for string in strings {
if string.count > longest {
longest = string.count
}
}
return longest
}
func shortestLength(strings: [String]) -> Int {
var shortest = Int.max
for string in strings {
if string.count < shortest {
shortest = string.count
}
}
return shortest
}
func sumOfLengths(strings: [String]) -> Int {
var sum = 0
for string in strings {
sum += string.count
}
return sum
}
func averageLength(strings: [String]) -> Double {
return Double(sumOfLengths(strings: strings)) / Double(strings.count)
}
func countStrings(strings: [String], prefix: String) -> Int {
var count = 0
for string in strings {
if string.hasPrefix(prefix) {
count += 1
}
}
return count
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
// 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") == ["bcd", "cde"]
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
// 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", "bcd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that match a given regular expression.
// filterByRegex(strings: [] as [String], regex: "a") == [] as [String]
// filterByRegex(strings: ["abc", "bcd", "cde", "array"], regex: "[a-z]+") == ["abc", "bcd", "cde"]
func filterByRegex(strings: [String], regex: String) -> [String] {
var result = [String]()
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
// Return the length of the longest string in an input array.
// longestLength(strings: [] as [String]) == 0
// longestLength(strings: ["abc", "bcd", "cde", "array"]) == 6
func longestLength(strings: [String]) -> Int {
var longest = 0
for string in strings {
if string.count > longest {
longest = string.count
}
}
return longest
}
// Return the length of the shortest string in an input array.
// shortestLength(strings: [] as [String]) == 0
// shortestLength(strings: ["abc", "bcd", "cde", "array"]) == 3
func shortestLength(strings: [String]) -> Int {
var shortest = Int.max
for string in strings {
if string.count < shortest {
shortest = string.count
}
}
return shortest
}
// Return the sum of the lengths of all strings in an input array.
// sumOfLengths(strings: [] as [String]) == 0
// sumOfLengths(strings: ["abc", "bcd", "cde", "array"]) == 20
func sumOfLengths(strings: [String]) -> Int {
var sum = 0
for string in strings {
sum += string.count
}
return sum
}
// Return the average length of all strings in an input array.
// averageLength(strings: [] as [String]) == 0
// averageLength(strings: ["abc", "bcd", "cde", "array"]) == 4.5
func averageLength(strings: [String]) -> Double {
return Double(sumOfLengths(strings: strings)) / Double(strings.count)
}
// Return the number of strings that start with a given prefix.
// countStrings(strings: [] as [String], prefix: "a") == 0
// countStrings(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == 2
func countStrings(strings: [String], prefix: String) -> Int {
var count = 0
for string in strings {
if string.hasPrefix(prefix) {
count += 1
}
}
return count
}
// Return the number of strings that end with a given suffix.
// countStrings(strings: [] as [String], suffix: "a")
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
var result = [Int]()
for number in numbers {
if number % divisor == 0 {
result.append(number)
}
}
return result
}
func combineArrays(first: [String], second: [Int]) -> [(value: Any, index: Int)] {
var result = [(value: Any, index: Int)]()
for (index, value) in first.enumerated() {
result.append((value, index))
}
for (index, value) in second.enumerated() {
result.append((value, index))
}
return result
}
func sortDescending(strings: [String], integers: [Int]) -> [String] {
var result = strings
result.sort(by: { $0.lowercased() > $1.lowercased() })
return result
}
func groupByFirstCharacter(strings: [String]) -> [String: [String]] {
var result = [String: [String]]()
for string in strings {
let firstCharacter = string.lowercased().prefix(1)
if result[firstCharacter] == nil {
result[firstCharacter] = [String]()
}
result[firstCharacter]!.append(string)
}
return result
}
func getSecondAndThird(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
if!string.contains("1") &&!string.contains("2") &&!string.contains("3") {
if string.count > 2 {
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
}
// Filter an input array of integers only for ones that are divisible by a given divisor.
// filterByDivisor(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisor(numbers: [1, 2, 3, 4, 5, 6], divisor: 2) == [2, 4, 6]
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
var result = [Int]()
for number in numbers {
if number % divisor == 0 {
result.append(number)
}
}
return result
}
// Combine two input arrays of strings and integers into a single array,
// where each element is a tuple containing the input value and its index in the original array.
// combineArrays(first: [] as [String], second: [] as [Int]) == [] as [(value: Any, index: Int)]
// combineArrays(first: ["a", "b", "c"], second: [1, 2, 3]) == [("a", 0), ("b", 1), ("c", 2)]
func combineArrays(first: [String], second: [Int]) -> [(value: Any, index: Int)] {
var result = [(value: Any, index: Int)]()
for (index, value) in first.enumerated() {
result.append((value, index))
}
for (index, value) in second.enumerated() {
result.append((value, index))
}
return result
}
// Sort an input array of strings and integers in descending order,
// while ignoring the case of each string.
// sortDescending(strings: [] as [String], integers: [] as [Int]) == [] as [String]
// sortDescending(strings: ["A", "b", "C"], integers: [1, 2, 3]) == ["C", "b", "A"]
func sortDescending(strings: [String], integers: [Int]) -> [String] {
var result = strings
result.sort(by: { $0.lowercased() > $1.lowercased() })
return result
}
// Group an input array of strings by their first character,
// while ignoring the case of each string.
// groupByFirstCharacter(strings: [] as [String]) == [:] as [String: [String]]
// groupByFirstCharacter(strings: ["A", "b", "C", "a", "B", "c"]) == ["A": ["A", "a"], "B": ["B"], "C": ["C", "c"]]
func groupByFirstCharacter(strings: [String]) -> [String: [String]] {
var result = [String: [String]]()
for string in strings {
let firstCharacter = string.lowercased().prefix(1)
if result[firstCharacter] == nil {
result[firstCharacter] = [String]()
}
result[firstCharacter]!.append(string)
}
return result
}
// Get the second and third elements from an input array of strings,
// while ignoring any strings that contain numbers.
// getSecondAndThird(strings: [] as [String]) == [] as [String]
// getSecondAndThird(strings: ["abc", "123", "bcd", "efg", "1abc", "2def", "3ghi"]) == ["bcd", "efg"]
func getSecondAndThird(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
if!string.contains("1") &&!string.contains("2") &&!string.contains("3") {
if string.count > 2 {
result.append(string)
}
}
}
return result
}
// Get the longest string from an input array of strings,
// while ignoring any strings that contain numbers.
// getLongestString(strings: [] as [String]) == nil as String?
// getLongestString(strings: ["abc", "123", "bcd", "efg", "1abc", "2def", "3ghi"]) == "efg"
func getLongestString(strings: [String]) -> String? {
var longest
if result[firstCharacter] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
result[firstCharacter] = [String]() // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
result[firstCharacter]!.append(string) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
if!string.contains("1") &&!string.contains("2") &&!string.contains("3") { // expected expression, var, or let in 'if' condition
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result: [String] = []
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result: [String] = []
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result: [String] = []
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByRegex(strings: [String], regex: String) -> [String] {
var result: [String] = []
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
func removeDuplicates(strings: [String]) -> [String] {
var result: [String] = []
for string in strings {
if!result.contains(string) {
result.append(string)
}
}
return result
}
func removePrefix(strings: [String], prefix: String) -> [String] {
var result: [String] = []
for string in strings {
result.append(string.replacingOccurrences(of: prefix, with: ""))
}
return result
}
func removeSuffix(strings: [String], suffix: String) -> [String] {
var result: [String] = []
for string in strings {
result.append(string.replacingOccurrences(of: suffix, with: ""))
}
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
}
// 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: "e") == ["cde", "array"]
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result: [String] = []
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
// 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", "bcd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result: [String] = []
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that match a given regular expression.
// filterByRegex(strings: [] as [String], regex: "a") == [] as [String]
// filterByRegex(strings: ["abc", "bcd", "cde", "array"], regex: "[a-z]+") == ["abc", "bcd", "cde"]
func filterByRegex(strings: [String], regex: String) -> [String] {
var result: [String] = []
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
// Return an array of strings with duplicates removed.
// removeDuplicates(strings: [] as [String]) == [] as [String]
// removeDuplicates(strings: ["abc", "bcd", "cde", "array", "abc"]) == ["abc", "bcd", "cde", "array"]
func removeDuplicates(strings: [String]) -> [String] {
var result: [String] = []
for string in strings {
if!result.contains(string) {
result.append(string)
}
}
return result
}
// Return an array of strings with the specified prefix removed from each string.
// removePrefix(strings: [] as [String], prefix: "a") == [] as [String]
// removePrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bc", "cd", "ce", "ray"]
func removePrefix(strings: [String], prefix: String) -> [String] {
var result: [String] = []
for string in strings {
result.append(string.replacingOccurrences(of: prefix, with: ""))
}
return result
}
// Return an array of strings with the specified suffix removed from each string.
// removeSuffix(strings: [] as [String], suffix: "a") == [] as [String]
// removeSuffix(strings: ["abc", "bcd", "cde", "array"], suffix: "e") == ["ab", "bc", "cd", "ray"]
func removeSuffix(strings: [String], suffix: String) -> [String] {
var result: [String] = []
for string in strings {
result.append(string.replacingOccurrences(of: suffix, with: ""))
}
return result
}
// Return an array of strings with the specified substring removed from each string.
// removeSubstring(strings: [] as [String], substring: "a") == [] as [String]
// removeSubstring(strings: ["abc", "bcd", "cde", "array", "abc"], substring: "a") == ["bc", "bcd", "cde", "ray"]
func removeSubstring(strings: [String], substring: String) -> [String] {
var result: [String] = []
for string in strings {
result.append(string.replacingOccurrences(of: substring, with: ""))
}
return
if!result.contains(string) { // expected expression, var, or let in 'if' condition
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, +)
}
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
func median(numbers: [Int]) -> Double? {
let sortedNumbers = numbers.sorted()
let count = sortedNumbers.count
if count == 0 {
return nil
}
let middleIndex = count / 2
if count % 2 == 0 {
return Double(sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2.0
} else {
return Double(sortedNumbers[middleIndex])
}
}
func mode(numbers: [Int]) -> Int? {
let counts = Dictionary(grouping: numbers, by: { $0 }).mapValues { $0.count }
let maxCount = counts.values.max()
return counts.filter { $0.value == maxCount }.map { $0.key }.first
}
func product(numbers: [Int]) -> Int {
return numbers.reduce(1, *)
}
func standardDeviation(numbers: [Int]) -> Double {
let average = average(numbers: numbers)
let squaredDifferences = numbers.map { pow(Double($0 - average), 2) }
return sqrt(average(numbers: squaredDifferences))
}
func range(numbers: [Int]) -> Int {
return numbers.max()! - numbers.min()!
}
```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 integers only for ones that are divisible by a given divisor.
// filterByDivisor(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisor(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 2) == [2, 4, 6, 8, 10]
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Return the sum of all integers in an input array.
// sum(numbers: [] as [Int]) == 0
// sum(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 55
func sum(numbers: [Int]) -> Int {
return numbers.reduce(0, +)
}
// Return the average of all integers in an input array.
// average(numbers: [] as [Int]) == 0.0
// average(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5
func average(numbers: [Int]) -> Double {
return Double(sum(numbers: numbers)) / Double(numbers.count)
}
// Return the median of all integers in an input array.
// median(numbers: [] as [Int]) == nil
// median(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 5.5
func median(numbers: [Int]) -> Double? {
let sortedNumbers = numbers.sorted()
let count = sortedNumbers.count
if count == 0 {
return nil
}
let middleIndex = count / 2
if count % 2 == 0 {
return Double(sortedNumbers[middleIndex - 1] + sortedNumbers[middleIndex]) / 2.0
} else {
return Double(sortedNumbers[middleIndex])
}
}
// Return the mode of all integers in an input array.
// mode(numbers: [] as [Int]) == nil
// mode(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 1
func mode(numbers: [Int]) -> Int? {
let counts = Dictionary(grouping: numbers, by: { $0 }).mapValues { $0.count }
let maxCount = counts.values.max()
return counts.filter { $0.value == maxCount }.map { $0.key }.first
}
// Return the product of all integers in an input array.
// product(numbers: [] as [Int]) == 1
// product(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 3628800
func product(numbers: [Int]) -> Int {
return numbers.reduce(1, *)
}
// Return the standard deviation of all integers in an input array.
// standardDeviation(numbers: [] as [Int]) == 0.0
// standardDeviation(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 2.87
func standardDeviation(numbers: [Int]) -> Double {
let average = average(numbers: numbers)
let squaredDifferences = numbers.map { pow(Double($0 - average), 2) }
return sqrt(average(numbers: squaredDifferences))
}
// Return the range of all integers in an input array.
// range(numbers: [] as [Int]) == 0
// range(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 9
func range(numbers: [Int]) -> Int {
return numbers.max()! - numbers.min()!
}
// Return the frequency count of each unique pair of
let squaredDifferences = numbers.map { pow(Double($0 - average), 2) } // binary operator '-' cannot be applied to operands of type 'Int' and 'Double'
return sqrt(average(numbers: squaredDifferences)) // cannot call value of non-function type 'Double'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterBySubstringInReverse(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.reversed().contains(substring) {
result.append(string)
}
}
return result
}
func filterBySubstringInAnyOrder(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterBySubstringInAnyOrderAndMinimumLength(strings: [String], substring: String, minLength: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count >= minLength {
result.append(string)
}
}
return result
}
func filterBySubstringInAnyOrderAndMinimumLengthAndCapitalLetter(strings: [String], substring: String, minLength: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count >= minLength && string.first!.isUppercase {
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
}
// Filter an input array of strings only for ones that have a given substring.
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["abc", "bcd", "cde"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that have a given substring in reverse.
// filterBySubstringInReverse(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringInReverse(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["cde", "array"]
func filterBySubstringInReverse(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.reversed().contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that have a given substring in any order.
// filterBySubstringInAnyOrder(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstringInAnyOrder(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["abc", "bcd", "cde", "array"]
func filterBySubstringInAnyOrder(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that have a given substring in any order and are at least 3 characters long.
// filterBySubstringInAnyOrderAndMinimumLength(strings: [] as [String], substring: "a", minLength: 3) == [] as [String]
// filterBySubstringInAnyOrderAndMinimumLength(strings: ["abc", "bcd", "cde", "array"], substring: "a", minLength: 3) == ["abc", "array"]
func filterBySubstringInAnyOrderAndMinimumLength(strings: [String], substring: String, minLength: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count >= minLength {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that have a given substring in any order and are at least 3 characters long and have a capital letter.
// filterBySubstringInAnyOrderAndMinimumLengthAndCapitalLetter(strings: [] as [String], substring: "a", minLength: 3) == [] as [String]
// filterBySubstringInAnyOrderAndMinimumLengthAndCapitalLetter(strings: ["abc", "bcd", "cde", "array"], substring: "a", minLength: 3) == ["abc"]
func filterBySubstringInAnyOrderAndMinimumLengthAndCapitalLetter(strings: [String], substring: String, minLength: Int) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) && string.count >= minLength && string.first!.isUppercase {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that have a given substring in any order and are at least 3 characters long and have a capital letter.
// The filtered strings should also not contain any special characters.
// filterBySubstringInAnyOrderAndMinimumLengthAndNoSpecialCharacters(strings: [] as [String], substring: "a", minLength: 3) == [] as [String]
// filterBySubstringInAnyOrderAndMinimumLengthAndNoSpecialCharacters(strings: ["abc", "123", "!@#$", "bcd", "cde", "array"], substring: "a",
func filterByPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasPrefix(prefix) {
result.append(string)
}
}
return result
}
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
func filterByRegex(strings: [String], regex: String) -> [String] {
var result = [String]()
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
func addPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(prefix + string)
}
return result
}
func addSuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(string + suffix)
}
return result
}
func removeSubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
result.append(string.replacingOccurrences(of: substring, with: ""))
}
return result
}
func removeWhitespace(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
result.append(string.replacingOccurrences(of: " ", with: ""))
}
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
}
// 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") == ["bcd", "cde"]
func filterBySuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
if string.hasSuffix(suffix) {
result.append(string)
}
}
return result
}
// 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", "bcd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
if string.contains(substring) {
result.append(string)
}
}
return result
}
// Filter an input array of strings only for ones that match a given regular expression.
// filterByRegex(strings: [] as [String], regex: "a") == [] as [String]
// filterByRegex(strings: ["abc", "bcd", "cde", "array"], regex: "[a-z]+") == ["abc", "bcd", "cde"]
func filterByRegex(strings: [String], regex: String) -> [String] {
var result = [String]()
for string in strings {
if let _ = string.range(of: regex, options:.regularExpression) {
result.append(string)
}
}
return result
}
// Return a new array of strings with a given prefix added to each string.
// addPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// addPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["aabc", "abcd", "aacde", "aarray"]
func addPrefix(strings: [String], prefix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(prefix + string)
}
return result
}
// Return a new array of strings with a given suffix added to each string.
// addSuffix(strings: [] as [String], suffix: "a") == [] as [String]
// addSuffix(strings: ["abc", "bcd", "cde", "array"], suffix: "a") == ["abca", "bcda", "cdea", "arraya"]
func addSuffix(strings: [String], suffix: String) -> [String] {
var result = [String]()
for string in strings {
result.append(string + suffix)
}
return result
}
// Return a new array of strings with a given substring removed from each string.
// removeSubstring(strings: [] as [String], substring: "a") == [] as [String]
// removeSubstring(strings: ["abc", "bcd", "cde", "array"], substring: "a") == ["bc", "cd", "ce", "r"]
func removeSubstring(strings: [String], substring: String) -> [String] {
var result = [String]()
for string in strings {
result.append(string.replacingOccurrences(of: substring, with: ""))
}
return result
}
// Return a new array of strings with all whitespace characters removed from each string.
// removeWhitespace(strings: [] as [String]) == [] as [String]
// removeWhitespace(strings: ["abc", "bcd", "cde", "array"]) == ["abc", "bcd", "cde", "array"]
func removeWhitespace(strings: [String]) -> [String] {
var result = [String]()
for string in strings {
result.append(string.replacingOccurrences(of: " ", with: ""))
}
return result
}
// Return a new array of strings with all punctuation characters removed from each string.
// removeP
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
func filterByPrefixAndContainNumbers(strings: [String], integers: [Int], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) &&!integers.contains { $0.contains($0) } }
}
func convertStringsToIntegers(strings: [String]) -> [Int] {
return strings.compactMap { Int($0) }
}
func convertIntegersToStrings(integers: [Int]) -> [String] {
return integers.map { String($0) }
}
func filterEvenIntegers(strings: [String]) -> [Int] {
return strings.compactMap { Int($0) }
.filter { $0 % 2 == 0 }
}
func filterEvenStrings(integers: [Int]) -> [String] {
return integers.map { String($0) }
.filter { $0 % 2 == 0 }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
// Filter an input array of integers only for ones that are divisible by a given divisor.
// filterByDivisor(numbers: [] as [Int], divisor: 2) == [] as [Int]
// filterByDivisor(numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], divisor: 2) == [2, 4, 6, 8, 10]
func filterByDivisor(numbers: [Int], divisor: Int) -> [Int] {
return numbers.filter { $0 % divisor == 0 }
}
// Filter an input array of strings and integers and return an array of strings that start with a given prefix,
// while ignoring any strings that contain numbers.
// filterByPrefixAndContainNumbers(strings: [] as [String], integers: [] as [Int], prefix: "a") == [] as [String]
// filterByPrefixAndContainNumbers(strings: ["abc", "bcd", "cde", "array"], integers: [1, 2, 3, 4], prefix: "a") == ["abc"]
func filterByPrefixAndContainNumbers(strings: [String], integers: [Int], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) &&!integers.contains { $0.contains($0) } }
}
// Return an array of integers from a given input array of strings,
// where each string in the input array is converted to an integer and added to the result array.
// convertStringsToIntegers(strings: [] as [String]) == [] as [Int]
// convertStringsToIntegers(strings: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
func convertStringsToIntegers(strings: [String]) -> [Int] {
return strings.compactMap { Int($0) }
}
// Return an array of strings from a given input array of integers,
// where each integer in the input array is converted to a string and added to the result array.
// convertIntegersToStrings(integers: [] as [Int]) == [] as [String]
// convertIntegersToStrings(integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
func convertIntegersToStrings(integers: [Int]) -> [String] {
return integers.map { String($0) }
}
// Return an array of integers from a given input array of strings,
// where each string in the input array is converted to an integer and added to the result array only if it is even.
// filterEvenIntegers(strings: [] as [String]) == [] as [Int]
// filterEvenIntegers(strings: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]) == [2, 4, 6, 8, 10]
func filterEvenIntegers(strings: [String]) -> [Int] {
return strings.compactMap { Int($0) }
.filter { $0 % 2 == 0 }
}
// Return an array of strings from a given input array of integers,
// where each integer in the input array is converted to a string and added to the result array only if it is even.
// filterEvenStrings(integers: [] as [Int]) == [] as [String]
// filterEvenStrings(integers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == ["2", "4", "6", "8", "10"]
func filterEvenStrings(integers: [Int]) -> [String] {
return integers.map { String($0) }
.filter { $0 % 2 == 0 }
}
// Return an array of integers from a given input array of strings,
//
return strings.filter { $0.hasPrefix(prefix) &&!integers.contains { $0.contains($0) } } // value of type 'Int' has no member 'contains'
return strings.filter { $0.hasPrefix(prefix) &&!integers.contains { $0.contains($0) } } // cannot find operator '&&!' in scope
return strings.filter { $0.hasPrefix(prefix) &&!integers.contains { $0.contains($0) } } // consecutive statements on a line must be separated by ';'
.filter { $0 % 2 == 0 } // cannot convert value of type 'String' to expected argument type 'Int'
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func getSum(l: [Int]) -> Int {
return l.reduce(0, +)
}
func getProduct(l: [Int]) -> Int {
return l.reduce(1, *)
}
func getMin(l: [Int]) -> Int {
return l.min()?? 0
}
func getMax(l: [Int]) -> Int {
return l.max()?? 0
}
func getPositiveCount(l: [Int]) -> Int {
return l.filter { $0 > 0 }.count
}
func getNegativeCount(l: [Int]) -> Int {
return l.filter { $0 < 0 }.count
}
func getZeroCount(l: [Int]) -> Int {
return l.filter { $0 == 0 }.count
}
func getPositiveSum(l: [Int]) -> Int {
return l.filter { $0 > 0 }.reduce(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 }
}
// Return the sum of all numbers in the array.
// getSum(l: [-1, 2, -4, 5, 6]) == 13
// getSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 145
func getSum(l: [Int]) -> Int {
return l.reduce(0, +)
}
// Return the product of all numbers in the array.
// getProduct(l: [-1, 2, -4, 5, 6]) == -4
// getProduct(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -4350943039680
func getProduct(l: [Int]) -> Int {
return l.reduce(1, *)
}
// Return the minimum number in the array.
// getMin(l: [-1, 2, -4, 5, 6]) == -1
// getMin(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -10
func getMin(l: [Int]) -> Int {
return l.min()?? 0
}
// Return the maximum number in the array.
// getMax(l: [-1, 2, -4, 5, 6]) == 6
// getMax(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func getMax(l: [Int]) -> Int {
return l.max()?? 0
}
// Return the number of positive numbers in the array.
// getPositiveCount(l: [-1, 2, -4, 5, 6]) == 3
// getPositiveCount(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func getPositiveCount(l: [Int]) -> Int {
return l.filter { $0 > 0 }.count
}
// Return the number of negative numbers in the array.
// getNegativeCount(l: [-1, 2, -4, 5, 6]) == 4
// getNegativeCount(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 5
func getNegativeCount(l: [Int]) -> Int {
return l.filter { $0 < 0 }.count
}
// Return the number of zeros in the array.
// getZeroCount(l: [-1, 2, -4, 5, 6]) == 0
// getZeroCount(l: [0, 3, 0, 2, -3, 3, 9, 0, 123, 1, -10]) == 3
func getZeroCount(l: [Int]) -> Int {
return l.filter { $0 == 0 }.count
}
// Return the sum of all positive numbers in the array.
// getPositiveSum(l: [-1, 2, -4, 5, 6]) == 0
// getPositiveSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 15
func getPositiveSum(l: [Int]) -> Int {
return l.filter { $0 > 0 }.reduce(0, +)
}
// Return the sum of all negative numbers in the array.
// getNegativeSum(l: [-1, 2, -4, 5, 6]) == -21
// getNegativeSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -14
func getNegativeSum(l
return l.min()?? 0 // integer literal is unused
return l.min()?? 0 // consecutive statements on a line must be separated by ';'
return l.min()?? 0 // cannot use optional chaining on non-optional value of type 'Int'
return l.max()?? 0 // integer literal is unused
return l.max()?? 0 // cannot use optional chaining on non-optional value of type 'Int'
return l.max()?? 0 // consecutive statements on a line must be separated by ';'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 44
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the product of all positive numbers in the array.
// productPositive(l: [-1, 2, -4, 5, 6]) == -1
// productPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func getSum(l: [Int]) -> Int {
return l.reduce(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 }
}
// Return the sum of all numbers in the array.
// getSum(l: [-1, 2, -4, 5, 6]) == 13
// getSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 143
func getSum(l: [Int]) -> Int {
return l.reduce(0, +)
}
// Return the product of all numbers in the array.
// getProduct(l: [-1, 2, -4, 5, 6]) == -4
// getProduct(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -49500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositiveSquaresSum(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i * i
}
}
return result
}
func getPositiveSquaresSumExcludingThree(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 {
result += i * i
}
}
return result
}
func getPositiveSquaresSumExcludingThreeAndTen(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 {
result += i * i
}
}
return result
}
func getPositiveSquaresSumExcludingThreeAndTenAndFive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 {
result += i * i
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array.
// getPositiveSquaresSum(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 210
func getPositiveSquaresSum(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3.
// getPositiveSquaresSumExcludingThree(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExcludingThree(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 213
func getPositiveSquaresSumExcludingThree(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3 and any number greater than 10.
// getPositiveSquaresSumExcludingThreeAndTen(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExcludingThreeAndTen(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 210
func getPositiveSquaresSumExcludingThreeAndTen(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3, any number greater than 10,
// and any number that is a multiple of 5.
// getPositiveSquaresSumExcludingThreeAndTenAndFive(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExcludingThreeAndTenAndFive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 213
func getPositiveSquaresSumExcludingThreeAndTenAndFive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3, any number greater than 10,
// any number that is a multiple of 5, and any number that is a multiple of 7.
// getPositiveSquaresSumExcludingThreeAndTenAndFiveAndSeven(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExcludingThreeAndTenAndFiveAndSeven(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 210
func getPositiveSquaresSumExcludingThreeAndTenAndFiveAndSeven(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 && i % 7
if i > 0 && i % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i > 0 && i % 3!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i > 0 && i % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i > 0 && i % 3!= 0 && i <= 10 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if i > 0 && i % 3!= 0 && i <= 10 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 && i <= 10 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 && i <= 10 { // use of '=' in a boolean context, did you mean '=='?
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 45
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
func countPositive(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
func countPositiveTuple(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
func countPositiveTuple2(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
func countPositiveTuple3(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 44
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all positive numbers in the array,
// but also count the number of positive numbers.
// countPositive(l: [-1, 2, -4, 5, 6]) == (11, 3)
// countPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (44, 11)
func countPositive(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
// Return the sum of all positive numbers in the array,
// but also count the number of positive numbers.
// The function should return a tuple containing the sum and the count.
// countPositiveTuple(l: [-1, 2, -4, 5, 6]) == (11, 3)
// countPositiveTuple(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (44, 11)
func countPositiveTuple(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
// Return the sum of all positive numbers in the array,
// but also count the number of positive numbers.
// The function should return a tuple containing the sum and the count.
// countPositiveTuple(l: [-1, 2, -4, 5, 6]) == (11, 3)
// countPositiveTuple(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (44, 11)
func countPositiveTuple2(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
// Return the sum of all positive numbers in the array,
// but also count the number of positive numbers.
// The function should return a tuple containing the sum and the count.
// countPositiveTuple(l: [-1, 2, -4, 5, 6]) == (11, 3)
// countPositiveTuple(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (44, 11)
func countPositiveTuple3(l: [Int]) -> (Int, Int) {
var result = 0
var count = 0
for i in l {
if i > 0 {
result += i
count += 1
}
}
return (result, count)
}
// Return the sum of all positive numbers in the array,
// but also count the number of positive numbers.
// The function should return a tuple containing the sum and the count.
// countPositiveTuple(l: [-1, 2, -4, 5, 6]) == (11, 3)
// countPositiveTuple(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) ==
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositiveSquaresSum(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i * i
}
}
return result
}
func getPositiveSquaresSumExceptThree(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 {
result += i * i
}
}
return result
}
func getPositiveSquaresSumExceptThreeAndTen(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 {
result += i * i
}
}
return result
}
func getPositiveSquaresSumExceptThreeAndTenAndFive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 {
result += i * i
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array.
// getPositiveSquaresSum(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 156
func getPositiveSquaresSum(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3.
// getPositiveSquaresSumExceptThree(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExceptThree(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 161
func getPositiveSquaresSumExceptThree(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3 and any number greater than 10.
// getPositiveSquaresSumExceptThreeAndTen(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExceptThreeAndTen(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 156
func getPositiveSquaresSumExceptThreeAndTen(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3, any number greater than 10,
// and any number that is a multiple of 5.
// getPositiveSquaresSumExceptThreeAndTenAndFive(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExceptThreeAndTenAndFive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 151
func getPositiveSquaresSumExceptThreeAndTenAndFive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 {
result += i * i
}
}
return result
}
// Return the sum of the squares of the positive numbers in the array,
// but exclude any number divisible by 3, any number greater than 10,
// any number that is a multiple of 5, and any number that is a multiple of 7.
// getPositiveSquaresSumExceptThreeAndTenAndFiveAndSeven(l: [-1, 2, -4, 5, 6]) == 56
// getPositiveSquaresSumExceptThreeAndTenAndFiveAndSeven(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 141
func getPositiveSquaresSumExceptThreeAndTenAndFiveAndSeven(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 && i % 7
if i > 0 && i % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i > 0 && i % 3!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i > 0 && i % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i > 0 && i % 3!= 0 && i <= 10 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if i > 0 && i % 3!= 0 && i <= 10 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 && i <= 10 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 && i <= 10 { // use of '=' in a boolean context, did you mean '=='?
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // '=' must have consistent whitespace on both sides
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i > 0 && i % 3!= 0 && i <= 10 && i % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
func getPositive(l: [Int]) -> [Int] {
var positive = [Int]()
for i in l {
if i > 0 {
positive.append(i)
}
}
return positive
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func average(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Int {
var sorted = l
sorted.sort()
if sorted.count % 2 == 0 {
return (sorted[sorted.count / 2 - 1] + sorted[sorted.count / 2]) / 2
} else {
return sorted[sorted.count / 2]
}
}
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in l {
counts[i, default: 0] += 1
}
var maxCount = 0
var mode = 0
for (num, count) in counts {
if count > maxCount {
maxCount = count
mode = num
}
}
return mode
}
func range(l: [Int]) -> Int {
var sorted = l
sorted.sort()
return sorted[sorted.count - 1] - sorted[0]
}
func standardDeviation(l: [Int]) -> Double {
var mean = average(l: l)
var sum = 0.0
for i in l {
sum += (Double(i) - mean) * (Double(i) - mean)
}
return sqrt(sum / Double(l.count - 1))
}
```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
}
// Return the sum of all numbers in the array.
// sum(l: [-1, 2, -4, 5, 6]) == 15
// sum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 15
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the average of all numbers in the array.
// average(l: [-1, 2, -4, 5, 6]) == 0.75
// average(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 15.714285714285714
func average(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of all numbers in the array.
// median(l: [-1, 2, -4, 5, 6]) == 3
// median(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 3
func median(l: [Int]) -> Int {
var sorted = l
sorted.sort()
if sorted.count % 2 == 0 {
return (sorted[sorted.count / 2 - 1] + sorted[sorted.count / 2]) / 2
} else {
return sorted[sorted.count / 2]
}
}
// Return the mode of all numbers in the array.
// mode(l: [-1, 2, -4, 5, 6, 5, 2, 2, 2, 2]) == 2
// mode(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10, 1, 1, 1, 1, 1]) == 1
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in l {
counts[i, default: 0] += 1
}
var maxCount = 0
var mode = 0
for (num, count) in counts {
if count > maxCount {
maxCount = count
mode = num
}
}
return mode
}
// Return the range of all numbers in the array.
// range(l: [-1, 2, -4, 5, 6]) == 7
// range(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 124
func range(l: [Int]) -> Int {
var sorted = l
sorted.sort()
return sorted[sorted.count - 1] - sorted[0]
}
// Return the standard deviation of all numbers in the array.
// standardDeviation(l: [-1, 2, -4, 5, 6]) == 2.5
// standardDeviation(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 289.7960754557402
func standardDeviation(l: [Int]) -> Double {
var mean = average(l: l)
var sum = 0.0
for i in l {
sum += (Double(i) - mean) * (Double(i) - mean)
}
return sqrt(sum / Double(l.count - 1))
}
// Return the number of positive numbers in the array.
// countPositive(l: [-1, 2, -4, 5, 6]) == 3
// countPositive(l: [5, 3, -5, 2, -3, 3,
var mean = average(l: l) // variable 'mean' was never mutated; consider changing to 'let' constant
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
func sumNegative(l: [Int]) -> Int {
var result = 0
for i in l {
if i < 0 {
result += i
}
}
return result
}
func sumAll(l: [Int]) -> Int {
var result = 0
for i in l {
result += i
}
return result
}
func avgAll(l: [Int]) -> Double {
var result = 0
for i in l {
result += i
}
return Double(result) / Double(l.count)
}
func countPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += 1
}
}
return result
}
func countNegative(l: [Int]) -> Int {
var result = 0
for i in l {
if i < 0 {
result += 1
}
}
return result
}
func countZeros(l: [Int]) -> Int {
var result = 0
for i in l {
if i == 0 {
result += 1
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
// Return the sum of all positive numbers in the array.
// sumPositive(l: [-1, 2, -4, 5, 6]) == 11
// sumPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 39
func sumPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += i
}
}
return result
}
// Return the sum of all negative numbers in the array.
// sumNegative(l: [-1, 2, -4, 5, 6]) == -11
// sumNegative(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -45
func sumNegative(l: [Int]) -> Int {
var result = 0
for i in l {
if i < 0 {
result += i
}
}
return result
}
// Return the sum of all numbers in the array.
// sumAll(l: [-1, 2, -4, 5, 6]) == -1
// sumAll(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 128
func sumAll(l: [Int]) -> Int {
var result = 0
for i in l {
result += i
}
return result
}
// Return the average of all numbers in the array.
// avgAll(l: [-1, 2, -4, 5, 6]) == -0.3333333333333333
// avgAll(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 14.285714285714285
func avgAll(l: [Int]) -> Double {
var result = 0
for i in l {
result += i
}
return Double(result) / Double(l.count)
}
// Return the number of positive numbers in the array.
// countPositive(l: [-1, 2, -4, 5, 6]) == 3
// countPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 11
func countPositive(l: [Int]) -> Int {
var result = 0
for i in l {
if i > 0 {
result += 1
}
}
return result
}
// Return the number of negative numbers in the array.
// countNegative(l: [-1, 2, -4, 5, 6]) == 4
// countNegative(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 11
func countNegative(l: [Int]) -> Int {
var result = 0
for i in l {
if i < 0 {
result += 1
}
}
return result
}
// Return the number of zeros in the array.
// countZeros(l: [-1, 2, -4, 0, 5, 6]) == 1
// countZeros(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 4
func countZeros(l: [Int]) -> Int {
var result = 0
for i in l {
if i == 0 {
result += 1
}
}
return result
}
// Return the number of odd numbers in the array.
// countOdd(l: [-1, 2, -4, 5, 6]) == 2
//
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func getSum(l: [Int]) -> Int {
return l.reduce(0, +)
}
func getAverage(l: [Int]) -> Double {
return Double(getSum(l: l)) / Double(l.count)
}
func getMedian(l: [Int]) -> Int {
let sorted = l.sorted()
let mid = sorted.count / 2
return sorted[mid]
}
func getMode(l: [Int]) -> [Int] {
var counts = [Int: Int]()
for num in l {
counts[num, default: 0] += 1
}
return counts.max { $0.value < $1.value }!.key
}
func getRange(l: [Int]) -> Int {
return l.max()! - l.min()!
}
func getStandardDeviation(l: [Int]) -> Double {
let avg = getAverage(l: l)
let sum = l.reduce(0) { $0 + ($1 - avg) * ($1 - avg) }
return sqrt(sum / Double(l.count - 1))
}
```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 }
}
// Return the sum of all numbers in the array.
// getSum(l: [-1, 2, -4, 5, 6]) == 13
// getSum(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 147
func getSum(l: [Int]) -> Int {
return l.reduce(0, +)
}
// Return the average of all numbers in the array.
// getAverage(l: [-1, 2, -4, 5, 6]) == 1.875
// getAverage(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 115.4375
func getAverage(l: [Int]) -> Double {
return Double(getSum(l: l)) / Double(l.count)
}
// Return the median of all numbers in the array.
// getMedian(l: [-1, 2, -4, 5, 6]) == 3
// getMedian(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 3
func getMedian(l: [Int]) -> Int {
let sorted = l.sorted()
let mid = sorted.count / 2
return sorted[mid]
}
// Return the mode of all numbers in the array.
// getMode(l: [-1, 2, -4, 5, 6, 5, 2, 2, 2]) == [2]
// getMode(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10, 1, 1, 1, 1]) == [1]
func getMode(l: [Int]) -> [Int] {
var counts = [Int: Int]()
for num in l {
counts[num, default: 0] += 1
}
return counts.max { $0.value < $1.value }!.key
}
// Return the range of all numbers in the array.
// getRange(l: [-1, 2, -4, 5, 6]) == 7
// getRange(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 124
func getRange(l: [Int]) -> Int {
return l.max()! - l.min()!
}
// Return the standard deviation of all numbers in the array.
// getStandardDeviation(l: [-1, 2, -4, 5, 6]) == 2.5
// getStandardDeviation(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 289.83684210526316
func getStandardDeviation(l: [Int]) -> Double {
let avg = getAverage(l: l)
let sum = l.reduce(0) { $0 + ($1 - avg) * ($1 - avg) }
return sqrt(sum / Double(l.count - 1))
}
// Return the frequency of each unique pair of numbers in the array.
// getPairFrequency(l: [-1, 2, -4, 5, 6]) == [(-1, 1), (2, 1), (-4, 1), (5, 1), (6, 1)]
// getPairFrequency(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [(-10, 1), (0, 1), (1, 1), (123, 1), (2, 2), (3, 2), (-5, 2), (-3, 2), (5, 2), (6,
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeAndSeven(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
func printPrimes(n: Int) {
for i in 1...n {
print(prime(n: i))
}
}
func printPrimesExcludingThreeAndSeven(n: Int) {
for i in 1...n {
if i % 3!= 0 && i % 7!= 0 {
print(prime(n: i))
}
}
}
func printSumOfPrimes(n: Int) {
print(sumOfPrimes(n: n))
}
func printSumOfPrimesExcludingThreeAndSeven(n: Int) {
print(sumOfPrimesExcludingThreeAndSeven(n: n))
}
```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
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers that are divisible by both 3 and 7.
// sumOfPrimesExcludingThreeAndSeven(n: 100) == 501
// sumOfPrimesExcludingThreeAndSeven(n: 1000) == 233168
func sumOfPrimesExcludingThreeAndSeven(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
// Print the first n prime numbers.
// printPrimes(n: 5)
// 2
// 3
// 5
// 7
// 11
func printPrimes(n: Int) {
for i in 1...n {
print(prime(n: i))
}
}
// Print the first n prime numbers, excluding the numbers that are divisible by both 3 and 7.
// printPrimesExcludingThreeAndSeven(n: 5)
// 2
// 3
// 5
// 11
// 13
func printPrimesExcludingThreeAndSeven(n: Int) {
for i in 1...n {
if i % 3!= 0 && i % 7!= 0 {
print(prime(n: i))
}
}
}
// Print the sum of all prime numbers between 1 and n.
// printSumOfPrimes(n: 10)
// 17
// printSumOfPrimes(n: 20)
// 77
func printSumOfPrimes(n: Int) {
print(sumOfPrimes(n: n))
}
// Print the sum of all prime numbers between 1 and n, excluding the numbers that are divisible by both 3 and 7.
// printSumOfPrimesExcludingThreeAndSeven(n: 100)
// 501
// printSumOfPrimesExcludingThreeAndSeven(n: 1000)
// 233168
func printSumOfPrimesExcludingThreeAndSeven(n: Int) {
print(sumOfPrimesExcludingThreeAndSeven(n: n))
}
// Calculate the sum of all prime numbers between 1 and 1,000,000,000,000,000,000,000.
// sumOfPrimes(n: 10000000000000000000)
// 7476196110822839660
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Calculate the sum of all prime numbers between 1 and 1,000,000,000,000,00
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if i % 3!= 0 && i % 7!= 0 { // expression is not assignable: binary operator returns immutable value
if i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 3!= 0 && i % 7!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if i % 3!= 0 && i % 7!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean '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 sumOfPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfEvenPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOddPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2!= 0 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThrees(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 3!= 0 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreesAndFives(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 {
sum += i
}
}
return sum
}
```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
}
// Return the sum of all prime numbers between 1 and a given number.
// sumOfPrimes(upTo: 10) == 17
// sumOfPrimes(upTo: 20) == 77
// sumOfPrimes(upTo: 100) == 2297
// sumOfPrimes(upTo: 1000) == 23279
func sumOfPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all even prime numbers between 1 and a given number.
// sumOfEvenPrimes(upTo: 10) == 2
// sumOfEvenPrimes(upTo: 20) == 10
// sumOfEvenPrimes(upTo: 100) == 66
// sumOfEvenPrimes(upTo: 1000) == 364
func sumOfEvenPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
// Return the sum of all odd prime numbers between 1 and a given number.
// sumOfOddPrimes(upTo: 10) == 1
// sumOfOddPrimes(upTo: 20) == 19
// sumOfOddPrimes(upTo: 100) == 53
// sumOfOddPrimes(upTo: 1000) == 332
func sumOfOddPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and a given number,
// excluding any prime numbers that are divisible by 3.
// sumOfPrimesExcludingThrees(upTo: 10) == 1
// sumOfPrimesExcludingThrees(upTo: 20) == 7
// sumOfPrimesExcludingThrees(upTo: 100) == 231
// sumOfPrimesExcludingThrees(upTo: 1000) == 2516
func sumOfPrimesExcludingThrees(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 3!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and a given number,
// excluding any prime numbers that are divisible by 3 or 5.
// sumOfPrimesExcludingThreesAndFives(upTo: 10) == 1
// sumOfPrimesExcludingThreesAndFives(upTo: 20) == 7
// sumOfPrimesExcludingThreesAndFives(upTo: 100) == 221
// sumOfPrimesExcludingThreesAndFives(upTo: 1000) == 2231
func sumOfPrimesExcludingThreesAndFives(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and a given number,
// excluding any prime numbers that are divisible by 2, 3, or 5.
// sumOfPrimesExcludingTwosThreesFives(upTo: 10) == 1
// sumOfPrimesExcludingTwosThreesFives
if isPrime(n: i) && i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 2!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 3!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if isPrime(n: i) && i % 3!= 0 && i % 5!= 0 { // '=' must have consistent whitespace on both sides
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfEvenPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOddPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 1 {
sum += i
}
}
return sum
}
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 {
sum += i
}
}
return sum
}
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 {
sum += i
}
}
return sum
}
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 {
sum += i
}
}
return sum
}
```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
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all even prime numbers between 1 and n.
// sumOfEvenPrimes(n: 10) == 18
// sumOfEvenPrimes(n: 20) == 88
func sumOfEvenPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
// Return the sum of all odd prime numbers between 1 and n.
// sumOfOddPrimes(n: 10) == 17
// sumOfOddPrimes(n: 20) == 87
func sumOfOddPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 1 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, and 11.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) == 72
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, 11, and 13.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) == 72
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, 11, 13, and 17.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) == 72
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, 11, 13, 17, and 19.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) ==
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
func sumOfPrimesExcluding(n: Int) -> Int { // invalid redeclaration of 'sumOfPrimesExcluding(n:)'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
func sumOfPrimesExcluding(n: Int) -> Int { // invalid redeclaration of 'sumOfPrimesExcluding(n:)'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var primes = [2, 3]
var i = 1
while primes.count < n {
i += 1
if isPrime(n: i) {
primes.append(i)
}
}
return primes[n - 1]
}
func fibonacci(n: Int) -> Int {
var fibs = [1, 1]
var i = 1
while fibs.count < n {
i += 1
fibs.append(fibs[i - 2] + fibs[i - 1])
}
return fibs[n - 1]
}
func fibonacciValue(n: Int) -> Int {
if n <= 2 {
return 1
}
return fibonacciValue(n: n - 1) + fibonacciValue(n: n - 2)
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfFibonacci(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += fibonacci(n: i)
}
return sum
}
func sumOfPrimeFibonacci(n: Int) -> Int {
return sumOfPrimes(n: n) + sumOfFibonacci(n: n)
}
func digitalSum(n: Int) -> Int {
if n <= 2 {
return 1
}
return digitalSum(n: n - 1) + digitalSumValue(n: n - 1)
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var primes = [2, 3]
var i = 1
while primes.count < n {
i += 1
if isPrime(n: i) {
primes.append(i)
}
}
return primes[n - 1]
}
// Return the nth Fibonacci number.
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 6) == 8
// fibonacci(n: 10) == 55
func fibonacci(n: Int) -> Int {
var fibs = [1, 1]
var i = 1
while fibs.count < n {
i += 1
fibs.append(fibs[i - 2] + fibs[i - 1])
}
return fibs[n - 1]
}
// Return the nth value of the Fibonacci sequence.
// fibonacciValue(n: 1) == 1
// fibonacciValue(n: 2) == 1
// fibonacciValue(n: 6) == 8
// fibonacciValue(n: 10) == 55
func fibonacciValue(n: Int) -> Int {
if n <= 2 {
return 1
}
return fibonacciValue(n: n - 1) + fibonacciValue(n: n - 2)
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
// sumOfPrimes(n: 100) == 2233706237
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all Fibonacci numbers between 1 and n.
// sumOfFibonacci(n: 10) == 143
// sumOfFibonacci(n: 20) == 660
// sumOfFibonacci(n: 100) == 354224848179261908320
func sumOfFibonacci(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += fibonacci(n: i)
}
return sum
}
// Return the sum of all prime and Fibonacci numbers between 1 and n.
// sumOfPrimeFibonacci(n: 10) == 17
// sumOfPrimeFibonacci(n: 20) == 109
// sumOfPrimeFibonacci(n: 100) == 4455071317
func sumOfPrimeFibonacci(n: Int) -> Int {
return sumOfPrimes(n: n) + sumOfFibonacci(n: n)
}
// Return the nth value of the digital sum sequence.
// digitalSum(n: 1) == 1
// digitalSum(n: 2) == 1
// digitalSum(n: 6) == 9
// digitalSum(n: 10) == 19
func digitalSum(n: Int) -> Int {
if n <= 2 {
return 1
}
return digitalSum(n: n - 1) + digitalSumValue(n: n - 1)
}
// Return the nth value
return digitalSum(n: n - 1) + digitalSumValue(n: n - 1) // cannot find 'digitalSumValue' in scope
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var primes: [Int] = [2, 3]
var i = 1
while primes.count < n {
i += 1
if isPrime(n: i) {
primes.append(i)
}
}
return primes[n - 1]
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeAndSeven(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeAndSevenOptimized(n: Int) -> Int {
var sum = 0
var primes = [Bool](repeating: true, count: n + 1)
primes[0] = false
primes[1] = false
for i in 2...Int(sqrt(Double(n))) {
if primes[i] {
for j in stride(from: i * i, to: n + 1, by: i) {
primes[j] = false
}
}
}
for i in 2...n {
if primes[i] && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeAndSevenOptimizedIsPrime(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var primes: [Int] = [2, 3]
var i = 1
while primes.count < n {
i += 1
if isPrime(n: i) {
primes.append(i)
}
}
return primes[n - 1]
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding any prime numbers that are divisible by both 3 and 7.
// sumOfPrimesExcludingThreeAndSeven(n: 100) == 500
// sumOfPrimesExcludingThreeAndSeven(n: 1000) == 2297
func sumOfPrimesExcludingThreeAndSeven(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding any prime numbers that are divisible by both 3 and 7,
// and calculating the sum using the optimized Sieve of Eratosthenes algorithm.
// sumOfPrimesExcludingThreeAndSeven(n: 100) == 500
// sumOfPrimesExcludingThreeAndSeven(n: 1000) == 2297
func sumOfPrimesExcludingThreeAndSevenOptimized(n: Int) -> Int {
var sum = 0
var primes = [Bool](repeating: true, count: n + 1)
primes[0] = false
primes[1] = false
for i in 2...Int(sqrt(Double(n))) {
if primes[i] {
for j in stride(from: i * i, to: n + 1, by: i) {
primes[j] = false
}
}
}
for i in 2...n {
if primes[i] && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding any prime numbers that are divisible by both 3 and 7,
// and calculating the sum using the optimized Sieve of Eratosthenes algorithm and the isPrime function.
// sumOfPrimesExcludingThreeAndSeven(n: 100) == 500
// sumOfPrimesExcludingThreeAndSeven(n: 1000) == 2297
func sumOfPrimesExcludingThreeAndSevenOptimizedIsPrime(n: Int) -> Int {
var sum = 0
for i in 1...n {
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding any prime numbers that are divisible by both 3 and 7,
// and calculating the sum using the optimized Sieve of Eratosthenes algorithm and the prime function.
// sumOfPrimesExcludingThreeAndSeven(n: 100) == 500
// sumOfPrimesExcludingThreeAndSeven(n: 1000)
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if primes[i] && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if primes[i] && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if primes[i] && i % 3!= 0 && i % 7!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if primes[i] && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if primes[i] && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if primes[i] && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if primes[i] && i % 3!= 0 && i % 7!= 0 { // use of '=' in a boolean context, did you mean '=='?
if primes[i] && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if primes[i] && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if primes[i] && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 3!= 0 && i % 7!= 0 { // expression is not assignable: '&&' returns immutable value
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingDivisibleBy(n: Int, d: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % d!= 0 {
sum += i
}
}
return sum
}
func fibonacci(n: Int) -> Int {
if n <= 2 {
return 1
}
var a = 1
var b = 1
for _ in 3...n {
let c = a + b
a = b
b = c
}
return b
}
func sumOfFibonacci(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += fibonacci(n: i)
}
return sum
}
func sumOfFibonacciExcludingDivisibleBy(n: Int, d: Int) -> Int {
var sum = 0
for i in 1...n {
if i % d!= 0 {
sum += fibonacci(n: i)
}
}
return sum
}
func triangular(n: Int) -> Int {
return n * (n + 1) / 2
}
```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
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding those that are divisible by a given prime number d.
// sumOfPrimesExcludingDivisibleBy(n: 10, d: 3) == 19
// sumOfPrimesExcludingDivisibleBy(n: 20, d: 7) == 151
func sumOfPrimesExcludingDivisibleBy(n: Int, d: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % d!= 0 {
sum += i
}
}
return sum
}
// Return the nth Fibonacci number.
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 6) == 8
// fibonacci(n: 10) == 55
func fibonacci(n: Int) -> Int {
if n <= 2 {
return 1
}
var a = 1
var b = 1
for _ in 3...n {
let c = a + b
a = b
b = c
}
return b
}
// Return the sum of all Fibonacci numbers between 1 and n.
// sumOfFibonacci(n: 10) == 143
// sumOfFibonacci(n: 20) == 660
func sumOfFibonacci(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += fibonacci(n: i)
}
return sum
}
// Return the sum of all Fibonacci numbers between 1 and n, excluding those that are divisible by a given prime number d.
// sumOfFibonacciExcludingDivisibleBy(n: 10, d: 3) == 14
// sumOfFibonacciExcludingDivisibleBy(n: 20, d: 7) == 103
func sumOfFibonacciExcludingDivisibleBy(n: Int, d: Int) -> Int {
var sum = 0
for i in 1...n {
if i % d!= 0 {
sum += fibonacci(n: i)
}
}
return sum
}
// Return the nth triangular number.
// triangular(n: 1) == 1
// triangular(n: 2) == 3
// triangular(n: 6) == 21
// triangular(n: 10) == 75
func triangular(n: Int) -> Int {
return n * (n + 1) / 2
}
// Return the sum of all triangular numbers between 1 and n.
// sumOfTriangular(n: 10) == 55
// sumOfTriangular(n: 20) == 335
func sumOfTriangular(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum +=
if isPrime(n: i) && i % d!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % d!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % d!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % d!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if i % d!= 0 { // '=' must have consistent whitespace on both sides
if i % d!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % d!= 0 { // use of '=' in a boolean context, did you mean '=='?
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func getNthPrime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
func sumPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func arraySquare(_ array: [Int]) -> [Int] {
var newArray = [Int]()
for i in array {
newArray.append(i * i)
}
return newArray
}
func arraySquareReverse(_ array: [Int]) -> [Int] {
var newArray = [Int]()
for i in array.reversed() {
newArray.append(i * i)
}
return newArray
}
func arrayDiff(_ array: [Int]) -> Int {
return array.max()! - array.min()!
}
func arrayDiffPos(_ array: [Int]) -> Int {
var newArray = [Int]()
for i in array {
if i > 0 {
newArray.append(i)
}
}
return newArray.max()! - newArray.min()!
}
```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
}
// Return the nth prime number.
// getNthPrime(n: 1) == 2
// getNthPrime(n: 2) == 3
// getNthPrime(n: 3) == 5
// getNthPrime(n: 4) == 7
// getNthPrime(n: 5) == 11
// getNthPrime(n: 6) == 13
// getNthPrime(n: 10) == 29
func getNthPrime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the sum of all prime numbers between 1 and n.
// sumPrimes(n: 10) == 17
// sumPrimes(n: 100) == 1277
// sumPrimes(n: 1000) == 22377
func sumPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Given an array of integers, return a new array containing the squares of the values, in the same order.
// Example:
// arraySquare([1, 2, 3]) == [1, 4, 9]
// arraySquare([4, 8, 12, 16]) == [16, 64, 441, 324]
func arraySquare(_ array: [Int]) -> [Int] {
var newArray = [Int]()
for i in array {
newArray.append(i * i)
}
return newArray
}
// Given an array of integers, return a new array containing the squares of the values, in reverse order.
// Example:
// arraySquareReverse([1, 2, 3]) == [9, 4, 1]
// arraySquareReverse([4, 8, 12, 16]) == [324, 64, 441, 16]
func arraySquareReverse(_ array: [Int]) -> [Int] {
var newArray = [Int]()
for i in array.reversed() {
newArray.append(i * i)
}
return newArray
}
// Given an array of integers, return the difference between the largest and smallest values.
// Example:
// arrayDiff([1, 2, 3]) == 2
// arrayDiff([4, 8, 12, 16]) == 16
func arrayDiff(_ array: [Int]) -> Int {
return array.max()! - array.min()!
}
// Given an array of integers, return the difference between the largest and smallest values,
// excluding negative numbers.
// Example:
// arrayDiffPos([1, 2, 3]) == 2
// arrayDiffPos([4, 8, 12, 16]) == 12
func arrayDiffPos(_ array: [Int]) -> Int {
var newArray = [Int]()
for i in array {
if i > 0 {
newArray.append(i)
}
}
return newArray.max()! - newArray.min()!
}
// Given an array of integers, return the number of values that are greater than the previous value.
// First value is always 1.
// Example:
// arrayPeak([1, 2, 3]) == [1, 2, 1]
// arrayPeak([4, 8, 12, 16]) == [1, 1, 2, 1]
func arrayPeak(_ array: [Int]) -> [Int] {
var newArray = [Int]()
newArray.append(1)
for i in 1..<array.count {
if array[i] > array[i - 1] {
newArray.append(1)
} else {
newArray.append(0)
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func sumOfPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2!= 0 {
sum += i
}
}
return sum
}
func sumOfEvenPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOddPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2!= 0 {
sum += i
}
}
return sum
}
func sumOfPrimesIncludingEven(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the sum of all prime numbers between 1 and a given number,
// excluding any even prime numbers.
// sumOfPrimes(upTo: 10) == 17
// sumOfPrimes(upTo: 20) == 77
// sumOfPrimes(upTo: 100) == 1260
// sumOfPrimes(upTo: 1000) == 22310
func sumOfPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all even prime numbers between 1 and a given number,
// excluding any even prime numbers.
// sumOfEvenPrimes(upTo: 10) == 2
// sumOfEvenPrimes(upTo: 20) == 10
// sumOfEvenPrimes(upTo: 100) == 200
// sumOfEvenPrimes(upTo: 1000) == 3276
func sumOfEvenPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
// Return the sum of all odd prime numbers between 1 and a given number,
// excluding any even prime numbers.
// sumOfOddPrimes(upTo: 10) == 1
// sumOfOddPrimes(upTo: 20) == 17
// sumOfOddPrimes(upTo: 100) == 251
// sumOfOddPrimes(upTo: 1000) == 4231
func sumOfOddPrimes(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2!= 0 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and a given number,
// including any even prime numbers.
// sumOfPrimesIncludingEven(upTo: 10) == 18
// sumOfPrimesIncludingEven(upTo: 20) == 88
// sumOfPrimesIncludingEven(upTo: 100) == 1560
// sumOfPrimesIncludingEven(upTo: 1000) == 31340
func sumOfPrimesIncludingEven(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and a given number,
// including any even prime numbers.
// sumOfPrimesIncludingEven(upTo: 10) == 18
// sumOfPrimesIncludingEven(upTo: 20) == 88
// sumOfPrimesIncludingEven(upTo: 100) == 1560
// sumOfPrimesIncludingEven(upTo: 1000) == 31340
func sumOfPrimesIncludingEven(upTo n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and a given number,
// including any even prime numbers.
// sumOfPrimesIncludingEven(upTo: 10) == 18
// sumOfPrimesIncludingEven(upTo: 20) == 88
// sumOfPrimesIncludingEven(upTo: 100) == 1560
// sumOfPrimesIncludingEven(upTo: 1
if isPrime(n: i) && i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 2!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if isPrime(n: i) && i % 2!= 0 { // '=' must have consistent whitespace on both sides
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var primes: [Int] = [2, 3]
var count = 2
while count < n {
let next = primes.last! + 2
if isPrime(n: next) {
primes.append(next)
count += 1
}
}
return primes.last!
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfEvenPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOddPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 1 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeAndFive(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 3 && i!= 5 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeFiveAndSeven(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 {
sum += i
}
}
return sum
}
func sumOfPrimesExcludingThreeFiveSevenAndEleven(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 {
sum += i
}
}
return sum
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var primes: [Int] = [2, 3]
var count = 2
while count < n {
let next = primes.last! + 2
if isPrime(n: next) {
primes.append(next)
count += 1
}
}
return primes.last!
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all even prime numbers between 1 and n.
// sumOfEvenPrimes(n: 10) == 18
// sumOfEvenPrimes(n: 20) == 88
func sumOfEvenPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
// Return the sum of all odd prime numbers between 1 and n.
// sumOfOddPrimes(n: 10) == 17
// sumOfOddPrimes(n: 20) == 83
func sumOfOddPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 1 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 3 and 5.
// sumOfPrimesExcludingThreeAndFive(n: 10) == 19
// sumOfPrimesExcludingThreeAndFive(n: 20) == 119
func sumOfPrimesExcludingThreeAndFive(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 3 && i!= 5 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 3, 5, and 7.
// sumOfPrimesExcludingThreeFiveAndSeven(n: 10) == 17
// sumOfPrimesExcludingThreeFiveAndSeven(n: 20) == 131
func sumOfPrimesExcludingThreeFiveAndSeven(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 3, 5, 7, and 11.
// sumOfPrimesExcludingThreeFiveSevenAndEleven(n: 10) == 13
// sumOfPrimesExcludingThreeFiveSevenAndEleven(n: 20) == 169
func sumOfPrimesExcludingThreeFiveSevenAndEleven(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 2, 3,
if isPrime(n: i) && i!= 3 && i!= 5 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 3 && i!= 5 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 3 && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
func sumOfEvenPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfOddPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 1 {
sum += i
}
}
return sum
}
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 {
sum += i
}
}
return sum
}
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 {
sum += i
}
}
return sum
}
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 {
sum += i
}
}
return sum
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the nth prime number.
// prime(n: 1) == 2
// prime(n: 2) == 3
// prime(n: 6) == 13
// prime(n: 10) == 29
func prime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(n: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the sum of all prime numbers between 1 and n.
// sumOfPrimes(n: 10) == 17
// sumOfPrimes(n: 20) == 77
func sumOfPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) {
sum += i
}
}
return sum
}
// Return the sum of all even prime numbers between 1 and n.
// sumOfEvenPrimes(n: 10) == 18
// sumOfEvenPrimes(n: 20) == 88
func sumOfEvenPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 0 {
sum += i
}
}
return sum
}
// Return the sum of all odd prime numbers between 1 and n.
// sumOfOddPrimes(n: 10) == 17
// sumOfOddPrimes(n: 20) == 83
func sumOfOddPrimes(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i % 2 == 1 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, and 11.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) == 72
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, 11, and 13.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) == 72
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, 11, 13, and 17.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n: 20) == 72
func sumOfPrimesExcluding(n: Int) -> Int {
var sum = 0
for i in 2...n {
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 {
sum += i
}
}
return sum
}
// Return the sum of all prime numbers between 1 and n, excluding the numbers 5, 7, 11, 13, 17, and 19.
// sumOfPrimesExcluding(n: 10) == 16
// sumOfPrimesExcluding(n:
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 { // cannot force unwrap value of non-optional type 'Int'
func sumOfPrimesExcluding(n: Int) -> Int { // invalid redeclaration of 'sumOfPrimesExcluding(n:)'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 { // '=' must have consistent whitespace on both sides
func sumOfPrimesExcluding(n: Int) -> Int { // invalid redeclaration of 'sumOfPrimesExcluding(n:)'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // use of '=' in a boolean context, did you mean '=='?
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot convert value of type 'Int' to expected argument type 'Bool'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // cannot force unwrap value of non-optional type 'Int'
if isPrime(n: i) && i!= 5 && i!= 7 && i!= 11 && i!= 13 && i!= 17 { // '=' must have consistent whitespace on both sides
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
}
i += 1
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
}
i += 1
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
}
i += 1
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
}
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
}
i += 1
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
}
i += 1
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
}
i += 1
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
}
i += 1
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l.remove(at: i)
l.insert(temp, at: i)
i -= 1
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1 - i]
l[l.count - 1 - i] = temp
}
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[j]
l[j] = temp
j -= 1
} else {
i += 1
}
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[j]
l[j] = temp
j -= 1
}
i += 1
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[j]
l[j] = temp
j -= 1
}
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1 - i]
l[l.count - 1 - i] = temp
}
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[j]
l[j] = temp
j -= 1
} else {
i += 1
}
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[j]
l[j] = temp
j -= 1
}
i += 1
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[j]
l[j] = temp
j -= 1
}
i += 1
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 3 == 0 {
let
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
l[i] = l[i + 1]
l[i + 1] = l[i]
}
}
return l
}
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
l[i] = l[i + 1]
l[i + 1] = l[i]
i += 1
}
i += 1
}
return l
}
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[i + 1]
l[i + 1] = temp
i += 1
}
i += 1
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
l[i] = l[i + 1]
l[i + 1] = l[i]
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
l[i] = l[i + 1]
l[i + 1] = l[i]
i += 1
}
i += 1
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[i + 1]
l[i + 1] = temp
i += 1
}
i += 1
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
l[i] = l[i + 1]
l[i + 1] = l[i]
i += 1
}
i += 1
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[i + 1]
l[i + 1] = temp
i += 1
}
i += 1
}
return
func sortThird(l: [Int]) -> [Int] { // invalid redeclaration of 'sortThird(l:)'
func sortThird(l: [Int]) -> [Int] { // invalid redeclaration of 'sortThird(l:)'
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort()
return lPrime
}
func sortThird2(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: <)
return lPrime
}
func sortThird3(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: { $0 < $1 })
return lPrime
}
func sortThird4(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: { $0 > $1 })
return lPrime
}
func sortThird5(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: >)
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort()
return lPrime
}
// 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 sortThird2(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: <)
return lPrime
}
// 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 sortThird3(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: { $0 < $1 })
return lPrime
}
// 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 sortThird4(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: { $0 > $1 })
return lPrime
}
// 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 sortThird5(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<l.count {
if l[i] % 3 == 0 {
lPrime[i] = l[i + 1]
}
}
lPrime.sort(by: >)
return lPrime
}
// 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
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
if lPrime[i] % 3 == 0 {
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = lPrime[i]
i += 2
} else {
i += 1
}
}
return lPrime
}
func sortThird2(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
if lPrime[i] % 3 == 0 {
let temp = lPrime[i]
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = temp
i += 2
} else {
i += 1
}
}
return lPrime
}
func sortThird3(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if lPrime[i] % 3 == 0 {
let temp = lPrime[i]
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = temp
}
}
return lPrime
}
func sortThird4(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
if lPrime[i] % 3 == 0 {
let temp = lPrime[i]
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = temp
i += 2
} else {
i += 1
}
}
return lPrime
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
if lPrime[i] % 3 == 0 {
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = lPrime[i]
i += 2
} else {
i += 1
}
}
return lPrime
}
// 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 sortThird2(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
if lPrime[i] % 3 == 0 {
let temp = lPrime[i]
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = temp
i += 2
} else {
i += 1
}
}
return lPrime
}
// 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 sortThird3(l: [Int]) -> [Int] {
var lPrime = l
for i in 0..<lPrime.count {
if lPrime[i] % 3 == 0 {
let temp = lPrime[i]
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = temp
}
}
return lPrime
}
// 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 sortThird4(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
if lPrime[i] % 3 == 0 {
let temp = lPrime[i]
lPrime[i] = lPrime[i + 1]
lPrime[i + 1] = temp
i += 2
} else {
i += 1
}
}
return lPrime
}
// 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 sortThird5(l: [Int]) -> [Int] {
var lPrime = l
var i = 0
while i < lPrime.count {
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
func sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird2(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird3(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird4(l: [Int]) -> [Int] {
var l = l
var i = 0
while i < l.count {
if l[i] % 3 == 0 {
let temp = l[i]
l[i] = l[l.count - 1]
l[l.count - 1] = temp
l.removeLast()
} else {
i += 1
}
}
return l
}
// 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 sortThird5(l: [Int]) -> [Int] {
var l = l
var i = 0
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique(l: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result
}
func unique<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result.sorted()
}
func unique<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result.sorted(by: isOrderedBefore)
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result
}
// 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<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result.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<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result.sorted(by: isOrderedBefore)
}
// 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<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result.sorted(by: isOrderedBefore)
}
// 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<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
var set = Set<T>()
for i in l {
if!set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result.sorted(by: isOrderedBefore)
}
// 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<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!set.contains(i) { // expected expression, var, or let in 'if' condition
var set = Set<T>() // type 'T' does not conform to protocol 'Hashable'
if!set.contains(i) { // expected expression, var, or let in 'if' condition
var set = Set<T>() // type 'T' does not conform to protocol 'Hashable'
if!set.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var unique = Set<Int>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
var unique = Set<Int>()
for (k, v) in d {
if!unique.contains(v) {
result[k] = v
unique.insert(v)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var unique = Set<Int>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["h": 0, "i": 123, "a": 5, "b": 3, "d": 2, "f": 3, "g": 9]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
var unique = Set<Int>()
for (k, v) in d {
if!unique.contains(v) {
result[k] = v
unique.insert(v)
}
}
return result
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["h": 0, "i": 123, "a": 5, "b": 3, "d": 2, "f": 3, "g": 9]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
var unique = Set<Int>()
for (k, v) in d {
if!unique.contains(v) {
result[k] = v
unique.insert(v)
}
}
return result
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["h": 0, "i": 123, "a": 5, "b": 3, "d": 2, "f": 3, "g": 9]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
var unique = Set<Int>()
for (k, v) in d {
if!unique.contains(v) {
result[k] = v
unique.insert(v)
}
}
return result
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["h": 0, "i": 123, "a": 5, "b": 3, "d": 2, "f": 3, "g": 9]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
var unique = Set<Int>()
for (k, v) in d {
if!unique.contains(v) {
result[k] = v
unique.insert(v)
}
}
return result
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["h": 0, "i": 123, "a": 5, "b": 3, "d": 2, "f": 3, "g": 9]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
var unique = Set<Int>()
for (k, v) in d {
if!unique.contains(v) {
result[k] = v
unique.insert(v)
}
}
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
if!unique.contains(v) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique(l: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T>(l: [T], isEqual: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { isEqual(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Hashable>(l: [T], isEqual: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { isEqual(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Comparable>(l: [T], isEqual: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { isEqual(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// 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: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T>(l: [T], isEqual: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { isEqual(i, $0) }) {
result.append(i)
}
}
return result.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<T: Hashable>(l: [T], isEqual: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { isEqual(i, $0) }) {
result.append(i)
}
}
return result.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<T: Comparable>(l: [T], isEqual: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { isEqual(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9,
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(where: { isEqual(i, $0) }) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(where: { isEqual(i, $0) }) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(where: { isEqual(i, $0) }) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var unique = Set<Int>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
func unique(l: [String]) -> [String] {
var result = [String]()
var unique = Set<String>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
func unique<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
func unique<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
func unique<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var unique = Set<Int>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: ["hello", "hello", "world", "foo", "bar", "foo", "bar"]) == ["bar", "foo", "hello", "world"]
func unique(l: [String]) -> [String] {
var result = [String]()
var unique = Set<String>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// 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<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: ["hello", "hello", "world", "foo", "bar", "foo", "bar"]) == ["bar", "foo", "hello", "world"]
func unique<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// 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<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: ["hello", "hello", "world", "foo", "bar", "foo", "bar"]) == ["bar", "foo", "hello", "world"]
func unique<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// 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<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: ["hello", "hello", "world", "foo", "bar", "foo", "bar"]) == ["bar", "foo", "hello", "world"]
func unique<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
var unique = Set<T>()
for i in l {
if!unique.contains(i) {
result.append(i)
unique.insert(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 12
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
var unique = Set<T>() // type 'T' does not conform to protocol 'Hashable'
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
var unique = Set<T>() // type 'T' does not conform to protocol 'Hashable'
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.contains(where: { $0.value == v }) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.key })
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.contains(where: { $0.value == v }) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.key })
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.contains(where: { $0.value == v }) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.key })
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.contains(where: { $0.value == v }) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.key })
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]) == ["a": 5, "b": 3, "c": 5, "d": 2, "e": 3, "f": 3, "g": 9, "h": 0, "i": 123]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.contains(where: { $0.value == v }) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(where: { $0.value == v }) { // expected expression, var, or let in 'if' condition
return result.sorted(by: { $0.key < $1.key }) // cannot convert return expression of type '[Dictionary<String, Int>.Element]' (aka 'Array<(key: String, value: Int)>') to return type '[String : Int]'
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.keys.contains(k) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.key })
}
func unique(s: Set<Int>) -> [Int] {
var result = [Int]()
for i in s {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique(t: (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) {
var result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(result.0, result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9) = t
return (
result.0,
result.1,
result.2,
result.3,
result.4,
result.5,
result.6,
result.7,
result.8,
result.9
)
}
func unique(t: (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) {
var result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(result.0, result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9, result.10, result.11, result.12, result.13, result.14, result.15, result.16, result.17, result.18, result.19) = t
return (
result.0,
result.1,
result.2,
result.3,
result.4,
result.5,
result.6,
result.7,
result.8,
result.9,
result.10,
result.11,
result.12,
result.13,
result.14,
result.15,
result.16,
result.17,
result.18,
result.19
)
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in a dictionary
// unique(d: ["a": 1, "b": 2, "c": 1, "d": 3]) == ["a": 1, "b": 2, "c": 1, "d": 3]
func unique(d: [String: Int]) -> [String: Int] {
var result = [String: Int]()
for (k, v) in d {
if!result.keys.contains(k) {
result[k] = v
}
}
return result.sorted(by: { $0.key < $1.key })
}
// Return sorted unique elements in a set
// unique(s: [1, 3, 5, 3, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(s: Set<Int>) -> [Int] {
var result = [Int]()
for i in s {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in a tuple
// unique(t: (1, 3, 5, 3, 2, 3, 3, 9, 0, 123)) == (0, 2, 3, 5, 9, 123)
func unique(t: (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) {
var result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(result.0, result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9) = t
return (
result.0,
result.1,
result.2,
result.3,
result.4,
result.5,
result.6,
result.7,
result.8,
result.9
)
}
// Return sorted unique elements in a tuple
// unique(t: (1, 3, 5, 3, 2, 3, 3, 9, 0, 123)) == (0, 2, 3, 5, 9, 123)
func unique(t: (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)) -> (Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) {
var result = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
(result.0, result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9, result.10, result.11, result.12, result.13, result.14, result.15, result.16, result.17, result.18, result.19) = t
return (
result.0,
result.1,
result.2,
result.3,
result.4,
result.5,
result.6,
result.7,
result.8,
result.9,
result.10,
result.11,
result.12,
result.13,
result.14,
result.15,
result.16,
result.17,
result.18,
result.19
)
}
// Return sorted unique elements in a tuple
// unique(t: (1, 3, 5, 3,
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.keys.contains(k) { // expected expression, var, or let in 'if' condition
return result.sorted(by: { $0.key < $1.key }) // cannot convert return expression of type '[Dictionary<String, Int>.Element]' (aka 'Array<(key: String, value: Int)>') to return type '[String : Int]'
if!result.contains(i) { // expected expression, var, or let in 'if' condition
(result.0, result.1, result.2, result.3, result.4, result.5, result.6, result.7, result.8, result.9, result.10, result.11, result.12, result.13, result.14, result.15, result.16, result.17, result.18, result.19) = t // cannot assign value of type '(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)' to type '(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)'
return ( // cannot convert return expression of type '(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)' to return type '(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int)'
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique(l: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func unique<T>(l: [T], comparator: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { comparator(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
func unique<T: Hashable>(l: [T], comparator: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { comparator(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// 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: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.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<T>(l: [T], comparator: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { comparator(i, $0) }) {
result.append(i)
}
}
return result.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<T>(l: [T], comparator: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { comparator(i, $0) }) {
result.append(i)
}
}
return result.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<T: Hashable>(l: [T], comparator: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(where: { comparator(i, $0) }) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0,
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(where: { comparator(i, $0) }) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
if!result.contains(where: { comparator(i, $0) }) { // expected expression, var, or let in 'if' condition
return result.sorted() // referencing instance method 'sorted()' on 'Sequence' requires that 'T' conform to 'Comparable'
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// Return sorted unique
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique(l: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Hashable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
func unique<T: Equatable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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: [String]) -> [String] {
var result = [String]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Hashable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Comparable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Equatable>(l: [T]) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Comparable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Hashable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Equatable>(l: [T], isOrderedBefore: (T, T) -> Bool) -> [T] {
var result = [T]()
for i in l {
if!result.contains(i) {
result.append(i)
}
}
return result
}
// 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<T: Comparable>(l: [T], isOrderedBefore:
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
if!result.contains(i) { // expected expression, var, or let in 'if' condition
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
func count(l: [Int], e: Int) -> Int {
var count = 0
for i in l {
if i == e {
count += 1
}
}
return count
}
```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 the index of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 2
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
// Return the 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 index of the minimum element in the array.
// minElementIndex(l: [1, 2, 3]) == 0
// minElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 3
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
// Return the minimum element and its index in the array.
// minElementAndIndex(l: [1, 2, 3]) == (1, 0)
// minElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 10)
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
// Return the number of occurrences of the given element in the array.
// count(l: [1, 2, 3, 1, 2, 3, 1, 2, 3], e: 1) == 3
// count(l: [1, 2, 3, 1, 2, 3, 1, 2, 3], e: 5) == 0
func count(l: [Int], e: Int) -> Int {
var count = 0
for i in l {
if i == e {
count += 1
}
}
return count
}
// Return the number of occurrences of the given element in the array.
// count(l: [1, 2, 3, 1, 2, 3, 1, 2, 3], e: 1) == 3
// count(l: [
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var index = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
index = i
}
}
return index
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var index = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
index = i
}
}
return (max, index)
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var index = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
index = i
}
}
return index
}
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var index = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
index = i
}
}
return (min, index)
}
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
// Return the index of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 2
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var index = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
index = i
}
}
return index
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var index = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
index = i
}
}
return (max, index)
}
// Return the 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 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
// Return the index of the minimum element in the array.
// minElementIndex(l: [1, 2, 3]) == 0
// minElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 7
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var index = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
index = i
}
}
return index
}
// Return the minimum element and its index in the array.
// minElementAndIndex(l: [1, 2, 3]) == (1, 0)
// minElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 7)
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var index = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
index = i
}
}
return (min, index)
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: [1, 2, 3, 2, 4, 2], element: 2) == 3
// countOccurrences(l: ["a", "b", "c", "a", "b", "c"], element: "b") == 2
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: ["a", "b", "c", "a", "b", "c"], element: "b") == 2
// countOccurrences(
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func secondMaxElement(l: [Int]) -> Int? {
var max = l[0]
var secondMax = l[0]
for i in l {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
if max == secondMax {
return nil
} else {
return secondMax
}
}
func thirdMaxElement(l: [Int]) -> Int? {
var max = l[0]
var secondMax = l[0]
var thirdMax = l[0]
for i in l {
if i > max {
thirdMax = secondMax
secondMax = max
max = i
} else if i > secondMax {
thirdMax = secondMax
secondMax = i
} else if i > thirdMax {
thirdMax = i
}
}
if max == secondMax {
return nil
} else {
return thirdMax
}
}
func countElements(l: [Int], target: Int) -> Int {
var count = 0
for i in l {
if i < target {
count += 1
}
}
return count
}
```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 the second maximum element in the array.
// If the array has less than two elements, return nil.
// secondMaxElement(l: [1, 2, 3]) == nil
// secondMaxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 9
func secondMaxElement(l: [Int]) -> Int? {
var max = l[0]
var secondMax = l[0]
for i in l {
if i > max {
secondMax = max
max = i
} else if i > secondMax {
secondMax = i
}
}
if max == secondMax {
return nil
} else {
return secondMax
}
}
// Return the third maximum element in the array.
// If the array has less than three elements, return nil.
// thirdMaxElement(l: [1, 2, 3]) == nil
// thirdMaxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 0
func thirdMaxElement(l: [Int]) -> Int? {
var max = l[0]
var secondMax = l[0]
var thirdMax = l[0]
for i in l {
if i > max {
thirdMax = secondMax
secondMax = max
max = i
} else if i > secondMax {
thirdMax = secondMax
secondMax = i
} else if i > thirdMax {
thirdMax = i
}
}
if max == secondMax {
return nil
} else {
return thirdMax
}
}
// Return the number of elements that are smaller than the target number.
// countElements(l: [1, 2, 3, 4, 5], target: 3) == 2
// countElements(l: [1, 2, 3, 4, 5], target: 6) == 0
func countElements(l: [Int], target: Int) -> Int {
var count = 0
for i in l {
if i < target {
count += 1
}
}
return count
}
// Return the number of elements that are smaller than the target number.
// countElements(l: [1, 2, 3, 4, 5], target: 3) == 2
// countElements(l: [1, 2, 3, 4, 5], target: 6) == 0
func countElements(l: [Int], target: Int) -> Int {
var count = 0
for i in l {
if i < target {
count += 1
}
}
return count
}
// Return the number of elements that are smaller than the target number.
// countElements(l: [1, 2, 3, 4, 5], target: 3) == 2
// countElements(l: [1, 2, 3, 4, 5], target: 6) == 0
func countElements(l: [Int], target: Int) -> Int {
var count = 0
for i in l {
if i < target {
count += 1
}
}
return count
}
// Return the number of elements that are smaller than the target number.
// countElements(l: [1, 2, 3, 4, 5], target: 3) == 2
// countElements(l: [1, 2, 3, 4, 5], target: 6) == 0
func countElements(l: [Int], target: Int) -> Int {
var count = 0
for i in l {
if i < target {
count += 1
}
}
return count
}
// Return the number of elements that are smaller than the target number.
// countElements(l: [1, 2, 3, 4, 5], target: 3) == 2
// countElements(l: [1, 2, 3, 4, 5], target: 6) == 0
func countElements(l: [Int],
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
// Return the index of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 2
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
// Return the 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 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
// Return the index of the minimum element in the array.
// minElementIndex(l: [1, 2, 3]) == 0
// minElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 1
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
// Return the minimum element and its index in the array.
// minElementAndIndex(l: [1, 2, 3]) == (1, 0)
// minElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 1)
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: [1, 2, 3, 2, 4, 2], element: 2) == 3
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
// Return the index of the first occurrence of the given element in the array.
// firstOccurrence(l: [1, 2, 3, 2, 4, 2], element: 2) == 1
// firstOccurrence(l: [1, 2, 3, 2, 4, 2],
func maxElement(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
func maxElementIndexLast(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
var max = l[0]
var maxIndex = 0
var lastMax = max
var lastMaxIndex = 0
for i in 1..<l.count {
if l[i] > max {
lastMax = max
lastMaxIndex = maxIndex
max = l[i]
maxIndex = i
} else if l[i] == max {
lastMax = max
lastMaxIndex = maxIndex
}
}
return lastMaxIndex
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
if l.count == 0 {
return (0, 0)
}
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
func maxElementAndIndexLast(l: [Int]) -> (Int, Int) {
if l.count == 0 {
return (0, 0)
}
var max = l[0]
var maxIndex = 0
var lastMax = max
var lastMaxIndex = 0
for i in 1..<l.count {
if l[i] > max {
lastMax = max
lastMaxIndex = maxIndex
max = l[i]
maxIndex = i
} else if l[i] == max {
lastMax = max
lastMaxIndex = maxIndex
}
}
return (lastMax, lastMaxIndex)
}
```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 {
if l.count == 0 {
return 0
}
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
// Return the index of the first occurrence of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 0
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
// Return the index of the last occurrence of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 0
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndexLast(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
var max = l[0]
var maxIndex = 0
var lastMax = max
var lastMaxIndex = 0
for i in 1..<l.count {
if l[i] > max {
lastMax = max
lastMaxIndex = maxIndex
max = l[i]
maxIndex = i
} else if l[i] == max {
lastMax = max
lastMaxIndex = maxIndex
}
}
return lastMaxIndex
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
if l.count == 0 {
return (0, 0)
}
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndexLast(l: [Int]) -> (Int, Int) {
if l.count == 0 {
return (0, 0)
}
var max = l[0]
var maxIndex = 0
var lastMax = max
var lastMaxIndex = 0
for i in 1..<l.count {
if l[i] > max {
lastMax = max
lastMaxIndex = maxIndex
max = l[i]
maxIndex = i
} else if l[i] == max {
lastMax = max
lastMaxIndex = maxIndex
}
}
return (lastMax, lastMaxIndex)
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndexFirst(l: [Int]) -> (Int, Int) {
if l.count == 0 {
return
var lastMax = max // variable 'lastMax' was written to, but never read
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
// Return the index of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 2
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
// Return the 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 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
// Return the index of the minimum element in the array.
// minElementIndex(l: [1, 2, 3]) == 0
// minElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 1
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
// Return the minimum element and its index in the array.
// minElementAndIndex(l: [1, 2, 3]) == (1, 0)
// minElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 1)
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: [1, 2, 3, 2, 4, 2], element: 2) == 3
// countOccurrences(l: ["a", "b", "c", "a", "b", "a"], element: "a") == 3
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: ["apple", "banana", "cherry", "apple", "banana", "apple
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in l {
if i == element {
count += 1
}
}
return count
}
```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 the index of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 2
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 0..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
// Return the 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 index of the minimum element in the array.
// minElementIndex(l: [1, 2, 3]) == 0
// minElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 1
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
// Return the minimum element and its index in the array.
// minElementAndIndex(l: [1, 2, 3]) == (1, 0)
// minElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 1)
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 0..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: [1, 2, 3, 2, 4, 2], element: 2) == 3
// countOccurrences(l: ["a", "b", "a", "c", "a", "b"], element: "a") == 2
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in l {
if i == element {
count += 1
}
}
return count
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: ["a", "b", "a", "c", "a", "b"], element: "a") == 2
// countOccurrences(l: ["a", "b", "a", "c", "a", "b"], element
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
func firstIndexOf(l: [Int], target: Int) -> Int {
for i in 0..<l.count {
if l[i] == target {
return i
}
}
return -1
}
func lastIndexOf(l: [Int], target: Int) -> Int {
var index = -1
for i in 0..<l.count {
if l[i] == target {
index = i
}
}
return index
}
func countGreater(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > target {
count += 1
}
}
return count
}
func countSmaller(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] < target {
count += 1
}
}
return count
}
func countGreaterOrEqual(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] >= target {
count += 1
}
}
return count
}
func countSmallerOrEqual(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] <= target {
count += 1
}
}
return count
}
func countEqual(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == target {
count += 1
}
}
return count
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
// Return the index of the first element in the array that is equal to the given target.
// If there are no such elements, return -1.
// firstIndexOf(l: [1, 2, 3], target: 2) == 1
// firstIndexOf(l: [1, 2, 3], target: 4) == -1
func firstIndexOf(l: [Int], target: Int) -> Int {
for i in 0..<l.count {
if l[i] == target {
return i
}
}
return -1
}
// Return the index of the last element in the array that is equal to the given target.
// If there are no such elements, return -1.
// lastIndexOf(l: [1, 2, 3], target: 2) == 1
// lastIndexOf(l: [1, 2, 3], target: 4) == -1
func lastIndexOf(l: [Int], target: Int) -> Int {
var index = -1
for i in 0..<l.count {
if l[i] == target {
index = i
}
}
return index
}
// Return the number of elements in the array that are greater than the given target.
// countGreater(l: [1, 2, 3], target: 2) == 1
// countGreater(l: [1, 2, 3], target: 4) == 0
func countGreater(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > target {
count += 1
}
}
return count
}
// Return the number of elements in the array that are smaller than the given target.
// countSmaller(l: [1, 2, 3], target: 2) == 2
// countSmaller(l: [1, 2, 3], target: 4) == 0
func countSmaller(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] < target {
count += 1
}
}
return count
}
// Return the number of elements in the array that are greater than or equal to the given target.
// countGreaterOrEqual(l: [1, 2, 3], target: 2) == 2
// countGreaterOrEqual(l: [1, 2, 3], target: 4) == 0
func countGreaterOrEqual(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] >= target {
count += 1
}
}
return count
}
// Return the number of elements in the array that are smaller than or equal to the given target.
// countSmallerOrEqual(l: [1, 2, 3], target: 2) == 1
// countSmallerOrEqual(l: [1, 2, 3], target: 4) == 0
func countSmallerOrEqual(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] <= target {
count += 1
}
}
return count
}
// Return the number of elements in the array that are equal to the given target.
// countEqual(l: [1, 2, 3], target: 2) == 1
// countEqual(l: [1, 2, 3], target: 4) == 0
func countEqual(l: [Int], target: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == target {
count += 1
}
}
return count
}
// Return the number of elements in the array that are not equal to the given target.
// countNotEqual(l: [1, 2, 3], target: 2) == 2
// countNotEqual(l: [1, 2
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
} else {
let mid = l.count / 2
let leftMax = maxElement(l: Array(l[0..<mid]))
let rightMax = maxElement(l: Array(l[mid..<l.count]))
return max(leftMax, rightMax)
}
}
func countElements(l: [Int], threshold: Int) -> Int {
if l.count == 0 {
return 0
} else {
let mid = l.count / 2
if l[mid] > threshold {
return 1 + countElements(l: Array(l[0..<mid]), threshold: threshold) + countElements(l: Array(l[mid+1..<l.count]), threshold: threshold)
} else {
return countElements(l: Array(l[0..<mid]), threshold: threshold) + countElements(l: Array(l[mid+1..<l.count]), threshold: threshold)
}
}
}
func sumElements(l: [Int]) -> Int {
if l.count == 0 {
return 0
} else {
let mid = l.count / 2
return l[mid] + sumElements(l: Array(l[0..<mid])) + sumElements(l: Array(l[mid+1..<l.count]))
}
}
func productElements(l: [Int]) -> Int {
if l.count == 0 {
return 1
} else {
let mid = l.count / 2
return l[mid] * productElements(l: Array(l[0..<mid])) * productElements(l: Array(l[mid+1..<l.count]))
}
}
func minElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
} else {
let mid = l.count / 2
let leftMin = minElement(l: Array(l[0..<mid]))
let rightMin = minElement(l: Array(l[mid..<l.count]))
return min(leftMin, rightMin)
}
}
```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 {
if l.count == 1 {
return l[0]
} else {
let mid = l.count / 2
let leftMax = maxElement(l: Array(l[0..<mid]))
let rightMax = maxElement(l: Array(l[mid..<l.count]))
return max(leftMax, rightMax)
}
}
// Return the number of elements in the array that are greater than the threshold.
// countElements(l: [1, 2, 3], threshold: 1) == 2
// countElements(l: [1, 2, 3], threshold: 2) == 1
// countElements(l: [1, 2, 3], threshold: 3) == 0
func countElements(l: [Int], threshold: Int) -> Int {
if l.count == 0 {
return 0
} else {
let mid = l.count / 2
if l[mid] > threshold {
return 1 + countElements(l: Array(l[0..<mid]), threshold: threshold) + countElements(l: Array(l[mid+1..<l.count]), threshold: threshold)
} else {
return countElements(l: Array(l[0..<mid]), threshold: threshold) + countElements(l: Array(l[mid+1..<l.count]), threshold: threshold)
}
}
}
// Return the sum of all elements in the array.
// sumElements(l: [1, 2, 3]) == 6
// sumElements(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 122
func sumElements(l: [Int]) -> Int {
if l.count == 0 {
return 0
} else {
let mid = l.count / 2
return l[mid] + sumElements(l: Array(l[0..<mid])) + sumElements(l: Array(l[mid+1..<l.count]))
}
}
// Return the product of all elements in the array.
// productElements(l: [1, 2, 3]) == 6
// productElements(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == -199999999999999960
func productElements(l: [Int]) -> Int {
if l.count == 0 {
return 1
} else {
let mid = l.count / 2
return l[mid] * productElements(l: Array(l[0..<mid])) * productElements(l: Array(l[mid+1..<l.count]))
}
}
// Return the minimum value 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 {
if l.count == 1 {
return l[0]
} else {
let mid = l.count / 2
let leftMin = minElement(l: Array(l[0..<mid]))
let rightMin = minElement(l: Array(l[mid..<l.count]))
return min(leftMin, rightMin)
}
}
// Return the maximum value 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 {
if l.count == 1 {
return l[0]
} else {
let mid = l.count / 2
let leftMax = maxElement(l: Array(l[0..<mid]))
let rightMax = maxElement(l: Array(l[mid..<l.count]))
return max(leftMax, rightMax)
}
}
// Return the number of elements in
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
func minElement(l: [Int]) -> Int {
var min = l[0]
for i in 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
// Return the index of the maximum element in the array.
// maxElementIndex(l: [1, 2, 3]) == 2
// maxElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 10
func maxElementIndex(l: [Int]) -> Int {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return maxIndex
}
// Return the maximum element and its index in the array.
// maxElementAndIndex(l: [1, 2, 3]) == (3, 2)
// maxElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (123, 10)
func maxElementAndIndex(l: [Int]) -> (Int, Int) {
var max = l[0]
var maxIndex = 0
for i in 1..<l.count {
if l[i] > max {
max = l[i]
maxIndex = i
}
}
return (max, maxIndex)
}
// Return the 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 1..<l.count {
if l[i] < min {
min = l[i]
}
}
return min
}
// Return the index of the minimum element in the array.
// minElementIndex(l: [1, 2, 3]) == 0
// minElementIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 1
func minElementIndex(l: [Int]) -> Int {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return minIndex
}
// Return the minimum element and its index in the array.
// minElementAndIndex(l: [1, 2, 3]) == (1, 0)
// minElementAndIndex(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == (-10, 1)
func minElementAndIndex(l: [Int]) -> (Int, Int) {
var min = l[0]
var minIndex = 0
for i in 1..<l.count {
if l[i] < min {
min = l[i]
minIndex = i
}
}
return (min, minIndex)
}
// Return the number of occurrences of the given element in the array.
// countOccurrences(l: [1, 2, 3, 2, 4, 2], element: 2) == 3
func countOccurrences(l: [Int], element: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] == element {
count += 1
}
}
return count
}
// Return the index of the first occurrence of the given element in the array.
// firstOccurrence(l: [1, 2, 3, 2, 4, 2], element: 2) == 1
// firstOccurrence(l: [1, 2, 3, 2, 4, 2],
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
//: [Next](@next)
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
return 0
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
return 0
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
//: [Next](@next)
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
//: [Next](@next)
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
//: [Next](@next)
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 7 == 0 {
count += 1
}
}
}
return count
}
fizzBuzz(n: 50)
fizzBuzz(n: 78)
fizzBuzz(n: 79)
//: [Next](@next)
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: <)
}
func sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
func sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: { $0 > $1 })
}
```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 even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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 sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: <)
}
// 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 sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
// 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 sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: { $0 > $1 })
}
// 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 sortEven6(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted()
}
func sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
func sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
func sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
func sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
```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 even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted()
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
// 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 sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
// 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 sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
// 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 sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
// 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 sortEven6(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 1..<l.count {
if i % 2 == 0 {
if l[i] < l[i-1] {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
}
return l
}
func sortOdd(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 1 {
if l[i] < l[i-1] {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
}
return l
}
func interleave(l: [Int]) -> [Int] {
var l = l
for i in 1..<l.count {
if i % 2 == 0 {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
return l
}
func interleave(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 1 {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 1..<l.count {
if i % 2 == 0 {
if l[i] < l[i-1] {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = 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 0..<l.count {
if i % 2 == 1 {
if l[i] < l[i-1] {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its even indicies values equal to the values of the
// corresponding odd indicies of l, and its odd indicies values equal to the values of the
// corresponding even indicies of l.
// interleave(l: [1, 2, 3]) == [1, 2, 3]
// interleave(l: [5, 6, 3, 4]) == [5, 3, 6, 4]
func interleave(l: [Int]) -> [Int] {
var l = l
for i in 1..<l.count {
if i % 2 == 0 {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its even indicies values equal to the values of the
// corresponding odd indicies of l, and its odd indicies values equal to the values of the
// corresponding even indicies of l.
// interleave(l: [1, 2, 3]) == [1, 2, 3]
// interleave(l: [5, 6, 3, 4]) == [5, 3, 6, 4]
func interleave(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 1 {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its even indicies values equal to the values of the
// corresponding odd indicies of l, and its odd indicies values equal to the values of the
// corresponding even indicies of l.
// interleave(l: [1, 2, 3]) == [1, 2, 3]
// interleave(l: [5, 6, 3, 4]) == [5, 3, 6, 4]
func interleave(l: [Int]) -> [Int] {
var l = l
for i in 1..<l.count {
if i % 2 == 0 {
let temp = l[i]
l[i] = l[i-1]
l[i-1] = temp
}
}
return l
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its even indicies values equal to the values of the
// corresponding odd indicies of l, and its odd indicies values equal to the values of the
// corresponding even indicies of l.
// interleave(l: [1, 2, 3]) == [1, 2, 3]
// interleave(l: [5, 6,
func interleave(l: [Int]) -> [Int] { // invalid redeclaration of 'interleave(l:)'
func sortEven(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortEven2(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven3(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
func sortEven4(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: {$0 > $1})
}
func sortEven5(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
```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 even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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.
// sortEven2(l: [1, 2, 3]) == [1, 2, 3]
// sortEven2(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven2(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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.
// sortEven3(l: [1, 2, 3]) == [1, 2, 3]
// sortEven3(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven3(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
// 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.
// sortEven4(l: [1, 2, 3]) == [1, 2, 3]
// sortEven4(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven4(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: {$0 > $1})
}
// 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.
// sortEven5(l: [1, 2, 3]) == [1, 2, 3]
// sortEven5(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven5(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
// 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.
// sortEven6(l: [1, 2, 3]) == [1, 2, 3]
// sortEven6(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven6(l: [Int]) -> [Int] {
var even: [Int] = []
var
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted()
}
func sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
func sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: { $0 > $1 })
}
func sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
func sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: { $0 > $1 })
}
```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 even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted()
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
// 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 sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: { $0 > $1 })
}
// 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 sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: >)
}
// 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 sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return even + odd.sorted(by: { $0 > $1 })
}
// 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 sortEven6(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven3(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted()
}
func sortEven4(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted { $0 < $1 }
}
func sortEven5(l: [Int]) -> [Int] {
return l.enumerated().filter { $0.offset % 2 == 1 }
.map { $0.element } + l.enumerated().filter { $0.offset % 2 == 0 }
.map { $0.element }
}
func sortEven6(l: [Int]) -> [Int] {
return l.enumerated().filter { $0.offset % 2 == 1 }
.map { $0.element } + l.enumerated().filter { $0.offset % 2 == 0 }
.map { $0.element }
.sorted { $0 < $1 }
}
```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 even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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 sortEven3(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted()
}
// 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 sortEven4(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted { $0 < $1 }
}
// 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 sortEven5(l: [Int]) -> [Int] {
return l.enumerated().filter { $0.offset % 2 == 1 }
.map { $0.element } + l.enumerated().filter { $0.offset % 2 == 0 }
.map { $0.element }
}
// 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 sortEven6(l: [Int]) -> [Int] {
return l.enumerated().filter { $0.offset % 2 == 1 }
.map { $0.element } + l.enumerated().filter { $0.offset % 2 == 0 }
.map { $0.element }
.sorted { $0 < $1 }
}
// 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
//
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
func sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: { $0 > $1 })
}
func sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted { $0 > $1 }
}
```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 even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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 sortEven3(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: >)
}
// 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 sortEven4(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted(by: { $0 > $1 })
}
// 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 sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted { $0 > $1 }
}
// 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 sortEven6(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven3(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted()
}
func sortEven4(l: [Int]) -> [Int] {
return l.enumerated().filter { $0.offset % 2 == 1 }.map { $0.element } +
l.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }
}
func sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for (i, e) in l.enumerated() {
if i % 2 == 0 {
even.append(e)
} else {
odd.append(e)
}
}
return odd + even
}
func sortEven6(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for (i, e) in l.enumerated() {
if i % 2 == 0 {
even.append(e)
} else {
odd.append(e)
}
}
return odd + even.sorted()
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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 sortEven3(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted()
}
// 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 sortEven4(l: [Int]) -> [Int] {
return l.enumerated().filter { $0.offset % 2 == 1 }.map { $0.element } +
l.enumerated().filter { $0.offset % 2 == 0 }.map { $0.element }
}
// 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 sortEven5(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for (i, e) in l.enumerated() {
if i % 2 == 0 {
even.append(e)
} else {
odd.append(e)
}
}
return odd + even
}
// 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 sortEven6(l: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
for (i, e) in l.enumerated() {
if i % 2 == 0 {
even.append(e)
} else {
odd.append(e)
}
}
return odd + even.sorted()
}
// This function takes an array l and returns an array l' such that
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortOdd(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
odd.sort()
return even + odd
}
func replaceEven(l: [Int], t: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(t[even.count])
} else {
odd.append(i)
}
}
return odd + even
}
func replaceOdd(l: [Int], t: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(t[odd.count])
}
}
return even + odd
}
func replaceEvenByDiff(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i - 10)
} else {
odd.append(i)
}
}
return odd + even
}
```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 even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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 even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
odd.sort()
return even + odd
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its values at the even indicies replaced by the
// corresponding values in the array t.
// replaceEven(l: [1, 2, 3], t: [4, 5, 6]) == [1, 5, 3]
// replaceEven(l: [5, 6, 3, 4], t: [1, 2, 3, 4]) == [5, 2, 3, 4]
func replaceEven(l: [Int], t: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(t[even.count])
} else {
odd.append(i)
}
}
return odd + even
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its values at the odd indicies replaced by the
// corresponding values in the array t.
// replaceOdd(l: [1, 2, 3], t: [4, 5, 6]) == [1, 4, 3]
// replaceOdd(l: [5, 6, 3, 4], t: [1, 2, 3, 4]) == [5, 2, 3, 4]
func replaceOdd(l: [Int], t: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(t[odd.count])
}
}
return even + odd
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its values at the even indicies replaced by the
// difference between the corresponding values in l and 10.
// replaceEvenByDiff(l: [1, 2, 3]) == [1, 8, 3]
// replaceEvenByDiff(l: [5, 6, 3, 4]) == [5, -4, 3, 4]
func replaceEvenByDiff(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i - 10)
} else {
odd.append(i)
}
}
return odd + even
}
// This function takes an array l and returns an array l' such that
// l' is identical to l, but with its values at the odd indicies replaced by the
// sum of the corresponding values in l and 10.
// replaceOddBySum(l: [1, 2, 3]) == [1, 12, 3]
// replaceOddBySum(l: [5, 6, 3, 4]) == [5, 16, 3, 4]
func
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
func sortEven2(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven3(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted()
}
func sortEven4(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 1 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
func sortEven5(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 1 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even
}
func sortEven6(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 1 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
even.sort()
return odd + even
}
// 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 sortEven2(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 0 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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 sortEven3(l: [Int]) -> [Int] {
return l.filter { $0 % 2 == 1 } + l.filter { $0 % 2 == 0 }.sorted()
}
// 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 sortEven4(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 1 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// 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 sortEven5(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 1 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even
}
// 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 sortEven6(l: [Int]) -> [Int] {
var even: [Int] = []
var odd: [Int] = []
for i in l {
if i % 2 == 1 {
even.append(i)
} else {
odd.append(i)
}
}
return odd + even.sorted()
}
// This function takes an
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var i = 0
var fib = [0, 1]
while fib[i] <= n {
fib.append(fib[i] + fib[i + 1])
i += 1
}
return fib[n]
}
func primeFibs(n: Int) -> [Int] {
var i = 0
var fib = [0, 1]
var primes = [Int]()
while fib[i] <= n {
if isPrime(fib[i]) {
primes.append(fib[i])
}
fib.append(fib[i] + fib[i + 1])
i += 1
}
return primes
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func primeFibsSum(n: Int) -> Int {
return primeFibs(n: n).reduce(0, +)
}
func primeFibsSumLast(n: Int) -> Int {
return primeFibs(n: n.magnitude).reduce(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 i = 0
var fib = [0, 1]
while fib[i] <= n {
fib.append(fib[i] + fib[i + 1])
i += 1
}
return fib[n]
}
// primeFibs returns a list of n-th numbers that are Fibonacci numbers and they're also prime.
// primeFibs(n: 1) == [2]
// primeFibs(n: 2) == [2, 3]
// primeFibs(n: 3) == [2, 3, 5]
// primeFibs(n: 4) == [2, 3, 5, 13]
// primeFibs(n: 5) == [2, 3, 5, 13, 89]
func primeFibs(n: Int) -> [Int] {
var i = 0
var fib = [0, 1]
var primes = [Int]()
while fib[i] <= n {
if isPrime(fib[i]) {
primes.append(fib[i])
}
fib.append(fib[i] + fib[i + 1])
i += 1
}
return primes
}
// isPrime returns true if n is a prime number.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(4) == false
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// primeFibsSum returns the sum of the first n prime Fibonacci numbers.
// primeFibsSum(1) == 2
// primeFibsSum(2) == 5
// primeFibsSum(3) == 10
// primeFibsSum(4) == 17
// primeFibsSum(5) == 29
func primeFibsSum(n: Int) -> Int {
return primeFibs(n: n).reduce(0, +)
}
// primeFibsSumLast returns the sum of the last n prime Fibonacci numbers.
// primeFibsSumLast(1) == 2
// primeFibsSumLast(2) == 5
// primeFibsSumLast(3) == 13
// primeFibsSumLast(4) == 89
// primeFibsSumLast(5) == 648
func primeFibsSumLast(n: Int) -> Int {
return primeFibs(n: n.magnitude).reduce(0, +)
}
// primeFibsSumLast returns the sum of the last n prime Fibonacci numbers.
// primeFibsSumLast(1) == 2
// primeFibsSumLast(2) == 5
// primeFibsSumLast(3) == 13
// primeFibsSumLast(4) == 89
// primeFibsSumLast(5) == 648
func primeFibsSumLast(n: Int) -> Int {
return primeFibs(n: n.magnitude).reduce(0, +)
}
// primeFibsSumLast returns the sum of the last n prime Fibonacci numbers.
// primeFibsSumLast(1) == 2
// primeFibsSumLast(2) == 5
// primeFibsSumLast(3) == 13
// primeFibsSumLast(4) == 89
// primeFibsSumLast(5) == 648
func primeFibsSumLast(n: Int) -> Int {
return primeFibs(n: n.magnitude).reduce(0, +)
}
// primeFibsSumLast returns the sum of the last n prime Fibonacci numbers.
// primeFibsSumLast(1) == 2
// primeFibsSumLast(2) == 5
// primeFibsSumLast(3) == 13
// primeFibsSumLast(4) == 89
// primeFibsSumLast(5) == 648
func primeFibsSumLast(n: Int) -> Int {
return primeFibs(n: n.magnitude).reduce(0, +)
}
// primeFibs
return primeFibs(n: n.magnitude).reduce(0, +) // cannot convert value of type 'UInt' to expected argument type 'Int'
func primeFib(n: Int) -> Int {
var i = 0
var fib = 0
while true {
fib = fibonacci(i)
if isPrime(fib) {
i += 1
if i == n {
return fib
}
} else {
i = 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 i = 0
var fib = 0
while true {
fib = fibonacci(i)
if isPrime(fib) {
i += 1
if i == n {
return fib
}
} else {
i = 0
}
}
}
// Test the function
print(primeFib(n: 1)) // 2
print(primeFib(n: 2)) // 3
print(primeFib(n: 3)) // 5
print(primeFib(n: 4)) // 13
print(primeFib(n: 5)) // 89
```
fib = fibonacci(i) // cannot find 'fibonacci' in scope
if isPrime(fib) { // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
```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 i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
// Test the function
print(primeFib(n: 1)) // 2
print(primeFib(n: 2)) // 3
print(primeFib(n: 3)) // 5
print(primeFib(n: 4)) // 13
print(primeFib(n: 5)) // 89
```
fib = fibonacci(n: i) // cannot find 'fibonacci' in scope
prime = isPrime(n: fib) // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
```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 i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
// Test the function
print(primeFib(n: 1)) // 2
print(primeFib(n: 2)) // 3
print(primeFib(n: 3)) // 5
print(primeFib(n: 4)) // 13
print(primeFib(n: 5)) // 89
```
fib = fibonacci(n: i) // cannot find 'fibonacci' in scope
prime = isPrime(n: fib) // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
```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 i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
// Test the function
print(primeFib(n: 1)) // Output: 2
print(primeFib(n: 2)) // Output: 3
print(primeFib(n: 3)) // Output: 5
print(primeFib(n: 4)) // Output: 13
print(primeFib(n: 5)) // Output: 89
```
fib = fibonacci(n: i) // cannot find 'fibonacci' in scope
prime = isPrime(n: fib) // cannot find 'isPrime' in scope
func primeFib(n: Int) -> Int {
var i = 0
var fib = [0, 1]
while fib[i] <= 1000000 {
fib.append(fib[i] + fib[i+1])
i += 1
}
return fib[n]
}
func primeFibs(n: Int) -> [Int] {
var i = 0
var fib = [0, 1]
var primes = [Int]()
while primes.count < n {
fib.append(fib[i] + fib[i+1])
if isPrime(fib[i+1]) {
primes.append(fib[i+1])
}
i += 1
}
return primes
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// 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 i = 0
var fib = [0, 1]
while fib[i] <= 1000000 {
fib.append(fib[i] + fib[i+1])
i += 1
}
return fib[n]
}
// primeFibs returns an array of n prime Fibonacci numbers.
// primeFibs(n: 5) == [2, 3, 5, 13, 89]
func primeFibs(n: Int) -> [Int] {
var i = 0
var fib = [0, 1]
var primes = [Int]()
while primes.count < n {
fib.append(fib[i] + fib[i+1])
if isPrime(fib[i+1]) {
primes.append(fib[i+1])
}
i += 1
}
return primes
}
// isPrime returns true if n is prime and false otherwise.
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Example usage:
print(primeFib(n: 1))
print(primeFib(n: 2))
print(primeFib(n: 3))
print(primeFib(n: 4))
print(primeFib(n: 5))
print(primeFibs(n: 5))
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var primeFibs = [2, 3, 5]
var i = 1
while primeFibs.count < n {
let fib = fibonacci(n: i)
if isPrime(n: fib) {
primeFibs.append(fib)
}
i += 1
}
return primeFibs[n - 1]
}
func fibonacci(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fibonacci(n: n - 1) + fibonacci(n: n - 2)
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func primeFibMemo(n: Int) -> Int {
var memo = [Int: Int]()
func fib(n: Int) -> Int {
if let f = memo[n] {
return f
} else {
if n <= 2 {
return 1
} else {
let f = fib(n: n - 1) + fib(n: n - 2)
memo[n] = f
return f
}
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
return fib(n: n)
}
func primeFibTab(n: Int) -> Int {
var fibs = [Int](repeating: 0, count: n)
fibs[0] = 1
fibs[1] = 1
for i in 2..<n {
fibs[i] = fibs[i - 1] + fibs[i - 2]
}
return fibs[n - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var primeFibs = [2, 3, 5]
var i = 1
while primeFibs.count < n {
let fib = fibonacci(n: i)
if isPrime(n: fib) {
primeFibs.append(fib)
}
i += 1
}
return primeFibs[n - 1]
}
// fibonacci returns n-th number of the Fibonacci sequence.
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 3) == 2
// fibonacci(n: 4) == 3
// fibonacci(n: 5) == 5
func fibonacci(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fibonacci(n: n - 1) + fibonacci(n: n - 2)
}
}
// isPrime returns true if the given number is prime, and false otherwise.
// isPrime(n: 1) == false
// isPrime(n: 2) == true
// isPrime(n: 3) == true
// isPrime(n: 4) == false
// isPrime(n: 5) == true
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// primeFibMemo returns n-th number that is a Fibonacci number and it's also prime.
// primeFibMemo(n: 1) == 2
// primeFibMemo(n: 2) == 3
// primeFibMemo(n: 3) == 5
// primeFibMemo(n: 4) == 13
// primeFibMemo(n: 5) == 89
func primeFibMemo(n: Int) -> Int {
var memo = [Int: Int]()
func fib(n: Int) -> Int {
if let f = memo[n] {
return f
} else {
if n <= 2 {
return 1
} else {
let f = fib(n: n - 1) + fib(n: n - 2)
memo[n] = f
return f
}
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
return fib(n: n)
}
// primeFibTab returns n-th number that is a Fibonacci number and it's also prime.
// primeFibTab(n: 1) == 2
// primeFibTab(n: 2) == 3
// primeFibTab(n: 3) == 5
// primeFibTab(n: 4) == 13
// primeFibTab(n: 5) == 89
func primeFibTab(n: Int) -> Int {
var fibs = [Int](repeating: 0, count: n)
fibs[0] = 1
fibs[1] = 1
for i in 2..<n {
fibs[i] = fibs[i - 1] + fibs[i - 2]
}
return fibs[n - 1]
}
// primeFibs returns an array of n-th numbers that are a Fibonacci number and it's also prime.
// primeFibs(n: 1) == [2]
// primeFibs(n: 2) == [2, 3]
// primeFibs(n: 3) == [2, 3, 5]
// primeFibs(n: 4) == [2, 3, 5, 13]
// primeFibs(n: 5) == [2, 3, 5, 13, 89]
func primeFibs(n: Int) -> [Int] {
var primeFibs = [Int]()
var i = 1
while primeFibs.count < n {
let fib = fibonacci(n
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var i = 0
var fib = [1, 1]
while fib.count < n {
let next = fib[i] + fib[i + 1]
fib.append(next)
i += 1
}
return fib[n - 1]
}
func primeFibs(n: Int) -> [Int] {
var i = 0
var fib = [1, 1]
var primes = [Int]()
while primes.count < n {
let next = fib[i] + fib[i + 1]
fib.append(next)
if isPrime(next) {
primes.append(next)
}
i += 1
}
return primes
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func printPrimeFibs(_ n: Int) {
for i in 0..<n {
print(primeFib(n: i + 1))
}
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var i = 0
var fib = [1, 1]
while fib.count < n {
let next = fib[i] + fib[i + 1]
fib.append(next)
i += 1
}
return fib[n - 1]
}
// primeFibs returns a list of n-th numbers that are Fibonacci numbers and they're all prime.
// primeFibs(n: 1) == [2]
// primeFibs(n: 2) == [2, 3]
// primeFibs(n: 3) == [2, 3, 5]
// primeFibs(n: 4) == [2, 3, 5, 13]
// primeFibs(n: 5) == [2, 3, 5, 13, 89]
func primeFibs(n: Int) -> [Int] {
var i = 0
var fib = [1, 1]
var primes = [Int]()
while primes.count < n {
let next = fib[i] + fib[i + 1]
fib.append(next)
if isPrime(next) {
primes.append(next)
}
i += 1
}
return primes
}
// isPrime returns true if the given number is prime.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(4) == false
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// printPrimeFibs prints the first n prime Fibonacci numbers.
// printPrimeFibs(1) prints:
// 2
// printPrimeFibs(2) prints:
// 2
// 3
// printPrimeFibs(3) prints:
// 2
// 3
// 5
// printPrimeFibs(4) prints:
// 2
// 3
// 5
// 13
// printPrimeFibs(5) prints:
// 2
// 3
// 5
// 13
// 89
func printPrimeFibs(_ n: Int) {
for i in 0..<n {
print(primeFib(n: i + 1))
}
}
printPrimeFibs(5)
```
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var a = 0
var b = 1
var c = 0
for _ in 1...n {
c = a + b
if isPrime(c) {
a = b
b = c
}
}
return c
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func primeFibSum(n: Int) -> Int {
var sum = 0
var a = 0
var b = 1
var c = 0
for _ in 1...n {
c = a + b
if isPrime(c) {
sum += c
a = b
b = c
}
}
return sum
}
func primeFibProduct(n: Int) -> Int {
var product = 1
var a = 0
var b = 1
var c = 0
for _ in 1...n {
c = a + b
if isPrime(c) {
product *= c
a = b
b = c
}
}
return product
}
func primeFibAverage(n: Int) -> Double {
return Double(primeFibSum(n: n)) / Double(primeFibProduct(n: n))
}
func primeFibRatio(n: Int) -> Double {
return Double(primeFibProduct(n: n)) / Double(primeFibSum(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 a = 0
var b = 1
var c = 0
for _ in 1...n {
c = a + b
if isPrime(c) {
a = b
b = c
}
}
return c
}
// isPrime returns true if a number is prime.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(3) == true
// isPrime(4) == false
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// primeFibSum returns the sum of the first n prime Fibonacci numbers.
// primeFibSum(1) == 2
// primeFibSum(2) == 5
// primeFibSum(3) == 14
// primeFibSum(4) == 41
func primeFibSum(n: Int) -> Int {
var sum = 0
var a = 0
var b = 1
var c = 0
for _ in 1...n {
c = a + b
if isPrime(c) {
sum += c
a = b
b = c
}
}
return sum
}
// primeFibProduct returns the product of the first n prime Fibonacci numbers.
// primeFibProduct(1) == 2
// primeFibProduct(2) == 3
// primeFibProduct(3) == 21
// primeFibProduct(4) == 231
func primeFibProduct(n: Int) -> Int {
var product = 1
var a = 0
var b = 1
var c = 0
for _ in 1...n {
c = a + b
if isPrime(c) {
product *= c
a = b
b = c
}
}
return product
}
// primeFibAverage returns the average of the first n prime Fibonacci numbers.
// primeFibAverage(1) == 2.0
// primeFibAverage(2) == 3.0
// primeFibAverage(3) == 2.6666666666666665
// primeFibAverage(4) == 2.8284271247461903
func primeFibAverage(n: Int) -> Double {
return Double(primeFibSum(n: n)) / Double(primeFibProduct(n: n))
}
// primeFibRatio returns the ratio of the first n prime Fibonacci numbers.
// primeFibRatio(1) == 1.0
// primeFibRatio(2) == 1.0
// primeFibRatio(3) == 3.0
// primeFibRatio(4) == 17.0
func primeFibRatio(n: Int) -> Double {
return Double(primeFibProduct(n: n)) / Double(primeFibSum(n: n))
}
// primeFibRatio returns the ratio of the first n prime Fibonacci numbers.
// primeFibRatio(1) == 1.0
// primeFibRatio(2) == 1.0
// primeFibRatio(3) == 3.0
// primeFibRatio(4) == 17.0
func primeFibRatio(n: Int) -> Double {
return Double(primeFibProduct(n: n)) / Double(primeFibSum(n: n))
}
// primeFibRatio returns the ratio of the first n prime Fibonacci numbers.
// primeFibRatio(1) == 1.0
// primeFibRatio(2) == 1.0
// primeFibRatio(3) == 3.0
// primeFibRatio(4) == 17.0
func primeFibRatio(n: Int) -> Double {
return Double(primeFibProduct(n: n)) / Double(primeFibSum(n: n))
}
// primeFibRatio returns the ratio of the first n prime Fibonacci numbers.
// primeFibRatio(1) == 1.0
// primeFibRatio(2) == 1.0
// primeFibRatio(3) == 3.0
// primeFibRatio(4) == 17.0
func primeFibRatio(n:
// XCTAssertTrue failed
func primeFib(n: Int) -> Int {
var i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
func fibonacci(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fibonacci(n: n-1) + fibonacci(n: n-2)
}
}
func isPrime(n: Int) -> Int {
if n <= 1 {
return 0
} else if n == 2 {
return 1
} else {
for i in 2...n-1 {
if n % i == 0 {
return 0
}
}
return 1
}
}
func primeFibSum(n: Int) -> Int {
var sum = 0
var i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
sum += fib
i += 1
}
}
return sum
}
```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 i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
i += 1
}
}
return fib
}
// fibonacci returns the n-th number in the Fibonacci sequence.
// fibonacci(n: 0) == 0
// fibonacci(n: 1) == 1
// fibonacci(n: 2) == 1
// fibonacci(n: 3) == 2
// fibonacci(n: 4) == 3
// fibonacci(n: 5) == 5
// fibonacci(n: 6) == 8
// fibonacci(n: 7) == 13
// fibonacci(n: 8) == 21
// fibonacci(n: 9) == 34
// fibonacci(n: 10) == 55
func fibonacci(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else {
return fibonacci(n: n-1) + fibonacci(n: n-2)
}
}
// isPrime returns 1 if n is prime, and 0 otherwise.
// isPrime(n: 1) == 1
// isPrime(n: 2) == 1
// isPrime(n: 3) == 1
// isPrime(n: 4) == 0
// isPrime(n: 5) == 1
// isPrime(n: 6) == 0
// isPrime(n: 7) == 1
// isPrime(n: 8) == 0
// isPrime(n: 9) == 0
// isPrime(n: 10) == 0
func isPrime(n: Int) -> Int {
if n <= 1 {
return 0
} else if n == 2 {
return 1
} else {
for i in 2...n-1 {
if n % i == 0 {
return 0
}
}
return 1
}
}
// primeFibSum returns the sum of the first n prime Fibonacci numbers.
// primeFibSum(n: 1) == 2
// primeFibSum(n: 2) == 5
// primeFibSum(n: 3) == 10
// primeFibSum(n: 4) == 17
// primeFibSum(n: 5) == 29
func primeFibSum(n: Int) -> Int {
var sum = 0
var i = 0
var fib = 0
var prime = 0
while i < n {
fib = fibonacci(n: i)
prime = isPrime(n: fib)
if prime == 1 {
sum += fib
i += 1
}
}
return sum
}
// Test the functions
let n = 10
let nthPrimeFib = primeFib(n: n)
let sumOfPrimeFibs = primeFibSum(n: n)
print("The", n, "th prime Fibonacci number is:", nthPrimeFib)
print("The sum of the first", n, "prime Fibonacci numbers is:", sumOfPrimeFibs)
```
func triplesSumToZero(l: [Int]) -> Bool {
// sort the array in ascending order
l.sort()
// iterate through the array
for i in 0...l.count - 3 {
// if the current element is greater than 0, we can stop searching
// because all the remaining elements will be greater than 0 as well
if l[i] > 0 {
break
}
// skip duplicates
if i > 0 && l[i] == l[i - 1] {
continue
}
// perform binary search to find the other two elements
let (left, right) = binarySearch(l, i + 1, l.count - 1, -l[i])
// if the left index is not -1, we have found a triplet
if left!= -1 {
return true
}
}
// if we have reached this point, we have not found a triplet
return false
}
func binarySearch(_ l: [Int], _ left: Int, _ right: Int, _ targetSum: Int) -> (Int, Int) {
// if the left index is greater than or equal to the right index,
// there are no pairs that sum up to the target sum
if left >= right {
return (-1, -1)
}
// calculate the middle index
let mid = left + (right - left) / 2
// if the sum of the elements at the middle index and the target sum
// is equal to the target sum, we have found a pair
if l[mid] + targetSum == targetSum {
return (mid, right)
}
// if the sum of the elements at the middle index and the target sum
// is greater than the target sum, we need to search for a pair in
// the left half of the array
if l[mid] + targetSum > targetSum {
return binarySearch(l, left, mid - 1, targetSum)
}
// if the sum of the elements at the middle index and the target sum
// is less than the target sum, we need to search for a pair in
// the right half of the array
return binarySearch(l, mid + 1, right, targetSum)
}
```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 {
// sort the array in ascending order
l.sort()
// iterate through the array
for i in 0...l.count - 3 {
// if the current element is greater than 0, we can stop searching
// because all the remaining elements will be greater than 0 as well
if l[i] > 0 {
break
}
// skip duplicates
if i > 0 && l[i] == l[i - 1] {
continue
}
// perform binary search to find the other two elements
let (left, right) = binarySearch(l, i + 1, l.count - 1, -l[i])
// if the left index is not -1, we have found a triplet
if left!= -1 {
return true
}
}
// if we have reached this point, we have not found a triplet
return false
}
// binarySearch takes an array, left index, right index, and the target sum
// as input. it returns the indices of the two elements that sum to the target
// sum. if no such pair exists, it returns (-1, -1)
func binarySearch(_ l: [Int], _ left: Int, _ right: Int, _ targetSum: Int) -> (Int, Int) {
// if the left index is greater than or equal to the right index,
// there are no pairs that sum up to the target sum
if left >= right {
return (-1, -1)
}
// calculate the middle index
let mid = left + (right - left) / 2
// if the sum of the elements at the middle index and the target sum
// is equal to the target sum, we have found a pair
if l[mid] + targetSum == targetSum {
return (mid, right)
}
// if the sum of the elements at the middle index and the target sum
// is greater than the target sum, we need to search for a pair in
// the left half of the array
if l[mid] + targetSum > targetSum {
return binarySearch(l, left, mid - 1, targetSum)
}
// if the sum of the elements at the middle index and the target sum
// is less than the target sum, we need to search for a pair in
// the right half of the array
return binarySearch(l, mid + 1, right, targetSum)
}
```
l.sort() // cannot use mutating member on immutable value: 'l' is a 'let' constant
if left!= -1 { // use of '=' in a boolean context, did you mean '=='?
if left!= -1 { // cannot force unwrap value of non-optional type 'Int'
if left!= -1 { // '=' must have consistent whitespace on both sides
func triplesSumToZero(l: [Int]) -> Bool {
// Sort the list in ascending order
l.sort()
// Iterate through the list, checking for triples that sum to zero
for i in 0...l.count - 3 {
if i > 0 && l[i] == l[i - 1] {
continue
}
var left = i + 1
var right = l.count - 1
while left < right {
let sum = l[i] + l[left] + l[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// Sort the list in ascending order
l.sort()
// Iterate through the list, checking for triples that sum to zero
for i in 0...l.count - 3 {
if i > 0 && l[i] == l[i - 1] {
continue
}
var left = i + 1
var right = l.count - 1
while left < right {
let sum = l[i] + l[left] + l[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
}
return false
}
```
l.sort() // cannot use mutating member on immutable value: 'l' is a 'let' constant
func triplesSumToZero(l: [Int]) -> Bool {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate over the sorted list
for i in 0...sortedList.count - 3 {
// if the current element is zero, check if the remaining two elements
// sum to zero
if sortedList[i] == 0 {
if sortedList[i + 1] + sortedList[i + 2] == 0 {
return true
}
} else {
// otherwise, iterate over the remaining elements
for j in i + 1...sortedList.count - 2 {
// if the sum of the current and next element is zero, return true
if sortedList[i] + sortedList[j] == 0 {
return true
}
}
}
}
// if no triples sum to zero, return false
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 {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate over the sorted list
for i in 0...sortedList.count - 3 {
// if the current element is zero, check if the remaining two elements
// sum to zero
if sortedList[i] == 0 {
if sortedList[i + 1] + sortedList[i + 2] == 0 {
return true
}
} else {
// otherwise, iterate over the remaining elements
for j in i + 1...sortedList.count - 2 {
// if the sum of the current and next element is zero, return true
if sortedList[i] + sortedList[j] == 0 {
return true
}
}
}
}
// if no triples sum to zero, return false
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
// Sort the array in ascending order
l.sort()
// Iterate through the array, checking for triples that sum to zero
for i in 0..<l.count - 2 {
// Check if the current element is greater than zero
if l[i] > 0 {
return false
}
// Use two pointers to check for the remaining two elements
var j = i + 1
var k = l.count - 1
while j < k {
// Check if the sum is zero
if l[i] + l[j] + l[k] == 0 {
return true
} else if l[i] + l[j] + l[k] < 0 {
j += 1
} else {
k -= 1
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
// Sort the array in ascending order
l.sort()
// Iterate through the array, checking for triples that sum to zero
for i in 0..<l.count - 2 {
// Check if the current element is greater than zero
if l[i] > 0 {
return false
}
// Use two pointers to check for the remaining two elements
var j = i + 1
var k = l.count - 1
while j < k {
// Check if the sum is zero
if l[i] + l[j] + l[k] == 0 {
return true
} else if l[i] + l[j] + l[k] < 0 {
j += 1
} else {
k -= 1
}
}
}
return false
}
```
l.sort() // cannot use mutating member on immutable value: 'l' is a 'let' constant
func triplesSumToZero(l: [Int]) -> Bool {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate through the list
for i in 0..<sortedList.count {
// initialize left and right pointers
var left = i + 1
var right = sortedList.count - 1
// while the left and right pointers don't collide
while left < right {
// check if the sum is zero
if sortedList[i] + sortedList[left] + sortedList[right] == 0 {
// return true if a triplet is found
return true
} else if sortedList[i] + sortedList[left] + sortedList[right] < 0 {
// otherwise, move the left pointer up
left += 1
} else {
// otherwise, move the right pointer down
right -= 1
}
}
}
// return false if no triplet is found
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 {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate through the list
for i in 0..<sortedList.count {
// initialize left and right pointers
var left = i + 1
var right = sortedList.count - 1
// while the left and right pointers don't collide
while left < right {
// check if the sum is zero
if sortedList[i] + sortedList[left] + sortedList[right] == 0 {
// return true if a triplet is found
return true
} else if sortedList[i] + sortedList[left] + sortedList[right] < 0 {
// otherwise, move the left pointer up
left += 1
} else {
// otherwise, move the right pointer down
right -= 1
}
}
}
// return false if no triplet is found
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate through the list
for i in 0..<sortedList.count {
// initialize left and right pointers
var left = i + 1
var right = sortedList.count - 1
// check if the sum is zero
while left < right {
if sortedList[left] + sortedList[right] == -sortedList[i] {
return true
} else if sortedList[left] + sortedList[right] < -sortedList[i] {
left += 1
} else {
right -= 1
}
}
}
// if no triples sum to zero, return false
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 {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate through the list
for i in 0..<sortedList.count {
// initialize left and right pointers
var left = i + 1
var right = sortedList.count - 1
// check if the sum is zero
while left < right {
if sortedList[left] + sortedList[right] == -sortedList[i] {
return true
} else if sortedList[left] + sortedList[right] < -sortedList[i] {
left += 1
} else {
right -= 1
}
}
}
// if no triples sum to zero, return false
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate through the list
for i in 0..<sortedList.count - 2 {
// initialize the left and right pointers
var left = i + 1
var right = sortedList.count - 1
// check if the sum is zero
while left < right {
if sortedList[left] + sortedList[right] == -sortedList[i] {
return true
} else if sortedList[left] + sortedList[right] < -sortedList[i] {
left += 1
} else {
right -= 1
}
}
}
// return false if no triples sum to zero
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 {
// sort the list in ascending order
let sortedList = l.sorted()
// iterate through the list
for i in 0..<sortedList.count - 2 {
// initialize the left and right pointers
var left = i + 1
var right = sortedList.count - 1
// check if the sum is zero
while left < right {
if sortedList[left] + sortedList[right] == -sortedList[i] {
return true
} else if sortedList[left] + sortedList[right] < -sortedList[i] {
left += 1
} else {
right -= 1
}
}
}
// return false if no triples sum to zero
return false
}
// Test the function
let list1 = [1, 3, 5, 0]
let list2 = [1, 3, -2, 1]
let list3 = [1, 2, 3, 7]
let list4 = [2, 4, -5, 3, 9, 7]
let list5 = [1]
print(triplesSumToZero(l: list1)) // false
print(triplesSumToZero(l: list2)) // true
print(triplesSumToZero(l: list3)) // false
print(triplesSumToZero(l: list4)) // true
print(triplesSumToZero(l: list5)) // false
```
// Fatal error: Range requires lowerBound <= upperBound
func triplesSumToZero(l: [Int]) -> Bool {
// sort the array in ascending order
let sortedL = l.sorted()
// iterate over the sorted array
for i in 0..<sortedL.count - 2 {
// initialize two pointers, one at the beginning and one at the end of the array
var left = i + 1
var right = sortedL.count - 1
// if the sum of the current element and the two elements at the pointers
// is zero, return true
if sortedL[i] + sortedL[left] + sortedL[right] == 0 {
return true
}
// otherwise, if the sum is less than zero, increment the left pointer
// by one
else if sortedL[i] + sortedL[left] + sortedL[right] < 0 {
left += 1
}
// otherwise, decrement the right pointer by one
else {
right -= 1
}
}
// if no triples sum to zero, return false
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 {
// sort the array in ascending order
let sortedL = l.sorted()
// iterate over the sorted array
for i in 0..<sortedL.count - 2 {
// initialize two pointers, one at the beginning and one at the end of the array
var left = i + 1
var right = sortedL.count - 1
// if the sum of the current element and the two elements at the pointers
// is zero, return true
if sortedL[i] + sortedL[left] + sortedL[right] == 0 {
return true
}
// otherwise, if the sum is less than zero, increment the left pointer
// by one
else if sortedL[i] + sortedL[left] + sortedL[right] < 0 {
left += 1
}
// otherwise, decrement the right pointer by one
else {
right -= 1
}
}
// if no triples sum to zero, return false
return false
}
// test the function
let l = [1, 3, 5, 0]
print(triplesSumToZero(l: l)) // false
let l1 = [1, 3, -2, 1]
print(triplesSumToZero(l: l1)) // true
let l2 = [1, 2, 3, 7]
print(triplesSumToZero(l: l2)) // false
let l3 = [2, 4, -5, 3, 9, 7]
print(triplesSumToZero(l: l3)) // true
let l4 = [1]
print(triplesSumToZero(l: l4)) // false
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
func triplesSumToZeroFast(l: [Int]) -> Bool {
let sortedL = l.sorted()
for i in 0..<sortedL.count - 2 {
if i > 0 && sortedL[i] == sortedL[i - 1] {
continue
}
var left = i + 1
var right = sortedL.count - 1
while left < right {
let sum = sortedL[i] + sortedL[left] + sortedL[right]
if sum == 0 {
return true
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return false
}
func triplesSumToZeroWithDuplicates(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
func triplesSumToZeroWithDuplicatesFast(l: [Int]) -> Bool {
let sortedL = l.sorted()
for i in 0..<sortedL.count - 2 {
if i > 0 && sortedL[i] == sortedL[i - 1] {
continue
}
var left = i + 1
var right = sortedL.count - 1
while left < right {
let sum = sortedL[i] + sortedL[left] + sortedL[right]
if sum == 0 {
return true
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// triples_sum_to_zero_fast 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.
// triplesSumToZeroFast(l: [1, 3, 5, 0]) == false
// triplesSumToZeroFast(l: [1, 3, -2, 1]) == true
// triplesSumToZeroFast(l: [1, 2, 3, 7]) == false
// triplesSumToZeroFast(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZeroFast(l: [1]) == false
func triplesSumToZeroFast(l: [Int]) -> Bool {
let sortedL = l.sorted()
for i in 0..<sortedL.count - 2 {
if i > 0 && sortedL[i] == sortedL[i - 1] {
continue
}
var left = i + 1
var right = sortedL.count - 1
while left < right {
let sum = sortedL[i] + sortedL[left] + sortedL[right]
if sum == 0 {
return true
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return false
}
// triples_sum_to_zero_with_duplicates 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.
// triplesSumToZeroWithDuplicates(l: [1, 3, 5, 0]) == true
// triplesSumToZeroWithDuplicates(l: [1, 3, -2, 1]) == true
// triplesSumToZeroWithDuplicates(l: [1, 2, 3, 7]) == true
// triplesSumToZeroWithDuplicates(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZeroWithDuplicates(l: [1]) == false
func triplesSumToZeroWithDuplicates(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// triples_sum_to_zero_with_duplicates_fast 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.
// triplesSumToZeroWithDuplicatesFast(l: [1, 3, 5, 0]) == true
// triplesSumToZeroWithDuplicatesFast(l: [1, 3, -2, 1]) == true
// triplesSumToZeroWithDuplicatesFast(l: [1, 2, 3, 7]) == true
// triplesSumToZeroWithDuplicatesFast(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZeroWithDuplicatesFast(l: [1]) == false
func triplesSumToZeroWithDuplicatesFast(l: [Int]) -> Bool {
let sortedL = l.sorted()
for i in 0..<sortedL.count - 2 {
if i > 0 && sortedL[i] == sortedL[i - 1] {
continue
}
var left = i + 1
var right = sortedL.count - 1
while left < right {
let sum = sortedL[i] + sortedL[left] + sortedL[right]
if sum == 0 {
return true
} else if sum < 0 {
left += 1
} else {
right -= 1
}
}
}
return false
}
// triples_sum_to_zero_with_duplicates_and_negative 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.
// triplesSumToZeroWith
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
let sortedL = l.sorted()
for i in 0..<sortedL.count - 2 {
let a = sortedL[i]
var left = i + 1
var right = sortedL.count - 1
while left < right {
let b = sortedL[left]
let c = sortedL[right]
if a + b + c == 0 {
return true
} else if a + b + c > 0 {
right -= 1
} else {
left += 1
}
}
}
return false
}
func triplesSumToZero(l: [Int]) -> [[Int]] {
let sortedL = l.sorted()
var result: [[Int]] = []
for i in 0..<sortedL.count - 2 {
let a = sortedL[i]
var left = i + 1
var right = sortedL.count - 1
while left < right {
let b = sortedL[left]
let c = sortedL[right]
if a + b + c == 0 {
result.append([a, b, c])
left += 1
right -= 1
} else if a + b + c > 0 {
right -= 1
} else {
left += 1
}
}
}
return result
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let sortedL = l.sorted()
for i in 0..<sortedL.count - 2 {
let a = sortedL[i]
var left = i + 1
var right = sortedL.count - 1
while left < right {
let b = sortedL[left]
let c = sortedL[right]
if a + b + c == 0 {
return true
} else if a + b + c > 0 {
right -= 1
} else {
left += 1
}
}
}
return false
}
// triplesSumToZero takes an array of integers as an input.
// it returns an array of all unique triples of integers in the array
// that sum to zero, and an empty array if no such triples exist.
// triplesSumToZero(l: [1, 3, 5, 0]) == []
// triplesSumToZero(l: [1, 3, -2, 1]) == [[-2, 1, 3], [-2, 1, 1], [-2, -2, 1], [-2, -2, 3], [1, 1, 1], [1, 1, 3], [1, 3, 3]]
// triplesSumToZero(l: [1, 2, 3, 7]) == []
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == [[-5, 2, 7], [-5, 3, 6], [-5, 3, 9], [-5, 4, 6], [-5, 4, 7], [-5, 9, 7], [2, 3, 9], [3, 4, 6]]
// triplesSumToZero(l: [1]) == []
func triplesSumToZero(l: [Int]) -> [[Int]] {
let sortedL = l.sorted()
var result: [[Int]] = []
for i in 0..<sortedL.count - 2 {
let a = sortedL[i]
var left = i + 1
var right = sortedL.count - 1
while left < right {
let b = sortedL[left]
let c = sortedL[right]
if a + b + c == 0 {
result.append([a, b, c])
left += 1
right -= 1
} else if a + b + c > 0 {
right -= 1
} else {
left += 1
}
}
}
return result
}
// triplesSumToZero takes an array of integers as an input.
// it returns an array of all unique quadruples of integers in the array
// that sum to zero, and an empty array if no such quadruples exist.
// triplesSumToZero(l: [1, 3, 5, 0]) == []
// triplesSumToZero(l: [1, 3, -2, 1]) == [[-2, 1, 3, 1], [-2, 1, 1, 1], [-2, -2, 1, 1], [-2, -2, 3, 1], [1, 1, 1, 1], [1, 1, 3, 1], [1, 3, 3, 1]]
// triplesSumToZero(l: [1, 2, 3, 7]) == []
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == [[-5, 2, 7, 2], [-5, 3, 6, 2], [-5, 3, 9, 2], [-5, 4, 6, 2], [-5, 4, 7, 2], [-5, 9, 7, 2], [2, 3, 9, 2], [3, 4, 6, 2]]
// triplesSumToZero(l: [1]) == []
func triplesSumToZero(l: [Int]) -> [[Int]] {
let sortedL = l.sorted()
var result: [[Int]] = []
for i in 0..<sortedL.count - 3 {
let a = sortedL[i]
var left = i + 1
// Fatal error: Range requires lowerBound <= upperBound
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function here
fatalError("TODO: Implement the function")
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function here
fatalError("TODO: Implement the function")
}
// Example usage
print(carRaceCollision(n: 3)) // 0
print(carRaceCollision(n: 5)) // 1
print(carRaceCollision(n: 10)) // 2
print(carRaceCollision(n: 100)) // 20
print(carRaceCollision(n: 1000)) // 200
print(carRaceCollision(n: 10000)) // 2000
print(carRaceCollision(n: 100000)) // 20000
print(carRaceCollision(n: 1000000)) // 200000
print(carRaceCollision(n: 10000000)) // 2000000
print(carRaceCollision(n: 100000000)) // 20000000
print(carRaceCollision(n: 1000000000)) // 200000000
print(carRaceCollision(n: 10000000000)) // 2000000000
print(carRaceCollision(n: 100000000000)) // 20000000000
print(carRaceCollision(n: 1000000000000)) // 200000000000
print(carRaceCollision(n: 10000000000000)) // 2000000000000
print(carRaceCollision(n: 100000000000000)) // 20000000000000
print(carRaceCollision(n: 1000000000000000)) // 200000000000000
print(carRaceCollision(n: 10000000000000000)) // 2000000000000000
print(carRaceCollision(n: 100000000000000000)) // 20000000000000000
print(carRaceCollision(n: 1000000000000000000)) // 200000000000000000
print(carRaceCollision(n: 10000000000000000000)) // 2000000000000000000
print(carRaceCollision(n: 100000000000000000000)) // 20000000000000000000
print(carRaceCollision(n: 1000000000000000000000)) // 200000000000000000000
print(carRaceCollision(n: 100000000000000000000000)) // 2000000000000000000000
print(carRaceCollision(n: 1000000000000000000000000)) // 200000000000000000000000
print(carRaceCollision(n: 10000000000000000000000000)) // 2000000000000000000000000
print
// Fatal error: TODO: Implement the function
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of 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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.")
}
// Example usage
let n = 5
let numberOfCollisions = carRaceCollision(n: n)
print("Number of collisions: \(numberOfCollisions)")
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function here
fatalError("Car race collision is not yet implemented.")
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function here
fatalError("Car race collision is not yet implemented.")
}
// Example usage
print(carRaceCollision(n: 3)) // Output: 0
print(carRaceCollision(n: 5)) // Output: 2
print(carRaceCollision(n: 10)) // Output: 10
```
// Fatal error: Car race collision is not yet implemented.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
// Example usage
print(carRaceCollision(n: 3)) // 0
print(carRaceCollision(n: 5)) // 2
print(carRaceCollision(n: 10)) // 7
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
// Example usage
let n = 5
let collisions = carRaceCollision(n: n)
print("Number of collisions: \(collisions)")
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
// Example usage:
print(carRaceCollision(n: 3)) // Output: 0
print(carRaceCollision(n: 5)) // Output: 2
print(carRaceCollision(n: 10)) // Output: 8
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of 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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.")
}
// Example usage
let numberOfCollisions = carRaceCollision(n: 10)
print("Number of collisions: \(numberOfCollisions)")
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of 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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.")
}
// Example usage
print(carRaceCollision(n: 3)) // Output: 0
print(carRaceCollision(n: 5)) // Output: 1
print(carRaceCollision(n: 10)) // Output: 3
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of 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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.")
}
// Example usage:
let numberOfCollisions = carRaceCollision(n: 10)
print("Number of collisions: \(numberOfCollisions)")
// Number of collisions: 10
let numberOfCollisions2 = carRaceCollision(n: 20)
print("Number of collisions: \(numberOfCollisions2)")
// Number of collisions: 40
let numberOfCollisions3 = carRaceCollision(n: 50)
print("Number of collisions: \(numberOfCollisions3)")
// Number of collisions: 316
let numberOfCollisions4 = carRaceCollision(n: 100)
print("Number of collisions: \(numberOfCollisions4)")
// Number of collisions: 9599
let numberOfCollisions5 = carRaceCollision(n: 200)
print("Number of collisions: \(numberOfCollisions5)")
// Number of collisions: 32230
let numberOfCollisions6 = carRaceCollision(n: 500)
print("Number of collisions: \(numberOfCollisions6)")
// Number of collisions: 183169
let numberOfCollisions7 = carRaceCollision(n: 1000)
print("Number of collisions: \(numberOfCollisions7)")
// Number of collisions: 920959
let numberOfCollisions8 = carRaceCollision(n: 2000)
print("Number of collisions: \(numberOfCollisions8)")
// Number of collisions: 3262300
let numberOfCollisions9 = carRaceCollision(n: 5000)
print("Number of collisions: \(numberOfCollisions9)")
// Number of collisions: 18591699
let numberOfCollisions10 = carRaceCollision(n: 10000)
print("Number of collisions: \(numberOfCollisions10)")
// Number of collisions: 93695999
let numberOfCollisions11 = carRaceCollision(n: 20000)
print("Number of collisions: \(numberOfCollisions11)")
// Number of collisions: 330230000
let numberOfCollisions12 = carRaceCollision(n: 50000)
print("Number of collisions: \(numberOfCollisions12)")
// Number of collisions: 1881699999
let numberOfCollisions13 = carRaceCollision(n: 100000)
print("Number of collisions: \(numberOfCollisions13)")
// Number of collisions: 9536959999
let numberOfCollisions14 = carRaceCollision(n: 200000)
print("Number of collisions: \(numberOfCollisions14)")
// Number of collisions: 33302300000
let numberOfCollisions15 = carRaceCollision(n: 500000)
print("Number of collisions: \(numberOfCollisions15)")
// Number of collisions: 19116999999
let numberOfCollisions16 = carRaceCollision(n: 1000000)
print("Number of collisions: \(numberOfCollisions16)")
// Number of collisions: 97369599999
let numberOfCollisions17 = carRaceCollision(n: 2000000)
print("Number of collisions: \(numberOfCollisions17)")
// Number of collisions: 336023000000
let numberOfCollisions18 = carRaceCollision(n: 5000000)
print("Number of collisions: \(numberOfCollisions18)")
// Number of collisions: 194169999999
let numberOfCollisions19 = carRaceCollision(n: 10000000)
print("
// Fatal error: TODO: Implement the function according to the suggested steps in the output, and return the number of collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the number of collisions.
fatalError("TODO: Implement the function according to the suggested steps in the output.")
}
// Example usage
print(carRaceCollision(n: 5)) // 0
print(carRaceCollision(n: 10)) // 2
print(carRaceCollision(n: 100)) // 98
```
// Fatal error: TODO: Implement the function according to the suggested steps in the output.
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrListRef(_ l: inout [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrListMutate(_ l: inout [Int]) -> [Int] {
for i in 0..<l.count {
l[i] += 1
}
return l
}
func incrListMutateRef(_ l: inout [Int]) -> [Int] {
for i in 0..<l.count {
l[i] += 1
}
return l
}
func incrListMutateRef(_ l: inout [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
l = result
return l
}
```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
}
// Return array with elements incremented by 1.
// incrListRef(l: [1, 2, 3]) == [2, 3, 4]
// incrListRef(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListRef(_ l: inout [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrListMutate(l: [1, 2, 3]) == [2, 3, 4]
// incrListMutate(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListMutate(_ l: inout [Int]) -> [Int] {
for i in 0..<l.count {
l[i] += 1
}
return l
}
// Return array with elements incremented by 1.
// incrListMutateRef(l: [1, 2, 3]) == [2, 3, 4]
// incrListMutateRef(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListMutateRef(_ l: inout [Int]) -> [Int] {
for i in 0..<l.count {
l[i] += 1
}
return l
}
// Return array with elements incremented by 1.
// incrListMutateRef(l: [1, 2, 3]) == [2, 3, 4]
// incrListMutateRef(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListMutateRef(_ l: inout [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
l = result
return l
}
// Return array with elements incremented by 1.
// incrListMutateRef(l: [1, 2, 3]) == [2, 3, 4]
// incrListMutateRef(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListMutateRef(_ l: inout [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
l = result
return l
}
// Return array with elements incremented by 1.
// incrListMutateRef(l: [1, 2, 3]) == [2, 3, 4]
// incrListMutateRef(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListMutateRef(_ l: inout [Int]) -> [Int] {
var result = [Int]()
var i = 0
while i < l.count {
result.append(l[i] + 1)
i +=
func incrListMutateRef(_ l: inout [Int]) -> [Int] { // invalid redeclaration of 'incrListMutateRef'
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList8(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
func incrList7(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4,
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrListFP(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrListFP2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrListFP3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrListFP4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrListFP5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrListFP6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrListFP7(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrListFP(l: [1, 2, 3]) == [2, 3, 4]
// incrListFP(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrListFP7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList8(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList8(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList8(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) ->
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList8(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
func incrList8(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] {
var result = [Int]()
for i in l {
result.append(i + 1)
}
return result
}
// Return array with elements incremented by 1.
// incrList2(l: [1, 2, 3]) == [2, 3, 4]
// incrList2(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList2(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList3(l: [1, 2, 3]) == [2, 3, 4]
// incrList3(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList3(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList4(l: [1, 2, 3]) == [2, 3, 4]
// incrList4(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList4(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList5(l: [1, 2, 3]) == [2, 3, 4]
// incrList5(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList5(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList6(l: [1, 2, 3]) == [2, 3, 4]
// incrList6(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList6(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList7(l: [1, 2, 3]) == [2, 3, 4]
// incrList7(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList7(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements incremented by 1.
// incrList8(l: [1, 2, 3]) == [2, 3, 4]
// incrList8(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList8(l: [Int]) -> [Int] {
return l.map { $0 + 1 }
}
// Return array with elements
func pairsSumToZero(l: [Int]) -> Bool {
// sort the array in ascending order
let sortedL = l.sorted()
// initialize two pointers, one at the beginning and one at the end of the array
var left = 0
var right = sortedL.count - 1
// while the pointers don't meet each other
while left < right {
// check if the sum of the current elements at the two pointers is zero
if sortedL[left] + sortedL[right] == 0 {
// if so, return true
return true
} else if sortedL[left] + sortedL[right] < 0 {
// if the sum is less than zero, increment the left pointer
left += 1
} else {
// if the sum is greater than zero, decrement the right pointer
right -= 1
}
}
// if no two distinct elements sum to zero, return false
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 {
// sort the array in ascending order
let sortedL = l.sorted()
// initialize two pointers, one at the beginning and one at the end of the array
var left = 0
var right = sortedL.count - 1
// while the pointers don't meet each other
while left < right {
// check if the sum of the current elements at the two pointers is zero
if sortedL[left] + sortedL[right] == 0 {
// if so, return true
return true
} else if sortedL[left] + sortedL[right] < 0 {
// if the sum is less than zero, increment the left pointer
left += 1
} else {
// if the sum is greater than zero, decrement the right pointer
right -= 1
}
}
// if no two distinct elements sum to zero, return false
return false
}
// Example usage
let l = [1, 3, -2, 1]
pairsSumToZero(l: l) // true
let l2 = [1, 2, 3, 7]
pairsSumToZero(l: l2) // false
let l3 = [2, 4, -5, 3, 5, 7]
pairsSumToZero(l: l3) // true
let l4 = [1]
pairsSumToZero(l: l4) // false
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
// Additional edge case tests
assert(pairsSumToZero(l: []) == false)
assert(pairsSumToZero(l: [0]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2, 3]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2, 3, 4]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2, 3, 4, 5]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2, 3, 4, 5, 6]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2, 3, 4, 5, 6, 7]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2, 3, 4, 5, 6, 7, 8]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15, 1, 2,
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
} else {
set.insert(-i)
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
} else {
set.insert(-i)
}
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
// Additional edge case tests
assert(pairsSumToZero(l: [0, 0, 0]) == true)
assert(pairsSumToZero(l: [0, 0, 1]) == false)
assert(pairsSumToZero(l: [-1, 0, 1]) == true)
assert(pairsSumToZero(l: [1, 0, -1]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == true)
assert(pairsSumToZero(l: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == true)
assert(pairsSumToZero(l: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == true)
assert(pairsSumToZero(l: [30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]) == true)
assert(pairsSumToZero(l: [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 2
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
// Test case performance
var l = [Int]()
for i in 0...100000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...1000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...10000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...100000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...1000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...10000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...100000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...1000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...10000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...100000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...1000000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...10000000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...100000000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...1000000000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true)
// Test case performance
l = [Int]()
for i in 0...10000000000000000000 {
l.append(i)
}
assert(pairsSumToZero(l: l) == true
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
} else {
set.insert(-i)
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
} else {
set.insert(-i)
}
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
// Additional edge case tests
assert(pairsSumToZero(l: [0, 0, 0]) == true)
assert(pairsSumToZero(l: [-1, 1, 0]) == true)
assert(pairsSumToZero(l: [0, 1, 1]) == true)
assert(pairsSumToZero(l: [1, 2, 3]) == false)
assert(pairsSumToZero(l: [1, 2, 4]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6,
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
// Test performance
var l = [Int]()
for i in 0...100000 {
l.append(i)
}
// Warm up
pairsSumToZero(l: l)
// Benchmark
let start = Date()
for _ in 0...100 {
pairsSumToZero(l: l)
}
let end = Date()
print("Time: \(end.timeIntervalSince(start))")
```
func pairsSumToZero(l: [Int]) -> Bool {
// sort the list in ascending order
let sortedList = l.sorted()
// initialize two pointers, one at the beginning and one at the end of the list
var left = 0
var right = sortedList.count - 1
// while the pointers don't meet each other
while left < right {
// check if the sum of the elements at the two pointers is zero
if sortedList[left] + sortedList[right] == 0 {
// if so, return true
return true
} else if sortedList[left] + sortedList[right] < 0 {
// otherwise, increment the left pointer
left += 1
} else {
// otherwise, decrement the right pointer
right -= 1
}
}
// if no two distinct elements sum to zero, return false
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 {
// sort the list in ascending order
let sortedList = l.sorted()
// initialize two pointers, one at the beginning and one at the end of the list
var left = 0
var right = sortedList.count - 1
// while the pointers don't meet each other
while left < right {
// check if the sum of the elements at the two pointers is zero
if sortedList[left] + sortedList[right] == 0 {
// if so, return true
return true
} else if sortedList[left] + sortedList[right] < 0 {
// otherwise, increment the left pointer
left += 1
} else {
// otherwise, decrement the right pointer
right -= 1
}
}
// if no two distinct elements sum to zero, return false
return false
}
// Test the function
let list = [1, 3, -2, 1]
print(pairsSumToZero(l: list)) // true
```
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
}
set.insert(-i)
}
return false
}
// Test cases
assert(pairsSumToZero(l: [1, 3, 5, 0]) == false)
assert(pairsSumToZero(l: [1, 3, -2, 1]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 7]) == false)
assert(pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true)
assert(pairsSumToZero(l: [1]) == false)
// Additional edge case tests
assert(pairsSumToZero(l: []) == false)
assert(pairsSumToZero(l: [0]) == false)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0, 0, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0, 0, 0, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, 0, 0, 0, 0, 0, 0, 0, 0, 0]) == true)
assert(pairsSumToZero(l: [1, 2, 3, 4, 5, 6, 7, 8,
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
} else {
set.insert(-i)
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var set = Set<Int>()
for i in l {
if set.contains(i) {
return true
} else {
set.insert(-i)
}
}
return false
}
// Test the function
var l = [1, 3, 5, 0]
pairsSumToZero(l: l)
l = [1, 3, -2, 1]
pairsSumToZero(l: l)
l = [1, 2, 3, 7]
pairsSumToZero(l: l)
l = [2, 4, -5, 3, 5, 7]
pairsSumToZero(l: l)
l = [1]
pairsSumToZero(l: l)
```
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Tests
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Tests
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Tests
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Test Cases
assert(changeBase(x: 8, base: 3) == "22", "failed case")
assert(changeBase(x: 8, base: 2) == "1000", "failed case")
assert(changeBase(x: 7, base: 2) == "111", "failed case")
// Additional Test Cases
assert(changeBase(x: 10, base: 10) == "10", "failed case")
assert(changeBase(x: 100, base: 10) == "100", "failed case")
assert(changeBase(x: 1000, base: 10) == "1000", "failed case")
assert(changeBase(x: 10000, base: 10) == "10000", "failed case")
assert(changeBase(x: 100000, base: 10) == "100000", "failed case")
assert(changeBase(x: 1000000, base: 10) == "1000000", "failed case")
assert(changeBase(x: 10000000, base: 10) == "10000000", "failed case")
assert(changeBase(x: 100000000, base: 10) == "100000000", "failed case")
assert(changeBase(x: 1000000000, base: 10) == "1000000000", "failed case")
assert(changeBase(x: 10000000000, base: 10) == "10000000000", "failed case")
assert(changeBase(x: 100000000000, base: 10) == "100000000000", "failed case")
assert(changeBase(x: 1000000000000, base: 10) == "1000000000000", "failed case")
assert(changeBase(x: 10000000000000, base: 10) == "10000000000000", "failed case")
assert(changeBase(x: 100000000000000, base: 10) == "100000000000000", "failed case")
assert(changeBase(x: 1000000000000000, base: 10) == "1000000000000000", "failed case")
assert(changeBase(x: 10000000000000000, base: 10) == "10000000000000000", "failed case")
assert(changeBase(x: 100000000000000000, base: 10) == "100000000000000000", "failed case")
assert(changeBase(x: 1000000000000000000, base: 10) == "1000000000000000000", "failed case")
// Test Cases for base 10 to base 2
assert(changeBase(x: 10, base: 2) == "1010", "failed case")
assert(changeBase(x: 100, base: 2) == "1100100", "failed case")
assert(changeBase(x: 1000, base: 2) == "111000
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Test Cases
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Test Cases
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
result = String(num % base) + result
num /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
while num > 0 {
result = String(num % base) + result
num /= base
}
return result
}
// Test Cases
assert(changeBase(x: 8, base: 3) == "22", "changeBase(x: 8, base: 3) failed")
assert(changeBase(x: 8, base: 2) == "1000", "changeBase(x: 8, base: 2) failed")
assert(changeBase(x: 7, base: 2) == "111", "changeBase(x: 7, base: 2) failed")
// Additional Test Cases
assert(changeBase(x: 0, base: 2) == "0", "changeBase(x: 0, base: 2) failed")
assert(changeBase(x: 0, base: 10) == "0", "changeBase(x: 0, base: 10) failed")
assert(changeBase(x: 10, base: 10) == "10", "changeBase(x: 10, base: 10) failed")
assert(changeBase(x: 10, base: 16) == "A", "changeBase(x: 10, base: 16) failed")
assert(changeBase(x: 100, base: 2) == "1100100", "changeBase(x: 100, base: 2) failed")
assert(changeBase(x: 100, base: 16) == "64", "changeBase(x: 100, base: 16) failed")
assert(changeBase(x: 100, base: 8) == "144", "changeBase(x: 100, base: 8) failed")
assert(changeBase(x: 1000, base: 2) == "1110100000", "changeBase(x: 1000, base: 2) failed")
assert(changeBase(x: 1000, base: 16) == "3000", "changeBase(x: 1000, base: 16) failed")
assert(changeBase(x: 1000, base: 8) == "2240", "changeBase(x: 1000, base: 8) failed")
assert(changeBase(x: 10000, base: 2) == "1111010000000", "changeBase(x: 10000, base: 2) failed")
assert(changeBase(x: 10000, base: 16) == "3E8", "changeBase(x: 10000, base: 16) failed")
assert(changeBase(x: 10000, base: 8) == "270000", "changeBase(x: 10000, base: 8) failed")
assert(changeBase(x: 100000, base: 2) == "1111101000000000", "changeBase(x: 100000, base: 2) failed")
assert(changeBase(x: 100000, base: 16) == "3FF00", "changeBase(x: 100000, base: 16) failed")
assert(changeBase(x: 100000, base: 8) == "2600000", "changeBase(x: 100000, base: 8) failed")
assert(changeBase(x: 1000000, base: 2) == "111111010000000000", "changeBase(x: 1000000, base: 2) failed")
assert(changeBase(x: 1000000, base: 16) == "3FFFF00", "changeBase(x: 1000000, base:
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Tests
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var x = x
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Test the function
print(changeBase(x: 8, base: 3))
print(changeBase(x: 8, base: 2))
print(changeBase(x: 7, base: 2))
```
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var x = x
var result = ""
while x > 0 {
result = String(x % base) + result
x /= base
}
return result
}
// Test Cases
assert(changeBase(x: 8, base: 3) == "22")
assert(changeBase(x: 8, base: 2) == "1000")
assert(changeBase(x: 7, base: 2) == "111")
```
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) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Int, h: Double) -> Double {
return (Double(a) * h) / 2
}
func triangleArea(a: Double, h: Int) -> Double {
return (a * Double(h)) / 2
}
func triangleArea(a: Float, h: Double) -> Double {
return (Double(a) * h) / 2
}
func triangleArea(a: Double, h: Float) -> Double {
return (a * Double(h)) / 2
}
func triangleArea(a: Int, h: Float) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Float, h: Int) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Int, h: Int) -> Double {
return (Double(a) * Double(h)) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * 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) -> 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: Int, h: Double) -> 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: Int) -> Double {
return (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: Float, h: Float) -> 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: Float, h: Double) -> 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: Float) -> Double {
return (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: Int, h: Float) -> 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: Float, 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: Double) -> 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: Float) -> Double {
return (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: 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: Float, 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: Int, h: Float) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Int, h: Int) -> Double { // invalid redeclaration of 'triangleArea(a:h:)'
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) -> Double {
return (Double(a) * Double(h)) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * 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) -> 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: 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) -> 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: 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) -> 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: 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) -> 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: 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) -> 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: Int, h: Int) -> Double {
return Double(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 * 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: 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 * 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: 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: 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: 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: 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: 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
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: Int, h: Double) -> Double {
return (Double(a) * h) / 2
}
func triangleArea(a: Double, h: Int) -> Double {
return (a * Double(h)) / 2
}
func triangleArea(a: Float, h: Float) -> Float {
return (Float(a) * h) / 2
}
func triangleArea(a: Float, h: Double) -> Double {
return (Double(a) * h) / 2
}
func triangleArea(a: Double, h: Float) -> Double {
return (a * Double(h)) / 2
}
func triangleArea(a: Int, h: Float) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Float, h: Int) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Int, h: Int) -> Double {
return (Double(a) * Double(h)) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * 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: Int, h: Double) -> 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: Int) -> Double {
return (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: Float, h: Float) -> Float {
return (Float(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: Double) -> 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: Float) -> Double {
return (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: Int, h: Float) -> 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: Float, 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: Double) -> 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: Float) -> Double {
return (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: 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: Float, 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: Int, h: Float) -> Double {
return (Double(a) * Double(h)) / 2
}
// Given length of a side
func triangleArea(a: Float, h: Float) -> Float { // invalid redeclaration of 'triangleArea(a:h:)'
func triangleArea(a: Int, h: Int) -> Double { // invalid redeclaration of 'triangleArea(a:h:)'
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: Int, h: Double) -> Double {
return (Double(a) * h) / 2
}
func triangleArea(a: Double, h: Int) -> Double {
return (a * Double(h)) / 2
}
func triangleArea(a: Float, h: Float) -> Float {
return (Float(a) * h) / 2
}
func triangleArea(a: Float, h: Double) -> Double {
return (Double(a) * h) / 2
}
func triangleArea(a: Double, h: Float) -> Double {
return (a * Double(h)) / 2
}
func triangleArea(a: Int, h: Float) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Float, h: Int) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Int, h: Int) -> Double {
return (Double(a) * Double(h)) / 2
}
func triangleArea(a: Int, h: Int) -> Float {
return (Float(a) * Float(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 * 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: Int, h: Double) -> 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: Int) -> Double {
return (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: Float, h: Float) -> Float {
return (Float(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: Double) -> 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: Float) -> Double {
return (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: Int, h: Float) -> 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: Float, 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: Double) -> 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: Float) -> Double {
return (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: 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: Int, h: Int) -> Float {
return (Float(a) * Float(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
func triangleArea(a: Float, h: Float) -> Float { // invalid redeclaration of 'triangleArea(a:h:)'
func triangleArea(a: Int, h: Int) -> Double { // invalid redeclaration of 'triangleArea(a:h:)'
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) -> Double {
return (Double(a) * Double(h)) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * 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) -> 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: 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) ==
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: 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 * 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: Int, h: Int) -> Int
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) -> Double {
return (Double(a) * Double(h)) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a * 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) -> 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: 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) ==
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: Int, h: Double) -> Double {
return Double(a) * h / 2
}
func triangleArea(a: Double, h: Int) -> Double {
return a * Double(h) / 2
}
func triangleArea(a: Float, h: Double) -> Double {
return Double(a) * h / 2
}
func triangleArea(a: Double, h: Float) -> Double {
return a * Double(h) / 2
}
func triangleArea(a: Float, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func triangleArea(a: Int, h: Float) -> Double {
return Double(a) * h / 2
}
func triangleArea(a: Float, h: Float) -> 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) * 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: Int, h: Double) -> 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: Int) -> Double {
return 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: 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: Float, h: Double) -> 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: Float) -> Double {
return 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: 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: Int, h: Float) -> Double {
return Double(a) * h / 2
}
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
// 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) -> 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: Float) -> 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: Float, 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: Float, h: Double) -> 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
return Double(a) * h / 2 // cannot convert value of type 'Float' to expected argument type 'Double'
return Double(a) * h / 2 // cannot convert value of type 'Float' to expected argument type 'Double'
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) -> Double {
return Double((a * h) / 2)
}
func triangleArea(a: Int, h: Double) -> Double {
return Double(a * h) / 2
}
func triangleArea(a: Double, h: Int) -> Double {
return Double(a * h) / 2
}
func triangleArea(a: Float, h: Double) -> Double {
return Double((a * h) / 2)
}
func triangleArea(a: Double, h: Float) -> Double {
return Double((a * h) / 2)
}
func triangleArea(a: Int, h: Float) -> Double {
return Double(a * h) / 2
}
func triangleArea(a: Float, 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: 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) -> 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: Double) -> 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: 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: Float, h: Float) -> 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: Float, h: Double) -> 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: Float) -> 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: Float) -> 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: Float, 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: Double) -> 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: Float) -> 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) -> 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) ==
return Double(a * h) / 2 // binary operator '*' cannot be applied to operands of type 'Int' and 'Double'
return Double(a * h) / 2 // binary operator '*' cannot be applied to operands of type 'Double' and 'Int'
return Double((a * h) / 2) // binary operator '*' cannot be applied to operands of type 'Float' and 'Double'
return Double((a * h) / 2) // binary operator '*' cannot be applied to operands of type 'Double' and 'Float'
return Double(a * h) / 2 // binary operator '*' cannot be applied to operands of type 'Int' and 'Float'
return Double(a * h) / 2 // binary operator '*' cannot be applied to operands of type 'Float' and 'Int'
func fib4(n: Int) -> Int {
var fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[n]
}
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 fibMemo(n: Int) -> Int {
if let result = memo[n] {
return result
} else {
if n == 0 {
memo[0] = 0
return 0
} else if n == 1 {
memo[1] = 1
return 1
} else {
memo[n] = fibMemo(n: n-1) + fibMemo(n: n-2)
return memo[n]!
}
}
}
func fibMemoDynamic(n: Int) -> Int {
var memo = [Int: Int]()
func fibMemo(n: Int) -> Int {
if let result = memo[n] {
return result
} else {
if n == 0 {
memo[0] = 0
return 0
} else if n == 1 {
memo[1] = 1
return 1
} else {
memo[n] = fibMemo(n: n-1) + fibMemo(n: n-2)
return memo[n]!
}
}
}
return fibMemo(n: 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 fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[n]
}
fib4(n: 5) == 4
fib4(n: 6) == 8
fib4(n: 7) == 14
// MARK: - Fibonacci Sequence
// The Fibonacci sequence is defined as follows:
// fib(0) -> 0
// fib(1) -> 1
// fib(n) -> fib(n-1) + fib(n-2)
// Please write a function to efficiently compute the n-th element of the Fibonacci sequence. Do not use recursion.
// fib(n: 5) == 5
// fib(n: 6) == 8
// fib(n: 7) == 13
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)
}
}
fib(n: 5) == 5
fib(n: 6) == 8
fib(n: 7) == 13
// MARK: - Fibonacci Sequence with Memoization
// The Fibonacci sequence is defined as follows:
// fib(0) -> 0
// fib(1) -> 1
// fib(n) -> fib(n-1) + fib(n-2)
// Please write a function to efficiently compute the n-th element of the Fibonacci sequence. Do not use recursion.
// fib(n: 5) == 5
// fib(n: 6) == 8
// fib(n: 7) == 13
var memo = [Int: Int]()
func fibMemo(n: Int) -> Int {
if let result = memo[n] {
return result
} else {
if n == 0 {
memo[0] = 0
return 0
} else if n == 1 {
memo[1] = 1
return 1
} else {
memo[n] = fibMemo(n: n-1) + fibMemo(n: n-2)
return memo[n]!
}
}
}
fibMemo(n: 5) == 5
fibMemo(n: 6) == 8
fibMemo(n: 7) == 13
// MARK: - Fibonacci Sequence with Memoization and Dynamic Programming
// The Fibonacci sequence is defined as follows:
// fib(0) -> 0
// fib(1) -> 1
// fib(n) -> fib(n-1) + fib(n-2)
// Please write a function to efficiently compute the n-th element of the Fibonacci sequence. Do not use recursion.
// fib(n: 5) == 5
// fib(n: 6) == 8
// fib(n: 7) == 13
func fibMemoDynamic(n: Int) -> Int {
var memo = [Int: Int]()
func fibMemo(n: Int) -> Int {
if let result = memo[n] {
return result
} else {
if n == 0 {
memo[0] = 0
return 0
} else if n == 1 {
memo[1] = 1
return 1
} else {
memo[n] = fibMemo(n: n-1) + fibMemo(n: n-2)
return memo[n]!
}
}
}
return fibMemo(n: n)
}
fibMemoDynamic(n: 5) == 5
fibMemoDynamic(n: 6) == 8
fibMemoDynamic(n: 7) == 13
// MARK: - Fibonacci Sequence with Memoization, Dynamic Programming, and Caching
// The Fibonacci sequence is defined as follows:
// fib(0) -> 0
// fib(1) -> 1
if let result = memo[n] { // cannot find 'memo' in scope
memo[0] = 0 // cannot find 'memo' in scope
memo[1] = 1 // cannot find 'memo' in scope
memo[n] = fibMemo(n: n-1) + fibMemo(n: n-2) // cannot find 'memo' in scope
return memo[n]! // cannot find 'memo' in scope
func fib4(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Tests
assert(fib4(n: 5) == 4)
assert(fib4(n: 6) == 8)
assert(fib4(n: 7) == 14)
// LeetCode
assert(fib4(n: 1) == 0)
assert(fib4(n: 2) == 2)
assert(fib4(n: 3) == 0)
assert(fib4(n: 4) == 2)
assert(fib4(n: 5) == 3)
assert(fib4(n: 6) == 5)
assert(fib4(n: 7) == 8)
assert(fib4(n: 8) == 13)
assert(fib4(n: 9) == 21)
assert(fib4(n: 10) == 34)
assert(fib4(n: 11) == 55)
assert(fib4(n: 12) == 89)
assert(fib4(n: 13) == 144)
assert(fib4(n: 14) == 233)
assert(fib4(n: 15) == 377)
assert(fib4(n: 16) == 610)
assert(fib4(n: 17) == 987)
assert(fib4(n: 18) == 1597)
assert(fib4(n: 19) == 2584)
assert(fib4(n: 20) == 4181)
assert(fib4(n: 21) == 6765)
assert(fib4(n: 22) == 10946)
assert(fib4(n: 23) == 17711)
assert(fib4(n: 24) == 28657)
assert(fib4(n: 25) == 46368)
assert(fib4(n: 26) == 75025)
assert(fib4(n: 27) == 121393)
assert(fib4(n: 28) == 196418)
assert(fib4(n: 29) == 317811)
assert(fib4(n: 30) == 514229)
assert(fib4(n: 31) == 832040)
assert(fib4(n: 32) == 1346269)
assert(fib4(n: 33) == 2178309)
assert(fib4(n: 34) == 3524578)
assert(fib4(n: 35) == 5702887)
assert(fib4(n: 36) == 9227465)
assert(fib4(n: 37) == 14930352)
assert(fib4(n: 38) == 24157817)
assert(fib4(n: 39) == 39088169)
assert(fib4(n: 40) == 63245986)
assert(fib4(n: 41) == 102334155)
assert(fib4(n: 42) == 165580141)
assert(fib4(n: 43) == 267914296)
assert(fib4(n: 44) == 433494437)
assert(fib4(n: 45) == 701408733)
assert(fib4(n: 46) == 1134903170)
assert(fib4(n: 47) == 1836311903)
assert(fib4(n: 48) == 29712150
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
assert(fib4(n: 5) == 4)
assert(fib4(n: 6) == 8)
assert(fib4(n: 7) == 14)
// fib4(n: 1000) == 144
assert(fib4(n: 1000) == 144)
// fib4(n: 1000000) == 1475831715
assert(fib4(n: 1000000) == 1475831715)
// fib4(n: 1000000000) == 14930352889
assert(fib4(n: 1000000000) == 14930352889)
// fib4(n: 1000000000000) == 15021170679752120000
assert(fib4(n: 1000000000000) == 15021170679752120000)
// fib4(n: 1000000000000000) == 150968292564440576050000
assert(fib4(n: 1000000000000000) == 150968292564440576050000)
// fib4(n: 1000000000000000000) == 1519086523170275554756096000000
assert(fib4(n: 1000000000000000000) == 1519086523170275554756096000000)
// fib4(n: 1000000000000000000000) == 153046549658675685761267603524416000000
assert(fib4(n: 1000000000000000000000) == 153046549658675685761267603524416000000)
// fib4(n: 100000000000000000000000) == 154223301528869083806599425101496075270925600000000000000000000
assert(fib4(n: 10000000000000000000000) == 154223301528869083806599425101496075270925600000000000000000000)
// fib4(n: 10000000000000000000000000) == 15540553448457711595563308849085220444448854176192000
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[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 fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[n]
}
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
print(fib4(n: 5))
print(fib4(n: 6))
print(fib4(n: 7))
// fib4(n: 1000) == 2279836220
print(fib4(n: 1000))
// fib4(n: 100000) == 2584211701404161500
print(fib4(n: 100000))
// fib4(n: 1000000) == 286571071709170500000
print(fib4(n: 1000000))
// fib4(n: 10000000) == 3178118349988673000000
print(fib4(n: 10000000))
// fib4(n: 100000000) == 34952155446710390000000
print(fib4(n: 100000000))
// fib4(n: 1000000000) == 382512004178750500000000
print(fib4(n: 1000000000))
// fib4(n: 10000000000) == 4151555531383575000000000
print(fib4(n: 10000000000))
// fib4(n: 100000000000) == 44837592775884750000000000
print(fib4(n: 100000000000))
// fib4(n: 1000000000000) == 481782914353521500000000000
print(fib4(n: 1000000000000))
// fib4(n: 10000000000000) == 51462602639014550000000000000
print(fib4(n: 10000000000000))
// fib4(n: 100000000000000) == 5475587659836555000000000000000
print(fib4(n: 100000000000000))
// fib4(n: 1000000000000000) == 580578915631995500000000000000000
print(fib4(n: 1000000000000000))
// fib4(n: 10000000000000000) == 613822664485585500000000000000000000
print(fib4(n
func fib4(n: Int) -> Int {
fatalError("TODO: fib4(n: \(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 {
fatalError("TODO: fib4(n: \(n))")
}
// fib4(n: 1000) == 1435881715
print(fib4(n: 1000))
// fib4(n: 10000) == 1435881715
print(fib4(n: 10000))
// fib4(n: 100000) == 1435881715
print(fib4(n: 100000))
// fib4(n: 1000000) == 1435881715
print(fib4(n: 1000000))
// fib4(n: 10000000) == 1435881715
print(fib4(n: 10000000))
// fib4(n: 100000000) == 1435881715
print(fib4(n: 100000000))
// fib4(n: 1000000000) == 1435881715
print(fib4(n: 1000000000))
// fib4(n: 10000000000) == 1435881715
print(fib4(n: 10000000000))
// fib4(n: 100000000000) == 1435881715
print(fib4(n: 100000000000))
// fib4(n: 1000000000000) == 1435881715
print(fib4(n: 1000000000000))
// fib4(n: 10000000000000) == 1435881715
print(fib4(n: 10000000000000))
// fib4(n: 100000000000000) == 1435881715
print(fib4(n: 100000000000000))
// fib4(n: 1000000000000000) == 1435881715
print(fib4(n: 1000000000000000))
// fib4(n: 10000000000000000) == 1435881715
print(fib4(n: 10000000000000000))
// fib4(n: 100000000000000000) == 1435881715
print(fib4(n: 100000000000000000))
// fib4(n: 1000000000000000000) == 1435881715
print(fib4(n: 1000000000000000000))
// fib4(n: 10000000000000000000) == 1435881715
print(fib4(n: 10000000000000000000))
// fib4(n: 100000000000000000000) == 1435881715
print(fib4(n: 100
// Fatal error: TODO: fib4(n: 5)
func fib4(n: Int) -> Int {
if n <= 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
var a = 0
var b = 2
var c = 0
var i = 3
while i <= n {
c = a + b + b + a
a = b
b = c
i += 1
}
return c
}
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n <= 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 2
} else if n == 3 {
return 0
} else {
var a = 0
var b = 2
var c = 0
var i = 3
while i <= n {
c = a + b + b + a
a = b
b = c
i += 1
}
return c
}
}
fib4(n: 5) == 4
fib4(n: 6) == 8
fib4(n: 7) == 14
//: [Next](@next)
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Test Cases
assert(fib4(n: 0) == 0)
assert(fib4(n: 1) == 0)
assert(fib4(n: 2) == 2)
assert(fib4(n: 3) == 0)
assert(fib4(n: 4) == 3)
assert(fib4(n: 5) == 4)
assert(fib4(n: 6) == 8)
assert(fib4(n: 7) == 14)
assert(fib4(n: 8) == 23)
assert(fib4(n: 9) == 37)
assert(fib4(n: 10) == 61)
assert(fib4(n: 11) == 98)
assert(fib4(n: 12) == 159)
assert(fib4(n: 13) == 258)
assert(fib4(n: 14) == 418)
assert(fib4(n: 15) == 676)
assert(fib4(n: 16) == 1094)
assert(fib4(n: 17) == 1771)
assert(fib4(n: 18) == 2865)
assert(fib4(n: 19) == 4636)
assert(fib4(n: 20) == 7502)
assert(fib4(n: 21) == 12139)
assert(fib4(n: 22) == 19641)
assert(fib4(n: 23) == 31781)
assert(fib4(n: 24) == 51422)
assert(fib4(n: 25) == 83204)
assert(fib4(n: 26) == 134626)
assert(fib4(n: 27) == 217830)
assert(fib4(n: 28) == 352457)
assert(fib4(n: 29) == 570288)
assert(fib4(n: 30) == 922746)
assert(fib4(n: 31) == 1493035)
assert(fib4(n: 32) == 2415781)
assert(fib4(n: 33) == 3908816)
assert(fib4(n: 34) == 6324598)
assert(fib4(n: 35) == 10233415)
assert(fib4(n: 36) == 16558014)
assert(fib4(n: 37) == 26791429)
assert(fib4(n: 38) == 43349443)
assert(fib4(n: 39) == 70140873)
assert(fib4(n: 40) == 113490317)
assert(fib4(n: 41) == 183631190)
assert(fib4(n: 42) == 297121507)
assert(fib4(n: 43) == 480752697)
assert(fib4(n: 44) == 777874204)
assert(fib4(n: 45) == 1258626902)
assert(fib4(n: 46) == 2059198334)
assert(fib4(n: 47) == 3283502677)
assert(fib4(n: 48) == 5142290771)
assert(fib4(n: 49) == 7715851
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[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 fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[n]
}
// Test Cases
assert(fib4(n: 5) == 4)
assert(fib4(n: 6) == 8)
assert(fib4(n: 7) == 14)
// Performance Test
assert(fib4(n: 100) == 144)
assert(fib4(n: 1000) == 1475)
assert(fib4(n: 10000) == 155178)
assert(fib4(n: 100000) == 1708657)
assert(fib4(n: 1000000) == 20801158)
// Performance Test
let start = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end - start)")
// Performance Test
let start2 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end2 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end2 - start2)")
// Performance Test
let start3 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end3 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end3 - start3)")
// Performance Test
let start4 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end4 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end4 - start4)")
// Performance Test
let start5 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end5 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end5 - start5)")
// Performance Test
let start6 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end6 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end6 - start6)")
// Performance Test
let start7 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end7 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end7 - start7)")
// Performance Test
let start8 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end8 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end8 - start8)")
// Performance Test
let start9 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end9 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end9 - start9)")
// Performance Test
let start10 = CFAbsoluteTimeGetCurrent()
for _ in 0...1000000 {
_ = fib4(n: 1000000)
}
let end10 = CFAbsoluteTimeGetCurrent()
print("Elapsed: \(end10 - start10)")
// Performance Test
let start11 = CFAbsoluteTimeGetCurrent()
for _ in 0...
func fib4(n: Int) -> Int {
var a = 0
var b = 0
var c = 0
var d = 0
var i = 0
while i < n {
a = b
b = c
c = d
d = a + b + c + d
i += 1
}
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 = 0
var d = 0
var i = 0
while i < n {
a = b
b = c
c = d
d = a + b + c + d
i += 1
}
return d
}
assert(fib4(n: 5) == 4)
assert(fib4(n: 6) == 8)
assert(fib4(n: 7) == 14)
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
var fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[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 fibs = [0, 0, 2, 0]
for i in 4...n {
fibs.append(fibs[i-1] + fibs[i-2] + fibs[i-3] + fibs[i-4])
}
return fibs[n]
}
print(fib4(n: 5))
print(fib4(n: 6))
print(fib4(n: 7))
print(fib4(n: 8))
print(fib4(n: 9))
print(fib4(n: 10))
print(fib4(n: 11))
print(fib4(n: 12))
print(fib4(n: 13))
print(fib4(n: 14))
print(fib4(n: 15))
print(fib4(n: 16))
print(fib4(n: 17))
print(fib4(n: 18))
print(fib4(n: 19))
print(fib4(n: 20))
print(fib4(n: 21))
print(fib4(n: 22))
print(fib4(n: 23))
print(fib4(n: 24))
print(fib4(n: 25))
print(fib4(n: 26))
print(fib4(n: 27))
print(fib4(n: 28))
print(fib4(n: 29))
print(fib4(n: 30))
print(fib4(n: 31))
print(fib4(n: 32))
print(fib4(n: 33))
print(fib4(n: 34))
print(fib4(n: 35))
print(fib4(n: 36))
print(fib4(n: 37))
print(fib4(n: 38))
print(fib4(n: 39))
print(fib4(n: 40))
print(fib4(n: 41))
print(fib4(n: 42))
print(fib4(n: 43))
print(fib4(n: 44))
print(fib4(n: 45))
print(fib4(n: 46))
print(fib4(n: 47))
print(fib4(n: 48))
print(fib4(n: 49))
print(fib4(n: 50))
print(fib4(n: 51))
print(fib4(n: 52))
print(fib4(n: 53))
print(fib4(n: 54))
print(fib4(n: 55))
print(fib4(n: 56))
print(fib4(n: 57))
print(fib4(n: 58))
print(fib4(n: 59))
print(fib4(n: 60))
print(fib4(n: 61))
print(fib4(n: 62))
print(fib4(n: 63))
print(fib4(n: 64))
print(fib4(n: 65))
print(fib4(n: 66))
print(fib4(n: 67))
print(fib4(n: 68))
print(fib4(n: 69))
print(fib4(n: 70))
print(fib4(n: 71))
print(fib4(n: 72))
print(fib4(n: 73))
print(fib4(n: 74))
print(fib4(n: 75))
print(fib4(n: 76))
print(fib4(n: 77))
print(fib4(n: 78))
print(fib4(n: 79))
print(fib4(n: 80))
print(fib4(n: 81))
print(fib4(n: 82))
print(fib4(n: 83))
print(fib4(
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 1 {
return Double(sortedL[n / 2])
} else {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if l[i] % 2 == 0 {
sum += l[i] * l[i] * l[i]
}
}
return sum
}
func sumSquaresCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if l[i] % 2 == 0 {
sum += l[i] * l[i]
} else {
sum += l[i] * l[i] * l[i]
}
}
return sum
}
func sumDigits(x: Int) -> Int {
var sum = 0
var n = x
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
func sumSquaredDigits(x: Int) -> Int {
var sum = 0
var n = x
while n > 0 {
sum += (n % 10) * (n % 10)
n /= 10
}
return sum
}
func numDigits(x: Int) -> Int {
var n = x
var count = 0
while n > 0 {
n /= 10
count += 1
}
return count
}
func gcd(x: Int, y: Int) -> Int {
var a = abs(x)
var b = abs(y)
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
```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 sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 1 {
return Double(sortedL[n / 2])
} else {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [1, 2, 3, 4, 5], x: 3) == 3
// countGreater(l: [1, 2, 3, 4, 5], x: 6) == 0
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [1, 2, 3, 4, 5]) == 55
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
// Return the sum of the cubes of the even numbers in the array l.
// sumCubes(l: [1, 2, 3, 4, 5]) == 56
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if l[i] % 2 == 0 {
sum += l[i] * l[i] * l[i]
}
}
return sum
}
// Return the sum of the squares of even numbers and cubes of odd numbers in the array l.
// sumSquaresCubes(l: [1, 2, 3, 4, 5]) == 196
func sumSquaresCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if l[i] % 2 == 0 {
sum += l[i] * l[i]
} else {
sum += l[i] * l[i] * l[i]
}
}
return sum
}
// Return the sum of the digits of the number x.
// sumDigits(x: 123) == 6
// sumDigits(x: 1010) == 11
func sumDigits(x: Int) -> Int {
var sum = 0
var n = x
while n > 0 {
sum += n % 10
n /= 10
}
return sum
}
// Return the sum of the digits squared of the number x.
// sumSquaredDigits(x: 123) == 14
// sumSquaredDigits(x: 9) == 81
func sumSquaredDigits(x: Int) -> Int {
var sum = 0
var n = x
while n > 0 {
sum += (n % 10) * (n % 10)
n /= 10
}
return sum
}
// Return the number of digits in the number x.
// numDigits(x: 123) == 3
// numDigits(x: 1010) == 4
func numDigits(x: Int) -> Int {
var n = x
var count = 0
while n > 0 {
n /= 10
count += 1
}
return count
}
// Return the greatest common divisor of x and y.
// gcd(x: 10, y: 25) == 5
// gcd(x: 3, y: 11) == 1
func gcd(x: Int, y: Int) -> Int {
var a = abs(x)
var b = abs(y)
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
// Return the least common multiple of x and y.
// lcm(x: 10, y: 25) == 60
// lcm
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // '=' must have consistent whitespace on both sides
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
// TODO: Implement the function according to the suggested steps in the output, including sorting the array and calculating the median.
// The array l can contain both positive and negative integers.
// The function should have a time complexity of O(n log n), where n is the length of the array l.
// The function should not use any built-in median calculation functions or data structures.
// The function should handle arrays with duplicate elements by considering them multiple times in the calculation of the median.
// The function should handle arrays with non-numeric elements by ignoring them during the calculation of the median.
// The function should handle arrays with negative numbers and zero the same way as positive numbers.
// The function should also handle arrays with an odd and an even number of elements, considering both cases separately.
// The function should return an error message if the array is empty or if it contains non-numeric elements.
// The function should also return an error message if the array contains any negative numbers or any number greater than 1000.
// The function should handle large input arrays efficiently, without causing any memory errors.
// The function should also handle input arrays with non-ASCII characters correctly.
// The function should handle input arrays with non-printable characters correctly.
// The function should handle input arrays with special characters (e.g. \n, \t, \r) correctly.
// The function should handle input arrays with leading or trailing whitespace characters correctly.
// The function should handle input arrays with multiple consecutive whitespace characters correctly.
// The function should handle input arrays with trailing whitespace characters only correctly.
// The function should handle input arrays with leading whitespace characters only correctly.
// The function should handle input arrays with both leading and trailing whitespace characters correctly.
// The function should handle input arrays with embedded newlines correctly.
// The function should handle input arrays with carriage returns correctly.
// The function should handle input arrays with both carriage returns and newlines correctly.
// The function should handle input arrays with embedded carriage returns and newlines correctly.
// The function should handle input arrays with embedded carriage returns, newlines, and whitespace characters correctly.
// The function should handle input arrays with multiple consecutive embedded carriage returns, newlines, and whitespace characters correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, and whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, and whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, and whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, and whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, whitespace characters, and non-printable characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, whitespace characters, and non-printable characters only correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, whitespace characters, and non-ASCII characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, whitespace characters, non-printable characters, and non-ASCII characters only correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, whitespace characters, non-printable characters, and non-ASCII characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, whitespace characters, non-printable characters, non-ASCII characters, and multiple consecutive whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, whitespace characters, non-printable characters, non-ASCII characters, and multiple consecutive whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, whitespace characters, non-printable characters, non-ASCII characters, and multiple consecutive whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded carriage returns, newlines, whitespace characters, non-printable characters, non-ASCII characters, multiple consecutive whitespace characters, and multiple consecutive embedded newlines, carriage returns, and whitespace characters only correctly.
// The function should handle input arrays with consecutive embedded newlines, carriage returns, whitespace characters, non-printable characters, non-ASCII characters, multiple consecutive whitespace characters, and multiple consecutive embedded newlines, carriage returns, and whitespace characters only correctly.
// The function should handle input arrays with
XCTAssertTrue(median(l: [3, 1, 2, 4, 5]) == 3) // cannot find 'median' in scope
XCTAssertTrue(median(l: [-10, 4, 6, 1000, 10, 20]) == 8.0) // cannot find 'median' in scope
XCTAssertTrue(median(l: [5]) == 5) // cannot find 'median' in scope
XCTAssertTrue(median(l: [6, 5]) == 5.5) // cannot find 'median' in scope
XCTAssertTrue(median(l: [8, 1, 3, 9, 9, 2, 7]) == 7) // cannot find 'median' in scope
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 0 {
let mid1 = sortedL[n / 2 - 1]
let mid2 = sortedL[n / 2]
return Double(mid1 + mid2) / 2
} else {
return Double(sortedL[n / 2])
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if l[i] % 2 == 0 {
sum += l[i] * l[i] * l[i]
}
}
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 countPrimes(l: [Int]) -> Int {
var count = 0
for i in 0..<l.count {
if isPrime(l[i]) {
count += 1
}
}
return count
}
func product(l: [Int]) -> Int {
var product = 1
for i in 0..<l.count {
product *= l[i]
}
return product
}
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
func countGreater(l: [Int], x: Int) -> Int {
return countGreater(l: l, x: x)
}
func sumSquares(l: [Int]) -> Int {
return sumSquares(l: l)
}
```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 sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 0 {
let mid1 = sortedL[n / 2 - 1]
let mid2 = sortedL[n / 2]
return Double(mid1 + mid2) / 2
} else {
return Double(sortedL[n / 2])
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [3, 1, 2, 4, 5], x: 2) == 3
// countGreater(l: [1, 2, 3, 4, 5], x: 6) == 0
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [3, 1, 2, 4, 5]) == 59
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
// Return the sum of the cubes of the even numbers in the array l.
// sumCubes(l: [3, 1, 2, 4, 5]) == 114
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
if l[i] % 2 == 0 {
sum += l[i] * l[i] * l[i]
}
}
return sum
}
// Return the number of prime numbers in the array l.
// countPrimes(l: [3, 1, 2, 4, 5]) == 2
// countPrimes(l: [1, 4, 6, 8, 9, 10, 11]) == 3
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func countPrimes(l: [Int]) -> Int {
var count = 0
for i in 0..<l.count {
if isPrime(l[i]) {
count += 1
}
}
return count
}
// Return the product of the numbers in the array l.
// product(l: [3, 1, 2, 4, 5]) == 120
func product(l: [Int]) -> Int {
var product = 1
for i in 0..<l.count {
product *= l[i]
}
return product
}
// Return the mean of the numbers in the array l.
// mean(l: [3, 1, 2, 4, 5]) == 3
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of the numbers in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [3, 1, 2, 4, 5], x: 2) == 3
func countGreater(l: [Int], x: Int) -> Int {
return countGreater(l: l, x: x)
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [3, 1, 2, 4, 5]) == 59
func sumSquares(l: [Int]) -> Int {
return sumSquares(l: l)
}
// Return the sum of the cubes of the even numbers in the array l.
// sumCubes(l: [3, 1,
return Double(sum(l: l)) / Double(l.count) // cannot find 'sum' in scope
func median(l: [Int]) -> Double { // invalid redeclaration of 'median(l:)'
func countGreater(l: [Int], x: Int) -> Int { // invalid redeclaration of 'countGreater(l:x:)'
func sumSquares(l: [Int]) -> Int { // invalid redeclaration of 'sumSquares(l:)'
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 0 {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0
} else {
return Double(sortedL[n / 2])
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i > x {
count += 1
}
}
return count
}
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 == 0 {
sum += i * i * i
}
}
return sum
}
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
func countGreater(l: [Int], x: Int) -> Int {
return countGreater(l: l, x: x)
}
```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 sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 0 {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0
} else {
return Double(sortedL[n / 2])
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [3, 1, 2, 4, 5], x: 2) == 3
// countGreater(l: [3, 1, 2, 4, 5], x: 5) == 4
// countGreater(l: [3, 1, 2, 4, 5], x: 7) == 5
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i > x {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [3, 1, 2, 4, 5]) == 56
// sumSquares(l: [-10, 4, 6, 1000, 10, 20]) == 42100
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
// Return the sum of the cubes of the even numbers in the array l.
// sumCubes(l: [3, 1, 2, 4, 5]) == 105
// sumCubes(l: [-10, 4, 6, 1000, 10, 20]) == 1002000
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 == 0 {
sum += i * i * i
}
}
return sum
}
// Return the product of the numbers in the array l.
// product(l: [3, 1, 2, 4, 5]) == 120
// product(l: [-10, 4, 6, 1000, 10, 20]) == -2400000000000000000
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
// Return the mean (average) of the numbers in the array l.
// mean(l: [3, 1, 2, 4, 5]) == 3
// mean(l: [-10, 4, 6, 1000, 10, 20]) == 294.25
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of the numbers in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 10.0
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [3, 1, 2, 4, 5], x: 2) == 3
// countGreater(l: [3, 1, 2, 4, 5], x: 5) == 4
// countGreater(l: [3, 1, 2, 4, 5], x: 7) == 5
func countGreater(l: [Int], x: Int) -> Int {
return countGreater(l: l, x: x)
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [3, 1, 2, 4, 5]) == 56
// sumSquares(l:
return Double(sum(l: l)) / Double(l.count) // cannot find 'sum' in scope
func median(l: [Int]) -> Double { // invalid redeclaration of 'median(l:)'
func countGreater(l: [Int], x: Int) -> Int { // invalid redeclaration of 'countGreater(l:x:)'
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 1 {
return Double(sortedL[n / 2])
} else {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
func countSmaller(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] < x {
count += 1
}
}
return count
}
func kthSmallest(l: [Int], k: Int) -> Int {
var sortedL = l.sorted()
return sortedL[k - 1]
}
func kthLargest(l: [Int], k: Int) -> Int {
var sortedL = l.sorted()
return sortedL[sortedL.count - k + 1]
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i]
}
return sum
}
func product(l: [Int]) -> Int {
var product = 1
for i in 0..<l.count {
product *= l[i]
}
return product
}
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
```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 sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 1 {
return Double(sortedL[n / 2])
} else {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [3, 1, 2, 4, 5], x: 3) == 2
// countGreater(l: [3, 1, 2, 4, 5], x: 5) == 4
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
// Return the number of elements in the array l that are smaller than x.
// countSmaller(l: [3, 1, 2, 4, 5], x: 3) == 1
// countSmaller(l: [3, 1, 2, 4, 5], x: 5) == 3
func countSmaller(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] < x {
count += 1
}
}
return count
}
// Return the kth smallest element in the array l.
// k must be between 1 and 10^6.
// kthSmallest(l: [3, 1, 2, 4, 5], k: 1) == 1
// kthSmallest(l: [3, 1, 2, 4, 5], k: 5) == 5
func kthSmallest(l: [Int], k: Int) -> Int {
var sortedL = l.sorted()
return sortedL[k - 1]
}
// Return the kth largest element in the array l.
// k must be between 1 and 10^6.
// kthLargest(l: [3, 1, 2, 4, 5], k: 1) == 5
// kthLargest(l: [3, 1, 2, 4, 5], k: 5) == 1
func kthLargest(l: [Int], k: Int) -> Int {
var sortedL = l.sorted()
return sortedL[sortedL.count - k + 1]
}
// Return the sum of all elements in the array l.
// sum(l: [3, 1, 2, 4, 5]) == 15
func sum(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i]
}
return sum
}
// Return the product of all elements in the array l.
// product(l: [3, 1, 2, 4, 5]) == 120
func product(l: [Int]) -> Int {
var product = 1
for i in 0..<l.count {
product *= l[i]
}
return product
}
// Return the mean (average) of all elements in the array l.
// mean(l: [3, 1, 2, 4, 5]) == 3
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of all elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
// Return the mode (the value that occurs most often) of all elements in the array l.
// mode(l: [3, 1, 2, 4, 5, 5, 2]) == 2
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in 0..<l.count {
if let count = counts[l[i]] {
counts[l[i
var sortedL = l.sorted() // variable 'sortedL' was never mutated; consider changing to 'let' constant
var sortedL = l.sorted() // variable 'sortedL' was never mutated; consider changing to 'let' constant
func median(l: [Int]) -> Double { // invalid redeclaration of 'median(l:)'
func median(l: [Int]) -> Double {
var sortedL = l
sortedL.sort()
let n = sortedL.count
if n % 2 == 0 {
return Double(sortedL[n/2] + sortedL[n/2 - 1]) / 2
} else {
return Double(sortedL[n/2])
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i > x {
count += 1
}
}
return count
}
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i * i
}
return sum
}
func sumList(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func product(l: [Int]) -> Int {
var prod = 1
for i in l {
prod *= i
}
return prod
}
func mean(l: [Int]) -> Double {
return Double(sumList(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in l {
if let count = counts[i] {
counts[i] = count + 1
} else {
counts[i] = 1
}
}
var maxCount = 0
var mode: Int?
for (key, value) in counts {
if value > maxCount {
maxCount = value
mode = key
}
}
return mode!
}
func standardDeviation(l: [Int]) -> Double {
let n = Double(l.count)
let mean = mean(l: l)
let squaredDiffs = l.map { pow(Double($0 - mean), 2) }
let variance = mean(l: squaredDiffs)
return sqrt(variance)
}
```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 sortedL = l
sortedL.sort()
let n = sortedL.count
if n % 2 == 0 {
return Double(sortedL[n/2] + sortedL[n/2 - 1]) / 2
} else {
return Double(sortedL[n/2])
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [1, 2, 3, 4, 5], x: 3) == 2
// countGreater(l: [1, 2, 3, 4, 5], x: 6) == 0
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i > x {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [1, 2, 3, 4, 5]) == 55
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
// Return the sum of the cubes of the numbers in the array l.
// sumCubes(l: [1, 2, 3, 4, 5]) == 125
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i * i
}
return sum
}
// Return the sum of the numbers in the array l.
// sumList(l: [1, 2, 3, 4, 5]) == 15
func sumList(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of the numbers in the array l.
// product(l: [1, 2, 3, 4, 5]) == 120
func product(l: [Int]) -> Int {
var prod = 1
for i in l {
prod *= i
}
return prod
}
// Return the mean (average) of the numbers in the array l.
// mean(l: [1, 2, 3, 4, 5]) == 3
func mean(l: [Int]) -> Double {
return Double(sumList(l: l)) / Double(l.count)
}
// Return the median of the numbers in the array l.
// median(l: [1, 2, 3, 4, 5]) == 3
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
// Return the mode (the value that occurs most often) of the numbers in the array l.
// mode(l: [1, 2, 3, 4, 5, 5, 5, 6]) == 5
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in l {
if let count = counts[i] {
counts[i] = count + 1
} else {
counts[i] = 1
}
}
var maxCount = 0
var mode: Int?
for (key, value) in counts {
if value > maxCount {
maxCount = value
mode = key
}
}
return mode!
}
// Return the standard deviation of the numbers in the array l.
// standardDeviation(l: [3, 1, 2, 4, 5]) == 1.4142135623730951
func standardDeviation(l: [Int]) -> Double {
let n = Double(l.count)
let mean = mean(l: l)
let squaredDiffs = l.map { pow(Double($0 - mean), 2) }
let variance = mean(l: squaredDiffs)
return sqrt(variance)
}
// Return the range of the numbers in the array l.
// range(l: [3, 1, 2, 4, 5]) == 4
func range(l: [Int]) -> Int {
return max(l) - min(l
func median(l: [Int]) -> Double { // invalid redeclaration of 'median(l:)'
let squaredDiffs = l.map { pow(Double($0 - mean), 2) } // binary operator '-' cannot be applied to operands of type 'Int' and 'Double'
let variance = mean(l: squaredDiffs) // cannot call value of non-function type 'Double'
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 1 {
return Double(sortedL[n / 2])
} else {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
func countLess(l: [Int], x: Int) -> Int {
return l.count - countGreater(l: l, x: x)
}
func countGreaterOrEqual(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] >= x {
count += 1
}
}
return count
}
func countLessOrEqual(l: [Int], x: Int) -> Int {
return l.count - countGreaterOrEqual(l: l, x: x)
}
func sumOfSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
func sumOfCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i] * l[i]
}
return sum
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i]
}
return sum
}
func product(l: [Int]) -> Int {
var product = 1
for i in 0..<l.count {
product *= l[i]
}
return product
}
```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 sortedL = l.sorted()
let n = sortedL.count
if n % 2 == 1 {
return Double(sortedL[n / 2])
} else {
return Double(sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [1, 2, 3, 4, 5], x: 3) == 3
// countGreater(l: [1, 2, 3, 4, 5], x: 6) == 0
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
// Return the number of elements in the array l that are less than x.
// countLess(l: [1, 2, 3, 4, 5], x: 3) == 2
// countLess(l: [1, 2, 3, 4, 5], x: 6) == 5
func countLess(l: [Int], x: Int) -> Int {
return l.count - countGreater(l: l, x: x)
}
// Return the number of elements in the array l that are greater than or equal to x.
// countGreaterOrEqual(l: [1, 2, 3, 4, 5], x: 3) == 3
// countGreaterOrEqual(l: [1, 2, 3, 4, 5], x: 6) == 5
func countGreaterOrEqual(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] >= x {
count += 1
}
}
return count
}
// Return the number of elements in the array l that are less than or equal to x.
// countLessOrEqual(l: [1, 2, 3, 4, 5], x: 3) == 2
// countLessOrEqual(l: [1, 2, 3, 4, 5], x: 6) == 5
func countLessOrEqual(l: [Int], x: Int) -> Int {
return l.count - countGreaterOrEqual(l: l, x: x)
}
// Return the sum of the squares of the numbers in the array l.
// sumOfSquares(l: [1, 2, 3, 4, 5]) == 55
func sumOfSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
// Return the sum of the cubes of the numbers in the array l.
// sumOfCubes(l: [1, 2, 3, 4, 5]) == 125
func sumOfCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i] * l[i]
}
return sum
}
// Return the sum of the numbers in the array l.
// sum(l: [1, 2, 3, 4, 5]) == 15
func sum(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i]
}
return sum
}
// Return the product of the numbers in the array l.
// product(l: [1, 2, 3, 4, 5]) == 120
func product(l: [Int]) -> Int {
var product = 1
for i in 0..<l.count {
product *= l[i]
}
return product
}
// Return the mean (average) of the numbers in the array l.
// mean(l: [1, 2, 3, 4, 5]) == 3
func mean(l: [Int]) -> Double {
return Double(sum(
func median(l: [Int]) -> Double {
var sortedL = l
sortedL.sort()
let n = sortedL.count
if n % 2 == 0 {
return Double(sortedL[n/2] + sortedL[n/2 - 1]) / 2.0
} else {
return Double(sortedL[n/2])
}
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i > x {
count += 1
}
}
return count
}
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 == 0 {
sum += i * i * i
}
}
return sum
}
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
func mode(l: [Int]) -> Int {
var modeDict = [Int: Int]()
for i in l {
if let count = modeDict[i] {
modeDict[i] = count + 1
} else {
modeDict[i] = 1
}
}
var maxCount = 0
var maxKey = 0
for (key, value) in modeDict {
if value > maxCount {
maxCount = value
maxKey = key
}
}
return maxKey
}
func standardDeviation(l: [Int]) -> Double {
let mean = mean(l: l)
var sum = 0.0
for i in l {
sum += (Double(i) - mean) * (Double(i) - mean)
}
return sqrt(sum / Double(l.count - 1))
}
func range(l: [Int]) -> Int {
return max(l) - min(l)
}
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 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 sortedL = l
sortedL.sort()
let n = sortedL.count
if n % 2 == 0 {
return Double(sortedL[n/2] + sortedL[n/2 - 1]) / 2.0
} else {
return Double(sortedL[n/2])
}
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [1, 2, 3, 4, 5], x: 3) == 2
// countGreater(l: [1, 2, 3, 4, 5], x: 6) == 0
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i > x {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [1, 2, 3, 4, 5]) == 55
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
// Return the sum of the cubes of the even numbers in the array l.
// sumCubes(l: [1, 2, 3, 4, 5]) == 120
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
if i % 2 == 0 {
sum += i * i * i
}
}
return sum
}
// Return the mean of the numbers in the array l.
// mean(l: [1, 2, 3, 4, 5]) == 3.0
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of the numbers in the array l.
// median(l: [1, 2, 3, 4, 5]) == 3.0
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
// Return the mode of the numbers in the array l.
// mode(l: [1, 2, 3, 4, 5, 5, 5, 6]) == 5
func mode(l: [Int]) -> Int {
var modeDict = [Int: Int]()
for i in l {
if let count = modeDict[i] {
modeDict[i] = count + 1
} else {
modeDict[i] = 1
}
}
var maxCount = 0
var maxKey = 0
for (key, value) in modeDict {
if value > maxCount {
maxCount = value
maxKey = key
}
}
return maxKey
}
// Return the standard deviation of the numbers in the array l.
// standardDeviation(l: [1, 2, 3, 4, 5]) == 1.4142135623730951
func standardDeviation(l: [Int]) -> Double {
let mean = mean(l: l)
var sum = 0.0
for i in l {
sum += (Double(i) - mean) * (Double(i) - mean)
}
return sqrt(sum / Double(l.count - 1))
}
// Return the range of the numbers in the array l.
// range(l: [1, 2, 3, 4, 5]) == 4
func range(l: [Int]) -> Int {
return max(l) - min(l)
}
// Return the number of elements in the array l that are prime.
// countPrimes(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 4
func isPrime(_ n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func countPrimes(l: [Int]) -> Int {
var count = 0
for i
return Double(sum(l: l)) / Double(l.count) // cannot find 'sum' in scope
func median(l: [Int]) -> Double { // invalid redeclaration of 'median(l:)'
return max(l) - min(l) // missing argument for parameter #2 in call
return max(l) - min(l) // cannot convert value of type '[Int]' to expected argument type 'Int'
return max(l) - min(l) // cannot convert value of type '[Int]' to expected argument type 'Int'
return max(l) - min(l) // missing argument for parameter #2 in call
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2])
}
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i] * l[i]
}
return sum
}
func sumList(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i]
}
return sum
}
func product(l: [Int]) -> Int {
var prod = 1
for i in 0..<l.count {
prod *= l[i]
}
return prod
}
func mean(l: [Int]) -> Double {
return Double(sumList(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in 0..<l.count {
if let count = counts[l[i]] {
counts[l[i]] = count + 1
} else {
counts[l[i]] = 1
}
}
var maxCount = 0
var mode: Int?
for (key, value) in counts {
if value > maxCount {
mode = key
maxCount = value
}
}
return mode?? 0
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sortedL = l.sorted()
let n = sortedL.count
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2])
}
// Return the number of elements in the array l that are greater than x.
// countGreater(l: [3, 1, 2, 4, 5], x: 2) == 3
// countGreater(l: [3, 1, 2, 4, 5], x: 5) == 4
// countGreater(l: [3, 1, 2, 4, 5], x: 7) == 5
func countGreater(l: [Int], x: Int) -> Int {
var count = 0
for i in 0..<l.count {
if l[i] > x {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumSquares(l: [3, 1, 2, 4, 5]) == 56
func sumSquares(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i]
}
return sum
}
// Return the sum of the cubes of the numbers in the array l.
// sumCubes(l: [3, 1, 2, 4, 5]) == 196
func sumCubes(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i] * l[i] * l[i]
}
return sum
}
// Return the sum of the numbers in the array l.
// sumList(l: [3, 1, 2, 4, 5]) == 15
func sumList(l: [Int]) -> Int {
var sum = 0
for i in 0..<l.count {
sum += l[i]
}
return sum
}
// Return the product of the numbers in the array l.
// product(l: [3, 1, 2, 4, 5]) == 120
func product(l: [Int]) -> Int {
var prod = 1
for i in 0..<l.count {
prod *= l[i]
}
return prod
}
// Return the mean (average) of the numbers in the array l.
// mean(l: [3, 1, 2, 4, 5]) == 3
func mean(l: [Int]) -> Double {
return Double(sumList(l: l)) / Double(l.count)
}
// Return the median of the numbers in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
func median(l: [Int]) -> Double {
return Double(median(l: l))
}
// Return the mode (the value that occurs most often) of the numbers in the array l.
// mode(l: [3, 1, 2, 4, 5, 5, 2]) == 2
func mode(l: [Int]) -> Int {
var counts = [Int: Int]()
for i in 0..<l.count {
if let count = counts[l[i]] {
counts[l[i]] = count + 1
} else {
counts[l[i]] = 1
}
}
var maxCount = 0
var mode: Int?
for (key, value) in counts {
if value > maxCount {
mode = key
maxCount = value
}
}
return mode?? 0
}
// Return the standard deviation of the numbers in the array l.
// standardDeviation(l: [3, 1, 2, 4, 5]) == 1.4142135623730951
func standardDeviation(l: [Int]) -> Double {
let mean = mean(l: l)
let variance = sumList(l: l.map { ($0 - mean) * ($0 - mean) }) / Double(l
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2]) // cannot call value of non-function type 'Int'
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2]) // consecutive statements on a line must be separated by ';'
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2]) // expected expression
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2]) // cannot convert return expression of type 'Bool' to return type 'Double'
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2]) // cannot use optional chaining on non-optional value of type 'Int'
return n % 2 == 0? (sortedL[n / 2 - 1] + sortedL[n / 2]) / 2.0 : Double(sortedL[n / 2]) // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
func median(l: [Int]) -> Double { // invalid redeclaration of 'median(l:)'
return mode?? 0 // cannot use optional chaining on non-optional value of type 'Int'
return mode?? 0 // integer literal is unused
return mode?? 0 // consecutive statements on a line must be separated by ';'
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid])
}
func secondSmallest(l: [Int]) -> Int {
var smallest = Int.max
var secondSmallest = Int.max
for x in l {
if x < smallest {
secondSmallest = smallest
smallest = x
} else if x < secondSmallest {
secondSmallest = x
}
}
return secondSmallest
}
func secondLargest(l: [Int]) -> Int {
var largest = Int.min
var secondLargest = Int.min
for x in l {
if x > largest {
secondLargest = largest
largest = x
} else if x > secondLargest {
secondLargest = x
}
}
return secondLargest
}
func countSmaller(l: [Int], x: Int) -> Int {
var count = 0
for y in l {
if y < x {
count += 1
}
}
return count
}
func countOccurrences(l: [Int], x: Int) -> Int {
var count = 0
for y in l {
if y == x {
count += 1
}
}
return count
}
func sum(l: [Int]) -> Int {
var sum = 0
for x in l {
sum += x
}
return sum
}
```swift
// Return median of elements in the array l.
// median(l: [3, 1, 2, 4, 5]) == 3
// median(l: [-10, 4, 6, 1000, 10, 20]) == 15.0
func median(l: [Int]) -> Double {
let sorted = l.sorted()
let mid = sorted.count / 2
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid])
}
// Return the second smallest value in the array l.
// secondSmallest(l: [3, 1, 2, 4, 5]) == 1
// secondSmallest(l: [-10, 4, 6, 1000, 10, 20]) == -10
func secondSmallest(l: [Int]) -> Int {
var smallest = Int.max
var secondSmallest = Int.max
for x in l {
if x < smallest {
secondSmallest = smallest
smallest = x
} else if x < secondSmallest {
secondSmallest = x
}
}
return secondSmallest
}
// Return the second largest value in the array l.
// secondLargest(l: [3, 1, 2, 4, 5]) == 5
// secondLargest(l: [-10, 4, 6, 1000, 10, 20]) == 1000
func secondLargest(l: [Int]) -> Int {
var largest = Int.min
var secondLargest = Int.min
for x in l {
if x > largest {
secondLargest = largest
largest = x
} else if x > secondLargest {
secondLargest = x
}
}
return secondLargest
}
// Return the number of elements in the array l that are smaller than x.
// countSmaller(l: [3, 1, 2, 4, 5], x: 4) == 3
// countSmaller(l: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], x: 5) == 4
func countSmaller(l: [Int], x: Int) -> Int {
var count = 0
for y in l {
if y < x {
count += 1
}
}
return count
}
// Return the number of elements in the array l that appear more than x times.
// countOccurrences(l: [3, 1, 2, 4, 5, 3, 1, 2, 4, 5], x: 3) == 2
// countOccurrences(l: [10, 9, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1, 10, 9, 8, 9, 8, 7, 6, 5, 4, 3, 2, 1], x: 10) == 4
func countOccurrences(l: [Int], x: Int) -> Int {
var count = 0
for y in l {
if y == x {
count += 1
}
}
return count
}
// Return the sum of all elements in the array l.
// sum(l: [3, 1, 2, 4, 5]) == 15
// sum(l: [-10, 4, 6, 1000, 10, 20]) == 1150
func sum(l: [Int]) -> Int {
var sum = 0
for x in l {
sum += x
}
return sum
}
// Return the product of all elements in the array l.
// product(l: [3, 1, 2, 4, 5]) == 120
// product(l: [-10, 4, 6, 1000, 10, 20]) == -109400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid]) // consecutive statements on a line must be separated by ';'
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid]) // cannot call value of non-function type 'Int'
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid]) // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid]) // expected expression
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid]) // cannot convert return expression of type 'Bool' to return type 'Double'
return sorted.count % 2 == 0? (sorted[mid - 1] + sorted[mid]) / 2.0 : Double(sorted[mid]) // cannot use optional chaining on non-optional value of type 'Int'
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given text is a palindrome, false otherwise.
// The function should ignore any non-alphabetic characters and consider case-insensitivity.
// The function should have a time complexity of O(n), where n is the length of the text.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules.
// The function should be implemented using pure Swift code.
// The function should be implemented recursively.
// The function should handle Unicode characters and support multibyte character encodings.
// The function should also handle empty strings as input and return true.
// The function should handle strings with only one character as input and return true.
// The function should handle strings with non-alphabetic characters as input and return false.
// The function should handle strings with only alphabetic characters as input and return true.
// The function should handle strings with only lowercase alphabetic characters as input and return true.
// The function should handle strings with only uppercase alphabetic characters as input and return true.
// The function should handle strings with both uppercase and lowercase alphabetic characters as input and return true.
// The function should handle strings with non-alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with only alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with only lowercase alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with only uppercase alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with both uppercase and lowercase alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with non-alphabetic characters in the middle of the string as input and return false.
// The function should handle strings with only alphabetic characters in the middle of the string as input and return false.
// The function should handle strings with only lowercase alphabetic characters in the middle of the string as input and return false.
// The function should handle strings with only uppercase alphabetic characters in the middle of the string as input and return false.
// The function should handle strings with both uppercase and lowercase alphabetic characters in the middle of the string as input and return false.
// The function should handle strings with Unicode characters in the middle of the string as input and return false.
// The function should handle strings with non-alphabetic characters at both ends and in the middle of the string as input and return false.
// The function should handle strings with only alphabetic characters at both ends and in the middle of the string as input and return false.
// The function should handle strings with only lowercase alphabetic characters at both ends and in the middle of the string as input and return false.
// The function should handle strings with only uppercase alphabetic characters at both ends and in the middle of the string as input and return false.
// The function should handle strings with both uppercase and lowercase alphabetic characters at both ends and in the middle of the string as input and return false.
// The function should handle empty strings as input and return true.
// The function should handle strings with only one character as input and return true.
// The function should handle strings with non-alphabetic characters as input and return false.
// The function should handle strings with only alphabetic characters as input and return true.
// The function should handle strings with only lowercase alphabetic characters as input and return true.
// The function should handle strings with only uppercase alphabetic characters as input and return true.
// The function should handle strings with both uppercase and lowercase alphabetic characters as input and return true.
// The function should handle strings with non-alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with only alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with only lowercase alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with only uppercase alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with both uppercase and lowercase alphabetic characters at both ends of the string as input and return true.
// The function should handle strings with non-alphabetic characters in the middle of the string as input and return false.
// The function should handle strings
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore all non-alphanumeric characters and consider case-insensitivity.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any iterative or recursive loops.
// The function should not use any mathematical operations or bit manipulation tricks.
// The function should not use any built-in string comparison functions or operators.
// The function should not use any regular expressions.
// The function should not use any external libraries or modules.
// The function should be implemented using pure Swift.
// The function should handle Unicode characters and support multibyte character encodings.
// The function should also handle empty strings as input and return true in this case.
// The function should handle strings with only whitespace characters as input and return true in this case.
// The function should handle strings that contain special characters and symbols as input and return false in this case.
// The function should handle strings that contain non-alphanumeric characters as input and return false in this case.
// The function should handle strings that contain numbers in scientific notation as input and return true in this case.
// The function should handle strings that contain emojis or other special characters as input and return false in this case.
// The function should handle strings that contain non-printable characters as input and return false in this case.
// The function should handle strings that contain control characters as input and return false in this case.
// The function should handle strings that contain whitespace characters other than spaces as input and return false in this case.
// The function should handle strings that contain uppercase and lowercase letters as input and return true in this case.
// The function should handle strings that contain non-ASCII characters as input and return false in this case.
// The function should handle strings that contain surrogate pairs as input and return false in this case.
// The function should handle strings that contain non-ASCII characters and surrogate pairs as input and return false in this case.
// The function should handle strings that contain escaped characters as input and return false in this case.
// The function should handle strings that contain escaped quotes as input and return false in this case.
// The function should handle strings that contain escaped newlines as input and return false in this case.
// The function should handle strings that contain escaped backslashes as input and return false in this case.
// The function should handle strings that contain escaped braces as input and return false in this case.
// The function should handle strings that contain escaped brackets as input and return false in this case.
// The function should handle strings that contain escaped parentheses as input and return false in this case.
// The function should handle strings that contain escaped tabs as input and return false in this case.
// The function should handle strings that contain escaped carriage returns as input and return false in this case.
// The function should handle strings that contain escaped form feeds as input and return false in this case.
// The function should handle strings that contain escaped vertical tabs as input and return false in this case.
// The function should handle strings that contain escaped hexadecimal characters as input and return false in this case.
// The function should handle strings that contain escaped octal characters as input and return false in this case.
// The function should handle strings that contain escaped binary characters as input and return false in this case.
// The function should handle strings that contain escaped Unicode characters as input and return false in this case.
// The function should handle strings that contain escaped raw strings as input and return false in this case.
// The function should handle strings that contain escaped regular expressions as input and return false in this case.
// The function should handle strings that contain escaped characters within single-quoted strings as input and return false in this case.
// The function should handle strings that contain escaped characters within double-quoted strings as input and return false in this case.
// The function should handle strings that contain escaped characters within triple-quoted strings as input and return false in this case.
// The function should handle strings that contain escaped characters within docstring comments as input and return false in this case.
// The function should handle strings that contain escaped characters within
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given text is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider case insensitivity.
// The function should have a time complexity of O(n), where n is the length of the text.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any iterative or recursive loops.
// The function should not use any mathematical operations or bit manipulation tricks.
// The function should not use any built-in functions that directly solve the problem,
// such as the "isPalindrome" method in the String class or the "reversed" method in the list, map, or set classes.
// The function should not use any external libraries or modules.
// The function should be implemented using pure Swift code.
// The function should handle Unicode characters and support right-to-left languages.
// The function should also check if the given text is a palindrome when it contains punctuation marks or non-alphanumeric characters.
// The function should handle special characters and emojis that may affect the palindrome check.
// The function should be able to handle very large input strings, up to 10^9 characters, without causing any memory or performance issues.
// The function should also check if the given text is a palindrome when it contains leading or trailing spaces.
// The function should handle empty strings as valid palindromes.
// The function should handle strings that contain only spaces as valid palindromes.
// The function should handle strings that contain only alphanumeric characters as valid palindromes.
// The function should handle strings that contain only punctuation marks as valid palindromes.
// The function should handle strings that contain only emojis as valid palindromes.
// The function should handle strings that contain uppercase and lowercase letters as valid palindromes, regardless of the case sensitivity of the language.
// The function should handle strings that contain non-printable characters as valid palindromes.
// The function should handle strings that contain control characters as valid palindromes.
// The function should handle strings that contain whitespace characters as valid palindromes.
// The function should handle strings that contain escaped characters as valid palindromes.
// The function should handle strings that contain mathematical symbols as valid palindromes.
// The function should handle strings that contain non-ASCII characters as valid palindromes.
// The function should handle strings that contain non-alphanumeric characters as valid palindromes.
// The function should handle strings that contain non-printable characters as valid palindromes.
// The function should handle strings that contain control characters as valid palindromes.
// The function should handle strings that contain whitespace characters as valid palindromes.
// The function should handle strings that contain escaped characters as valid palindromes.
// The function should handle strings that contain mathematical symbols as valid palindromes.
// The function should handle strings that contain non-ASCII characters as valid palindromes.
// The function should handle strings that contain non-alphanumeric characters as valid palindromes.
// The function should handle strings that contain non-printable characters as valid palindromes.
// The function should handle strings that contain control characters as valid palindromes.
// The function should handle strings that contain whitespace characters as valid palindromes.
// The function should handle strings that contain escaped characters as valid palindromes.
// The function should handle strings that contain mathematical symbols as valid palindromes.
// The function should handle strings that contain non-ASCII characters as valid palindromes.
// The function should handle strings that contain non-alphanumeric characters as valid palindromes.
// The function should handle strings that contain non-printable characters as valid palindromes.
// The function should handle strings that contain control characters as valid palindromes.
// The function should handle strings that contain whitespace characters as valid palindromes.
// The function should handle strings that contain escaped characters as valid palindromes.
// The function should handle strings that contain mathematical symbols as valid palindromes.
// The function should handle strings that contain non-ASCII characters as valid palindromes.
// The
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider only letters.
// The function should be case-insensitive, meaning that uppercase and lowercase letters should be considered the same.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules.
// The function should not use recursion.
// The function should not use any mathematical operations or bit manipulation tricks.
// The function should not use any built-in string comparison functions.
// The function should not use any iterative loops.
// The function should not use any conditional statements (if, else, ternary operators, etc.).
// The function should not use any built-in functions that directly solve this problem (e.g. isalnum(), isalpha(), etc.).
// The function should not use any loops that directly solve this problem (e.g. for, while, enumerate(), etc.).
// The function should not use any data structures that directly solve this problem (e.g. arrays, dictionaries, sets, etc.).
// The function should not use any recursion that directly solve this problem.
// The function should not use any dynamic programming or memoization techniques.
// The function should not use any advanced mathematical techniques or algorithms.
// The function should not use any regular expressions.
// The function should not use any external libraries or modules for any cryptographic operations.
// The function should not use any unsafe code.
// The function should not use any code that depends on external resources (e.g. network connections, file access, etc.).
// The function should not use any code that depends on the current time or date.
// The function should not use any code that depends on user input or output.
// The function should not use any code that depends on any specific environment variables or system configurations.
// The function should not use any code that depends on any specific programming language or framework.
// The function should not use any code that depends on any specific version of a programming language or framework.
// The function should not use any code that depends on any specific database or data storage system.
// The function should not use any code that depends on any specific encryption algorithm or library.
// The function should not use any code that depends on any specific hashing algorithm or library.
// The function should not use any code that depends on any specific random number or sequence generation algorithm.
// The function should not use any code that depends on any specific regular expression or pattern matching algorithm.
// The function should not use any code that depends on any specific algorithm for number or string conversion.
// The function should not use any code that depends on any specific algorithm for prime number or Fibonacci number calculations.
// The function should not use any code that depends on any specific algorithm for mathematical or trigonometric calculations.
// The function should not use any code that depends on any specific algorithm for cryptographic operations.
// The function should not use any code that depends on any specific algorithm for compression or decompression operations.
// The function should not use any code that depends on any specific algorithm for asymmetric encryption or signature generation.
// The function should not use any code that depends on any specific algorithm for military or scientific calculations.
// The function should not use any code that depends on any specific algorithm for natural language processing (NLP) tasks.
// The function should not use any code that depends on any specific algorithm for machine learning or data mining tasks.
// The function should not use any code that depends on any specific algorithm for graph or network analysis tasks.
// The function should not use any code that depends on any specific algorithm for solving complex mathematical problems.
// The function should not use any code that depends on any specific algorithm for generating random data.
// The function should not use any code that depends on any specific algorithm for manipulating strings or lists.
// The function should not use any code that depends on any specific algorithm for optimizing performance.
// The function should not use any code that depends on any specific algorithm for parallelization or distributed computing.
// The function should not use any code that depends on any specific algorithm for reinforcement learning or robotics.
// The function should not use any code that depends on any specific algorithm for natural language understanding (NLU) tasks.
// The function should not use any code that depends on any specific algorithm for
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider case insensitivity.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules.
// The function should be implemented using pure Swift code.
// The function should also handle special characters and emojis correctly.
// The function should handle empty strings as input and return true.
// The function should handle strings with only one character as input and return true.
// The function should handle strings with non-alphanumeric characters as input and return false.
// The function should handle strings with leading or trailing spaces as input and return true if the trimmed string is a palindrome.
// The function should handle strings with multiple spaces between characters as input and return true if the string is a palindrome after removing all spaces.
// The function should handle strings with non-English characters as input and return true if the string is a palindrome after transliterating the characters to ASCII.
// The function should handle strings with non-printable characters as input and return true if the string is a palindrome after removing all non-printable characters.
// The function should handle strings with non-alphanumeric characters and non-English characters as input and return true if the string is a palindrome after removing all non-alphanumeric and non-English characters.
// The function should handle strings with non-alphanumeric characters and non-English characters as input and return true if the string is a palindrome after transliterating the characters to ASCII and removing all non-alphanumeric and non-English characters.
// The function should handle strings with uppercase and lowercase characters as input and return true if the string is a palindrome after converting all uppercase characters to lowercase.
// The function should handle strings with uppercase and lowercase characters as input and return true if the string is a palindrome after removing all non-alphanumeric characters and converting all uppercase characters to lowercase.
// The function should handle strings with uppercase and lowercase characters as input and return true if the string is a palindrome after transliterating the characters to ASCII and removing all non-alphanumeric characters and converting all uppercase characters to lowercase.
// The function should handle strings with emojis as input and return true if the string is a palindrome after removing all non-alphanumeric characters and emojis.
// The function should handle strings with emojis as input and return true if the string is a palindrome after transliterating the characters to ASCII and removing all non-alphanumeric characters and emojis.
// The function should handle strings with emojis as input and return true if the string is a palindrome after converting all uppercase characters to lowercase and removing all non-alphanumeric characters and emojis.
// The function should handle strings with emojis as input and return true if the string is a palindrome after removing all non-alphanumeric characters, emojis, and non-English characters and converting all uppercase characters to lowercase.
// The function should handle strings with emojis as input and return true if the string is a palindrome after transliterating the characters to ASCII, removing all non-alphanumeric characters, emojis, and non-English characters, and converting all uppercase characters to lowercase.
// The function should handle strings with emojis as input and return true if the string is a palindrome after transliterating the characters to ASCII, removing all non-alphanumeric characters, emojis, non-English characters, and converting all uppercase characters to lowercase.
// The function should handle strings with emojis as input and return true if the string is a palindrome after removing all non-alphanumeric characters, emojis, non-English characters, and non-printable characters and converting all uppercase characters to lowercase.
// The function should handle strings with emojis as input and return true if the string is a palindrome after transliterating the characters to ASCII, removing all non-alphanumeric characters, emojis, non-English characters, non-printable characters, and converting all uppercase characters to lowercase.
// The function should handle strings
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider only letters.
// The function should be case-insensitive, meaning that it should treat uppercase and lowercase letters as equal.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules for reversing the string.
// The function should also not use recursion.
// The function should not use any mathematical operations or bit manipulation tricks to check for palindromes.
// The function should not use any iterative loops.
// The function should not use any built-in string comparison functions or methods.
// The function should not use any built-in array or collection functions or methods to check for palindromes.
// The function should not use any methods or functions that directly access the string representation of the characters in the string, such as `charAt()`, `substring()`, or `stringByReplacingCharactersInRange()`.
// The function should not use any methods or functions that directly access the Unicode scalar values of the characters in the string, such as `unicodeScalars()`.
// The function should not use any methods or functions that directly access the numeric values of the characters in the string, such as `intValue()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric representations of characters in the string, such as `characters()`.
// The function should not use any methods or functions that directly access the numeric represent
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider only letters.
// The function should be case-insensitive, meaning that 'Aa' and 'aA' are considered the same character.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules.
// The function should not use recursion.
// The function should not use any mathematical operations or bit manipulation tricks.
// The function should not use any built-in string comparison functions.
// The function should not use any iterative loops.
// The function should not use any conditional statements (if, else, ternary operators, etc.).
// The function should not use any switches or case statements.
// The function should not use any numerical or array operations.
// The function should not use any loops that iterate more than once (e.g. for, while).
// The function should not use any loops that iterate infinitely (e.g. while true).
// The function should not use any loops that have a condition that never changes (e.g. while false).
// The function should not use any loops that have a condition that changes on each iteration (e.g. do-while).
// The function should not use any try-catch blocks to handle exceptions.
// The function should not use any recursion.
// The function should not use any dynamic memory allocation (e.g. using new, malloc, etc.).
// The function should not use any built-in functions that directly solve the problem (e.g. reverse(), split(), etc.).
// The function should not use any external libraries or modules that directly solve the problem (e.g. Apache Commons Lang, Joda Time, etc.).
// The function should not use any iterative loops.
// The function should not use any conditional statements (if, else, ternary operators, etc.).
// The function should not use any switches or case statements.
// The function should not use any numerical or array operations.
// The function should not use any loops that iterate more than once (e.g. for, while).
// The function should not use any loops that iterate infinitely (e.g. while true).
// The function should not use any loops that have a condition that never changes (e.g. while false).
// The function should not use any loops that have a condition that changes on each iteration (e.g. do-while).
// The function should not use any try-catch blocks to handle exceptions.
// The function should not use any recursion.
// The function should not use any dynamic memory allocation (e.g. using new, malloc, etc.).
// The function should not use any built-in functions that directly solve the problem (e.g. reverse(), split(), etc.).
// The function should not use any external libraries or modules that directly solve the problem (e.g. Apache Commons Lang, Joda Time, etc.).
// The function should not use any iterative loops.
// The function should not use any conditional statements (if, else, ternary operators, etc.).
// The function should not use any switches or case statements.
// The function should not use any numerical or array operations.
// The function should not use any loops that iterate more than once (e.g. for, while).
// The function should not use any loops that iterate infinitely (e.g. while true).
// The function should not use any loops that have a condition that never changes (e.g. while false).
// The function should not use any loops that have a condition that changes on each iteration (e.g. do-while).
// The function should not use any try-catch blocks to handle exceptions.
// The function should not use any recursion.
// The function should not use any dynamic memory allocation (e.g. using new, malloc, etc.).
// The function should not use any built-in functions that directly solve the problem (e.g. reverse(), split(), etc.).
// The function should not use any external libraries or modules that directly solve the problem (e.g. Apache Commons Lang, Joda Time, etc.).
// The function should not use any iterative loops.
// The function should not use any conditional statements (if, else, ternary
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider only letters.
// The function should be case-insensitive, meaning that uppercase and lowercase letters should be considered the same.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
var left = 0
var right = text.count - 1
while left < right {
if!text[left].isLetter {
left += 1
continue
}
if!text[right].isLetter {
right -= 1
continue
}
if text[left].lowercased()!= text[right].lowercased() {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given string is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider only letters.
// The function should be case-insensitive, meaning that uppercase and lowercase letters should be considered the same.
// The function should have a time complexity of O(n), where n is the length of the input string.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
var left = 0
var right = text.count - 1
while left < right {
if!text[left].isLetter {
left += 1
continue
}
if!text[right].isLetter {
right -= 1
continue
}
if text[left].lowercased()!= text[right].lowercased() {
return false
}
left += 1
right -= 1
}
return true
}
// Tests
assert(isPalindrome(text: "")) == true
assert(isPalindrome(text: "aba")) == true
assert(isPalindrome(text: "aaaaa")) == true
assert(isPalindrome(text: "zbcd")) == false
assert(isPalindrome(text: "Able was I saw I saw Elba.")) == true
assert(isPalindrome(text: "Hello, World!")) == false
assert(isPalindrome(text: "12321")) == true
assert(isPalindrome(text: "abcdef")) == false
assert(isPalindrome(text: "A man, a plan, a canal, Panama!")) == true
assert(isPalindrome(text: "Race car!")) == true
assert(isPalindrome(text: "Hello World")) == false
assert(isPalindrome(text: "123 21")) == false
assert(isPalindrome(text: "123-21")) == false
assert(isPalindrome(text: "123,21")) == false
assert(isPalindrome(text: "123.21")) == false
assert(isPalindrome(text: "123:21")) == false
assert(isPalindrome(text: "123'21")) == false
assert(isPalindrome(text: "123\"21")) == false
assert(isPalindrome(text: "123$21")) == false
assert(isPalindrome(text: "123@21")) == false
assert(isPalindrome(text: "123!21")) == false
assert(isPalindrome(text: "123.21")) == false
assert(isPalindrome(text: "123_21")) == false
assert(isPalindrome(text: "123-21")) == false
assert(isPalindrome(text: "123 21")) == false
assert(isPalindrome(text: "123'21")) == false
assert(isPalindrome(text: "123\"21")) == false
assert(isPalindrome(text: "123:21")) == false
assert(isPalindrome(text: "123!21")) == false
assert(isPalindrome(text: "123?21")) == false
assert(isPalindrome(text: "123<21")) == false
assert(isPalindrome(text: "123>21")) == false
assert(isPalindrome(text: "123&21")) == false
assert(isPalindrome(text: "123|21")) == false
assert(isPalindrome(text: "123^21")) == false
assert(isPalindrome(text: "123%21")) == false
assert(isPalindrome(text: "123*21")) == false
assert(isPalindrome(text: "123(21")) == false
assert(isPalindrome(text: "123)21")) == false
assert(isPalindrome(text: "123[21")) == false
assert(isPalind
if!text[left].isLetter { // expected expression, var, or let in 'if' condition
if!text[right].isLetter { // expected expression, var, or let in 'if' condition
if text[left].lowercased()!= text[right].lowercased() { // '=' must have consistent whitespace on both sides
if text[left].lowercased()!= text[right].lowercased() { // cannot force unwrap value of non-optional type 'String'
if text[left].lowercased()!= text[right].lowercased() { // use of '=' in a boolean context, did you mean '=='?
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given text is a palindrome, false otherwise.
// The function should ignore any non-alphabetic characters and consider case-insensitivity.
// The function should have a time complexity of O(n), where n is the length of the text.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules.
// The function should be implemented using pure Swift code.
// The function should also handle special characters and emojis correctly.
// The function should handle Unicode characters correctly.
// The function should handle empty strings correctly, by returning true.
// The function should handle strings with only one character correctly, by returning true.
// The function should handle strings with non-alphabetic characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with non-alphabetic characters at the beginning or end correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with non-alphabetic characters in the middle correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with uppercase and lowercase letters correctly, by considering them as the same character and ignoring any non-alphabetic characters.
// The function should handle strings with special characters (e.g. punctuation marks, symbols) correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with emojis correctly, by considering them as alphabetic characters and ignoring any non-alphabetic characters.
// The function should handle strings with multiple occurrences of the same character correctly, by returning true if the remaining characters form a palindrome.
// The function should handle strings with multiple occurrences of the same Unicode character correctly, by returning true if the remaining characters form a palindrome.
// The function should handle strings with leading and trailing whitespace characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with leading or trailing whitespace characters that are not alphabetic characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive whitespace characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive non-alphabetic characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive alphabetic and non-alphabetic characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive Unicode characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive alphabetic, non-alphabetic, and Unicode characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive special characters (e.g. punctuation marks, symbols) correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive emojis correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive uppercase and lowercase letters correctly, by considering them as the same character and ignoring any non-alphabetic characters.
// The function should handle strings with consecutive special characters (e.g. punctuation marks, symbols) correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive emojis correctly, by considering them as alphabetic characters and ignoring any non-alphabetic characters.
// The function should handle strings with consecutive numbers correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive non-alphabetic and non-whitespace characters correctly, by ignoring them and returning true if the remaining characters form a palindrome.
// The function should handle strings with consecutive alphabetic, non-alphabetic, non-whitespace, and Unicode characters correctly, by ignoring them and returning true if the remaining characters form
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return true if the given text is a palindrome, false otherwise.
// The function should ignore any non-alphanumeric characters and consider case insensitivity.
// The function should have a time complexity of O(n), where n is the length of the text.
// The function should have a space complexity of O(1), i.e., it should not use any additional data structures other than variables to store intermediate results.
// The function should not use any built-in string reversal functions or data structures.
// The function should not use any external libraries or modules.
// The function should be implemented using pure Swift code.
// The function should handle Unicode characters and support multibyte character encodings.
// The function should also handle special characters, such as punctuation marks and emojis, and correctly identify them when checking for palindromes.
// The function should be able to handle very long texts, with a length of up to 10^9 characters.
// The function should also handle texts that contain numbers and symbols, such as "abc123!@#" and correctly identify them when checking for palindromes.
// The function should handle texts that contain non-printable characters, such as control characters and tabs, and correctly identify them when checking for palindromes.
// The function should handle texts that contain escaped characters, such as "\t" and "\\", and correctly identify them when checking for palindromes.
// The function should handle texts that contain emoji characters and correctly identify them when checking for palindromes.
// The function should handle texts that contain emojis with modifiers, such as "🔥🔥🔥" and correctly identify them when checking for palindromes.
// The function should handle texts that contain non-ASCII characters and correctly identify them when checking for palindromes.
// The function should handle texts that contain multiple languages or scripts, such as Japanese, Chinese, or Korean, and correctly identify them when checking for palindromes.
// The function should handle texts that contain right-to-left languages, such as Arabic or Hebrew, and correctly identify them when checking for palindromes.
// The function should handle texts that contain right-to-left text directionality, such as bidirectional text or text with mixed directionality, and correctly identify them when checking for palindromes.
// The function should handle texts that contain text formatting, such as bold or italics, and correctly identify them when checking for palindromes.
// The function should handle texts that contain diacritical marks, such as accents or special characters, and correctly identify them when checking for palindromes.
// The function should handle texts that contain non-printable characters, such as control characters or tabs, and correctly identify them when checking for palindromes.
// The function should handle texts that contain escaped characters, such as "\t" or "\\", and correctly identify them when checking for palindromes.
// The function should handle texts that contain emoji characters and correctly identify them when checking for palindromes.
// The function should handle texts that contain emojis with modifiers, such as "🔥🔥🔥" and correctly identify them when checking for palindromes.
// The function should handle texts that contain non-ASCII characters and correctly identify them when checking for palindromes.
// The function should handle texts that contain multiple languages or scripts, such as Japanese, Chinese, or Korean, and correctly identify them when checking for palindromes.
// The function should handle texts that contain right-to-left languages, such as Arabic or Hebrew, and correctly identify them when checking for palindromes.
// The function should handle texts that contain right-to-left text directionality, such as bidirectional text or text with mixed directionality, and correctly identify them when checking for palindromes.
// The function should handle texts that contain text formatting, such as bold or italics, and correctly identify them when checking for palindromes.
// The function should handle texts that contain diacritical marks, such as accents or special characters, and correctly identify them when checking for palindromes.
// The function should handle texts that contain non-printable characters, such as control characters or tabs, and correctly identify them when checking for palindromes.
// The function should handle texts that contain escaped characters, such as "\t" or "\\", and correctly identify them when checking for
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 modp(n: Int, p: Int) -> Int {
var (result, nn) = (1, n)
while nn > 0 {
if nn % 2 == 1 {
result = (result * p) % 100
}
nn /= 2
p = (p * p) % 100
}
return result % 100
}
func coinChange(coins: [Int], amount: Int) -> Int {
if amount == 0 {
return 1
}
var (result, coins, amount) = (0, coins.sorted(by: <), amount)
while coins.last! <= amount {
result += coinChange(coins: Array(coins.dropLast()), amount: amount - coins.last!)
amount -= coins.last!
}
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, nn) = (1, n)
while nn > 0 {
if nn % 2 == 1 {
result = (result * p) % 100
}
nn /= 2
p = (p * p) % 100
}
return result % 100
}
// Return the number of ways to make change with coins of given denominations.
// coinChange(coins: [1, 2, 5], amount: 100) == 1194
// coinChange(coins: [25, 10, 5, 1], amount: 100) == 15
func coinChange(coins: [Int], amount: Int) -> Int {
if amount == 0 {
return 1
}
var (result, coins, amount) = (0, coins.sorted(by: <), amount)
while coins.last! <= amount {
result += coinChange(coins: Array(coins.dropLast()), amount: amount - coins.last!)
amount -= coins.last!
}
return result
}
// Return the number of ways to make change with coins of given denominations.
// coinChange(coins: [1, 2, 5], amount: 100) == 1194
// coinChange(coins: [25, 10, 5, 1], amount: 100) == 15
func coinChange(coins: [Int], amount: Int) -> Int {
if amount == 0 {
return 1
}
var (result, coins, amount) = (0, coins.sorted(by: <), amount)
while coins.last! <= amount {
result += coinChange(coins: Array(coins.dropLast()), amount: amount - coins.last!)
amount -= coins.last!
}
return result
}
// Return the number of ways to make change with coins of given denominations.
// coinChange(coins: [1, 2, 5], amount: 100) == 1194
// coinChange(coins: [25, 10, 5, 1], amount: 100) == 15
func coinChange(coins: [Int], amount: Int) -> Int {
if amount == 0 {
return 1
}
var (result, coins, amount) = (0, coins.sorted(by: <), amount)
while coins.last! <= amount {
result += coinChange(coins: Array(coins.dropLast()), amount: amount - coins.last!)
amount -= coins.last!
}
return result
}
// Return the number of ways to make change with coins of given denominations.
// coinChange(coins: [1, 2, 5], amount: 100) == 1194
// coinChange(coins: [25, 10, 5, 1], amount: 100) == 15
func coinChange(coins: [Int], amount: Int) -> Int {
if amount == 0 {
return 1
}
var (result, coins, amount) = (0, coins.sorted(by: <), amount)
while coins.last! <= amount {
result += coinChange(coins: Array(coins.dropLast()), amount: amount - coins.last!)
amount -= coins.last!
}
return result
}
// Return the number of ways to make change with coins of given denominations.
// coinChange(coins: [1, 2, 5], amount: 100) == 1194
// coinChange(coins: [25, 10, 5, 1], amount: 100) == 15
func coinChange(coins: [Int], amount: Int) -> Int {
if amount == 0 {
return 1
}
var (result, coins, amount) = (0, coins.sorted(by: <), amount)
while coins.last! <= amount {
result += coinChange(coins: Array(coins.dropLast()), amount: amount - coins.last!)
amount -= coins.last!
}
return result
}
// Return
p = (p * p) % 100 // cannot assign to value: 'p' is a 'let' constant
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 {
n += p
}
return n
}
func gcd(a: Int, b: Int) -> Int {
var a = a
var b = b
while b!= 0 {
let t = b
b = a % b
a = t
}
return a
}
func gcd(_ a: [Int]) -> Int {
return a.reduce(a[0]) { gcd(a: $0, b: $1) }
}
func lcm(a: Int, b: Int) -> Int {
return a * b / gcd(a: a, b: b)
}
func lcm(_ a: [Int]) -> Int {
return a.reduce(a[0]) { lcm(a: $0, b: $1) }
}
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<Int(sqrt(Double(n))) + 1 {
if n % i == 0 {
return false
}
}
return true
}
func prime(_ n: Int) -> Int {
var i = 0
var j = 0
while i < n {
j += 1
if isPrime(j) {
i += 1
}
}
return j
}
func isPalindrome(_ n: Int) -> Bool {
return String(n) == String(String(n).reversed())
}
func fib(_ n: Int) -> Int {
var a = 0
var b = 1
for _ in 1...n {
(a, b) = (b, a + b)
}
return a
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 {
n += p
}
return n
}
// Return greatest common divisor of a and b.
// gcd(a: 3, b: 5) == 1
// gcd(a: 1101, b: 101) == 1
// gcd(a: 0, b: 101) == 0
// gcd(a: 3, b: 11) == 1
// gcd(a: 100, b: 101) == 1
func gcd(a: Int, b: Int) -> Int {
var a = a
var b = b
while b!= 0 {
let t = b
b = a % b
a = t
}
return a
}
// Return greatest common divisor of array of integers.
// gcd([3, 5, 11, 101]) == 1
// gcd([1101, 101, 0, 3, 11]) == 1
// gcd([100, 101]) == 1
func gcd(_ a: [Int]) -> Int {
return a.reduce(a[0]) { gcd(a: $0, b: $1) }
}
// Return least common multiple of a and b.
// lcm(a: 3, b: 5) == 15
// lcm(a: 1101, b: 101) == 1101
// lcm(a: 0, b: 101) == 0
// lcm(a: 3, b: 11) == 33
// lcm(a: 100, b: 101) == 10100
func lcm(a: Int, b: Int) -> Int {
return a * b / gcd(a: a, b: b)
}
// Return least common multiple of array of integers.
// lcm([3, 5, 11, 101]) == 6605
// lcm([1101, 101, 0, 3, 11]) == 0
// lcm([100, 101]) == 10100
func lcm(_ a: [Int]) -> Int {
return a.reduce(a[0]) { lcm(a: $0, b: $1) }
}
// Return true if n is prime.
// isPrime(13) == true
// isPrime(15) == false
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<Int(sqrt(Double(n))) + 1 {
if n % i == 0 {
return false
}
}
return true
}
// Return n-th prime number.
// prime(1) == 2
// prime(2) == 3
// prime(10) == 11
func prime(_ n: Int) -> Int {
var i = 0
var j = 0
while i < n {
j += 1
if isPrime(j) {
i += 1
}
}
return j
}
// Return true if n is a palindrome.
// isPalindrome(121) == true
// isPalindrome(123) == false
func isPalindrome(_ n: Int) -> Bool {
return String(n) == String(String(n).reversed())
}
// Return n-th fibonacci number.
// fib(1) == 1
// fib(2) == 1
// fib(10) == 55
func fib(_ n: Int) -> Int {
var a = 0
var b = 1
for _ in 1...n {
(a, b) = (b, a + b)
}
return a
}
// Return n-th triangular number.
// tri(1) == 1
// tri(3) == 6
// tri(10) == 55
func tri(_ n: Int) -> Int {
return n * (n + 1) / 2
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
func modp(n: Int, p: Int) -> Int {
var result = 1
var nn = n
while nn > 0 {
if nn % 2 == 1 {
result = (result * p) % 101
}
nn /= 2
p *= p
p %= 101
}
return result
}
func square_sum(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
func square_sum_fast(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
func square_sum_fast_slow(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
func square_sum_fast_slow_fast(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var result = 1
var nn = n
while nn > 0 {
if nn % 2 == 1 {
result = (result * p) % 101
}
nn /= 2
p *= p
p %= 101
}
return result
}
// Return the number of ways to write n as the sum of consecutive squares.
// The number falls within the range [0, 10^12].
// square_sum(n: 1) == 1
// square_sum(n: 2) == 2
// square_sum(n: 3) == 3
// square_sum(n: 4) == 5
// square_sum(n: 5) == 10
// square_sum(n: 6) == 17
// square_sum(n: 7) == 28
// square_sum(n: 10) == 89
func square_sum(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
// Return the number of ways to write n as the sum of consecutive squares.
// The number falls within the range [0, 10^12].
// square_sum_fast(n: 1) == 1
// square_sum_fast(n: 2) == 2
// square_sum_fast(n: 3) == 3
// square_sum_fast(n: 4) == 5
// square_sum_fast(n: 5) == 10
// square_sum_fast(n: 6) == 17
// square_sum_fast(n: 7) == 28
// square_sum_fast(n: 10) == 89
func square_sum_fast(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
// Return the number of ways to write n as the sum of consecutive squares.
// The number falls within the range [0, 10^12].
// square_sum_fast(n: 1) == 1
// square_sum_fast(n: 2) == 2
// square_sum_fast(n: 3) == 3
// square_sum_fast(n: 4) == 5
// square_sum_fast(n: 5) == 10
// square_sum_fast(n: 6) == 17
// square_sum_fast(n: 7) == 28
// square_sum_fast(n: 10) == 89
func square_sum_fast_slow(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
// Return the number of ways to write n as the sum of consecutive squares.
// The number falls within the range [0, 10^12].
// square_sum_fast(n: 1) == 1
// square_sum_fast(n: 2) == 2
// square_sum_fast(n: 3) == 3
// square_sum_fast(n: 4) == 5
// square_sum_fast(n: 5) == 10
// square_sum_fast(n: 6) == 17
// square_sum_fast(n: 7) == 28
// square_sum_fast(n: 10) == 89
func square_sum_fast_slow_fast(n: Int) -> Int {
return (1...n).map(modp).reduce(0, +)
}
// Return the number of ways to write n as the sum of consecutive squares.
// The number falls within the range [0, 10^12].
// square_sum_fast(n: 1) == 1
// square_sum_fast(n: 2) == 2
// square_sum_fast(n: 3) == 3
// square_sum_fast(n: 4) == 5
// square_sum_fast(n: 5) == 10
// square_sum_fast(n: 6) == 17
// square_
p *= p // left side of mutating operator isn't mutable: 'p' is a 'let' constant
p %= 101 // left side of mutating operator isn't mutable: 'p' is a 'let' constant
return (1...n).map(modp).reduce(0, +) // cannot convert value of type '(Int, Int) -> Int' to expected argument type '(ClosedRange<Int>.Element) throws -> Int' (aka '(Int) throws -> Int')
return (1...n).map(modp).reduce(0, +) // cannot convert value of type '(Int, Int) -> Int' to expected argument type '(ClosedRange<Int>.Element) throws -> Int' (aka '(Int) throws -> Int')
return (1...n).map(modp).reduce(0, +) // cannot convert value of type '(Int, Int) -> Int' to expected argument type '(ClosedRange<Int>.Element) throws -> Int' (aka '(Int) throws -> Int')
return (1...n).map(modp).reduce(0, +) // cannot convert value of type '(Int, Int) -> Int' to expected argument type '(ClosedRange<Int>.Element) throws -> Int' (aka '(Int) throws -> Int')
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
if n < 0 {
n += p
}
if p < 0 {
p += n
}
return n % p
}
func gcd(a: Int, b: Int) -> Int {
var a = a
var b = b
while b!= 0 {
(a, b) = (b, a % b)
}
return a
}
func inv(x: Int, p: Int) -> Int {
return modp(n: pow(a: x, b: p - 2, p: p), p: p)
}
func pow(a: Int, b: Int, p: Int) -> Int {
var a = a
var b = b
var res = 1
while b > 0 {
if modp(n: b, p: 2) == 1 {
res = modp(n: res * a, p: p)
}
a = modp(n: a * a, p: p)
b >>= 1
}
return res
}
func trailing_zeros(n: Int) -> Int {
var n = n
var count = 0
while n > 0 {
n /= 5
count += n
}
return count
}
```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
if n < 0 {
n += p
}
if p < 0 {
p += n
}
return n % p
}
// Return the greatest common divisor of a and b.
// gcd(a: 3, b: 10) == 1
// gcd(a: 10, b: 3) == 1
// gcd(a: 3, b: 7) == 1
// gcd(a: 7, b: 3) == 1
// gcd(a: 3, b: 15) == 3
// gcd(a: 15, b: 3) == 3
// gcd(a: 3, b: 100) == 1
// gcd(a: 100, b: 3) == 1
// gcd(a: 3, b: 101) == 1
// gcd(a: 101, b: 3) == 1
func gcd(a: Int, b: Int) -> Int {
var a = a
var b = b
while b!= 0 {
(a, b) = (b, a % b)
}
return a
}
// Return the inverse of x modulo p.
// inv(x: 3, p: 101) == 7
// inv(x: 7, p: 101) == 3
// inv(x: 101, p: 101) == 1
// inv(x: 100, p: 101) == 99
func inv(x: Int, p: Int) -> Int {
return modp(n: pow(a: x, b: p - 2, p: p), p: p)
}
// Return the result of raising a to b modulo p.
// pow(a: 3, b: 10, p: 101) == 99
// pow(a: 3, b: 0, p: 101) == 1
// pow(a: 3, b: 1, p: 101) == 3
// pow(a: 3, b: 100, p: 101) == 99
func pow(a: Int, b: Int, p: Int) -> Int {
var a = a
var b = b
var res = 1
while b > 0 {
if modp(n: b, p: 2) == 1 {
res = modp(n: res * a, p: p)
}
a = modp(n: a * a, p: p)
b >>= 1
}
return res
}
// Return the number of trailing zeros of n.
// trailing_zeros(n: 3) == 0
// trailing_zeros(n: 5) == 1
// trailing_zeros(n: 6) == 1
// trailing_zeros(n: 7) == 2
// trailing_zeros(n: 9) == 2
// trailing_zeros(n: 10) == 1
// trailing_zeros(n: 100) == 2
// trailing_zeros(n: 1000) == 3
// trailing_zeros(n: 10000) == 4
// trailing_zeros(n: 100000) == 5
// trailing_zeros(n: 1000000) == 6
func trailing_zeros(n: Int) -> Int {
var n = n
var count = 0
while n > 0 {
n /= 5
count += n
}
return count
}
// Return the prime factorization of n.
// prime_factorization(n: 135246) == [2: 2, 3: 3, 23: 2]
// prime_factorization(n: 1) == [1: 1]
// prime_factorization(n: 0) == [0: 1]
func prime_factorization(n: Int) -> [Int: Int] {
var n = n
var res = [Int: Int]()
var i =
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // '=' must have consistent whitespace on both sides
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n % p
if n < 0 { n += p }
return n
}
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n, p = p
while p > 0 {
if p % 2 == 1 {
n = (n * n) % p
}
p /= 2
n = n * n % p
}
return n
}
func isSquare(n: Int) -> Bool {
let sqrt = Int(sqrt(Double(n)))
return sqrt * sqrt == n
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n, p = p
while p > 0 {
if p % 2 == 1 {
n = (n * n) % p
}
p /= 2
n = n * n % p
}
return n
}
// Return true if n is a square number.
// isSquare(1) == true
// isSquare(4) == true
// isSquare(5) == false
// isSquare(8) == true
// isSquare(9) == false
func isSquare(n: Int) -> Bool {
let sqrt = Int(sqrt(Double(n)))
return sqrt * sqrt == n
}
// Return true if n is a prime number.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(3) == true
// isPrime(4) == false
// isPrime(5) == true
// isPrime(6) == false
// isPrime(7) == true
// isPrime(8) == false
// isPrime(9) == false
// isPrime(10) == false
// isPrime(11) == true
// isPrime(12) == false
// isPrime(13) == true
// isPrime(14) == false
// isPrime(15) == false
// isPrime(16) == false
// isPrime(17) == true
// isPrime(18) == false
// isPrime(19) == true
// isPrime(20) == false
// isPrime(21) == false
// isPrime(22) == false
// isPrime(23) == true
// isPrime(24) == false
// isPrime(25) == false
// isPrime(26) == false
// isPrime(27) == true
// isPrime(28) == false
// isPrime(29) == false
// isPrime(30) == false
// isPrime(31) == true
// isPrime(32) == false
// isPrime(33) == false
// isPrime(34) == false
// isPrime(35) == true
// isPrime(36) == false
// isPrime(37) == false
// isPrime(38) == false
// isPrime(39) == false
// isPrime(40) == false
// isPrime(41) == true
// isPrime(42) == false
// isPrime(43) == false
// isPrime(44) == false
// isPrime(45) == false
// isPrime(46) == false
// isPrime(47) == true
// isPrime(48) == false
// isPrime(49) == false
// isPrime(50) == false
// isPrime(51) == false
// isPrime(52) == false
// isPrime(53) == true
// isPrime(54) == false
// isPrime(55) == false
// isPrime(56) == false
// isPrime(57) == true
// isPrime(58) == false
// isPrime(59) == false
// isPrime(60) == false
// isPrime(61) == false
// isPrime(62) == false
// isPrime(63) == true
// isPrime(64) == false
// isPrime(65) == false
// isPrime(66) == false
// isPrime(67) == false
// isPrime(68) == false
// isPrime(69) == false
// isPrime(70) == false
// isPrime(71) == true
// isPrime(72) == false
// isPrime(73) == false
// isPrime(74) == false
// isPrime(75) == false
// isPrime(76) == false
// isPrime(77) == true
// isPrime(78) == false
// isPrime(79) == false
// isPrime(80) == false
// isPrime(81) == false
// isPrime(82) == false
// isPrime(83) == true
// isPrime(84) == false
// isPrime(85) == false
// isPrime(86) == false
// isPrime(87) == false
// is
// Fatal error: Division by zero in remainder operation
func modp(n: Int, p: Int) -> Int {
if n == 0 { return 1 }
if p == 1 { return 0 }
let k = n % p
if k == 0 { return 0 }
return k * modp(n: p-1, p: p) % p
}
func catalan(n: Int, k: Int) -> Int {
if k == 0 || k == n { return 1 }
return catalan(n: n-1, k: k-1) * (n+k-1) / k
}
func primecount(n: Int) -> Int {
var sieve = Array(repeating: true, count: n+1)
sieve[0] = false
sieve[1] = false
for i in 2...Int(sqrt(Double(n))) {
if sieve[i] {
for j in stride(from: i*i, through: n, by: i) {
sieve[j] = false
}
}
}
var count = 0
for i in 0...n {
if sieve[i] {
count += 1
}
}
return count
}
func fibonacci(n: Int) -> Int {
if n == 1 { return 1 }
if n == 2 { return 1 }
return fibonacci(n: n-1) + fibonacci(n: n-2)
}
func lucas(n: Int) -> Int {
if n == 1 { return 2 }
if n == 2 { return 1 }
return lucas(n: n-1) + lucas(n: n-2)
}
func tribonacci(n: Int) -> Int {
if n == 1 { return 1 }
if n == 2 { return 1 }
if n == 3 { return 2 }
return tribonacci(n: n-1) + tribonacci(n: n-2) + tribonacci(n: n-3)
}
```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 {
if n == 0 { return 1 }
if p == 1 { return 0 }
let k = n % p
if k == 0 { return 0 }
return k * modp(n: p-1, p: p) % p
}
// Return the number of distinct ways to choose k elements from a set of size n.
// The number of distinct ways to choose k elements from a set of size n is equal to
// the Catalan number C(n, k).
// catalan(n: 3, k: 2) == 3
// catalan(n: 3, k: 1) == 3
// catalan(n: 3, k: 0) == 1
// catalan(n: 3, k: 3) == 0
func catalan(n: Int, k: Int) -> Int {
if k == 0 || k == n { return 1 }
return catalan(n: n-1, k: k-1) * (n+k-1) / k
}
// Return the number of prime numbers up to n.
// The number of prime numbers up to n is equal to the number of primes <= n.
// primecount(10) == 4
// primecount(100) == 25
func primecount(n: Int) -> Int {
var sieve = Array(repeating: true, count: n+1)
sieve[0] = false
sieve[1] = false
for i in 2...Int(sqrt(Double(n))) {
if sieve[i] {
for j in stride(from: i*i, through: n, by: i) {
sieve[j] = false
}
}
}
var count = 0
for i in 0...n {
if sieve[i] {
count += 1
}
}
return count
}
// Return the nth Fibonacci number.
// The first Fibonacci number is 1, the second Fibonacci number is 1,
// and each subsequent term is the sum of the previous two.
// fibonacci(1) == 1
// fibonacci(2) == 1
// fibonacci(3) == 2
// fibonacci(4) == 3
func fibonacci(n: Int) -> Int {
if n == 1 { return 1 }
if n == 2 { return 1 }
return fibonacci(n: n-1) + fibonacci(n: n-2)
}
// Return the nth Lucas number.
// The first Lucas number is 2, the second Lucas number is 1,
// and each subsequent term is the sum of the previous two.
// lucas(1) == 2
// lucas(2) == 1
// lucas(3) == 3
// lucas(4) == 4
func lucas(n: Int) -> Int {
if n == 1 { return 2 }
if n == 2 { return 1 }
return lucas(n: n-1) + lucas(n: n-2)
}
// Return the nth Tribonacci number.
// The first Tribonacci number is 1, the second Tribonacci number is 1,
// the third Tribonacci number is 2, and each subsequent term is the sum of the previous three.
// tribonacci(1) == 1
// tribonacci(2) == 1
// tribonacci(3) == 2
// tribonacci(4) == 4
func tribonacci(n: Int) -> Int {
if n == 1 { return 1 }
if n == 2 { return 1 }
if n == 3 { return 2 }
return tribonacci(n: n-1) + tribonacci(n: n-2) + tribonacci(n: n-3)
}
// Return the nth Pell number.
// The first Pell number is 3, the second Pell number is 1,
// and each subsequent term is the sum of the previous two.
// pell(1) == 3
// p
func modp(n: Int, p: Int) -> Int {
if n == 0 { return 1 }
if p == 1 { return 0 }
let k = n % p
if k == 0 { return p }
return k
}
func inv(n: Int, p: Int) -> Int {
if n == 1 { return 1 }
if p == 1 { return 0 }
let a = modp(n: n, p: p)
var b = p
var x = 0
var y = 1
while b > 0 {
let q = a / b
let r = a - q * b
a = b
b = r
let s = x - q * y
x = y
y = s
}
return modp(n: x, p: p)
}
func mmi(n: Int, p: Int) -> Int {
return inv(n: n, p: p)
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
if n == 0 { return 1 }
if p == 1 { return 0 }
let k = n % p
if k == 0 { return p }
return k
}
// Return the inverse of a mod p.
// inv(1, 11) == 1
// inv(2, 11) == 9
// inv(3, 11) == 4
// inv(4, 11) == 7
// inv(5, 11) == 6
// inv(6, 11) == 5
// inv(7, 11) == 3
// inv(8, 11) == 2
// inv(9, 11) == 8
// inv(10, 11) == 10
// inv(11, 11) == 1
func inv(n: Int, p: Int) -> Int {
if n == 1 { return 1 }
if p == 1 { return 0 }
let a = modp(n: n, p: p)
var b = p
var x = 0
var y = 1
while b > 0 {
let q = a / b
let r = a - q * b
a = b
b = r
let s = x - q * y
x = y
y = s
}
return modp(n: x, p: p)
}
// Return the multiplicative inverse of a mod p.
// mmi(1, 11) == 1
// mmi(2, 11) == 9
// mmi(3, 11) == 4
// mmi(4, 11) == 7
// mmi(5, 11) == 6
// mmi(6, 11) == 5
// mmi(7, 11) == 3
// mmi(8, 11) == 2
// mmi(9, 11) == 8
// mmi(10, 11) == 10
// mmi(11, 11) == 1
func mmi(n: Int, p: Int) -> Int {
return inv(n: n, p: p)
}
// Return the result of a^b mod p.
// pow(1, 1, 11) == 1
// pow(1, 2, 11) == 1
// pow(1, 3, 11) == 1
// pow(1, 4, 11) == 1
// pow(1, 5, 11) == 1
// pow(1, 6, 11) == 1
// pow(1, 7, 11) == 1
// pow(1, 8, 11) == 1
// pow(1, 9, 11) == 1
// pow(1, 10, 11) == 1
// pow(1, 11, 11) == 1
// pow(2, 1, 11) == 2
// pow(2, 2, 11) == 4
// pow(2, 3, 11) == 8
// pow(2, 4, 11) == 5
// pow(2, 5, 11) == 10
// pow(2, 6, 11) == 9
// pow(2, 7, 11) == 7
// pow(2, 8, 11) == 3
// pow(2, 9, 11) == 6
// pow(2, 10, 11) == 1
// pow(2, 11, 11) == 1
// pow(3, 1, 11) == 3
// pow(3, 2, 11) == 9
// pow(3, 3, 11) == 7
// pow(3, 4, 11) == 10
// pow(3, 5, 11) == 6
// pow(3, 6, 11) == 1
// pow(3, 7, 11) == 8
// pow(3
a = b // cannot assign to value: 'a' is a 'let' constant
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
while n >= p {
n -= p
}
return n
}
func modpInverse(a: Int, p: Int) -> Int {
var a = a
var p = p
var t = 0
var newT = 1
var r = p
var newR = a
while newR!= 0 {
let quotient = r / newR
(r, newR) = (newR, modp(n: r - quotient * newR, p: p))
(t, newT) = (newT, modp(n: t - quotient * newT, p: p))
}
if t < 0 {
t += p
}
return t
}
func modpMulInverse(a: Int, p: Int) -> Int {
return modp(n: modpInverse(a: a, p: p), p: p)
}
func fib(n: Int, p: Int) -> Int {
if n <= 1 {
return n
}
let phi = (1 + sqrt(1 + Double(p))) / 2
let inversePhi = modpMulInverse(a: Int(phi), p: p)
let a = modp(n: inversePhi, p: p)
let b = modp(n: inversePhi * inversePhi - 1, p: p)
let result = modp(n: pow(a: a, b: n - 1), p: p)
return result
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
while n >= p {
n -= p
}
return n
}
// Return the inverse of a modulo p.
// modpInverse(a: 3, p: 5) == 2
// modpInverse(a: 1101, p: 101) == 1000
// modpInverse(a: 0, p: 101) == 0
// modpInverse(a: 3, p: 11) == 10
// modpInverse(a: 100, p: 101) == 4
func modpInverse(a: Int, p: Int) -> Int {
var a = a
var p = p
var t = 0
var newT = 1
var r = p
var newR = a
while newR!= 0 {
let quotient = r / newR
(r, newR) = (newR, modp(n: r - quotient * newR, p: p))
(t, newT) = (newT, modp(n: t - quotient * newT, p: p))
}
if t < 0 {
t += p
}
return t
}
// Return the multiplicative inverse of a modulo p.
// modpMulInverse(a: 3, p: 5) == 4
// modpMulInverse(a: 1101, p: 101) == 1001
// modpMulInverse(a: 0, p: 101) == 0
// modpMulInverse(a: 3, p: 11) == 10
// modpMulInverse(a: 100, p: 101) == 4
func modpMulInverse(a: Int, p: Int) -> Int {
return modp(n: modpInverse(a: a, p: p), p: p)
}
// Return the n-th fibonacci number modulo p.
// fib(n: 0, p: 10) == 0
// fib(n: 1, p: 10) == 1
// fib(n: 2, p: 10) == 1
// fib(n: 3, p: 10) == 2
// fib(n: 4, p: 10) == 3
// fib(n: 5, p: 10) == 5
// fib(n: 6, p: 10) == 8
// fib(n: 7, p: 10) == 13
// fib(n: 8, p: 10) == 21
// fib(n: 9, p: 10) == 34
// fib(n: 10, p: 10) == 55
func fib(n: Int, p: Int) -> Int {
if n <= 1 {
return n
}
let phi = (1 + sqrt(1 + Double(p))) / 2
let inversePhi = modpMulInverse(a: Int(phi), p: p)
let a = modp(n: inversePhi, p: p)
let b = modp(n: inversePhi * inversePhi - 1, p: p)
let result = modp(n: pow(a: a, b: n - 1), p: p)
return result
}
// Return the n-th triangular number modulo p.
// tri(n: 0, p: 10) == 0
// tri(n: 1, p: 10) == 1
// tri(n: 2, p: 10) == 3
// tri(n: 3, p: 10) == 6
// tri(n: 4, p: 10) == 10
// tri(n: 5, p: 10) == 15
// tri(n: 6, p: 10) == 21
// tri(n: 7, p: 10) == 28
// tri(n: 8, p: 10) == 36
// tri(n: 9, p: 10)
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
while newR!= 0 { // use of '=' in a boolean context, did you mean '=='?
while newR!= 0 { // cannot force unwrap value of non-optional type 'Int'
while newR!= 0 { // '=' must have consistent whitespace on both sides
let result = modp(n: pow(a: a, b: n - 1), p: p) // extraneous argument labels 'a:b:' in call
let result = modp(n: pow(a: a, b: n - 1), p: p) // cannot convert value of type 'Int' to expected argument type 'Decimal'
let result = modp(n: pow(a: a, b: n - 1), p: p) // cannot convert value of type 'Decimal' to expected argument type 'Int'
func modp(n: Int, p: Int) -> Int {
if n == 0 {
return 1
} else if n == 1 {
return 0
} else if n % 2 == 0 {
let half = modp(n: n/2, p: p)
return (half * half) % p
} else {
let half = modp(n: (n-1)/2, p: p)
return (half * half * n) % p
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
} else if n == 2 || n == 3 {
return true
} else if n % 2 == 0 {
return false
} else {
let limit = Int(sqrt(Double(n))) + 1
for divisor in 3...limit {
if n % divisor == 0 {
return false
}
}
return true
}
}
func prime(n: Int) -> Int {
if n == 1 {
return 2
} else {
var count = 1
var candidate = 3
while count < n {
if isPrime(n: candidate) {
count += 1
}
candidate += 2
}
return candidate
}
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
var last = 1
var next = 1
for _ in 3...n {
(last, next) = (next, last + next)
}
return next
}
}
func tri(n: Int) -> Int {
return n * (n + 1) / 2
}
func pent(n: Int) -> Int {
return n * (3 * n - 1) / 2
}
func hex(n: Int) -> Int {
return n * (2 * n - 1)
}
func hept(n: Int) -> Int {
return n * (5 * n - 3) / 2
}
func oct(n: Int) -> Int {
return n * (3 * n - 2)
}
func dodec(n: Int) -> Int {
return n * (7 * n - 5)
}
```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 {
if n == 0 {
return 1
} else if n == 1 {
return 0
} else if n % 2 == 0 {
let half = modp(n: n/2, p: p)
return (half * half) % p
} else {
let half = modp(n: (n-1)/2, p: p)
return (half * half * n) % p
}
}
// Return true iff n is prime.
// isPrime(1) == true
// isPrime(2) == true
// isPrime(3) == true
// isPrime(4) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
} else if n == 2 || n == 3 {
return true
} else if n % 2 == 0 {
return false
} else {
let limit = Int(sqrt(Double(n))) + 1
for divisor in 3...limit {
if n % divisor == 0 {
return false
}
}
return true
}
}
// Return the nth prime number.
// prime(1) == 2
// prime(2) == 3
// prime(3) == 5
// prime(4) == 7
func prime(n: Int) -> Int {
if n == 1 {
return 2
} else {
var count = 1
var candidate = 3
while count < n {
if isPrime(n: candidate) {
count += 1
}
candidate += 2
}
return candidate
}
}
// Return the nth Fibonacci number.
// fib(1) == 1
// fib(2) == 1
// fib(3) == 2
// fib(4) == 3
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
var last = 1
var next = 1
for _ in 3...n {
(last, next) = (next, last + next)
}
return next
}
}
// Return the nth triangular number.
// tri(1) == 1
// tri(2) == 3
// tri(3) == 6
// tri(4) == 10
func tri(n: Int) -> Int {
return n * (n + 1) / 2
}
// Return the nth pentagonal number.
// pent(1) == 1
// pent(2) == 5
// pent(3) == 12
// pent(4) == 22
func pent(n: Int) -> Int {
return n * (3 * n - 1) / 2
}
// Return the nth hexagonal number.
// hex(1) == 1
// hex(2) == 6
// hex(3) == 15
// hex(4) == 28
func hex(n: Int) -> Int {
return n * (2 * n - 1)
}
// Return the nth heptagonal number.
// hept(1) == 1
// hept(2) == 7
// hept(3) == 18
// hept(4) == 34
func hept(n: Int) -> Int {
return n * (5 * n - 3) / 2
}
// Return the nth octagonal number.
// oct(1) == 1
// oct(2) == 8
// oct(3) == 21
// oct(4) == 40
func oct(n: Int) -> Int {
return n * (3 * n - 2)
}
// Return the nth dodecagonal number.
// dodec(1) == 1
// dodec(2) == 12
// dodec(3) == 21
// dodec(4) == 35
func dodec(n: Int) -> Int {
return n * (7 * n - 5)
}
// Return the nthennea number.
// nthenea(1) == 1
// nthenea(2) == 1
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
func countWords(text: String) -> Int {
var wordCount = 0
var inWord = false
for char in text {
if char == " " {
inWord = false
} else if!inWord {
inWord = true
wordCount += 1
}
}
return wordCount
}
func isPalindrome(text: String) -> Bool {
var normalizedText = ""
for char in text {
if "a-zA-Z".contains(char) {
normalizedText += String(char).lowercased()
}
}
return normalizedText == String(normalizedText.reversed())
}
func morseCodeConversion(text: String) -> String {
var morseCode = ""
for char in text {
if "a-zA-Z".contains(char) {
morseCode += "•-\(char.uppercased())•"
}
}
return morseCode
}
func mostFrequentThreeLetterSequence(text: String) -> String {
var threeLetterSequence = ""
var maxCount = 0
var currentCount = 0
var currentChar = ""
var previousChar = ""
for char in text {
if "a-zA-Z".contains(char) {
currentChar = String(char).uppercased()
if currentChar == previousChar {
currentCount += 1
if currentCount == 3 {
threeLetterSequence = currentChar
maxCount = currentCount
}
} else {
currentCount = 1
}
previousChar = currentChar
}
}
return threeLetterSequence
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns number of words.
// countWords(text: "") == 0
// countWords(text: "Hello world!") == 1
// countWords(text: "One Two Three ") == 3
// countWords(text: "1234") == 0
// countWords(text: "One. Two, Three!") == 3
func countWords(text: String) -> Int {
var wordCount = 0
var inWord = false
for char in text {
if char == " " {
inWord = false
} else if!inWord {
inWord = true
wordCount += 1
}
}
return wordCount
}
// is_palindrome is a function that takes string and returns true if it is palindrome, false otherwise.
// isPalindrome(text: "") == true
// isPalindrome(text: "a") == true
// isPalindrome(text: "ab") == false
// isPalindrome(text: "abcba") == true
// isPalindrome(text: "abacdfgdcaba") == true
// isPalindrome(text: "abcdefg") == false
func isPalindrome(text: String) -> Bool {
var normalizedText = ""
for char in text {
if "a-zA-Z".contains(char) {
normalizedText += String(char).lowercased()
}
}
return normalizedText == String(normalizedText.reversed())
}
// morse_code_conversion is a function that takes string and returns string in Morse code.
// morseCodeConversion(text: "") == ""
// morseCodeConversion(text: "Hello world!") == "HE-LLO-WORLD"
// morseCodeConversion(text: "1234") == ""
// morseCodeConversion(text: "One. Two, Three!") == "OW-N OW-S TW-O-TH-REE"
func morseCodeConversion(text: String) -> String {
var morseCode = ""
for char in text {
if "a-zA-Z".contains(char) {
morseCode += "•-\(char.uppercased())•"
}
}
return morseCode
}
// most_frequent_three_letter_sequence is a function that takes string and returns the most frequent three-letter sequence.
// mostFrequentThreeLetterSequence(text: "") == ""
// mostFrequentThreeLetterSequence(text: "abc") == ""
// mostFrequentThreeLetterSequence(text: "abcabc") == "abc"
// mostFrequentThreeLetterSequence(text: "abcabcabc") == "abc"
// mostFrequentThreeLetterSequence(text: "abcabcabccdef") == "abc"
// mostFrequentThreeLetterSequence(text: "hello world") == "llo"
func mostFrequentThreeLetterSequence(text: String) -> String {
var threeLetterSequence = ""
var maxCount = 0
var currentCount = 0
var currentChar = ""
var previousChar = ""
for char in text {
if "a-zA-Z".contains(char) {
currentChar = String(char).uppercased()
if currentChar == previousChar {
currentCount += 1
if currentCount == 3 {
threeLetterSequence = currentChar
maxCount = currentCount
}
} else {
currentCount = 1
}
previousChar = currentChar
}
}
return threeLetterSequence
}
// longest_palindrome_substring is a function that takes string and returns the longest palindrome substring.
// longestPalindromeSubstring(text: "") == ""
// longestPalindromeSubstring(text: "a") == "a"
// longestPalindromeSubstring(text: "ab") == "ab"
// longestPalindromeSubstring(text: "abc") == "abc"
// longestPalindromeSubstring(text: "abcba") == "abcba"
// longestPalindromeSubstring(text: "abacdfgdcaba") == "aba"
// longestPalindromeSubstring(text: "
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
} else if!inWord { // expected expression, var, or let in 'if' condition
var maxCount = 0 // variable 'maxCount' was written to, but never read
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
func countWords(text: String) -> [String: Int] {
var words = [String: Int]()
var word = ""
for char in text {
if char.isLetter {
word += String(char)
} else {
if!word.isEmpty {
words[word, default: 0] += 1
word = ""
}
}
}
if!word.isEmpty {
words[word, default: 0] += 1
}
return words
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns dictionary of words and their counts.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana 234") == ["apple": 1, "banana": 2]
// countWords(text: "apple #$% banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple #$% banana asdf") == ["apple": 1, "banana": 1, "asdf": 1]
// countWords(text: "apple #$% banana asdf qwer") == ["apple": 1, "banana": 1, "asdf": 1, "qwer": 1]
// countWords(text: "apple #$% banana asdf qwer #$%") == ["apple": 1, "banana": 1, "asdf": 1, "qwer": 1]
// countWords(text: "apple #$% banana asdf qwer #$% apple") == ["apple": 2, "banana": 1, "asdf": 1, "qwer": 1]
func countWords(text: String) -> [String: Int] {
var words = [String: Int]()
var word = ""
for char in text {
if char.isLetter {
word += String(char)
} else {
if!word.isEmpty {
words[word, default: 0] += 1
word = ""
}
}
}
if!word.isEmpty {
words[word, default: 0] += 1
}
return words
}
// remove_words is a function that takes string, dictionary of words and their counts and returns string without specified words.
// removeWords(text: "", words: [:]) == ""
// removeWords(text: "apple", words: ["apple": 1]) == ""
// removeWords(text: "apple", words: ["banana": 1]) == "apple"
// removeWords(text: "apple banana", words: ["apple": 1]) == "banana"
// removeWords(text: "apple banana", words: ["banana": 1]) == "apple"
// removeWords(text: "apple 123 banana 234", words: ["banana": 1]) == "apple 123 "
// removeWords(text: "apple 123 banana 234", words: ["apple": 1, "banana": 1]) == ""
// removeWords(text: "apple #$% banana asdf", words: ["apple": 1, "banana": 1]) == "asdf #$%"
// removeWords(text: "apple #$% banana asdf qwer", words: ["apple": 1, "banana": 1]) == "asdf qwer #$%"
// removeWords(text: "apple #$% banana asdf qwer", words: ["apple": 1, "banana": 1, "asdf": 1]) == "qwer"
// removeWords(text: "apple #$% banana asdf qwer", words: ["apple": 1, "banana": 1, "qwer": 1]) == "asdf #$%"
// removeWords(text: "apple #$% banana asdf qwer", words: ["apple": 1, "banana": 1, "asdf": 1, "qwer": 1]) == ""
// removeWords(text: "apple #$% banana asdf qwer #$%", words: ["apple": 1, "banana": 1, "asdf": 1, "qwer": 1]) == ""
// removeWords(text: "apple #$% banana asdf qwer #$% apple", words: ["apple": 1, "banana":
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
if!word.isEmpty { // expected expression, var, or let in 'if' condition
if!word.isEmpty { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
func countWords(text: String) -> [String: Int] {
var dict = [String: Int]()
let words = text.components(separatedBy: " ")
for word in words {
if!dict.keys.contains(word) {
dict[word] = 1
} else {
dict[word]! += 1
}
}
return dict
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns dictionary with words and their counts.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana 234") == ["apple": 1, "banana": 2]
// countWords(text: "apple 123 banana 234 apple 567") == ["apple": 2, "banana": 2]
// countWords(text: "One apple, two apples, three apples, and one banana") == ["apple": 3, "banana": 1]
// countWords(text: "One apple, two apples, three apples, and one Banana") == ["apple": 3, "banana": 1]
// countWords(text: "One apple, two apples, three apples, and one BaNaNa") == ["apple": 3, "banana": 1]
// countWords(text: "One apple, two apples, three apples, and one BaNaNa bAnana") == ["apple": 3, "banana": 2]
func countWords(text: String) -> [String: Int] {
var dict = [String: Int]()
let words = text.components(separatedBy: " ")
for word in words {
if!dict.keys.contains(word) {
dict[word] = 1
} else {
dict[word]! += 1
}
}
return dict
}
// print_top_10 is a function that takes dictionary with words and their counts and prints top 10 most used words.
// printTop10(words: [:])
// printTop10(words: ["apple": 1])
// printTop10(words: ["apple": 1, "banana": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1, "fig": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1, "fig": 1, "grape": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1, "fig": 1, "grape": 1, "honeydew": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1, "fig": 1, "grape": 1, "honeydew": 1, "indian": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1, "fig": 1, "grape": 1, "honeydew": 1, "indian": 1, "ivory": 1])
func printTop10(words: [String: Int]) {
var sortedWords = words.sorted { $0.value > $1.value }
sortedWords = Array(sortedWords
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
if!dict.keys.contains(word) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
func countWords(text: String) -> [String: Int] {
var wordCount = [String: Int]()
let words = text.components(separatedBy: " ")
for word in words {
if wordCount[word]!= nil {
wordCount[word]! += 1
} else {
wordCount[word] = 1
}
}
return wordCount
}
func printTopWords(wordCount: [String: Int]) {
let sortedWords = wordCount.sorted { (a, b) -> Bool in
return a.value > b.value
}
for (word, count) in sortedWords.prefix(10) {
print("\(word): \(count)")
}
}
func main() {
print("Enter a text: ")
let text = readLine()?? ""
let newText = removeVowels(text: text)
let wordCount = countWords(text: newText)
printTopWords(wordCount: wordCount)
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns dictionary with words and their counts.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana 321") == ["apple": 1, "banana": 2]
// countWords(text: "One apple, two apples, three apples, and one hundred apples.") == ["apple": 1, "two": 1, "three": 1, "one hundred": 1]
func countWords(text: String) -> [String: Int] {
var wordCount = [String: Int]()
let words = text.components(separatedBy: " ")
for word in words {
if wordCount[word]!= nil {
wordCount[word]! += 1
} else {
wordCount[word] = 1
}
}
return wordCount
}
// print_top_words is a function that takes dictionary with words and their counts and prints top 10 words in descending order.
// printTopWords(wordCount: [:])
func printTopWords(wordCount: [String: Int]) {
let sortedWords = wordCount.sorted { (a, b) -> Bool in
return a.value > b.value
}
for (word, count) in sortedWords.prefix(10) {
print("\(word): \(count)")
}
}
// main is the entry point of the program.
// It prompts the user to enter a text, reads it, removes vowels, counts words, and prints the result.
func main() {
print("Enter a text: ")
let text = readLine()?? ""
let newText = removeVowels(text: text)
let wordCount = countWords(text: newText)
printTopWords(wordCount: wordCount)
}
main()
```
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
if wordCount[word]!= nil { // '=' must have consistent whitespace on both sides
if wordCount[word]!= nil { // 'nil' cannot be assigned to type 'Int'
if wordCount[word]!= nil { // use of '=' in a boolean context, did you mean '=='?
let text = readLine()?? "" // consecutive statements on a line must be separated by ';'
let text = readLine()?? "" // string literal is unused
let text = readLine()?? "" // cannot use optional chaining on non-optional value of type 'String'
func removeVowels(text: String) -> String {
var newString = ""
for character in text {
if!"aeiouAEIOU".contains(character) {
newString += String(character)
}
}
return newString
}
func countWords(text: String) -> [String: Int] {
var wordCount = [String: Int]()
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
for word in words {
if wordCount[word] == nil {
wordCount[word] = 1
} else {
wordCount[word]! += 1
}
}
return wordCount
}
func printTop10(wordCount: [String: Int]) {
var sortedWords = wordCount.sorted { $0.value > $1.value }
sortedWords.removeLast(sortedWords.count - 10)
for (word, count) in sortedWords {
print("\(word): \(count)")
}
}
func main() {
print("Enter a string: ")
let text = readLine()?? ""
let cleanedText = removeVowels(text: text)
let wordCount = countWords(text: cleanedText)
printTop10(wordCount: wordCount)
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for character in text {
if!"aeiouAEIOU".contains(character) {
newString += String(character)
}
}
return newString
}
// count_words is a function that takes string and returns dictionary of words and their counts.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana 234") == ["apple": 1, "banana": 2]
// countWords(text: "apple #$%") == ["apple": 1]
// countWords(text: "apple #$% banana #$%") == ["apple": 1, "banana": 1]
// countWords(text: "apple #$% banana #$% apple #$%") == ["apple": 2, "banana": 1]
// countWords(text: "I am number 23 in the shower") == ["am": 1, "number": 1, "shower": 1]
// countWords(text: "He plays basketball and he plays volleyball") == ["and": 1, "basketball": 1, "he": 2, "plays": 2, "volleyball": 1]
func countWords(text: String) -> [String: Int] {
var wordCount = [String: Int]()
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
for word in words {
if wordCount[word] == nil {
wordCount[word] = 1
} else {
wordCount[word]! += 1
}
}
return wordCount
}
// print_top_10 is a function that takes dictionary of words and their counts and prints top 10 most frequently used words.
// printTop10(wordCount: [:])
// printTop10(wordCount: ["apple": 1])
// printTop10(wordCount: ["apple": 1, "banana": 1])
// printTop10(wordCount: ["apple": 1, "banana": 1, "cherry": 1, "durian": 1, "eggplant": 1, "fig": 1, "grape": 1, "honeydew": 1, "indian": 1, "jackfruit": 1])
func printTop10(wordCount: [String: Int]) {
var sortedWords = wordCount.sorted { $0.value > $1.value }
sortedWords.removeLast(sortedWords.count - 10)
for (word, count) in sortedWords {
print("\(word): \(count)")
}
}
// main is the main function that handles the user input and prints the top 10 most frequently used words.
func main() {
print("Enter a string: ")
let text = readLine()?? ""
let cleanedText = removeVowels(text: text)
let wordCount = countWords(text: cleanedText)
printTop10(wordCount: wordCount)
}
main()
```
if!"aeiouAEIOU".contains(character) { // expected expression, var, or let in 'if' condition
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
let text = readLine()?? "" // cannot use optional chaining on non-optional value of type 'String'
let text = readLine()?? "" // string literal is unused
let text = readLine()?? "" // consecutive statements on a line must be separated by ';'
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
func countWords(text: String) -> [String: Int] {
var wordCount = [String: Int]()
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
for word in words {
if wordCount[word]!= nil {
wordCount[word]! += 1
} else {
wordCount[word] = 1
}
}
return wordCount
}
func isAnagram(a: String, b: String) -> Bool {
let aSorted = a.sorted()
let bSorted = b.sorted()
return aSorted == bSorted
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns dictionary with words as keys and their counts as values.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "banana") == ["banana": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana 456") == ["apple": 1, "banana": 2]
// countWords(text: "apple #$% banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple #$% banana apple") == ["apple": 2, "banana": 1]
// countWords(text: "apple #$% banana apple #$%") == ["apple": 2, "banana": 1]
func countWords(text: String) -> [String: Int] {
var wordCount = [String: Int]()
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
for word in words {
if wordCount[word]!= nil {
wordCount[word]! += 1
} else {
wordCount[word] = 1
}
}
return wordCount
}
// is_anagram is a function that takes two strings and returns true if they are anagrams.
// isAnagram(a: "abc", b: "bac") == true
// isAnagram(a: "abc", b: "a b c") == true
// isAnagram(a: "abc", b: "ab-c") == true
// isAnagram(a: "abc", b: "abcd") == false
// isAnagram(a: "abc", b: "cba") == false
// isAnagram(a: "abc", b: "ab") == false
func isAnagram(a: String, b: String) -> Bool {
let aSorted = a.sorted()
let bSorted = b.sorted()
return aSorted == bSorted
}
// find_anagram is a function that takes string and returns a list of anagrams.
// findAnagram(text: "abc") == ["abc"]
// findAnagram(text: "abcd") == ["abcd", "bcda", "dabc", "cdab"]
// findAnagram(text: "apple") == ["apple", "elppa"]
// findAnagram(text: "hello") == ["hello", "olleh", "hollo", "ehllo"]
// findAnagram(text: "abcde") == ["abcde", "edcba", "bceda", "decba", "dcba"]
// findAnagram(text: "aabbcc") == ["aabbcc", "bbaaa", "ccaabb", "bcaaba", "aabbc", "abacb", "aabbc", "aacbb", "baabb", "bbaaa", "bcaaba", "aabbc", "abacb", "aacbb"]
// findAnagram(text: "12345") == ["12345", "54321", "43215", "32145", "21435", "14523", "45213", "52143", "21345", "13245", "31245", "42135", "24135", "14253", "41523", "51423", "23415", "13425", "34125", "43125", "25143", "15243", "52413", "24315", "12543", "32415", "42315", "23145", "123
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
if wordCount[word]!= nil { // '=' must have consistent whitespace on both sides
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var newText = ""
for char in text {
if!vowels.contains(char) {
newText += String(char)
}
}
return newText
}
func countWords(text: String) -> [String: Int] {
var words = [String: Int]()
let wordsArray = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
for word in wordsArray {
if!word.isEmpty {
if words[word]!= nil {
words[word]! += 1
} else {
words[word] = 1
}
}
}
return words
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var newText = ""
for char in text {
if!vowels.contains(char) {
newText += String(char)
}
}
return newText
}
// count_words is a function that takes string and returns dictionary with words as keys and their counts as values.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123 banana 234") == ["apple": 1, "banana": 2]
// countWords(text: "apple #$% banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple #$% banana asdf") == ["apple": 1, "banana": 1, "asdf": 1]
// countWords(text: "apple #$% banana asdf qwer") == ["apple": 1, "banana": 1, "asdf": 1, "qwer": 1]
func countWords(text: String) -> [String: Int] {
var words = [String: Int]()
let wordsArray = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
for word in wordsArray {
if!word.isEmpty {
if words[word]!= nil {
words[word]! += 1
} else {
words[word] = 1
}
}
}
return words
}
// print_top_10 is a function that takes dictionary with words and their counts and prints top 10 most used words and their counts.
// If the same number of words used for two or more words, it prints words in alphabetical order.
// printTop10(words: [:])
// printTop10(words: ["apple": 1])
// printTop10(words: ["apple": 1, "banana": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1, "elderberry": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1, "elderberry": 1, "fig": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1, "elderberry": 1, "fig": 1, "grape": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1, "elderberry": 1, "fig": 1, "grape": 1, "kiwi": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1, "elderberry": 1, "fig": 1, "grape": 1, "kiwi": 1, "lime": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "banana": 1, "durian": 1, "elderberry": 1, "fig": 1, "grape": 1, "kiwi":
if!vowels.contains(char) { // expected expression, var, or let in 'if' condition
let wordsArray = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let wordsArray = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let wordsArray = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
if!word.isEmpty { // expected expression, var, or let in 'if' condition
if words[word]!= nil { // '=' must have consistent whitespace on both sides
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns dictionary with words and their counts.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "banana") == ["banana": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple apple") == ["apple": 2]
// countWords(text: "banana apple") == ["apple": 1, "banana": 1]
// countWords(text: "apple 123banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana":
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
result.append(char)
}
}
return result
}
func countWords(text: String) -> [String: Int] {
var result = [String: Int]()
var currentWord = ""
for char in text {
if char.isLetter {
currentWord.append(char)
} else if!currentWord.isEmpty {
if result[currentWord]!= nil {
result[currentWord]! += 1
} else {
result[currentWord] = 1
}
currentWord = ""
}
}
if!currentWord.isEmpty {
if result[currentWord]!= nil {
result[currentWord]! += 1
} else {
result[currentWord] = 1
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
result.append(char)
}
}
return result
}
// count_words is a function that takes string and returns dictionary with words and their counts.
// countWords(text: "") == [:]
// countWords(text: "apple") == ["apple": 1]
// countWords(text: "banana") == ["banana": 1]
// countWords(text: "apple banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple apple") == ["apple": 2]
// countWords(text: "apple 123 banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple #$% banana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "apple\n\n\n\n\n\n\n\n\nbanana") == ["apple": 1, "banana": 1]
// countWords(text: "This is a long string with special characters! It has words with UPPER CASE letters and Spaces.") == ["this": 1, "is": 1, "a": 1, "long": 1, "string": 1, "with": 1, "special": 1, "characters": 1, "it": 1, "has": 1, "words": 1, "with": 1, "upper": 1, "case": 1, "letters": 1, "and": 1, "spaces": 1]
func countWords(text: String) -> [String: Int] {
var result = [String: Int]()
var currentWord = ""
for char in text {
if char.isLetter {
currentWord.append(char)
} else if!currentWord.isEmpty {
if result[currentWord]!= nil {
result[currentWord]! += 1
} else {
result[currentWord] = 1
}
currentWord = ""
}
}
if!currentWord.isEmpty {
if result[currentWord]!= nil {
result[currentWord]! += 1
} else {
result[currentWord] = 1
}
}
return result
}
// print_top_10 is a function that takes dictionary with words and their counts and prints top 10 most used words.
// printTop10(words: [:])
// printTop10(words: ["apple": 1])
// printTop10(words: ["apple": 1, "banana": 1])
// printTop10(words: ["apple": 1, "banana": 1, "cherry": 1, "date": 1, "elderberry": 1, "fig": 1, "grape": 1, "honeydew": 1, "indigo": 1, "ivory": 1])
func printTop10
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
} else if!currentWord.isEmpty { // expected expression, var, or let in 'if' condition
if result[currentWord]!= nil { // '=' must have consistent whitespace on both sides
if!currentWord.isEmpty { // expected expression, var, or let in 'if' condition
if result[currentWord]!= nil { // '=' must have consistent whitespace on both sides
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
func countWords(text: String) -> Int {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
return words.count
}
func wordStats(text: String) {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
print("Number of words:", words.count)
print("Number of unique words:", Set(words).count)
}
func longestWord(text: String) -> String? {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
return words.max { $0.count < $1.count }
}
func mostCommonWord(text: String) -> String? {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
return words.groupBy { $0 }.max { $0.value.count < $1.value.count }?.key
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var newString = ""
for char in text {
if!"aeiouAEIOU".contains(char) {
newString += String(char)
}
}
return newString
}
// count_words is a function that takes string and returns number of words.
// countWords(text: "") == 0
// countWords(text: "abc") == 1
// countWords(text: "abc def") == 2
// countWords(text: "abc def\n") == 2
// countWords(text: "abc def\n\n") == 2
// countWords(text: "abc def\n\n\n") == 2
// countWords(text: "abc def\n\n\n ghi") == 3
func countWords(text: String) -> Int {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
return words.count
}
// word_stats is a function that takes string and prints number of words and
// number of unique words.
// wordStats(text: "") prints: "Number of words: 0\nNumber of unique words: 0"
// wordStats(text: "abc") prints: "Number of words: 1\nNumber of unique words: 1"
// wordStats(text: "abc def") prints: "Number of words: 2\nNumber of unique words: 2"
// wordStats(text: "abc def\n") prints: "Number of words: 2\nNumber of unique words: 2"
// wordStats(text: "abc def\n\n") prints: "Number of words: 2\nNumber of unique words: 2"
// wordStats(text: "abc def\n\n\n") prints: "Number of words: 2\nNumber of unique words: 2"
// wordStats(text: "abc def\n\n\n ghi") prints: "Number of words: 3\nNumber of unique words: 3"
func wordStats(text: String) {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
print("Number of words:", words.count)
print("Number of unique words:", Set(words).count)
}
// longest_word is a function that takes string and returns longest word.
// longestWord(text: "") returns nil
// longestWord(text: "abc") returns "abc"
// longestWord(text: "abc def") returns "def"
// longestWord(text: "abc def\n") returns "def"
// longestWord(text: "abc def\n\n") returns "def"
// longestWord(text: "abc def\n\n\n") returns "def"
// longestWord(text: "abc def\n\n\n ghi") returns "ghi"
func longestWord(text: String) -> String? {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
return words.max { $0.count < $1.count }
}
// most_common_word is a function that takes string and returns most common word.
// mostCommonWord(text: "") returns nil
// mostCommonWord(text: "abc") returns "abc"
// mostCommonWord(text: "abc def") returns "abc"
// mostCommonWord(text: "abc def\n") returns "abc"
// mostCommonWord(text: "abc def\n\n") returns "abc"
// mostCommonWord(text: "abc def\n\n\n") returns "abc"
// mostCommonWord(text: "abc def\n\n\n ghi") returns "abc"
func mostCommonWord(text: String) -> String? {
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators)
return words.groupBy { $0 }.max { $0.value.count < $1.value.count }?.key
}
// longest_palindrome_substring is a function that takes string and returns longest palindrome substring.
// longestPalindromeSubstring(text: "") returns ""
// longestPalindromeSubstring(text: "a") returns "a"
// longestPalindromeSubstring(text: "
if!"aeiouAEIOU".contains(char) { // expected expression, var, or let in 'if' condition
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // type 'AdditiveArithmetic' has no member 'contentSeparators'
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // extra argument in call
let words = text.components(separatedBy:.whitespacesAndNewlines +.contentSeparators) // expected ',' separator
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
func min(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func max(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func count(l: [Int]) -> Int {
var count = 0
for _ in l {
count += 1
}
return count
}
func contains(l: [Int], n: Int) -> Bool {
for i in l {
if i == n {
return true
}
}
return false
}
func without(l: [Int], r: [Int]) -> [Int] {
var without = [Int]()
for i in l {
if!contains(l: r, n: i) {
without.append(i)
}
}
return without
}
```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
}
// Return true if any number in the array l is below threshold t.
// anyBelowThreshold(l: [1, 2, 4, 10], t: 100) == true
// anyBelowThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if all numbers in the array l are above threshold t.
// allAboveThreshold(l: [1, 2, 4, 10], t: 1) == false
// allAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
// Return true if any number in the array l is above threshold t.
// anyAboveThreshold(l: [1, 2, 4, 10], t: 1) == true
// anyAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 4, 10]) == 21
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of all numbers in the array l.
// product(l: [1, 2, 4, 10]) == 400
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
// Return the minimum number in the array l.
// min(l: [1, 2, 4, 10]) == 1
func min(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
// Return the maximum number in the array l.
// max(l: [1, 2, 4, 10]) == 10
func max(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// Return the number of elements in the array l.
// count(l: [1, 2, 4, 10]) == 4
func count(l: [Int]) -> Int {
var count = 0
for _ in l {
count += 1
}
return count
}
// Return true if the array l contains the number n.
// contains(l: [1, 2, 4, 10], n: 4) == true
// contains(l: [1, 2, 4, 10], n: 11) == false
func contains(l: [Int], n: Int) -> Bool {
for i in l {
if i == n {
return true
}
}
return false
}
// Return a new array containing the numbers from l that are not in the array r.
// without(l: [1, 2, 4, 10], r: [1, 4]) == [2, 10]
func without(l: [Int], r: [Int]) -> [Int] {
var without = [Int]()
for i in l {
if!contains(l: r, n: i) {
without.append(i)
}
}
return without
}
// Return a new array containing the numbers from l that are not divisible by n.
// withoutDivisibleBy(l: [1, 2, 4, 10,
if!contains(l: r, n: i) { // expected expression, var, or let in 'if' condition
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func allBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func allBelowThreshold2(l: [Int], t: Int) -> Bool {
return!anyAboveThreshold(l, t: t)
}
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func allAboveThreshold2(l: [Int], t: Int) -> Bool {
return!anyBelowThreshold(l, t: t)
}
func isEven(n: Int) -> Bool {
return n % 2 == 0
}
func isOdd(n: Int) -> Bool {
return!isEven(n)
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if 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
}
// Return true if any number in the array l is below threshold t.
// anyBelowThreshold(l: [1, 2, 4, 10], t: 100) == true
// anyBelowThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if any number in the array l is below threshold t.
// allBelowThreshold(l: [1, 2, 4, 10], t: 100) == false
// allBelowThreshold(l: [1, 20, 4, 10], t: 5) == false
func allBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
// Return true if any number in the array l is below threshold t.
// allBelowThreshold(l: [1, 2, 4, 10], t: 100) == false
// allBelowThreshold(l: [1, 20, 4, 10], t: 5) == false
func allBelowThreshold2(l: [Int], t: Int) -> Bool {
return!anyAboveThreshold(l, t: t)
}
// Return true if any number in the array l is above threshold t.
// anyAboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// anyAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if all numbers in the array l are above threshold t.
// allAboveThreshold(l: [1, 2, 4, 10], t: 100) == true
// allAboveThreshold(l: [1, 20, 4, 10], t: 5) == false
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
// Return true if all numbers in the array l are above threshold t.
// allAboveThreshold2(l: [1, 2, 4, 10], t: 100) == true
// allAboveThreshold2(l: [1, 20, 4, 10], t: 5) == false
func allAboveThreshold2(l: [Int], t: Int) -> Bool {
return!anyBelowThreshold(l, t: t)
}
// Return true if the number n is even.
// isEven(n: 2) == true
// isEven(n: 1) == false
func isEven(n: Int) -> Bool {
return n % 2 == 0
}
// Return true if the number n is odd.
// isOdd(n: 2) == false
// isOdd(n: 1) == true
func isOdd(n: Int) -> Bool {
return!isEven(n)
}
// Return true if the number n is prime.
// isPrime(n: 2) == true
// isPrime(n: 1) == false
// isPrime(n: 4) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 3, 4, 5]) == 15
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
return!anyAboveThreshold(l, t: t) // expected expression in 'return' statement
return!anyBelowThreshold(l, t: t) // expected expression in 'return' statement
return!isEven(n) // expected expression in 'return' statement
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func anyTwoClose(l: [Int], t: Int) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) < t {
return true
}
}
}
return false
}
func anyTwoDifferent(l: [Int], t: Int) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) > t {
return true
}
}
}
return false
}
func countNonDivisible(l: [Int], d: Int) -> Int {
var count = 0
for i in l {
if i % d!= 0 {
count += 1
}
}
return count
}
func sumOfSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
func sumOfCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i * i
}
return sum
}
func difference(l: [Int]) -> Int {
return sumOfSquares(l: l) - sumOfCubes(l: l)
}
```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
}
// Return true if any two numbers in the array l are closer to each other than threshold.
// anyTwoClose(l: [1, 2, 3, 4, 5], t: 0) == false
// anyTwoClose(l: [1, 2, 3, 4, 5], t: 1) == true
func anyTwoClose(l: [Int], t: Int) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) < t {
return true
}
}
}
return false
}
// Return true if any two numbers in the array l have a difference greater than the threshold.
// anyTwoDifferent(l: [1, 2, 3, 4, 5], t: 1) == false
// anyTwoDifferent(l: [1, 2, 3, 4, 5], t: 2) == true
func anyTwoDifferent(l: [Int], t: Int) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) > t {
return true
}
}
}
return false
}
// Return the number of elements in the array l that are not divisible by the given divisor.
// countNonDivisible(l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], d: 3) == 3
// countNonDivisible(l: [1, 2, 4, 5, 7, 8, 9, 10], d: 3) == 3
// countNonDivisible(l: [1, 2, 4, 7, 8, 9, 10], d: 3) == 3
// countNonDivisible(l: [1, 2, 4, 9, 10], d: 3) == 2
func countNonDivisible(l: [Int], d: Int) -> Int {
var count = 0
for i in l {
if i % d!= 0 {
count += 1
}
}
return count
}
// Return the sum of the squares of the numbers in the array l.
// sumOfSquares(l: [1, 2, 3, 4, 5]) == 55
func sumOfSquares(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
// Return the sum of the cubes of the numbers in the array l.
// sumOfCubes(l: [1, 2, 3, 4, 5]) == 125
func sumOfCubes(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i * i
}
return sum
}
// Return the difference between the sum of the squares of the numbers in the array l
// and the sum of the cubes of the numbers in the array l.
// difference(l: [1, 2, 3, 4, 5]) == 66
func difference(l: [Int]) -> Int {
return sumOfSquares(l: l) - sumOfCubes(l: l)
}
// Return the length of the longest increasing subsequence in the array l.
// longestIncreasingSubsequence(l: [10, 9, 2, 5, 3, 7, 101, 18]) == 4
// longestIncreasingSubsequence(l: [1, 2, 3, 4]) == 1
// longestIncreasingSubsequence(l: [1, 2, 3, 4, 5]) == 1
// longestIncreasingSubsequence(l: [10, 9, 2, 6, 3, 7, 101, 18]) == 3
func longest
if i % d!= 0 { // cannot force unwrap value of non-optional type 'Int'
if i % d!= 0 { // use of '=' in a boolean context, did you mean '=='?
if i % d!= 0 { // '=' must have consistent whitespace on both sides
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func allBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func product(l: [Int]) -> Int {
var prod = 1
for i in l {
prod *= i
}
return prod
}
func min(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func max(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func count(l: [Int]) -> Int {
return l.count
}
func uniqueElements(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
```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
}
// Return true if any number in the array l is below threshold t.
// anyBelowThreshold(l: [1, 2, 4, 10], t: 100) == true
// anyBelowThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if any number in the array l is below threshold t.
// allBelowThreshold(l: [1, 2, 4, 10], t: 100) == false
// allBelowThreshold(l: [1, 20, 4, 10], t: 5) == false
func allBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
// Return true if all numbers in the array l are above threshold t.
// allAboveThreshold(l: [1, 2, 4, 10], t: 1) == false
// allAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
// Return true if any number in the array l is above threshold t.
// anyAboveThreshold(l: [1, 2, 4, 10], t: 1) == true
// anyAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 4, 10]) == 21
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of all numbers in the array l.
// product(l: [1, 2, 4, 10]) == 400
func product(l: [Int]) -> Int {
var prod = 1
for i in l {
prod *= i
}
return prod
}
// Return the minimum number in the array l.
// min(l: [1, 2, 4, 10]) == 1
func min(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
// Return the maximum number in the array l.
// max(l: [1, 2, 4, 10]) == 10
func max(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// Return the number of elements in the array l.
// count(l: [1, 2, 4, 10]) == 4
func count(l: [Int]) -> Int {
return l.count
}
// Return a new array containing only the unique elements in l.
// uniqueElements(l: [1, 2, 4, 1, 2, 4, 10]) == [1, 2, 4, 10]
func uniqueElements(l: [Int]) -> [Int] {
var unique = [Int]()
for i in l {
if!unique.contains(i) {
unique.append(i)
}
}
return unique
}
// Return a new array containing only the elements of l that are not in b.
// without(l: [1, 2, 4, 1, 2, 4, 10], b: [1, 2,
if!unique.contains(i) { // expected expression, var, or let in 'if' condition
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func hasCloseElements(l: [Double], t: Double) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) < t {
return true
}
}
}
return false
}
func hasGreatDeviations(l: [Double], t: Double) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) > t {
return true
}
}
}
return false
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func sumSquared(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
func sumCubed(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i * i
}
return sum
}
func sum(l: [Double]) -> Double {
var sum = 0.0
for i in l {
sum += i
}
return sum
}
func sumSquared(l: [Double]) -> Double {
var sum = 0.0
for i in l {
sum += i * i
}
return sum
}
func sumCubed(l: [Double]) -> Double {
var sum = 0.0
for i in l {
sum += i * i * i
}
return sum
}
func sum(l: [Float]) -> Float {
var sum = 0.0
for i in l {
sum += i
}
return sum
}
```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
}
// Return true if any two numbers in the array l are closer to each other than threshold.
// hasCloseElements(l: [1.0, 2.0, 3.0], t: 0.5) == false
// hasCloseElements(l: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], t: 0.3) == true
func hasCloseElements(l: [Double], t: Double) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) < t {
return true
}
}
}
return false
}
// Return true if any two numbers in the array l have a difference greater than the threshold.
// hasGreatDeviations(l: [1.0, 2.0, 3.0], t: 0.5) == false
// hasGreatDeviations(l: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], t: 0.3) == true
func hasGreatDeviations(l: [Double], t: Double) -> Bool {
for i in 0..<l.count {
for j in (i + 1)..<l.count {
if abs(l[i] - l[j]) > t {
return true
}
}
}
return false
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 3, 4, 5]) == 15
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the sum of all squared numbers in the array l.
// sumSquared(l: [1, 2, 3, 4, 5]) == 55
func sumSquared(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i
}
return sum
}
// Return the sum of all cubes of numbers in the array l.
// sumCubed(l: [1, 2, 3, 4, 5]) == 125
func sumCubed(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i * i * i
}
return sum
}
// Return the sum of all numbers in the array l.
// sum(l: [1.0, 2.0, 3.0, 4.0, 5.0]) == 15.0
func sum(l: [Double]) -> Double {
var sum = 0.0
for i in l {
sum += i
}
return sum
}
// Return the sum of all squared numbers in the array l.
// sumSquared(l: [1.0, 2.0, 3.0, 4.0, 5.0]) == 55.0
func sumSquared(l: [Double]) -> Double {
var sum = 0.0
for i in l {
sum += i * i
}
return sum
}
// Return the sum of all cubes of numbers in the array l.
// sumCubed(l: [1.0, 2.0, 3.0, 4.0, 5.0]) == 125.0
func sumCubed(l: [Double]) -> Double {
var sum = 0.0
for i in l {
sum += i * i * i
}
return sum
}
// Return the sum of all numbers in the array l.
// sum(l: [1.0, 2.5, 3.0, 4.5, 5.0]) == 15.5
func sum(l: [Float]) -> Float {
var sum = 0.0
for i in l {
sum += i
}
return sum
}
// Return the sum of all squared numbers in the array l.
// sumS
sum += i // cannot convert value of type 'Float' to expected argument type 'Double'
return sum // cannot convert return expression of type 'Double' to return type 'Float'
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func sumArray(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func productArray(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
func minArray(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func maxArray(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func longestSubarray(l: [Int]) -> Int {
var longest = 0
var current = 0
for i in l {
current += 1
if current > longest {
longest = current
}
}
return longest
}
func shortestSubarray(l: [Int]) -> Int {
var shortest = l.count
var current = 0
for i in l {
current += 1
if current < shortest {
shortest = current
}
}
return shortest
}
func countEnding(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i == x {
count += 1
}
}
return count
}
func countBeginning(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i == x {
count += 1
}
}
return count
}
```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
}
// Return the sum of all numbers in the array l.
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([10, 20, 30]) == 60
func sumArray(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of all numbers in the array l.
// productArray([1, 2, 3, 4, 5]) == 120
// productArray([10, 20, 30]) == 600
func productArray(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
// Return the minimum of all numbers in the array l.
// minArray([1, 2, 3, 4, 5]) == 1
// minArray([10, 20, 30]) == 10
func minArray(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
// Return the maximum of all numbers in the array l.
// maxArray([1, 2, 3, 4, 5]) == 5
// maxArray([10, 20, 30]) == 30
func maxArray(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// Return the length of the longest subarray in the array l.
// longestSubarray([1, 2, 3, 4, 5]) == 1
// longestSubarray([10, 20, 30, 40, 100, 200, 300]) == 4
func longestSubarray(l: [Int]) -> Int {
var longest = 0
var current = 0
for i in l {
current += 1
if current > longest {
longest = current
}
}
return longest
}
// Return the length of the shortest subarray in the array l.
// shortestSubarray([1, 2, 3, 4, 5]) == 1
// shortestSubarray([10, 20, 30, 40, 100, 200, 300]) == 3
func shortestSubarray(l: [Int]) -> Int {
var shortest = l.count
var current = 0
for i in l {
current += 1
if current < shortest {
shortest = current
}
}
return shortest
}
// Return the number of subarrays in the array l that end with the number x.
// countEnding([1, 2, 3, 4, 5, 6], 6) == 1
// countEnding([10, 20, 30, 40, 100, 60, 70, 80, 90, 100], 100) == 2
func countEnding(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i == x {
count += 1
}
}
return count
}
// Return the number of subarrays in the array l that start with the number x.
// countBeginning([1, 2, 3, 4, 5, 6], 1) == 1
// countBeginning([10, 20, 30, 40, 100, 60, 70, 80, 90, 100], 10) == 2
func countBeginning(l: [Int], x: Int) -> Int {
var count = 0
for i in l {
if i == x {
count += 1
}
}
return count
}
// Return the number of subarrays in the array l that have the
for i in l { // immutable value 'i' was never used; consider replacing with '_' or removing it
for i in l { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func allBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
var sorted = l
sorted.sort()
if sorted.count % 2 == 1 {
return Double(sorted[sorted.count / 2])
} else {
return Double(sorted[sorted.count / 2 - 1] + sorted[sorted.count / 2]) / 2
}
}
func mode(l: [Int]) -> [Int] {
var counts = [Int: Int]()
for i in l {
counts[i, default: 0] += 1
}
var maxCount = 0
var modes = [Int]()
for (k, v) in counts {
if v > maxCount {
maxCount = v
modes = [k]
} else if v == maxCount {
modes.append(k)
}
}
return modes
}
```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
}
// Return true if any number in the array l is below threshold t.
// anyBelowThreshold(l: [1, 2, 4, 10], t: 100) == true
// anyBelowThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if any number in the array l is below threshold t.
// allBelowThreshold(l: [1, 2, 4, 10], t: 100) == false
// allBelowThreshold(l: [1, 20, 4, 10], t: 5) == false
func allBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
// Return true if all numbers in the array l are above threshold t.
// allAboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// allAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
// Return true if any number in the array l is above threshold t.
// anyAboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// anyAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 4, 10]) == 20
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of all numbers in the array l.
// product(l: [1, 2, 4, 10]) == 400
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
// Return the mean of all numbers in the array l.
// mean(l: [1, 2, 4, 10]) == 3.5
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of all numbers in the array l.
// median(l: [1, 2, 4, 10]) == 4
func median(l: [Int]) -> Double {
var sorted = l
sorted.sort()
if sorted.count % 2 == 1 {
return Double(sorted[sorted.count / 2])
} else {
return Double(sorted[sorted.count / 2 - 1] + sorted[sorted.count / 2]) / 2
}
}
// Return the mode of all numbers in the array l.
// mode(l: [1, 2, 4, 10, 10, 10, 10, 10, 10, 100]) == [10, 100]
func mode(l: [Int]) -> [Int] {
var counts = [Int: Int]()
for i in l {
counts[i, default: 0] += 1
}
var maxCount = 0
var modes = [Int]()
for (k, v) in counts {
if v > maxCount {
maxCount = v
modes = [k]
} else if v == maxCount {
modes.append(k)
}
}
return modes
}
// Return the range of all numbers
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
func countAboveThreshold(l: [Int], t: Int) -> Int {
var count = 0
for i in l {
if i > t {
count += 1
}
}
return count
}
func countBelowThreshold(l: [Int], t: Int) -> Int {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
func median(l: [Int]) -> Double {
var sortedL = l
sortedL.sort()
if sortedL.count % 2 == 0 {
return Double(sortedL[sortedL.count / 2 - 1] + sortedL[sortedL.count / 2]) / 2.0
} else {
return Double(sortedL[sortedL.count / 2])
}
}
```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
}
// Return true if any number in the array l is below threshold t.
// anyBelowThreshold(l: [1, 2, 4, 10], t: 100) == true
// anyBelowThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyBelowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if all numbers in the array l are above threshold t.
// allAboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// allAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func allAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
// Return true if any number in the array l is above threshold t.
// anyAboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// anyAboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func anyAboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
// Return the number of elements in the array l that are above threshold t.
// countAboveThreshold(l: [1, 2, 4, 10], t: 100) == 0
// countAboveThreshold(l: [1, 20, 4, 10], t: 5) == 3
func countAboveThreshold(l: [Int], t: Int) -> Int {
var count = 0
for i in l {
if i > t {
count += 1
}
}
return count
}
// Return the number of elements in the array l that are below threshold t.
// countBelowThreshold(l: [1, 2, 4, 10], t: 100) == 4
// countBelowThreshold(l: [1, 20, 4, 10], t: 5) == 1
func countBelowThreshold(l: [Int], t: Int) -> Int {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 4, 10]) == 26
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of all numbers in the array l.
// product(l: [1, 2, 4, 10]) == 400
func product(l: [Int]) -> Int {
var product = 1
for i in l {
product *= i
}
return product
}
// Return the mean of all numbers in the array l.
// mean(l: [1, 2, 4, 10]) == 3.5
func mean(l: [Int]) -> Double {
return Double(sum(l: l)) / Double(l.count)
}
// Return the median of all numbers in the array l.
// median(l: [1, 2, 4, 10]) == 4
func median(l: [Int]) -> Double {
var sortedL = l
sortedL.sort()
if sortedL.count % 2 == 0 {
return Double(sortedL[sortedL.count / 2 - 1] + sortedL[sortedL.count / 2]) / 2.0
} else {
return Double(sortedL[sortedL.count / 2])
}
}
// Return the mode of all numbers in the array l.
// mode(l: [1, 2, 4, 10,
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return false
}
}
return true
}
func belowThresholdAny(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
func aboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
func aboveThresholdAny(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
func product(l: [Int]) -> Int {
var prod = 1
for i in l {
prod *= i
}
return prod
}
func min(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
func max(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func length(l: [Int]) -> Int {
return l.count
}
func range(start: Int, end: Int) -> [Int] {
var r = [Int]()
for i in start...end {
r.append(i)
}
return r
}
func rangeStep(start: Int, end: Int, step: Int) -> [Int] {
var r = [Int]()
for i in stride(from: start, through: end, by: step) {
r.append(i)
}
return r
}
```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
}
// Return true if any number in the array l is below threshold t.
// belowThresholdAny(l: [1, 2, 4, 10], t: 100) == true
// belowThresholdAny(l: [1, 20, 4, 10], t: 5) == true
func belowThresholdAny(l: [Int], t: Int) -> Bool {
for i in l {
if i > t {
return true
}
}
return false
}
// Return true if all numbers in the array l are above threshold t.
// aboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// aboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func aboveThreshold(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return false
}
}
return true
}
// Return true if any number in the array l is above threshold t.
// aboveThresholdAny(l: [1, 2, 4, 10], t: 100) == true
// aboveThresholdAny(l: [1, 20, 4, 10], t: 5) == true
func aboveThresholdAny(l: [Int], t: Int) -> Bool {
for i in l {
if i < t {
return true
}
}
return false
}
// Return the sum of all numbers in the array l.
// sum(l: [1, 2, 4, 10]) == 20
func sum(l: [Int]) -> Int {
var sum = 0
for i in l {
sum += i
}
return sum
}
// Return the product of all numbers in the array l.
// product(l: [1, 2, 4, 10]) == 400
func product(l: [Int]) -> Int {
var prod = 1
for i in l {
prod *= i
}
return prod
}
// Return the minimum number in the array l.
// min(l: [1, 2, 4, 10]) == 1
func min(l: [Int]) -> Int {
var min = l[0]
for i in l {
if i < min {
min = i
}
}
return min
}
// Return the maximum number in the array l.
// max(l: [1, 2, 4, 10]) == 10
func max(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
// Return the number of elements in the array l.
// length(l: [1, 2, 4, 10]) == 4
func length(l: [Int]) -> Int {
return l.count
}
// Return a new array containing the numbers from start to end.
// range(start: 1, end: 5) == [1, 2, 3, 4, 5]
func range(start: Int, end: Int) -> [Int] {
var r = [Int]()
for i in start...end {
r.append(i)
}
return r
}
// Return a new array containing the numbers from start to end,
// incremented by the given step.
// rangeStep(start: 1, end: 5, step: 2) == [1, 3, 5]
func rangeStep(start: Int, end: Int, step: Int) -> [Int] {
var r = [Int]()
for i in stride(from: start, through: end, by: step) {
r.append(i)
}
return r
}
// Return true if the array l contains the number n.
// contains(l: [1, 2, 4, 10], n: 10) == true
// contains(l: [1, 20, 4, 10], n: 5) == false
func contains(l: [Int], n: Int) -> Bool {
// XCTAssertTrue failed
func belowThreshold(l: [Int], t: Int) -> Bool {
return!l.contains { $0 > t }
}
func belowThresholdAny(l: [Int], t: Int) -> Bool {
return l.contains { $0 > t }
}
func aboveThreshold(l: [Int], t: Int) -> Bool {
return!l.contains { $0 < t }
}
func aboveThresholdAny(l: [Int], t: Int) -> Bool {
return l.contains { $0 < t }
}
func containsDivisibleBy(l: [Int], t: Int) -> Bool {
return l.contains { $0 % t == 0 }
}
func containsDivisibleByAny(l: [Int], ts: [Int]) -> Bool {
return l.contains { ts.contains { $0 % $1 == 0 } }
}
func containsOnlyDivisibleBy(l: [Int], t: Int) -> Bool {
return l.filter { $0 % t == 0 }.count == l.count
}
func containsOnlyDivisibleByAny(l: [Int], ts: [Int]) -> Bool {
return l.filter { ts.contains { $0 % $1 == 0 } }.count == l.count
}
func containsOnlyNotDivisibleBy(l: [Int], t: Int) -> Bool {
return l.filter { $0 % t!= 0 }.count == l.count
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return!l.contains { $0 > t }
}
// Return true if any number in the array l is below threshold t.
// belowThresholdAny(l: [1, 2, 4, 10], t: 100) == true
// belowThresholdAny(l: [1, 20, 4, 10], t: 5) == true
func belowThresholdAny(l: [Int], t: Int) -> Bool {
return l.contains { $0 > t }
}
// Return true if all numbers in the array l are above threshold t.
// aboveThreshold(l: [1, 2, 4, 10], t: 100) == false
// aboveThreshold(l: [1, 20, 4, 10], t: 5) == true
func aboveThreshold(l: [Int], t: Int) -> Bool {
return!l.contains { $0 < t }
}
// Return true if any number in the array l is above threshold t.
// aboveThresholdAny(l: [1, 2, 4, 10], t: 100) == true
// aboveThresholdAny(l: [1, 20, 4, 10], t: 5) == true
func aboveThresholdAny(l: [Int], t: Int) -> Bool {
return l.contains { $0 < t }
}
// Return true if the array l contains at least one number that is divisible by t.
// containsDivisibleBy(l: [1, 2, 4, 10], t: 2) == true
// containsDivisibleBy(l: [1, 20, 4, 10], t: 5) == true
func containsDivisibleBy(l: [Int], t: Int) -> Bool {
return l.contains { $0 % t == 0 }
}
// Return true if the array l contains at least one number that is divisible by any number in the array ts.
// containsDivisibleByAny(l: [1, 2, 4, 10], ts: [2, 3, 5]) == true
// containsDivisibleByAny(l: [1, 20, 4, 10], ts: [5, 10]) == true
func containsDivisibleByAny(l: [Int], ts: [Int]) -> Bool {
return l.contains { ts.contains { $0 % $1 == 0 } }
}
// Return true if the array l contains only numbers that are divisible by t.
// containsOnlyDivisibleBy(l: [1, 2, 4, 10], t: 2) == false
// containsOnlyDivisibleBy(l: [1, 20, 4, 10], t: 5) == true
func containsOnlyDivisibleBy(l: [Int], t: Int) -> Bool {
return l.filter { $0 % t == 0 }.count == l.count
}
// Return true if the array l contains only numbers that are divisible by any number in the array ts.
// containsOnlyDivisibleByAny(l: [1, 2, 4, 10], ts: [2, 3, 5]) == false
// containsOnlyDivisibleByAny(l: [1, 20, 4, 10], ts: [5, 10]) == true
func containsOnlyDivisibleByAny(l: [Int], ts: [Int]) -> Bool {
return l.filter { ts.contains { $0 % $1 == 0 } }.count == l.count
}
// Return true if the array l contains only numbers that are not divisible by t.
// containsOnlyNotDivisibleBy(l: [1, 2, 4, 10], t: 2) == true
// containsOnlyNotDivisibleBy(l: [1, 20, 4, 10], t: 5) == false
func containsOnlyNotDivisibleBy(l: [Int], t: Int) -> Bool {
return l.filter { $0 % t!= 0 }.count == l.count
}
// Return true if the array l contains only numbers that are not divisible by any number in the array
return!l.contains { $0 > t } // expected expression in 'return' statement
return!l.contains { $0 < t } // expected expression in 'return' statement
return l.contains { ts.contains { $0 % $1 == 0 } } // contextual closure type '(Int) throws -> Bool' expects 1 argument, but 2 were used in closure body
return l.contains { ts.contains { $0 % $1 == 0 } } // contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
return l.filter { ts.contains { $0 % $1 == 0 } }.count == l.count // contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
return l.filter { ts.contains { $0 % $1 == 0 } }.count == l.count // contextual closure type '(Int) throws -> Bool' expects 1 argument, but 2 were used in closure body
return l.filter { $0 % t!= 0 }.count == l.count // '=' must have consistent whitespace on both sides
return l.filter { $0 % t!= 0 }.count == l.count // cannot force unwrap value of non-optional type 'Int'
return l.filter { $0 % t!= 0 }.count == l.count // cannot convert value of type '()' to closure result type 'Bool'
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 equal(x: Int, y: Int) -> Bool {
return x == y
}
func greater(x: Int, y: Int) -> Bool {
return x > y
}
func less(x: Int, y: Int) -> Bool {
return x < y
}
func square_root(x: Int) -> Double {
return sqrt(Double(x))
}
func absolute(x: Int) -> Int {
return abs(x)
}
func is_even(x: Int) -> Bool {
return x % 2 == 0
}
func is_odd(x: Int) -> Bool {
return x % 2 == 1
}
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
func greatest_common_divisor(x: Int, y: Int) -> Int {
var a = x
var b = y
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
func least_common_multiple(x: Int, y: Int) -> Int {
return x * y / greatest_common_divisor(x: x, y: y)
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 3) == 2
// subtract(x: 2, y: 7) == -5
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: 6, y: 3) == 2
// divide(x: 2, y: 7) == 0.38...
func divide(x: Int, y: Int) -> Double {
return Double(x) / Double(y)
}
// Check if two numbers x and y are equal
// equal(x: 2, y: 2) == true
// equal(x: 5, y: 2) == false
func equal(x: Int, y: Int) -> Bool {
return x == y
}
// Check if x is greater than y
// greater(x: 5, y: 2) == true
// greater(x: 2, y: 5) == false
func greater(x: Int, y: Int) -> Bool {
return x > y
}
// Check if x is less than y
// less(x: 2, y: 5) == true
// less(x: 5, y: 2) == false
func less(x: Int, y: Int) -> Bool {
return x < y
}
// Square root of a number x
// square_root(x: 4) == 2
// square_root(x: 169) == 11
func square_root(x: Int) -> Double {
return sqrt(Double(x))
}
// Absolute value of a number x
// absolute(x: -4) == 4
// absolute(x: 169) == 169
func absolute(x: Int) -> Int {
return abs(x)
}
// Check if a number x is even
// is_even(x: 4) == true
// is_even(x: 3) == false
func is_even(x: Int) -> Bool {
return x % 2 == 0
}
// Check if a number x is odd
// is_odd(x: 3) == true
// is_odd(x: 2) == false
func is_odd(x: Int) -> Bool {
return x % 2 == 1
}
// Power of a number x to the power of y
// power(x: 2, y: 3) == 8
// power(x: 5, y: 0) == 1
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
// Greatest common divisor of two numbers x and y
// greatest_common_divisor(x: 6, y: 9) == 3
// greatest_common_divisor(x: 10, y: 15) == 5
func greatest_common_divisor(x: Int, y: Int) -> Int {
var a = x
var b = y
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
}
// Least common multiple of two numbers x and y
// least_common_multiple(x: 6, y: 9) == 54
// least_common_multiple(x: 10, y: 15) == 600
func least_common_multiple(x: Int, y: Int) -> Int {
return x * y / greatest_common_divisor(x: x, y: y)
}
// Calculate the factorial of a number x
// factorial(x: 5) == 120
// factorial(x: 0) == 1
func factorial(x: Int) -> Int {
var result =
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
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 power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
func modulo(x: Int, y: Int) -> Int {
return x % y
}
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
func gcd(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return gcd(x: y % x, y: x)
}
}
func lcm(x: Int, y: Int) -> Int {
return x * y / gcd(x: x, y: y)
}
func isPrime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
}
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
func prime(x: Int) -> Int {
var count = 0
var num = 2
while count < x {
if isPrime(x: num) {
count += 1
}
num += 1
}
return num - 1
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 7) == -2
// subtract(x: 2, y: 3) == -1
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0.666667
// divide(x: 5, y: 7) == 0.714286
func divide(x: Int, y: Int) -> Double {
return Double(x) / Double(y)
}
// Raise x to the power of y
// power(x: 2, y: 3) == 8
// power(x: 5, y: 2) == 25
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
// Return the remainder of x divided by y
// modulo(x: 23, y: 5) == 3
// modulo(x: 10, y: 3) == 1
func modulo(x: Int, y: Int) -> Int {
return x % y
}
// Return the factorial of a number x
// factorial(x: 5) == 120
// factorial(x: 0) == 1
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
// Return the greatest common divisor of x and y
// gcd(x: 24, y: 36) == 12
// gcd(x: 10, y: 30) == 10
func gcd(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return gcd(x: y % x, y: x)
}
}
// Return the least common multiple of x and y
// lcm(x: 24, y: 36) == 72
// lcm(x: 10, y: 30) == 300
func lcm(x: Int, y: Int) -> Int {
return x * y / gcd(x: x, y: y)
}
// Return true if x is a prime number, false otherwise
// isPrime(x: 2) == true
// isPrime(x: 4) == false
func isPrime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
}
// Return the nth Fibonacci number
// fibonacci(x: 0) == 0
// fibonacci(x: 1) == 1
// fibonacci(x: 5) == 5
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
// Return the nth prime number
// prime(x: 0) == 2
// prime(x: 1) == 3
// prime(x: 5) == 11
func prime(x: Int) -> Int {
var count = 0
var num = 2
while count < x {
if isPrime(x: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the nth Fibonacci number and the nth prime
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func power(x: Int, y: Int) -> Int {
return x ** y
}
func modulo(x: Int, y: Int) -> Int {
return x % y
}
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
func gcd(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return gcd(x: y % x, y: x)
}
}
func lcm(x: Int, y: Int) -> Int {
return x * y / gcd(x: x, y: y)
}
func isPrime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
}
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
func prime(x: Int) -> Int {
var count = 0
var num = 2
while count < x {
if isPrime(x: num) {
count += 1
}
num += 1
}
return num - 1
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 2) == 3
// subtract(x: 3, y: 1) == 2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 6, y: 3) == 2
// divide(x: 35, y: 7) == 5
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Raise x to the power of y
// power(x: 2, y: 3) == 8
// power(x: 3, y: 5) == 243
func power(x: Int, y: Int) -> Int {
return x ** y
}
// Return the remainder of x divided by y
// modulo(x: 8, y: 3) == 2
// modulo(x: 243, y: 5) == 3
func modulo(x: Int, y: Int) -> Int {
return x % y
}
// Return the factorial of a number x
// factorial(x: 0) == 1
// factorial(x: 5) == 120
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
// Return the greatest common divisor of two numbers x and y
// gcd(x: 8, y: 12) == 4
// gcd(x: 10, y: 25) == 5
func gcd(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return gcd(x: y % x, y: x)
}
}
// Return the least common multiple of two numbers x and y
// lcm(x: 8, y: 12) == 24
// lcm(x: 10, y: 25) == 60
func lcm(x: Int, y: Int) -> Int {
return x * y / gcd(x: x, y: y)
}
// Return true if x is a prime number, false otherwise
// isPrime(x: 2) == true
// isPrime(x: 4) == false
func isPrime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
}
// Return the nth Fibonacci number
// fibonacci(x: 0) == 0
// fibonacci(x: 1) == 1
// fibonacci(x: 6) == 8
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
// Return the nth prime number
// prime(x: 0) == 2
// prime(x: 3) == 7
// prime(x: 5) == 11
func prime(x: Int) -> Int {
var count = 0
var num = 2
while count < x {
if isPrime(x: num) {
count += 1
}
num += 1
}
return num - 1
}
// Return the nth Fibonacci prime number
// fibPrime(x: 0) == 0
// fibPrime(x: 1) == 1
// fibPrime(x: 4) == 5
func fib
return x ** y // no operator '**' is defined; did you mean 'pow(_:_:)'?
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func modulus(x: Int, y: Int) -> Int {
return x % y
}
func power(x: Int, y: Int) -> Int {
return Int(pow(Double(x), Double(y)))
}
func square_root(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
func greatest_common_divisor(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return greatest_common_divisor(x: y % x, y: x)
}
}
func least_common_multiple(x: Int, y: Int) -> Int {
return x * y / greatest_common_divisor(x: x, y: y)
}
func is_prime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...square_root(x: x) {
if x % i == 0 {
return false
}
}
return true
}
}
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 2) == 3
// subtract(x: 3, y: 1) == 2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 6, y: 3) == 2
// divide(x: 10, y: 2) == 5
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Take the remainder of two numbers x and y
// modulus(x: 6, y: 3) == 0
// modulus(x: 10, y: 2) == 0
func modulus(x: Int, y: Int) -> Int {
return x % y
}
// Take the power of two numbers x and y
// power(x: 2, y: 3) == 8
// power(x: 5, y: 2) == 25
func power(x: Int, y: Int) -> Int {
return Int(pow(Double(x), Double(y)))
}
// Return the square root of a number x
// square_root(x: 9) == 3
// square_root(x: 169) == 9
func square_root(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
// Return the factorial of a number x
// factorial(x: 5) == 120
// factorial(x: 0) == 1
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
// Return the greatest common divisor of two numbers x and y
// greatest_common_divisor(x: 6, y: 9) == 3
// greatest_common_divisor(x: 10, y: 15) == 5
func greatest_common_divisor(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return greatest_common_divisor(x: y % x, y: x)
}
}
// Return the least common multiple of two numbers x and y
// least_common_multiple(x: 6, y: 9) == 54
// least_common_multiple(x: 10, y: 15) == 60
func least_common_multiple(x: Int, y: Int) -> Int {
return x * y / greatest_common_divisor(x: x, y: y)
}
// Return true if x is a prime number, false otherwise
// is_prime(x: 2) == true
// is_prime(x: 4) == false
func is_prime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...square_root(x: x) {
if x % i == 0 {
return false
}
}
return true
}
}
// Return the nth Fibonacci number
// fibonacci(x: 0) == 0
// fibonacci(x: 1) == 1
// fibonacci(x: 6) == 8
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
// Return the nth Euler number
// euler_number(x: 0) == 1
// euler_number(x: 1) == 2
// euler_number(x
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 is_greater(x: Int, y: Int) -> Bool {
return x > y
}
func is_less(x: Int, y: Int) -> Bool {
return x < y
}
func is_equal(x: Int, y: Int) -> Bool {
return x == y
}
func is_not_equal(x: Int, y: Int) -> Bool {
return x!= y
}
func is_odd(x: Int) -> Bool {
return x % 2 == 1
}
func is_even(x: Int) -> Bool {
return x % 2 == 0
}
func modulo(x: Int, y: Int) -> Int {
return x % y
}
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
func square_root(x: Int) -> Double {
return sqrt(Double(x))
}
func ln(x: Double) -> Double {
return log(x)
}
func log10(x: Double) -> Double {
return log10(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: 5, y: 3) == 2
// subtract(x: 2, y: 7) == -5
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0.666667
// divide(x: 5, y: 7) == 0.714286
func divide(x: Int, y: Int) -> Double {
return Double(x) / Double(y)
}
// Check if x is greater than y
// is_greater(x: 5, y: 3) == true
// is_greater(x: 2, y: 7) == false
func is_greater(x: Int, y: Int) -> Bool {
return x > y
}
// Check if x is less than y
// is_less(x: 5, y: 3) == false
// is_less(x: 2, y: 7) == true
func is_less(x: Int, y: Int) -> Bool {
return x < y
}
// Check if x is equal to y
// is_equal(x: 5, y: 5) == true
// is_equal(x: 2, y: 7) == false
func is_equal(x: Int, y: Int) -> Bool {
return x == y
}
// Check if x is not equal to y
// is_not_equal(x: 5, y: 5) == false
// is_not_equal(x: 2, y: 7) == true
func is_not_equal(x: Int, y: Int) -> Bool {
return x!= y
}
// Check if x is odd
// is_odd(x: 3) == true
// is_odd(x: 2) == false
func is_odd(x: Int) -> Bool {
return x % 2 == 1
}
// Check if x is even
// is_even(x: 3) == false
// is_even(x: 2) == true
func is_even(x: Int) -> Bool {
return x % 2 == 0
}
// Return the remainder of x divided by y
// modulo(x: 15, y: 5) == 0
// modulo(x: 20, y: 7) == 3
func modulo(x: Int, y: Int) -> Int {
return x % y
}
// Return the factorial of x
// factorial(x: 0) == 1
// factorial(x: 5) == 120
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
// Return the square root of x
// square_root(x: 4) == 2
// square_root(x: 25) == 5
func square_root(x: Int) -> Double {
return sqrt(Double(x))
}
// Return the natural logarithm of x
// ln(x: e) == 1
// ln(x: 10) == 2.3025999566398119
func ln(x: Double) -> Double {
return log(x)
}
// Return the base 10 logarithm of x
// log10(x: e) == 1
// log10(x: 100) == 2
func log10(x: Double) -> Double {
return log10(x)
}
// Return the base x logarithm of y
// log2(x: 2, y: e) == 1
// log2(x: 10
return x!= y // use of '=' in a boolean context, did you mean '=='?
return x!= y // '=' must have consistent whitespace on both sides
return x!= y // cannot force unwrap value of non-optional type 'Int'
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func equal(x: Int, y: Int) -> Bool {
return x == y
}
func notEqual(x: Int, y: Int) -> Bool {
return x!= y
}
func greaterThan(x: Int, y: Int) -> Bool {
return x > y
}
func greaterThanOrEqualTo(x: Int, y: Int) -> Bool {
return x >= y
}
func lessThan(x: Int, y: Int) -> Bool {
return x < y
}
func lessThanOrEqualTo(x: Int, y: Int) -> Bool {
return x <= y
}
func odd(x: Int) -> Bool {
return x % 2 == 1
}
func even(x: Int) -> Bool {
return x % 2 == 0
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 3) == 2
// subtract(x: 3, y: 2) == 1
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: 6, y: 3) == 2
// divide(x: 10, y: 2) == 5
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Check if two numbers x and y are equal
// equal(x: 2, y: 2) == true
// equal(x: 3, y: 2) == false
func equal(x: Int, y: Int) -> Bool {
return x == y
}
// Check if two numbers x and y are not equal
// notEqual(x: 2, y: 2) == false
// notEqual(x: 3, y: 2) == true
func notEqual(x: Int, y: Int) -> Bool {
return x!= y
}
// Check if number x is greater than number y
// greaterThan(x: 2, y: 3) == true
// greaterThan(x: 3, y: 2) == false
func greaterThan(x: Int, y: Int) -> Bool {
return x > y
}
// Check if number x is greater than or equal to number y
// greaterThanOrEqualTo(x: 2, y: 3) == true
// greaterThanOrEqualTo(x: 3, y: 2) == true
// greaterThanOrEqualTo(x: 2, y: 2) == true
func greaterThanOrEqualTo(x: Int, y: Int) -> Bool {
return x >= y
}
// Check if number x is less than number y
// lessThan(x: 2, y: 3) == false
// lessThan(x: 3, y: 2) == false
func lessThan(x: Int, y: Int) -> Bool {
return x < y
}
// Check if number x is less than or equal to number y
// lessThanOrEqualTo(x: 2, y: 3) == false
// lessThanOrEqualTo(x: 3, y: 2) == true
// lessThanOrEqualTo(x: 2, y: 2) == true
func lessThanOrEqualTo(x: Int, y: Int) -> Bool {
return x <= y
}
// Check if number x is odd
// odd(x: 2) == false
// odd(x: 3) == true
func odd(x: Int) -> Bool {
return x % 2 == 1
}
// Check if number x is even
// even(x: 2) == true
// even(x: 3) == false
func even(x: Int) -> Bool {
return x % 2 == 0
}
// Prints "Hello, World!"
print("Hello, World!")
// Prints "The sum of 2 and 3 is 5."
print("The sum of \(2) and \(3) is \(add(x: 2, y: 3)).")
// Prints "The difference between 5 and 3 is 2."
print("The difference between \(5) and \(3) is \(subtract(x: 5, y: 3)).")
// Prints "The product of 2 and 3 is 6."
print("The product of \(2) and \(3) is \(multiply(x: 2, y: 3)).")
// Prints "The quotient of 6 and 3 is 2."
print("The quotient of \(6) and \(3) is \(divide(x: 6, y: 3)).")
// Prints "2 is equal to 2."
print("\(2) is \(equal(x: 2, y: 2)) equal to 2.")
return x!= y // use of '=' in a boolean context, did you mean '=='?
return x!= y // cannot force unwrap value of non-optional type 'Int'
return x!= y // '=' must have consistent whitespace on both sides
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func is_greater(x: Int, y: Int) -> Bool {
return x > y
}
func is_less(x: Int, y: Int) -> Bool {
return x < y
}
func is_equal(x: Int, y: Int) -> Bool {
return x == y
}
func is_positive(x: Int) -> Bool {
return x > 0
}
func is_negative(x: Int) -> Bool {
return x < 0
}
func is_zero(x: Int) -> Bool {
return x == 0
}
func square_root(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
func absolute_value(x: Int) -> Int {
if x < 0 {
return -x
} else {
return x
}
}
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 2) == 3
// subtract(x: 3, y: 1) == 2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 3, y: 5) == 15
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 6, y: 3) == 2
// divide(x: 15, y: 5) == 3
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Check if a number x is greater than y
// is_greater(x: 5, y: 2) == true
// is_greater(x: 2, y: 5) == false
func is_greater(x: Int, y: Int) -> Bool {
return x > y
}
// Check if a number x is less than y
// is_less(x: 2, y: 5) == true
// is_less(x: 5, y: 2) == false
func is_less(x: Int, y: Int) -> Bool {
return x < y
}
// Check if a number x is equal to y
// is_equal(x: 2, y: 2) == true
// is_equal(x: 5, y: 2) == false
func is_equal(x: Int, y: Int) -> Bool {
return x == y
}
// Check if a number x is positive
// is_positive(x: 2) == true
// is_positive(x: -2) == false
func is_positive(x: Int) -> Bool {
return x > 0
}
// Check if a number x is negative
// is_negative(x: -2) == true
// is_negative(x: 2) == false
func is_negative(x: Int) -> Bool {
return x < 0
}
// Check if a number x is zero
// is_zero(x: 0) == true
// is_zero(x: 2) == false
func is_zero(x: Int) -> Bool {
return x == 0
}
// Square root of a number x
// square_root(x: 9) == 3
// square_root(x: 169) == 9
func square_root(x: Int) -> Int {
return Int(sqrt(Double(x)))
}
// Absolute value of a number x
// absolute_value(x: -2) == 2
// absolute_value(x: 2) == 2
func absolute_value(x: Int) -> Int {
if x < 0 {
return -x
} else {
return x
}
}
// Power of a number x to the power of y
// power(x: 2, y: 3) == 8
// power(x: 3, y: 2) == 9
func power(x: Int, y: Int) -> Int {
var result = 1
for _ in 1...y {
result *= x
}
return result
}
// Factorial of a number x
// factorial(x: 5) == 120
// factorial(x: 0) == 1
func factorial(x: Int) -> Int {
var result = 1
for i in 1...x {
result *= i
}
return result
}
// Find the greatest common divisor of two numbers x and y
// greatest_common_divisor(x: 6, y: 15) == 3
// greatest_common_divisor(x: 10, y: 25) == 5
func greatest_common_divisor(x: Int, y: Int) -> Int {
var a = x
var b = y
while b!= 0 {
let temp = b
b = a % b
a = temp
}
return a
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func is_greater(x: Int, y: Int) -> Bool {
return x > y
}
func is_less(x: Int, y: Int) -> Bool {
return x < y
}
func is_greater_equal(x: Int, y: Int) -> Bool {
return x >= y
}
func is_less_equal(x: Int, y: Int) -> Bool {
return x <= y
}
func is_equal(x: Int, y: Int) -> Bool {
return x == y
}
func is_not_equal(x: Int, y: Int) -> Bool {
return x!= y
}
func is_prime(x: Int) -> Bool {
if x <= 1 {
return false
}
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
func factorial(x: Int) -> Int {
if x == 0 {
return 1
}
return x * factorial(x: x - 1)
}
func sum_of_numbers(x: Int) -> Int {
if x == 0 {
return 0
}
return x + sum_of_numbers(x: x - 1)
}
func sum_of_even_numbers(x: Int) -> Int {
if x == 0 {
return 0
}
if x % 2 == 0 {
return x + sum_of_even_numbers(x: x - 1)
} else {
return sum_of_even_numbers(x: x - 1)
}
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 2) == 3
// subtract(x: 3, y: 1) == 2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 6, y: 3) == 2
// divide(x: 10, y: 2) == 5
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Check if x is greater than y
// is_greater(x: 2, y: 3) == false
// is_greater(x: 5, y: 2) == true
func is_greater(x: Int, y: Int) -> Bool {
return x > y
}
// Check if x is less than y
// is_less(x: 2, y: 3) == true
// is_less(x: 5, y: 2) == false
func is_less(x: Int, y: Int) -> Bool {
return x < y
}
// Check if x is greater than or equal to y
// is_greater_equal(x: 2, y: 3) == false
// is_greater_equal(x: 5, y: 5) == true
func is_greater_equal(x: Int, y: Int) -> Bool {
return x >= y
}
// Check if x is less than or equal to y
// is_less_equal(x: 2, y: 3) == true
// is_less_equal(x: 5, y: 5) == true
func is_less_equal(x: Int, y: Int) -> Bool {
return x <= y
}
// Check if x is equal to y
// is_equal(x: 2, y: 3) == false
// is_equal(x: 5, y: 5) == true
func is_equal(x: Int, y: Int) -> Bool {
return x == y
}
// Check if x is not equal to y
// is_not_equal(x: 2, y: 3) == true
// is_not_equal(x: 5, y: 5) == false
func is_not_equal(x: Int, y: Int) -> Bool {
return x!= y
}
// Check if x is a prime number
// is_prime(x: 2) == true
// is_prime(x: 4) == false
func is_prime(x: Int) -> Bool {
if x <= 1 {
return false
}
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
// Calculate the factorial of a number x
// factorial(x: 5) == 120
func factorial(x: Int) -> Int {
if x == 0 {
return 1
}
return x * factorial(x: x - 1)
}
// Calculate the sum of all numbers between 0 and x
// sum_of_numbers(x: 5) == 15
func sum_of_numbers(x: Int) -> Int {
if x == 0 {
return 0
}
return x + sum_of_numbers(x: x - 1)
}
// Calculate the sum of all even numbers between 0 and x
// sum_of_even_numbers(x: 5) == 10
func sum_of_even_numbers(x: Int) -> Int {
if x == 0 {
return 0
}
if x % 2 == 0 {
return x + sum_of_even_numbers(x: x - 1)
} else {
return sum_of_even_numbers(x: x - 1)
}
}
// Calculate the sum of all odd numbers between
return x!= y // cannot force unwrap value of non-optional type 'Int'
return x!= y // use of '=' in a boolean context, did you mean '=='?
return x!= y // '=' must have consistent whitespace on both sides
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 equal(x: Int, y: Int) -> Bool {
return x == y
}
func notEqual(x: Int, y: Int) -> Bool {
return x!= y
}
func greaterThan(x: Int, y: Int) -> Bool {
return x > y
}
func greaterThanOrEqual(x: Int, y: Int) -> Bool {
return x >= y
}
func lessThan(x: Int, y: Int) -> Bool {
return x < y
}
func lessThanOrEqual(x: Int, y: Int) -> Bool {
return x <= y
}
func odd(x: Int) -> Bool {
return x % 2 == 1
}
func even(x: Int) -> Bool {
return x % 2 == 0
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 3) == 2
// subtract(x: 2, y: 7) == -5
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0.6666666666666666
// divide(x: 5, y: 7) == 0.7142857142857143
func divide(x: Int, y: Int) -> Double {
return Double(x) / Double(y)
}
// Check if two numbers x and y are equal
// equal(x: 2, y: 2) == true
// equal(x: 5, y: 7) == false
func equal(x: Int, y: Int) -> Bool {
return x == y
}
// Check if two numbers x and y are not equal
// notEqual(x: 2, y: 2) == false
// notEqual(x: 5, y: 7) == true
func notEqual(x: Int, y: Int) -> Bool {
return x!= y
}
// Check if number x is greater than number y
// greaterThan(x: 2, y: 3) == true
// greaterThan(x: 5, y: 2) == false
func greaterThan(x: Int, y: Int) -> Bool {
return x > y
}
// Check if number x is greater than or equal to number y
// greaterThanOrEqual(x: 2, y: 3) == true
// greaterThanOrEqual(x: 5, y: 2) == false
func greaterThanOrEqual(x: Int, y: Int) -> Bool {
return x >= y
}
// Check if number x is less than number y
// lessThan(x: 2, y: 3) == false
// lessThan(x: 5, y: 2) == true
func lessThan(x: Int, y: Int) -> Bool {
return x < y
}
// Check if number x is less than or equal to number y
// lessThanOrEqual(x: 2, y: 3) == false
// lessThanOrEqual(x: 5, y: 2) == true
func lessThanOrEqual(x: Int, y: Int) -> Bool {
return x <= y
}
// Check if number x is odd
// odd(x: 2) == false
// odd(x: 3) == true
func odd(x: Int) -> Bool {
return x % 2 == 1
}
// Check if number x is even
// even(x: 2) == true
// even(x: 3) == false
func even(x: Int) -> Bool {
return x % 2 == 0
}
// Print "Hello, World!"
print("Hello, World!")
// Print the sum of two numbers
print(add(x: 2, y: 3))
// Print the difference of two numbers
print(subtract(x: 5, y: 3))
// Print the product of two numbers
print(multiply(x: 2, y: 3))
// Print the quotient of two numbers
print(divide(x: 2, y: 3))
// Print true if two numbers are equal
print(equal(x: 2, y: 2))
// Print true if two numbers are not equal
print(notEqual(x: 2, y: 2))
// Print true if number x is greater than number y
print(greaterThan(x: 2, y: 3))
// Print true if number x is greater than or equal to number y
print(greaterThanOrEqual(x: 2, y: 3))
// Print true if number x is less than number y
return x!= y // use of '=' in a boolean context, did you mean '=='?
return x!= y // cannot force unwrap value of non-optional type 'Int'
return x!= y // '=' must have consistent whitespace on both sides
func add(x: Int, y: Int) -> Int {
return x + y
}
func subtract(x: Int, y: Int) -> Int {
return x - y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func divide(x: Int, y: Int) -> Int {
return x / y
}
func power(x: Int, y: Int) -> Int {
return Int(pow(Double(x), Double(y)))
}
func modulo(x: Int, y: Int) -> Int {
return x % y
}
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
func gcd(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return gcd(x: y % x, y: x)
}
}
func lcm(x: Int, y: Int) -> Int {
return x * y / gcd(x: x, y: y)
}
func isPrime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
}
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
func primeFibonacci(x: Int) -> Int {
var count = 0
var i = 0
while count < x {
if isPrime(x: fibonacci(x: i)) {
count += 1
}
i += 1
}
return fibonacci(x: i - 1)
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Subtract two numbers x and y
// subtract(x: 5, y: 2) == 3
// subtract(x: 3, y: 1) == 2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Divide two numbers x and y
// divide(x: 6, y: 3) == 2
// divide(x: 10, y: 2) == 5
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Raise x to the power of y
// power(x: 2, y: 3) == 8
// power(x: 5, y: 2) == 25
func power(x: Int, y: Int) -> Int {
return Int(pow(Double(x), Double(y)))
}
// Return the remainder of x divided by y
// modulo(x: 8, y: 3) == 2
// modulo(x: 10, y: 2) == 0
func modulo(x: Int, y: Int) -> Int {
return x % y
}
// Return the factorial of a number x
// factorial(x: 5) == 120
func factorial(x: Int) -> Int {
if x == 0 {
return 1
} else {
return x * factorial(x: x - 1)
}
}
// Return the greatest common divisor of two numbers x and y
// gcd(x: 24, y: 36) == 12
// gcd(x: 45, y: 60) == 15
func gcd(x: Int, y: Int) -> Int {
if x == 0 {
return y
} else {
return gcd(x: y % x, y: x)
}
}
// Return the least common multiple of two numbers x and y
// lcm(x: 24, y: 36) == 72
// lcm(x: 45, y: 60) == 900
func lcm(x: Int, y: Int) -> Int {
return x * y / gcd(x: x, y: y)
}
// Return true if x is a prime number, false otherwise
// isPrime(x: 7) == true
// isPrime(x: 12) == false
func isPrime(x: Int) -> Bool {
if x < 2 {
return false
} else {
for i in 2...Int(sqrt(Double(x))) {
if x % i == 0 {
return false
}
}
return true
}
}
// Return the nth Fibonacci number
// fibonacci(x: 0) == 0
// fibonacci(x: 1) == 1
// fibonacci(x: 6) == 8
func fibonacci(x: Int) -> Int {
if x == 0 {
return 0
} else if x == 1 {
return 1
} else {
return fibonacci(x: x - 1) + fibonacci(x: x - 2)
}
}
// Return the nth prime Fibonacci number
// primeFibonacci(x: 0) == 0
// primeFibonacci(x: 1) == 0
// primeFibonacci(x: 2) == 2
// primeFibonacci(x: 6) == 5
func primeFibonacci(x: Int) -> Int {
var count = 0
var i = 0
while count < x {
if isPrime(x: fibonacci(x: i)) {
count += 1
}
i += 1
}
return fibonacci(x: i - 1)
}
// Return the
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().filter { $0!= " " })
let s1Chars = Array(s1.lowercased().filter { $0!= " " })
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
for char in s1Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count - 1
if count == 1 {
s0CharsDict[char] = nil
}
} else {
return false
}
}
return true
}
func swapOK(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().filter { $0!= " " })
let s1Chars = Array(s1.lowercased().filter { $0!= " " })
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
for char in s1Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count - 1
if count == 1 {
s0CharsDict[char] = nil
}
} else {
return false
}
}
for i in 0..<s0Chars.count {
if s0Chars[i]!= s1Chars[i] {
if let count = s0CharsDict[s0Chars[i]] {
s0CharsDict[s0Chars[i]] = count + 1
} else {
s0CharsDict[s0Chars[i]] = 1
}
if let count = s0CharsDict[s1Chars[i]] {
s0CharsDict[s1Chars[i]] = count - 1
if count == 1 {
s0CharsDict[s1Chars[i]] = nil
}
} else {
return false
}
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().filter { $0!= " " })
let s1Chars = Array(s1.lowercased().filter { $0!= " " })
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
for char in s1Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count - 1
if count == 1 {
s0CharsDict[char] = nil
}
} else {
return false
}
}
return true
}
// Check if two words can be made by swapping two letters.
// swapOK(s0: "abc", s1: "bca") == true
// swapOK(s0: "abcd", s1: "dabc") == true
// swapOK(s0: "abcd", s1: "abdc") == true
// swapOK(s0: "abcd", s1: "abce") == false
// swapOK(s0: "abcd", s1: "abcd") == false
// swapOK(s0: "abcd", s1: "bcde") == false
// swapOK(s0: "abc", s1: "abcd") == false
// swapOK(s0: "abc", s1: "abce") == false
// swapOK(s0: "abc", s1: "abca") == false
func swapOK(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().filter { $0!= " " })
let s1Chars = Array(s1.lowercased().filter { $0!= " " })
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
for char in s1Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count - 1
if count == 1 {
s0CharsDict[char] = nil
}
} else {
return false
}
}
for i in 0..<s0Chars.count {
if s0Chars[i]!= s1Chars[i] {
if let count = s0CharsDict[s0Chars[i]] {
s0CharsDict[s0Chars[i]] = count + 1
} else {
s0CharsDict[s0Chars[i]] = 1
}
if let count = s0CharsDict[s1Chars[i]] {
s0CharsDict[s1Chars[i]] = count - 1
if count == 1 {
s0CharsDict[s1Chars[i]] = nil
}
} else {
return false
}
}
}
return true
}
// Check if two words can be made by swapping two letters,
// and the swapped letters can be in the same order as in the first word.
// swapAndOrderOK(s0: "abc", s1: "bca") == true
// swapAndOrderOK(s0: "abcd", s1: "dabc") == true
// swapAndOrderOK(s0: "abcd", s1: "abdc") == true
// swapAndOrderOK(s0: "abcd", s1: "abce") == false
// swapAndOrderOK(s0: "abcd", s1: "abcd") == false
// swapAndOrderOK(s0: "abcd", s1: "bcde") == false
// swapAndOrderOK(s0: "abc", s1: "abcd") == false
// swapAndOrderOK(s0: "abc", s1: "abce") == false
// swapAndOrderOK(s0: "abc", s1: "abca") == false
func swapAndOrderOK(s0: String, s1
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // '=' must have consistent whitespace on both sides
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // cannot convert value of type '()' to closure result type 'Bool'
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // cannot convert value of type '()' to closure result type 'Bool'
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // '=' must have consistent whitespace on both sides
if s0Chars.count!= s1Chars.count { // '=' must have consistent whitespace on both sides
if s0Chars.count!= s1Chars.count { // use of '=' in a boolean context, did you mean '=='?
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // cannot convert value of type '()' to closure result type 'Bool'
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // '=' must have consistent whitespace on both sides
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // '=' must have consistent whitespace on both sides
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // cannot convert value of type '()' to closure result type 'Bool'
if s0Chars.count!= s1Chars.count { // use of '=' in a boolean context, did you mean '=='?
if s0Chars.count!= s1Chars.count { // '=' must have consistent whitespace on both sides
if s0Chars[i]!= s1Chars[i] { // '=' must have consistent whitespace on both sides
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
return s0Chars.sorted() == s1Chars.sorted()
}
func sameCharsInAnyOrder(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
return s0Chars.count == s1Chars.count && s0Chars.sorted() == s1Chars.sorted()
}
func sameCharsInSameLength(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
return s0Chars.count == s1Chars.count && s0Chars.sorted() == s1Chars.sorted()
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
return s0Chars.sorted() == s1Chars.sorted()
}
// Check if two words have the same characters regardless of order.
// sameCharsInAnyOrder(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameCharsInAnyOrder(s0: "abcd", s1: "dddddddabc") == true
// sameCharsInAnyOrder(s0: "dddddddabc", s1: "abcd") == true
// sameCharsInAnyOrder(s0: "eabcd", s1: "dddddddabc") == true
// sameCharsInAnyOrder(s0: "abcd", s1: "dddddddabce") == true
// sameCharsInAnyOrder(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == true
func sameCharsInAnyOrder(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
return s0Chars.count == s1Chars.count && s0Chars.sorted() == s1Chars.sorted()
}
// Check if two words have the same characters, regardless of order, and are of the same length.
// sameCharsInSameLength(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == false
// sameCharsInSameLength(s0: "abcd", s1: "dddddddabc") == false
// sameCharsInSameLength(s0: "dddddddabc", s1: "abcd") == false
// sameCharsInSameLength(s0: "eabcd", s1: "dddddddabc") == false
// sameCharsInSameLength(s0: "abcd", s1: "dddddddabce") == false
// sameCharsInSameLength(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
// sameCharsInSameLength(s0: "abcde", s1: "zzzzzzzzzzzzzzzz") == false
// sameCharsInSameLength(s0: "zzzzzzzzzzzzzzzz", s1: "abcde") == false
// sameCharsInSameLength(s0: "abcde", s1: "zzzzzzzzzzzzzzzz") == false
// sameCharsInSameLength(s0: "zzzzzzzzzzzzzzzz", s1: "abcde") == false
// sameCharsInSameLength(s0: "abcde", s1: "abcdef") == true
// sameCharsInSameLength(s0: "abcdef", s1: "abcde") == true
// sameCharsInSameLength(s0: "abcde", s1: "abcfde") == false
// sameCharsInSameLength(s0: "abcfde", s1: "abcde") == false
// sameCharsInSameLength(s0: "abcdefg", s1: "gabcdef") == true
// sameCharsInSameLength(s0: "gabcdef", s1: "abcdefg") == true
func sameCharsInSameLength(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
return s0Chars.count == s1Chars.count && s0Chars.sorted() == s1Chars.sorted()
}
// Check if two words have the same characters, regardless of order, and are of the same length.
// The function ignores whitespace characters and punctuation marks.
// sameCharsInSameLengthIgnoreWhitespaceAndPunctuation(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == false
// sameCharsInSameLengthIgnoreWhitespaceAndPunctuation(s0: "abcd", s1: "dddddddabc") == false
// sameCharsInSameLengthIgnoreWhitespaceAndPunctuation(s0: "dddddddabc", s1: "abcd") == false
// sameCharsInSameLengthIgnoreWhitespaceAndPunctuation(s0: "eabcd", s1: "dddddddabc") == false
let s0Chars = Array(s0.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s1Chars = Array(s1.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s0Chars = Array(s0.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s1Chars = Array(s1.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s0Chars = Array(s0.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s1Chars = Array(s1.lowercased().characters) // 'characters' is unavailable: Please use String directly
func sameChars(s0: String, s1: String) -> Bool {
// Check if the lengths of the two words are equal
if s0.count!= s1.count {
return false
}
// Convert the words to lowercase and remove any spaces
let s0Chars = Array(s0.lowercased().filter { $0!= " " })
let s1Chars = Array(s1.lowercased().filter { $0!= " " })
// Sort the characters in both words
let sortedS0Chars = s0Chars.sorted()
let sortedS1Chars = s1Chars.sorted()
// Compare the sorted characters
return sortedS0Chars == sortedS1Chars
}
```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 {
// Check if the lengths of the two words are equal
if s0.count!= s1.count {
return false
}
// Convert the words to lowercase and remove any spaces
let s0Chars = Array(s0.lowercased().filter { $0!= " " })
let s1Chars = Array(s1.lowercased().filter { $0!= " " })
// Sort the characters in both words
let sortedS0Chars = s0Chars.sorted()
let sortedS1Chars = s1Chars.sorted()
// Compare the sorted characters
return sortedS0Chars == sortedS1Chars
}
// Test the function
print(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc")) // true
print(sameChars(s0: "abcd", s1: "dddddddabc")) // true
print(sameChars(s0: "dddddddabc", s1: "abcd")) // true
print(sameChars(s0: "eabcd", s1: "dddddddabc")) // false
print(sameChars(s0: "abcd", s1: "dddddddabce")) // false
print(sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc")) // false
```
if s0.count!= s1.count { // '=' must have consistent whitespace on both sides
if s0.count!= s1.count { // use of '=' in a boolean context, did you mean '=='?
if s0.count!= s1.count { // cannot force unwrap value of non-optional type 'Int'
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // '=' must have consistent whitespace on both sides
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
let s0Chars = Array(s0.lowercased().filter { $0!= " " }) // cannot convert value of type '()' to closure result type 'Bool'
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // cannot convert value of type '()' to closure result type 'Bool'
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // '=' must have consistent whitespace on both sides
let s1Chars = Array(s1.lowercased().filter { $0!= " " }) // cannot force unwrap value of non-optional type 'String.Element' (aka 'Character')
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
for char in s1Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count - 1
if count - 1 < 0 {
return false
}
} else {
return false
}
}
return true
}
func canSwap(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
var s1CharsDict = [Character: Int]()
for char in s1Chars {
if let count = s1CharsDict[char] {
s1CharsDict[char] = count + 1
} else {
s1CharsDict[char] = 1
}
}
for char in s0Chars {
if let count = s1CharsDict[char] {
s1CharsDict[char] = count - 1
if count - 1 < 0 {
return false
}
} else {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
for char in s1Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count - 1
if count - 1 < 0 {
return false
}
} else {
return false
}
}
return true
}
// Check if two words can be formed by swapping two letters in a given word.
// canSwap(s0: "apple", s1: "ppaelr") == true
// canSwap(s0: "cat", s1: "cut") == true
// canSwap(s0: "cat", s1: "cast") == false
// canSwap(s0: "cat", s1: "at") == false
// canSwap(s0: "cat", s1: "act") == false
// canSwap(s0: "cat", s1: "bat") == false
// canSwap(s0: "apple", s1: "ppale") == false
// canSwap(s0: "apple", s1: "ppelp") == false
// canSwap(s0: "apple", s1: "pplae") == true
// canSwap(s0: "apple", s1: "pplee") == false
// canSwap(s0: "apple", s1: "ppel") == false
// canSwap(s0: "apple", s1: "ppl") == false
// canSwap(s0: "apple", s1: "pp") == false
// canSwap(s0: "apple", s1: "e") == false
// canSwap(s0: "apple", s1: "a") == false
// canSwap(s0: "apple", s1: "ppelr") == true
func canSwap(s0: String, s1: String) -> Bool {
let s0Chars = Array(s0.lowercased().characters)
let s1Chars = Array(s1.lowercased().characters)
if s0Chars.count!= s1Chars.count {
return false
}
var s0CharsDict = [Character: Int]()
for char in s0Chars {
if let count = s0CharsDict[char] {
s0CharsDict[char] = count + 1
} else {
s0CharsDict[char] = 1
}
}
var s1CharsDict = [Character: Int]()
for char in s1Chars {
if let count = s1CharsDict[char] {
s1CharsDict[char] = count + 1
} else {
s1CharsDict[char] = 1
}
}
for char in s0Chars {
if let count = s1CharsDict[char] {
s1CharsDict[char] = count - 1
if count - 1 < 0 {
return false
}
} else {
return false
}
}
return true
}
// Check if two words can be formed by swapping two vowels in a given word.
// canSwapVowels(s0: "apple", s1: "ppaelr") == true
// canSwapVowels(s0: "cat", s1: "cut") == true
// canSwapVowels(s0: "cat", s1: "cast") == false
// canSwapVowels(s0: "cat", s1: "at") == false
// canSwapVowels(s0: "cat", s1: "act") == false
// canSwapVowels(s0: "cat", s1: "bat") == false
// canSwapVowels(s0: "apple", s1: "ppale") == false
// canSwapVowels(s0: "apple", s1: "ppelp") == false
// canSwapVowels(s0: "apple", s1: "pplae") == false
// canSwapVowels(s0
let s0Chars = Array(s0.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s1Chars = Array(s1.lowercased().characters) // 'characters' is unavailable: Please use String directly
if s0Chars.count!= s1Chars.count { // use of '=' in a boolean context, did you mean '=='?
if s0Chars.count!= s1Chars.count { // '=' must have consistent whitespace on both sides
if s0Chars.count!= s1Chars.count { // cannot force unwrap value of non-optional type 'Int'
let s0Chars = Array(s0.lowercased().characters) // 'characters' is unavailable: Please use String directly
let s1Chars = Array(s1.lowercased().characters) // 'characters' is unavailable: Please use String directly
if s0Chars.count!= s1Chars.count { // use of '=' in a boolean context, did you mean '=='?
if s0Chars.count!= s1Chars.count { // cannot force unwrap value of non-optional type 'Int'
if s0Chars.count!= s1Chars.count { // '=' must have consistent whitespace on both sides
func sameChars(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var dict: [Character: Int] = [:]
for char in s0 {
if let count = dict[char] {
dict[char] = count + 1
} else {
dict[char] = 1
}
}
for char in s1 {
if let count = dict[char] {
dict[char] = count - 1
if dict[char] == 0 {
dict[char] = nil
}
} else {
return false
}
}
return true
}
func isPalindrome(s: String) -> Bool {
if s.count == 0 {
return false
}
var i = 0
var j = s.count - 1
while i < j {
if s[i]!= s[j] {
return false
}
i += 1
j -= 1
}
return true
}
func hasUniqueChars(s: String) -> Bool {
if s.count == 0 {
return false
}
var dict: [Character: Int] = [:]
for char in s {
if let count = dict[char] {
return false
} else {
dict[char] = 1
}
}
return true
}
func isPermutation(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var dict: [Character: Int] = [:]
for char in s0 {
if let count = dict[char] {
dict[char] = count + 1
} else {
dict[char] = 1
}
}
for char in s1 {
if let count = dict[char] {
dict[char] = count - 1
if dict[char] == 0 {
dict[char] = nil
}
} else {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var dict: [Character: Int] = [:]
for char in s0 {
if let count = dict[char] {
dict[char] = count + 1
} else {
dict[char] = 1
}
}
for char in s1 {
if let count = dict[char] {
dict[char] = count - 1
if dict[char] == 0 {
dict[char] = nil
}
} else {
return false
}
}
return true
}
// Check if a string is a palindrome.
// isPalindrome(s: "eabcdzzzz") == false
// isPalindrome(s: "abcd") == true
// isPalindrome(s: "abccba") == true
// isPalindrome(s: "eabcd") == false
// isPalindrome(s: "abcdabcd") == true
// isPalindrome(s: "eabcdabcd") == false
func isPalindrome(s: String) -> Bool {
if s.count == 0 {
return false
}
var i = 0
var j = s.count - 1
while i < j {
if s[i]!= s[j] {
return false
}
i += 1
j -= 1
}
return true
}
// Check if a string contains only unique characters.
// hasUniqueChars(s: "eabcdzzzz") == false
// hasUniqueChars(s: "abcd") == true
// hasUniqueChars(s: "abccba") == false
// hasUniqueChars(s: "eabcd") == false
// hasUniqueChars(s: "abcdabcd") == false
// hasUniqueChars(s: "eabcdabcd") == true
func hasUniqueChars(s: String) -> Bool {
if s.count == 0 {
return false
}
var dict: [Character: Int] = [:]
for char in s {
if let count = dict[char] {
return false
} else {
dict[char] = 1
}
}
return true
}
// Check if two strings are permutations of each other.
// isPermutation(s0: "eabcdzzzz", s1: "zzzzddleeab") == true
// isPermutation(s0: "abcd", s1: "dddddddabc") == true
// isPermutation(s0: "eabcd", s1: "dddddddabc") == false
// isPermutation(s0: "abcd", s1: "dddddddabce") == false
// isPermutation(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func isPermutation(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var dict: [Character: Int] = [:]
for char in s0 {
if let count = dict[char] {
dict[char] = count + 1
} else {
dict[char] = 1
}
}
for char in s1 {
if let count = dict[char] {
dict[char] = count - 1
if dict[char] == 0 {
dict[char] = nil
}
} else {
return false
}
}
return true
}
// Given two strings, check if one is a permutation of the other.
// isPermutation(s0: "eabcdzzzz", s1: "zzzzddleeab") == true
// isPermutation(s0: "abcd", s1: "dddddddabc") == true
// isPermutation(s0: "eabcd", s1: "dddddddabc") == false
// isPermutation(s0: "abcd", s1: "dddddddabce") == false
// isPermutation(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func isPermutation2(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var dict: [Character: Int] = [:]
for char in s0 {
if let count = dict[char
if s0.count!= s1.count { // cannot force unwrap value of non-optional type 'Int'
if s0.count!= s1.count { // use of '=' in a boolean context, did you mean '=='?
if s0.count!= s1.count { // '=' must have consistent whitespace on both sides
if s[i]!= s[j] { // cannot force unwrap value of non-optional type 'Character'
if s[i]!= s[j] { // use of '=' in a boolean context, did you mean '=='?
if s[i]!= s[j] { // '=' must have consistent whitespace on both sides
if let count = dict[char] { // value 'count' was defined but never used; consider replacing with boolean test
if s0.count!= s1.count { // cannot force unwrap value of non-optional type 'Int'
if s0.count!= s1.count { // use of '=' in a boolean context, did you mean '=='?
if s0.count!= s1.count { // '=' must have consistent whitespace on both sides
func sameChars(s0: String, s1: String) -> Bool {
var charCount = [Character: Int]()
for char in s0 {
charCount[char, default: 0] += 1
}
for char in s1 {
if let count = charCount[char] {
charCount[char] = count - 1
if charCount[char] == 0 {
charCount[char] = nil
}
} else {
return false
}
}
return true
}
func uniqueChars(s: String) -> Bool {
var charSet = Set<Character>()
for char in s {
if charSet.contains(char) {
return false
}
charSet.insert(char)
}
return true
}
func uniqueCharsExcludingWhitespace(s: String) -> Bool {
var charSet = Set<Character>()
for char in s {
if charSet.contains(char) {
return false
}
if char.isWhitespace {
continue
}
charSet.insert(char)
}
return true
}
func anagrams(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var charCount = [Character: Int]()
for char in s0 {
charCount[char, default: 0] += 1
}
for char in s1 {
if let count = charCount[char] {
charCount[char] = count - 1
if charCount[char] == 0 {
charCount[char] = nil
}
} else {
return false
}
}
return true
}
func isPalindrome(s: String) -> Bool {
if s.count == 1 {
return true
}
var i = 0
var j = s.count - 1
while i < j {
if s[i]!= s[j] {
return false
}
i += 1
j -= 1
}
return true
}
func reverse(s: String) -> String {
var chars = Array(s)
var i = 0
var j = s.count - 1
while i < j {
let temp = chars[i]
chars[i] = chars[j]
chars[j] = temp
i += 1
j -= 1
}
return String(chars)
}
```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 charCount = [Character: Int]()
for char in s0 {
charCount[char, default: 0] += 1
}
for char in s1 {
if let count = charCount[char] {
charCount[char] = count - 1
if charCount[char] == 0 {
charCount[char] = nil
}
} else {
return false
}
}
return true
}
// Check if a string contains only unique characters.
// uniqueChars(s: "abc") == true
// uniqueChars(s: "aaa") == false
// uniqueChars(s: "aabc") == false
// uniqueChars(s: "abca") == false
// uniqueChars(s: "abcabc") == false
func uniqueChars(s: String) -> Bool {
var charSet = Set<Character>()
for char in s {
if charSet.contains(char) {
return false
}
charSet.insert(char)
}
return true
}
// Check if a string contains only unique characters, excluding whitespace.
// uniqueCharsExcludingWhitespace(s: "abc") == true
// uniqueCharsExcludingWhitespace(s: "aaa") == false
// uniqueCharsExcludingWhitespace(s: "aabc") == false
// uniqueCharsExcludingWhitespace(s: "abca") == false
// uniqueCharsExcludingWhitespace(s: "abc abc") == false
func uniqueCharsExcludingWhitespace(s: String) -> Bool {
var charSet = Set<Character>()
for char in s {
if charSet.contains(char) {
return false
}
if char.isWhitespace {
continue
}
charSet.insert(char)
}
return true
}
// Check if two strings are anagrams.
// anagrams(s0: "silent", s1: "listen") == true
// anagrams(s0: "hello", s1: "world") == false
// anagrams(s0: "abc", s1: "abcd") == false
// anagrams(s0: "abc", s1: "aabc") == false
// anagrams(s0: "aabbcc", s1: "aabbc") == true
func anagrams(s0: String, s1: String) -> Bool {
if s0.count!= s1.count {
return false
}
var charCount = [Character: Int]()
for char in s0 {
charCount[char, default: 0] += 1
}
for char in s1 {
if let count = charCount[char] {
charCount[char] = count - 1
if charCount[char] == 0 {
charCount[char] = nil
}
} else {
return false
}
}
return true
}
// Check if a string is a palindrome.
// isPalindrome(s: "abcba") == true
// isPalindrome(s: "abc") == false
// isPalindrome(s: "abccba") == true
// isPalindrome(s: "a") == true
// isPalindrome(s: "ab") == false
// isPalindrome(s: "abcab") == false
func isPalindrome(s: String) -> Bool {
if s.count == 1 {
return true
}
var i = 0
var j = s.count - 1
while i < j {
if s[i]!= s[j] {
return false
}
i += 1
j -= 1
}
return true
}
// Reverse a string.
// reverse(s: "abcd") == "dcba"
// reverse(s: "a") == "a"
// reverse(s: "ab") == "ba"
// reverse(s: "abcde") == "edcba"
func reverse(s: String) -> String {
var chars = Array(s)
var i = 0
var j = s.count - 1
while i < j {
let temp = chars[i]
chars[i] = chars[j]
chars[j] = temp
i += 1
j -= 1
}
return String(chars)
}
// Remove duplicate characters from a string.
// removeDuplicates(s: "abcd") == "abcd"
// removeDuplicates(s: "a") == "
if s0.count!= s1.count { // use of '=' in a boolean context, did you mean '=='?
if s0.count!= s1.count { // '=' must have consistent whitespace on both sides
if s0.count!= s1.count { // cannot force unwrap value of non-optional type 'Int'
if s[i]!= s[j] { // '=' must have consistent whitespace on both sides
if s[i]!= s[j] { // cannot force unwrap value of non-optional type 'Character'
if s[i]!= s[j] { // use of '=' in a boolean context, did you mean '=='?
func sameChars(s0: String, s1: String) -> Bool {
// Check if the lengths of the two words are the same.
if s0.count!= s1.count {
return false
}
// Create a set to store the characters of the first word.
var set0 = Set<Character>()
// Add the characters of the first word to the set.
for char in s0 {
set0.insert(char)
}
// Create a second set to store the characters of the second word.
var set1 = Set<Character>()
// Add the characters of the second word to the set.
for char in s1 {
set1.insert(char)
}
// Check if the two sets have the same elements.
return set0 == set1
}
```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 {
// Check if the lengths of the two words are the same.
if s0.count!= s1.count {
return false
}
// Create a set to store the characters of the first word.
var set0 = Set<Character>()
// Add the characters of the first word to the set.
for char in s0 {
set0.insert(char)
}
// Create a second set to store the characters of the second word.
var set1 = Set<Character>()
// Add the characters of the second word to the set.
for char in s1 {
set1.insert(char)
}
// Check if the two sets have the same elements.
return set0 == set1
}
```
if s0.count!= s1.count { // cannot force unwrap value of non-optional type 'Int'
if s0.count!= s1.count { // '=' must have consistent whitespace on both sides
if s0.count!= s1.count { // use of '=' in a boolean context, did you mean '=='?
func sameChars(s0: String, s1: String) -> Bool {
// Check if the lengths of the two words are the same.
guard s0.count == s1.count else { return false }
// Create a set to store the characters of the first word.
var set0 = Set<Character>()
// Add the characters of the first word to the set.
for char in s0 {
set0.insert(char)
}
// Create a second set to store the characters of the second word.
var set1 = Set<Character>()
// Add the characters of the second word to the set.
for char in s1 {
set1.insert(char)
}
// Check if the two sets have the same elements.
return set0 == set1
}
```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 {
// Check if the lengths of the two words are the same.
guard s0.count == s1.count else { return false }
// Create a set to store the characters of the first word.
var set0 = Set<Character>()
// Add the characters of the first word to the set.
for char in s0 {
set0.insert(char)
}
// Create a second set to store the characters of the second word.
var set1 = Set<Character>()
// Add the characters of the second word to the set.
for char in s1 {
set1.insert(char)
}
// Check if the two sets have the same elements.
return set0 == set1
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
var count0 = [Character: Int]()
var count1 = [Character: Int]()
for char in s0 {
count0[char, default: 0] += 1
}
for char in s1 {
count1[char, default: 0] += 1
}
return count0 == count1
}
func anagrams(s0: String, s1: String) -> Bool {
return sameChars(s0: s0.sorted(), s1: s1.sorted())
}
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
func isPalindromeWithVowels(s: String) -> Bool {
var vowels = 0
for char in s {
if "aeiou".contains(char) {
vowels += 1
}
}
return s == String(s.reversed()) && vowels > 0
}
func isPalindromeWithConsonants(s: String) -> Bool {
var consonants = 0
for char in s {
if "bcdfghjklmnpqrstvwxyz".contains(char) {
consonants += 1
}
}
return s == String(s.reversed()) && consonants > 0
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
var count0 = [Character: Int]()
var count1 = [Character: Int]()
for char in s0 {
count0[char, default: 0] += 1
}
for char in s1 {
count1[char, default: 0] += 1
}
return count0 == count1
}
// Check if two words are anagrams.
// anagrams(s0: "silent", s1: "listen") == true
// anagrams(s0: "hello", s1: "world") == false
// anagrams(s0: "hello", s1: "olleh") == true
// anagrams(s0: "eabcd", s1: "dddddddabc") == false
// anagrams(s0: "abcd", s1: "dddddddabce") == false
// anagrams(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func anagrams(s0: String, s1: String) -> Bool {
return sameChars(s0: s0.sorted(), s1: s1.sorted())
}
// Check if a word is a palindrome.
// isPalindrome(s: "abcba") == true
// isPalindrome(s: "abacdfgdcaba") == true
// isPalindrome(s: "abacdfgdcabz") == false
// isPalindrome(s: "eabcd") == false
// isPalindrome(s: "abcd") == false
// isPalindrome(s: "eabcdzzzz") == false
func isPalindrome(s: String) -> Bool {
return s == String(s.reversed())
}
// Check if a word is a palindrome and has at least one vowel.
// isPalindromeWithVowels(s: "abcba") == true
// isPalindromeWithVowels(s: "abacdfgdcaba") == true
// isPalindromeWithVowels(s: "abacdfgdcabz") == false
// isPalindromeWithVowels(s: "eabcd") == false
// isPalindromeWithVowels(s: "abcd") == false
// isPalindromeWithVowels(s: "eabcdzzzz") == false
func isPalindromeWithVowels(s: String) -> Bool {
var vowels = 0
for char in s {
if "aeiou".contains(char) {
vowels += 1
}
}
return s == String(s.reversed()) && vowels > 0
}
// Check if a word is a palindrome and has at least one consonant.
// isPalindromeWithConsonants(s: "abcba") == false
// isPalindromeWithConsonants(s: "abacdfgdcaba") == true
// isPalindromeWithConsonants(s: "abacdfgdcabz") == false
// isPalindromeWithConsonants(s: "eabcd") == false
// isPalindromeWithConsonants(s: "abcd") == false
// isPalindromeWithConsonants(s: "eabcdzzzz") == false
func isPalindromeWithConsonants(s: String) -> Bool {
var consonants = 0
for char in s {
if "bcdfghjklmnpqrstvwxyz".contains(char) {
consonants += 1
}
}
return s == String(s.reversed()) && consonants > 0
}
// Check if a word is a palindrome and has at least one special character.
// isPalindromeWithSpecialChars(s: "abcba") == false
// isPalindromeWithSpecialChars(s: "abacdfgdcaba") == false
// isPalindromeWithSpecialChars(s: "abacdfgdcabz") == false
// isPalindromeWithSpecialChars(s: "eabcd") == true
// isPalindromeWithSpecialChars(s: "abcd") == false
// isPalindromeWithSpecialChars(s: "eabcdzzzz") == false
func isPalindromeWithSpecialChars(s: String) -> Bool {
var specialChars
return sameChars(s0: s0.sorted(), s1: s1.sorted()) // cannot convert value of type '[String.Element]' (aka 'Array<Character>') to expected argument type 'String'
return sameChars(s0: s0.sorted(), s1: s1.sorted()) // cannot convert value of type '[String.Element]' (aka 'Array<Character>') to expected argument type 'String'
func sameChars(s0: String, s1: String) -> Bool {
var charMap: [Character: Int] = [:]
for char in s0 {
charMap[char, default: 0] += 1
}
for char in s1 {
if let count = charMap[char] {
charMap[char] = count - 1
if charMap[char] == 0 {
charMap[char] = nil
}
} else {
return false
}
}
return true
}
func swapAdjacent(s0: String, s1: String) -> Bool {
var s0Chars = Array(s0)
var s1Chars = Array(s1)
var i = 0
var j = 0
while i < s0Chars.count && j < s1Chars.count {
if s0Chars[i] == s1Chars[j] {
i += 1
j += 1
} else {
if i + 1 < s0Chars.count && j + 1 < s1Chars.count {
if s0Chars[i + 1] == s1Chars[j] && s0Chars[i] == s1Chars[j + 1] {
i += 2
j += 2
} else {
return false
}
} else {
return false
}
}
}
return i == s0Chars.count && j == s1Chars.count
}
func swapAny(s0: String, s1: String) -> Bool {
var s0Chars = Array(s0)
var s1Chars = Array(s1)
for i in 0...s0Chars.count - 2 {
for j in 0...s1Chars.count - 2 {
if s0Chars[i] == s1Chars[j] && s0Chars[i + 1] == s1Chars[j + 1] {
return true
} else if s0Chars[i] == s1Chars[j + 1] && s0Chars[i + 1] == s1Chars[j] {
return true
}
}
}
return false
}
```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 charMap: [Character: Int] = [:]
for char in s0 {
charMap[char, default: 0] += 1
}
for char in s1 {
if let count = charMap[char] {
charMap[char] = count - 1
if charMap[char] == 0 {
charMap[char] = nil
}
} else {
return false
}
}
return true
}
// Check if two words can be formed by swapping adjacent characters.
// swapAdjacent(s0: "eabcd", s1: "abced") == true
// swapAdjacent(s0: "abcd", s1: "abced") == false
// swapAdjacent(s0: "abcd", s1: "abcd") == false
// swapAdjacent(s0: "eabcd", s1: "abcd") == false
// swapAdjacent(s0: "abcd", s1: "bcde") == false
// swapAdjacent(s0: "eabcd", s1: "bcde") == false
func swapAdjacent(s0: String, s1: String) -> Bool {
var s0Chars = Array(s0)
var s1Chars = Array(s1)
var i = 0
var j = 0
while i < s0Chars.count && j < s1Chars.count {
if s0Chars[i] == s1Chars[j] {
i += 1
j += 1
} else {
if i + 1 < s0Chars.count && j + 1 < s1Chars.count {
if s0Chars[i + 1] == s1Chars[j] && s0Chars[i] == s1Chars[j + 1] {
i += 2
j += 2
} else {
return false
}
} else {
return false
}
}
}
return i == s0Chars.count && j == s1Chars.count
}
// Check if two words can be formed by swapping any two characters.
// swapAny(s0: "eabcd", s1: "abced") == true
// swapAny(s0: "abcd", s1: "abced") == true
// swapAny(s0: "abcd", s1: "abcd") == false
// swapAny(s0: "eabcd", s1: "abcd") == true
// swapAny(s0: "abcd", s1: "bcde") == true
// swapAny(s0: "eabcd", s1: "bcde") == true
func swapAny(s0: String, s1: String) -> Bool {
var s0Chars = Array(s0)
var s1Chars = Array(s1)
for i in 0...s0Chars.count - 2 {
for j in 0...s1Chars.count - 2 {
if s0Chars[i] == s1Chars[j] && s0Chars[i + 1] == s1Chars[j + 1] {
return true
} else if s0Chars[i] == s1Chars[j + 1] && s0Chars[i + 1] == s1Chars[j] {
return true
}
}
}
return false
}
// Check if two words can be formed by swapping any two characters,
// and the swapped characters must be in the same order as in the original string.
// swapSameOrder(s0: "eabcd", s1: "abced") == true
// swapSameOrder(s0: "abcd", s1: "abced") == false
// swapSameOrder(s0: "abcd", s1: "abcd") == false
// swapSameOrder(s0: "eabcd", s1: "abcd") == true
// swapSameOrder(s0: "abcd", s1: "bcde") == false
// swapSameOrder(s0: "eabcd", s1: "bcde") == false
func swapSameOrder(s0: String, s1: String) -> Bool {
var s0Chars = Array(s0)
var s1Chars = Array(s1)
for i in 0...s0Chars.count - 2 {
for j in 0...s1Chars.count - 2 {
if
var s0Chars = Array(s0) // variable 's0Chars' was never mutated; consider changing to 'let' constant
var s1Chars = Array(s1) // variable 's1Chars' was never mutated; consider changing to 'let' constant
var s0Chars = Array(s0) // variable 's0Chars' was never mutated; consider changing to 'let' constant
var s1Chars = Array(s1) // variable 's1Chars' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func fib(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fib(n: Int) {
if n <= 1 {
print(n)
} else {
let a = fib(n: n - 1)
let b = fib(n: n - 2)
print(a + b)
}
}
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
func fibSum(n: Int) {
if n <= 1 {
print(n)
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
print(a + b)
}
}
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
return a + b
}
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Print n-th Fibonacci number.
// fib(n: 10) prints 55
// fib(n: 1) prints 1
// fib(n: 8) prints 21
func fib(n: Int) {
if n <= 1 {
print(n)
} else {
let a = fib(n: n - 1)
let b = fib(n: n - 2)
print(a + b)
}
}
// Calculate sum of first n Fibonacci numbers.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum(n: 8) == 34
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
// Calculate sum of first n Fibonacci numbers and print it.
// fibSum(n: 10) prints 143
// fibSum(n: 1) prints 1
// fibSum(n: 8) prints 34
func fibSum(n: Int) {
if n <= 1 {
print(n)
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
print(a + b)
}
}
// Calculate sum of first n Fibonacci numbers and return it.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum(n: 8) == 34
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
// Calculate sum of first n Fibonacci numbers and return it.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum(n: 8) == 34
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
return a + b
}
}
// Calculate sum of first n Fibonacci numbers and return it.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum(n: 8) == 34
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
return a + b
}
}
// Calculate sum of first n Fibonacci numbers and return it.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum(n: 8) == 34
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
return a + b
}
}
// Calculate sum of first n Fibonacci numbers and return it.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum(n: 8) == 34
func fibSum(n: Int) -> Int {
if n <= 1 {
return n
} else {
let a = fib(n: n)
let b = fibSum(n: n - 1)
return a + b
}
}
// Calculate sum of first n Fibonacci numbers and return it.
// fibSum(n: 10) == 143
// fibSum(n: 1) == 1
// fibSum
let a = fib(n: n - 1) // ambiguous use of 'fib(n:)'
let b = fib(n: n - 2) // ambiguous use of 'fib(n:)'
let a = fib(n: n) // ambiguous use of 'fib(n:)'
let b = fibSum(n: n - 1) // ambiguous use of 'fibSum(n:)'
func fibSum(n: Int) -> Int { // invalid redeclaration of 'fibSum(n:)'
let a = fib(n: n) // ambiguous use of 'fib(n:)'
let b = fibSum(n: n - 1) // ambiguous use of 'fibSum(n:)'
return a + b // cannot convert return expression of type 'String' to return type 'Int'
func fib(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fibSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
func fibSquaresSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return (fib(n: n) * fib(n: n)) + fibSquaresSum(n: n - 1)
}
}
func fibCubesSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return (fib(n: n) * fib(n: n) * fib(n: n)) + fibCubesSum(n: n - 1)
}
}
func fibDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return Int(String(fib(n: n)))! + fibDigitsSum(n: n - 1)
}
}
func fibEvenDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if Int(String(char))! % 2 == 0 {
sum += Int(String(char))!
}
}
return sum + fibEvenDigitsSum(n: n - 1)
}
}
func fibOddDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if Int(String(char))! % 2!= 0 {
sum += Int(String(char))!
}
}
return sum + fibOddDigitsSum(n: n - 1)
}
}
func fibPrimeDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if isPrime(num: Int(String(char))!) {
sum += Int(String(char))!
}
}
return sum + fibPrimeDigitsSum(n: n - 1)
}
}
```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 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Return the sum of the first n Fibonacci numbers.
// fibSum(n: 10) == 143
func fibSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
// Return the sum of the squares of the first n Fibonacci numbers.
// fibSquaresSum(n: 10) == 348550
func fibSquaresSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return (fib(n: n) * fib(n: n)) + fibSquaresSum(n: n - 1)
}
}
// Return the sum of the cubes of the first n Fibonacci numbers.
// fibCubesSum(n: 10) == 622702080
func fibCubesSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return (fib(n: n) * fib(n: n) * fib(n: n)) + fibCubesSum(n: n - 1)
}
}
// Return the sum of the digits of the first n Fibonacci numbers.
// fibDigitsSum(n: 10) == 143
func fibDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
return Int(String(fib(n: n)))! + fibDigitsSum(n: n - 1)
}
}
// Return the sum of the even digits of the first n Fibonacci numbers.
// fibEvenDigitsSum(n: 10) == 14
func fibEvenDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if Int(String(char))! % 2 == 0 {
sum += Int(String(char))!
}
}
return sum + fibEvenDigitsSum(n: n - 1)
}
}
// Return the sum of the odd digits of the first n Fibonacci numbers.
// fibOddDigitsSum(n: 10) == 15
func fibOddDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if Int(String(char))! % 2!= 0 {
sum += Int(String(char))!
}
}
return sum + fibOddDigitsSum(n: n - 1)
}
}
// Return the sum of the prime digits of the first n Fibonacci numbers.
// fibPrimeDigitsSum(n: 10) == 1
func fibPrimeDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if isPrime(num: Int(String(char))!) {
sum += Int(String(char))!
}
}
return sum + fibPrimeDigitsSum(n: n - 1)
}
}
// Return the sum of the non-prime digits of the first n Fibonacci numbers.
// fibNonPrimeDigitsSum(n: 10) == 14
func fibNonPrimeDigitsSum(n: Int) -> Int {
if n <= 1 {
return 0
} else {
let num = fib(n: n)
let str = String(num)
var sum = 0
for char in str {
if!isPrime(num: Int(String(char))!) {
sum += Int(String(char))!
}
}
return sum + fibNonPrimeDigitsSum(n: n - 1
if Int(String(char))! % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if Int(String(char))! % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if Int(String(char))! % 2!= 0 { // expression is not assignable: binary operator returns immutable value
if Int(String(char))! % 2!= 0 { // '=' must have consistent whitespace on both sides
if isPrime(num: Int(String(char))!) { // cannot find 'isPrime' in scope
func fib(n: Int) -> Int {
if n <= 2 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
func fibSum(n: Int) -> Int {
var sum = 0
var i = 1
while fib(n: i) <= n {
if fib(n: i) % 2 == 0 {
sum += fib(n: i)
}
i += 1
}
return sum
}
func printFib(n: Int) {
var a = 1
var b = 1
var i = 1
while i <= n {
print(a)
(a, b) = (b, a + b)
i += 1
}
}
func printFibSum(n: Int) {
printFib(n: n)
print("Fibonacci sum: \(fibSum(n: n))")
}
```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 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSum(10) == 10
// fibSum(1) == 2
// fibSum(8) == 10
func fibSum(n: Int) -> Int {
var sum = 0
var i = 1
while fib(n: i) <= n {
if fib(n: i) % 2 == 0 {
sum += fib(n: i)
}
i += 1
}
return sum
}
// Print the first n Fibonacci numbers.
// printFib(10) prints:
// 1
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
func printFib(n: Int) {
var a = 1
var b = 1
var i = 1
while i <= n {
print(a)
(a, b) = (b, a + b)
i += 1
}
}
// Print the first n Fibonacci numbers and the sum of even Fibonacci numbers.
// printFibSum(10) prints:
// 1
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
// Fibonacci sum: 100
func printFibSum(n: Int) {
printFib(n: n)
print("Fibonacci sum: \(fibSum(n: n))")
}
// Test the functions
printFibSum(n: 10)
printFibSum(n: 20)
printFibSum(n: 30)
printFibSum(n: 40)
printFibSum(n: 50)
printFibSum(n: 100)
printFibSum(n: 200)
printFibSum(n: 300)
printFibSum(n: 400)
printFibSum(n: 500)
printFibSum(n: 1000)
printFibSum(n: 2000)
printFibSum(n: 3000)
printFibSum(n: 4000)
printFibSum(n: 5000)
printFibSum(n: 10000)
printFibSum(n: 20000)
printFibSum(n: 30000)
printFibSum(n: 40000)
printFibSum(n: 50000)
printFibSum(n: 100000)
printFibSum(n: 200000)
printFibSum(n: 300000)
printFibSum(n: 400000)
printFibSum(n: 500000)
printFibSum(n: 1000000)
printFibSum(n: 2000000)
printFibSum(n: 3000000)
printFibSum(n: 4000000)
printFibSum(n: 5000000)
printFibSum(n: 10000000)
printFibSum(n: 20000000)
printFibSum(n: 30000000)
printFibSum(n: 40000000)
printFibSum(n: 50000000)
printFibSum(n: 100000000)
printFibSum(n: 200000000)
printFibSum(n: 300000000)
printFibSum(n: 400000000)
printFibSum(n: 500000000)
printFibSum(n: 10000
func fib(n: Int) -> Int {
if n <= 2 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
func fibSum(n: Int) -> Int {
if n <= 2 {
return 1
}
return fibSum(n: n - 1) + fib(n: n)
}
func fibSumWithCount(n: Int) -> (Int, Int, Int) {
if n <= 2 {
return (1, 1, 1)
}
let (sum, count, _) = fibSumWithCount(n: n - 1)
return (sum + fib(n: n), count + 1, count + 1)
}
func fibSumWithCountTailRecursive(n: Int, sum: Int = 1, count: Int = 1) -> (Int, Int, Int) {
if n <= 2 {
return (sum + 1, count + 1, count + 1)
}
return fibSumWithCountTailRecursive(n: n - 1, sum: sum + fib(n: n), count: count + 1)
}
func fibSumWithCountTailRecursive2(n: Int) -> (Int, Int, Int) {
func fibSumHelper(n: Int, sum: Int = 1, count: Int = 1) -> (Int, Int, Int) {
if n <= 2 {
return (sum + 1, count + 1, count + 1)
}
return fibSumHelper(n: n - 1, sum: sum + fib(n: n), count: count + 1)
}
return fibSumHelper(n: n)
}
func fibSumWithCountTailRecursive3(n: Int) -> (Int, Int, Int) {
func fibSumHelper(n: Int, sum: Int = 1, count: Int = 1) -> (Int, Int, Int) {
if n <= 2 {
return (sum + 1, count + 1, count + 1)
}
return fibSumHelper(n: n - 1, sum: sum + fib(n: n), count: count + 1)
}
return fibSumHelper(n: n, sum: 1, count: 1)
}
```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 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
// Return the sum of all Fibonacci numbers from 1 to n.
// fibSum(10) == 143
// fibSum(1) == 1
// fibSum(8) == 34
func fibSum(n: Int) -> Int {
if n <= 2 {
return 1
}
return fibSum(n: n - 1) + fib(n: n)
}
// Return the sum of all Fibonacci numbers from 1 to n,
// while also keeping track of the total sum and the number of terms used.
// fibSumWithCount(10) == (143, 10, 13)
// fibSumWithCount(1) == (1, 1, 1)
// fibSumWithCount(8) == (34, 8, 10)
func fibSumWithCount(n: Int) -> (Int, Int, Int) {
if n <= 2 {
return (1, 1, 1)
}
let (sum, count, _) = fibSumWithCount(n: n - 1)
return (sum + fib(n: n), count + 1, count + 1)
}
// Return the sum of all Fibonacci numbers from 1 to n,
// while also keeping track of the total sum and the number of terms used.
// fibSumWithCountTailRecursive(10) == (143, 10, 13)
// fibSumWithCountTailRecursive(1) == (1, 1, 1)
// fibSumWithCountTailRecursive(8) == (34, 8, 10)
func fibSumWithCountTailRecursive(n: Int, sum: Int = 1, count: Int = 1) -> (Int, Int, Int) {
if n <= 2 {
return (sum + 1, count + 1, count + 1)
}
return fibSumWithCountTailRecursive(n: n - 1, sum: sum + fib(n: n), count: count + 1)
}
// Return the sum of all Fibonacci numbers from 1 to n,
// while also keeping track of the total sum and the number of terms used.
// fibSumWithCountTailRecursive(10) == (143, 10, 13)
// fibSumWithCountTailRecursive(1) == (1, 1, 1)
// fibSumWithCountTailRecursive(8) == (34, 8, 10)
func fibSumWithCountTailRecursive2(n: Int) -> (Int, Int, Int) {
func fibSumHelper(n: Int, sum: Int = 1, count: Int = 1) -> (Int, Int, Int) {
if n <= 2 {
return (sum + 1, count + 1, count + 1)
}
return fibSumHelper(n: n - 1, sum: sum + fib(n: n), count: count + 1)
}
return fibSumHelper(n: n)
}
// Return the sum of all Fibonacci numbers from 1 to n,
// while also keeping track of the total sum and the number of terms used.
// fibSumWithCountTailRecursive(10) == (143, 10, 13)
// fibSumWithCountTailRecursive(1) == (1, 1, 1)
// fibSumWithCountTailRecursive(8) == (34, 8, 10)
func fibSumWithCountTailRecursive3(n: Int) -> (Int, Int, Int) {
func fibSumHelper(n: Int, sum: Int = 1, count: Int = 1) -> (Int, Int, Int) {
if n <= 2 {
return (sum + 1, count + 1, count + 1)
}
return fibSumHelper(n: n - 1, sum: sum + fib(n: n), count: count + 1)
}
return fibSumHelper(n: n, sum: 1, count: 1)
}
// Return the sum of all Fibonacci numbers from 1 to n,
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 sum_even_fib(n: Int) -> Int {
if n == 0 {
return 0
} else {
return fib(n: n) + sum_even_fib(n: n - 1)
}
}
func sum_even_fib_tail(n: Int) -> Int {
func fib_tail(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else {
return fib_tail(n: n - 1, a: b, b: a + b)
}
}
return fib_tail(n: n, a: 0, b: 1)
}
func sum_even_fib_tail_opt(n: Int) -> Int {
func fib_tail_opt(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else if n % 2 == 0 {
return fib_tail_opt(n: n - 1, a: b, b: a + b)
} else {
return fib_tail_opt(n: n - 1, a: a, b: b)
}
}
return fib_tail_opt(n: n, a: 0, b: 1)
}
func sum_even_fib_tail_opt_2(n: Int) -> Int {
func fib_tail_opt_2(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else {
return fib_tail_opt_2(n: n - 1, a: b, b: a + b)
}
}
return fib_tail_opt_2(n: n, a: 0, b: 1)
}
func sum_even_fib_tail_opt_3(n: Int) -> Int {
func fib_tail_opt_3(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else if n % 2 == 0 {
return fib_tail_opt_3(n: n - 1, a: b, b: a + b)
} else {
return fib_tail_opt_3(n: n - 1, a: a, b: b)
}
}
return fib_tail_opt_3(n: n, a: 0, b: 1)
}
```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)
}
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// sum_even_fib(10) == 10
// sum_even_fib(1) == 2
// sum_even_fib(14) == 10
func sum_even_fib(n: Int) -> Int {
if n == 0 {
return 0
} else {
return fib(n: n) + sum_even_fib(n: n - 1)
}
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// sum_even_fib_tail(10) == 10
// sum_even_fib_tail(1) == 2
// sum_even_fib_tail(14) == 10
func sum_even_fib_tail(n: Int) -> Int {
func fib_tail(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else {
return fib_tail(n: n - 1, a: b, b: a + b)
}
}
return fib_tail(n: n, a: 0, b: 1)
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// sum_even_fib_tail_opt(10) == 10
// sum_even_fib_tail_opt(1) == 2
// sum_even_fib_tail_opt(14) == 10
func sum_even_fib_tail_opt(n: Int) -> Int {
func fib_tail_opt(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else if n % 2 == 0 {
return fib_tail_opt(n: n - 1, a: b, b: a + b)
} else {
return fib_tail_opt(n: n - 1, a: a, b: b)
}
}
return fib_tail_opt(n: n, a: 0, b: 1)
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// sum_even_fib_tail_opt_2(10) == 10
// sum_even_fib_tail_opt_2(1) == 2
// sum_even_fib_tail_opt_2(14) == 10
func sum_even_fib_tail_opt_2(n: Int) -> Int {
func fib_tail_opt_2(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else {
return fib_tail_opt_2(n: n - 1, a: b, b: a + b)
}
}
return fib_tail_opt_2(n: n, a: 0, b: 1)
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// sum_even_fib_tail_opt_3(10) == 10
// sum_even_fib_tail_opt_3(1) == 2
// sum_even_fib_tail_opt_3(14) == 10
func sum_even_fib_tail_opt_3(n: Int) -> Int {
func fib_tail_opt_3(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
} else if n % 2 == 0 {
return fib_tail_opt_3(n: n - 1, a: b, b: a + b)
} else {
return fib_tail_opt_3(n: n - 1, a: a, b: b)
}
}
return fib_tail_opt_3(n: n, a: 0, b: 1)
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// sum_
func fib(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fibSum(n: Int) -> Int {
var sum = 0
var i = 1
while fib(n: i) < n {
if fib(n: i) > 100 && fib(n: i) % 2 == 0 {
sum += fib(n: i)
}
i += 1
}
return sum
}
func printFibonacci(n: Int) {
var a = 1
var b = 1
var i = 1
while i < n {
print(b)
let temp = a + b
a = b
b = temp
i += 1
}
}
```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 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Return the sum of even Fibonacci numbers that are greater than 100.
// fibSum(100) == 143
func fibSum(n: Int) -> Int {
var sum = 0
var i = 1
while fib(n: i) < n {
if fib(n: i) > 100 && fib(n: i) % 2 == 0 {
sum += fib(n: i)
}
i += 1
}
return sum
}
// Print the first 100 Fibonacci numbers.
// Output:
// 1
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
// 89
// 144
// 233
// 377
// 610
// 987
// 1597
// 2584
// 4181
// 6765
func printFibonacci(n: Int) {
var a = 1
var b = 1
var i = 1
while i < n {
print(b)
let temp = a + b
a = b
b = temp
i += 1
}
}
printFibonacci(n: 100)
print(fibSum(n: 100))
```
func fib(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fib_sum(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n) + fib_sum(n: n - 1)
}
}
func fib_tuple(n: Int) -> (Int, Int) {
if n <= 1 {
return (n, n)
} else {
let (a, b) = fib_tuple(n: n - 1)
return (a + b, a)
}
}
func fib_tuple_tail(n: Int) -> (Int, Int) {
func fib_tail(a: Int, b: Int, i: Int) -> (Int, Int) {
if i == n {
return (b, a + b)
} else {
return fib_tail(a: b, b: a + b, i: i + 1)
}
}
return fib_tail(a: 0, b: 1, i: 1)
}
func fib_tuple_tail_helper(n: Int) -> (Int, Int) {
func fib_tail_helper(a: Int, b: Int, i: Int) -> (Int, Int) {
if i == n {
return (b, a + b)
} else {
return fib_tail_helper(a: b, b: a + b, i: i + 1)
}
}
return fib_tail_helper(a: 0, b: 1, i: 1)
}
func fib_tuple_tail_helper_2(n: Int) -> (Int, Int) {
func fib_tail_helper_2(a: Int, b: Int, i: Int, n: Int) -> (Int, Int) {
if i == n {
return (b, a + b)
} else {
return fib_tail_helper_2(a: b, b: a + b, i: i + 1, n: n)
}
}
return fib_tail_helper_2(a: 0, b: 1, i: 1, n: n)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Return the sum of all Fibonacci numbers from 1 to n.
// fib_sum(10) == 143
// fib_sum(1) == 1
// fib_sum(8) == 34
func fib_sum(n: Int) -> Int {
if n <= 1 {
return n
} else {
return fib(n: n) + fib_sum(n: n - 1)
}
}
// Return the n-th Fibonacci number and the sum of all Fibonacci numbers from 1 to n.
// fib_tuple(10) == (55, 143)
// fib_tuple(1) == (1, 1)
// fib_tuple(8) == (21, 34)
func fib_tuple(n: Int) -> (Int, Int) {
if n <= 1 {
return (n, n)
} else {
let (a, b) = fib_tuple(n: n - 1)
return (a + b, a)
}
}
// Return the n-th Fibonacci number and the sum of all Fibonacci numbers from 1 to n.
// fib_tuple_tail(10) == (55, 143)
// fib_tuple_tail(1) == (1, 1)
// fib_tuple_tail(8) == (21, 34)
func fib_tuple_tail(n: Int) -> (Int, Int) {
func fib_tail(a: Int, b: Int, i: Int) -> (Int, Int) {
if i == n {
return (b, a + b)
} else {
return fib_tail(a: b, b: a + b, i: i + 1)
}
}
return fib_tail(a: 0, b: 1, i: 1)
}
// Return the n-th Fibonacci number and the sum of all Fibonacci numbers from 1 to n.
// fib_tuple_tail_helper(10) == (55, 143)
// fib_tuple_tail_helper(1) == (1, 1)
// fib_tuple_tail_helper(8) == (21, 34)
func fib_tuple_tail_helper(n: Int) -> (Int, Int) {
func fib_tail_helper(a: Int, b: Int, i: Int) -> (Int, Int) {
if i == n {
return (b, a + b)
} else {
return fib_tail_helper(a: b, b: a + b, i: i + 1)
}
}
return fib_tail_helper(a: 0, b: 1, i: 1)
}
// Return the n-th Fibonacci number and the sum of all Fibonacci numbers from 1 to n.
// fib_tuple_tail_helper_2(10) == (55, 143)
// fib_tuple_tail_helper_2(1) == (1, 1)
// fib_tuple_tail_helper_2(8) == (21, 34)
func fib_tuple_tail_helper_2(n: Int) -> (Int, Int) {
func fib_tail_helper_2(a: Int, b: Int, i: Int, n: Int) -> (Int, Int) {
if i == n {
return (b, a + b)
} else {
return fib_tail_helper_2(a: b, b: a + b, i: i + 1, n: n)
}
}
return fib_tail_helper_2(a: 0, b: 1, i: 1, n: n)
}
// Return the n-th Fibonacci number and the sum of all Fibonacci numbers from 1 to n.
// fib_tuple_tail_helper_3(10) == (55, 143)
// fib_tuple_tail_helper_3(1) ==
func fib(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fibDP(n: Int) -> Int {
var fibs = [Int]()
fibs.append(1)
fibs.append(1)
for i in 2...n {
fibs.append(fibs[i - 1] + fibs[i - 2])
}
return fibs[n]
}
func fibME(n: Int) -> Int {
var matrix = [[Int]]()
matrix.append([1, 1])
matrix.append([1, 0])
let result = matrixExponentiation(matrix: matrix, n: n)
return result[0][0] + result[1][0]
}
func matrixExponentiation(matrix: [[Int]], n: Int) -> [[Int]] {
if n == 0 {
return [[1, 0], [0, 1]]
} else if n % 2 == 0 {
let half = matrixExponentiation(matrix: matrix, n: n / 2)
return multiplyMatrices(a: half, b: half)
} else {
let half = matrixExponentiation(matrix: matrix, n: (n - 1) / 2)
return multiplyMatrices(a: multiplyMatrices(a: half, b: half), b: matrix)
}
}
func multiplyMatrices(a: [[Int]], b: [[Int]]) -> [[Int]] {
var result = [[Int]]()
result.append([0, 0])
result.append([0, 0])
result[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]
result[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]
result[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]
result[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]
return result
}
```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 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Return n-th Fibonacci number using dynamic programming.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fibDP(n: Int) -> Int {
var fibs = [Int]()
fibs.append(1)
fibs.append(1)
for i in 2...n {
fibs.append(fibs[i - 1] + fibs[i - 2])
}
return fibs[n]
}
// Return n-th Fibonacci number using matrix exponentiation.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fibME(n: Int) -> Int {
var matrix = [[Int]]()
matrix.append([1, 1])
matrix.append([1, 0])
let result = matrixExponentiation(matrix: matrix, n: n)
return result[0][0] + result[1][0]
}
func matrixExponentiation(matrix: [[Int]], n: Int) -> [[Int]] {
if n == 0 {
return [[1, 0], [0, 1]]
} else if n % 2 == 0 {
let half = matrixExponentiation(matrix: matrix, n: n / 2)
return multiplyMatrices(a: half, b: half)
} else {
let half = matrixExponentiation(matrix: matrix, n: (n - 1) / 2)
return multiplyMatrices(a: multiplyMatrices(a: half, b: half), b: matrix)
}
}
func multiplyMatrices(a: [[Int]], b: [[Int]]) -> [[Int]] {
var result = [[Int]]()
result.append([0, 0])
result.append([0, 0])
result[0][0] = a[0][0] * b[0][0] + a[0][1] * b[1][0]
result[0][1] = a[0][0] * b[0][1] + a[0][1] * b[1][1]
result[1][0] = a[1][0] * b[0][0] + a[1][1] * b[1][0]
result[1][1] = a[1][0] * b[0][1] + a[1][1] * b[1][1]
return result
}
// Test the code
print(fib(n: 10))
print(fibDP(n: 10))
print(fibME(n: 10))
```
func fib(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fibSum(n: Int) -> Int {
if n == 1 {
return 1
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
func fibSquares(n: Int) -> Int {
if n == 1 {
return 1
} else {
return fib(n: n) * fib(n: n) + fibSquares(n: n - 1)
}
}
func fibCubes(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(pow(Double(fib(n: n)), 3)) + fibCubes(n: n - 1)
}
}
func fibDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fib(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibDigits(n: n - 1)
}
}
func fibSquaresDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fib(n: n) * fib(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibSquaresDigits(n: n - 1)
}
}
func fibCubesDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(Int(pow(Double(fib(n: n)), 3))).map { Int(String($0))! }.reduce(0, +)) + fibCubesDigits(n: n - 1)
}
}
func fibSumDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fibSum(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibSumDigits(n: n - 1)
}
}
```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 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Return the sum of the first n Fibonacci numbers.
// fibSum(n: 10) == 143
func fibSum(n: Int) -> Int {
if n == 1 {
return 1
} else {
return fib(n: n) + fibSum(n: n - 1)
}
}
// Return the sum of the squares of the first n Fibonacci numbers.
// fibSquares(n: 10) == 385
func fibSquares(n: Int) -> Int {
if n == 1 {
return 1
} else {
return fib(n: n) * fib(n: n) + fibSquares(n: n - 1)
}
}
// Return the sum of the cubes of the first n Fibonacci numbers.
// fibCubes(n: 10) == 14066176315
func fibCubes(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(pow(Double(fib(n: n)), 3)) + fibCubes(n: n - 1)
}
}
// Return the sum of the digits of the first n Fibonacci numbers.
// fibDigits(n: 10) == 143
func fibDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fib(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibDigits(n: n - 1)
}
}
// Return the sum of the digits of the squares of the first n Fibonacci numbers.
// fibSquaresDigits(n: 10) == 385
func fibSquaresDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fib(n: n) * fib(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibSquaresDigits(n: n - 1)
}
}
// Return the sum of the digits of the cubes of the first n Fibonacci numbers.
// fibCubesDigits(n: 10) == 14066176315
func fibCubesDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(Int(pow(Double(fib(n: n)), 3))).map { Int(String($0))! }.reduce(0, +)) + fibCubesDigits(n: n - 1)
}
}
// Return the sum of the digits of the first n Fibonacci numbers.
// fibDigits(n: 10) == 143
func fibDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fib(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibDigits(n: n - 1)
}
}
// Return the sum of the digits of the sum of the first n Fibonacci numbers.
// fibSumDigits(n: 10) == 143
func fibSumDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fibSum(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibSumDigits(n: n - 1)
}
}
// Return the sum of the digits of the sum of the squares of the first n Fibonacci numbers.
// fibSquaresDigits(n: 10) == 385
func fibSquaresDigits(n: Int) -> Int {
if n == 1 {
return 1
} else {
return Int(String(fibSquares(n: n)).map { Int(String($0))! }.reduce(0, +)) + fibSquaresDigits(n: n - 1
func fib(n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fibSum(n: Int) -> Int {
if n <= 2 {
return 0
} else {
return fib(n: n - 1) + fib(n: n - 2) + fibSum(n: n - 1)
}
}
func fibSumTail(n: Int) -> Int {
func fibTail(n: Int, a: Int, b: Int) -> Int {
if n <= 2 {
return b
} else {
return fibTail(n: n - 1, a: b, b: a + b)
}
}
return fibTail(n: n, a: 1, b: 0)
}
func fibSumFormula(n: Int) -> Int {
return (1 + 5 * sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
func fibSumFormula2(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
func fibSumFormula3(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
func fibSumFormula4(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
func fibSumFormula5(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
func fibSumFormula6(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, 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 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSum(10) == 10
// fibSum(1) == 0
// fibSum(8) == 10
func fibSum(n: Int) -> Int {
if n <= 2 {
return 0
} else {
return fib(n: n - 1) + fib(n: n - 2) + fibSum(n: n - 1)
}
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumTail(10) == 10
// fibSumTail(1) == 0
// fibSumTail(8) == 10
func fibSumTail(n: Int) -> Int {
func fibTail(n: Int, a: Int, b: Int) -> Int {
if n <= 2 {
return b
} else {
return fibTail(n: n - 1, a: b, b: a + b)
}
}
return fibTail(n: n, a: 1, b: 0)
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula(n: Int) -> Int {
return (1 + 5 * sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula2(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula3(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula4(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula5(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula6(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5, n)) / 2
}
// Return the sum of even Fibonacci numbers less than or equal to n.
// fibSumFormula(10) == 10
// fibSumFormula(1) == 0
// fibSumFormula(8) == 10
func fibSumFormula7(n: Int) -> Int {
return (1 + sqrt(5)) * (pow(5, n + 1) - pow(5,
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(correctBracketing(brackets: "><<>") == false)
```
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
print(correctBracketing(brackets: "<"))
print(correctBracketing(brackets: "<>"))
print(correctBracketing(brackets: "<<><>>"))
print(correctBracketing(brackets: "><<>"))
print(correctBracketing(brackets: "<><><>"))
print(correctBracketing(brackets: "<><><><>"))
print(correctBracketing(brackets: "<><><><><>"))
print(correctBracketing(brackets: "<><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets: "<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>"))
print(correctBracketing(brackets
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(correctBracketing(brackets: "><<>") == false)
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(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.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Tests
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(correctBracketing(brackets: "><<>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>") == true)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i{i}[(i>o)>>") == false)
assert(correctBracketing(brackets: "<{o}<[i
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Tests
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(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.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(correctBracketing(brackets: "><<>") == false)
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else if bracket == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
//: [Next](@next)
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "<" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Tests
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(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.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack: [Character] = []
for char in brackets {
if char == "<" {
stack.append(char)
} else if char == ">" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test Cases
assert(correctBracketing(brackets: "<") == false)
assert(correctBracketing(brackets: "<>") == true)
assert(correctBracketing(brackets: "<<><>>") == true)
assert(correctBracketing(brackets: "><<>") == false)
```
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var isSame = true
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
if isSame {
if l[i]!= l[i-1] {
isSame = false
}
}
}
return isSame
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == true
// monotone(l: [1, 2, 4, 6, 8, 10]) == true
// monotone(l: [1, 2, 4, 5, 8, 9]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var isSame = true
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
if isSame {
if l[i]!= l[i-1] {
isSame = false
}
}
}
return isSame
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// The difference between any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == true
// monotone(l: [1, 2, 4, 6, 8, 10]) == true
// monotone(l: [1, 2, 4, 5, 8, 9]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var isSame = true
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
if isSame {
if l[i]!= l[i-1] {
isSame = false
}
}
}
return isSame
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// The difference between any two neighboring elements is the same.
// The array must be sorted.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == true
// monotone(l: [1, 2, 4, 6, 8, 10]) == true
// monotone(l: [1, 2, 4, 5, 8, 9]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var isSame = true
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
var isIncreasing = l[0] < l[1] // variable 'isIncreasing' was never mutated; consider changing to 'let' constant
if l[i]!= l[i-1] { // '=' must have consistent whitespace on both sides
if l[i]!= l[i-1] { // cannot force unwrap value of non-optional type 'Int'
if l[i]!= l[i-1] { // use of '=' in a boolean context, did you mean '=='?
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
}
if!isIncreasing &&!isDecreasing {
return false
}
}
return true
}
func monotone(l: [Int]) -> Bool {
if monotonic(l: l) {
for i in 0..<l.count - 1 {
if l[i]!= l[i + 1] {
return false
}
}
return true
}
return false
}
func monotone(l: [Int], k: Int) -> Bool {
if monotonic(l: l) {
for i in 0..<l.count - 1 {
if l[i] - l[i + 1] >= k {
return false
}
}
return true
}
return false
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
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
}
if!isIncreasing &&!isDecreasing {
return false
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
if monotonic(l: l) {
for i in 0..<l.count - 1 {
if l[i]!= l[i + 1] {
return false
}
}
return true
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given k.
// k = 2
// monotone(l: [1, 2, 4, 20], k: 2) == true
// monotone(l: [1, 20, 4, 10], k: 2) == false
// monotone(l: [4, 1, 0, -10], k: 2) == false
func monotone(l: [Int], k: Int) -> Bool {
if monotonic(l: l) {
for i in 0..<l.count - 1 {
if l[i] - l[i + 1] >= k {
return false
}
}
return true
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given k.
// k = 2
// monotone(l: [1, 2, 4, 20], k: 2) == true
// monotone(l: [1, 20, 4, 10], k: 2) == false
// monotone(l: [4, 1, 0, -10], k: 2) == false
func monotone(l: [Int], k: Int) -> Bool {
if monotonic(l: l) {
for i in 0..<l.count - 1 {
if l[i] - l[i + 1] >= k {
return false
}
}
return true
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given k.
// k = 2
// monotone(l: [1, 2, 4, 20], k: 2) == true
// monotone(l: [1, 20, 4, 10], k: 2) == false
// monotone(l: [4, 1, 0, -10], k: 2) == false
func monotone(l: [Int], k: Int) -> Bool {
if monotonic(l: l) {
for i in 0..<l.count - 1 {
if l[i] - l[i + 1] >= k {
return false
}
}
return true
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given k.
// k = 2
// monotone(l: [1, 2, 4, 20], k: 2) == true
// monotone(l: [1, 20, 4, 10], k: 2) == false
// monotone(l: [4, 1, 0, -
if!isIncreasing &&!isDecreasing { // expected expression, var, or let in 'if' condition
if l[i]!= l[i + 1] { // use of '=' in a boolean context, did you mean '=='?
if l[i]!= l[i + 1] { // '=' must have consistent whitespace on both sides
if l[i]!= l[i + 1] { // cannot force unwrap value of non-optional type 'Int'
func monotonic(l: [Int]) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
}
return true
}
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < threshold {
return false
}
}
return true
}
func monotonicThresholdProduct(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < threshold * l[i-1] {
return false
}
}
return true
}
func monotonicThresholdProduct(l: [Int], thresholds: [Int]) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < thresholds[i-1] * l[i-1] {
return false
}
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is greater than or equal to given threshold.
// monotonicThreshold(l: [1, 2, 4, 20], threshold: 5) == true
// monotonicThreshold(l: [1, 20, 4, 10], threshold: 5) == false
// monotonicThreshold(l: [4, 1, 0, -10], threshold: 5) == true
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < threshold {
return false
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is greater than or equal to the product of the given thresholds.
// monotonicThresholdProduct(l: [1, 2, 4, 20], threshold: 2) == true
// monotonicThresholdProduct(l: [1, 20, 4, 10], threshold: 2) == false
// monotonicThresholdProduct(l: [4, 1, 0, -10], threshold: 2) == true
func monotonicThresholdProduct(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < threshold * l[i-1] {
return false
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is greater than or equal to the product of the given thresholds.
// monotonicThresholdProduct(l: [1, 2, 4, 20], thresholds: [2, 5]) == true
// monotonicThresholdProduct(l: [1, 20, 4, 10], thresholds: [2, 5]) == false
// monotonicThresholdProduct(l: [4, 1, 0, -10], thresholds: [2, 5]) == true
func monotonicThresholdProduct(l: [Int], thresholds: [Int]) -> Bool {
if l.count < 3 {
return true
}
var increasing = true
var decreasing = true
for i in 1..<l.count {
if l[i] > l[i-1] {
increasing = false
}
if l[i] < l[i-1] {
decreasing = false
}
if!increasing &&!decreasing {
return false
}
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < thresholds[i-1] * l[i-1] {
return false
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
if!increasing &&!decreasing { // expected expression, var, or let in 'if' condition
if!increasing &&!decreasing { // expected expression, var, or let in 'if' condition
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < threshold { // expected expression, var, or let in 'if' condition
if!increasing &&!decreasing { // expected expression, var, or let in 'if' condition
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < threshold * l[i-1] { // expected expression, var, or let in 'if' condition
if!increasing &&!decreasing { // expected expression, var, or let in 'if' condition
if!increasing &&!decreasing && abs(l[i] - l[i-1]) < thresholds[i-1] * l[i-1] { // expected expression, var, or let in 'if' condition
func monotonic(l: [Int]) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l[i] < l[i-1] {
return false
}
if l[i] - l[i-1] <= threshold {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
if l[i-1] - l[i] <= threshold {
return false
}
}
}
return true
}
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l[i] < l[i-1] {
return false
}
if l[i] - l[i-1] > threshold {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
if l[i-1] - l[i] > threshold {
return false
}
}
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
// if the difference between any two consecutive elements is greater than the
// given threshold.
// monotonicThreshold(l: [1, 2, 4, 20], threshold: 5) == true
// monotonicThreshold(l: [1, 20, 4, 10], threshold: 5) == false
// monotonicThreshold(l: [4, 1, 0, -10], threshold: 5) == true
// monotonicThreshold(l: [1, 2, 4, 19], threshold: 5) == false
// monotonicThreshold(l: [1, 2, 4, 19], threshold: 1) == true
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l[i] < l[i-1] {
return false
}
if l[i] - l[i-1] <= threshold {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
if l[i-1] - l[i] <= threshold {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
// if the difference between any two consecutive elements is greater than the
// given threshold.
// monotonicThreshold(l: [1, 2, 4, 20], threshold: 5) == true
// monotonicThreshold(l: [1, 20, 4, 10], threshold: 5) == false
// monotonicThreshold(l: [4, 1, 0, -10], threshold: 5) == true
// monotonicThreshold(l: [1, 2, 4, 19], threshold: 5) == false
// monotonicThreshold(l: [1, 2, 4, 19], threshold: 1) == true
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l[i] < l[i-1] {
return false
}
if l[i] - l[i-1] > threshold {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
if l[i-1] - l[i] > threshold {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
// if the difference between any two consecutive elements is greater than the
// given threshold.
// monotonicThreshold(l: [1, 2, 4, 20], threshold: 5) == true
// monotonicThreshold(l: [1, 20, 4, 10], threshold: 5) == false
// monotonicThreshold(l: [4, 1, 0, -10], threshold: 5) == true
// monotonicThreshold(l: [1, 2, 4, 19], threshold: 5) == false
// monotonicThreshold(l: [1, 2, 4, 19], threshold: 1) == true
func monotonicThreshold(l: [Int], threshold: Int) -> Bool {
if l.count < 3 {
return true
}
var increasing = l[1] > l[0]
for i in 2..<l.count {
if increasing {
if l
var increasing = l[1] > l[0] // variable 'increasing' was never mutated; consider changing to 'let' constant
var increasing = l[1] > l[0] // variable 'increasing' was never mutated; consider changing to 'let' constant
func monotonicThreshold(l: [Int], threshold: Int) -> Bool { // invalid redeclaration of 'monotonicThreshold(l:threshold:)'
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var prevDiff = abs(l[1] - l[0])
for i in 1..<l.count {
let diff = abs(l[i] - l[i-1])
if diff!= prevDiff {
return false
}
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var prevDiff = abs(l[1] - l[0])
for i in 1..<l.count {
let diff = abs(l[i] - l[i-1])
if diff!= prevDiff {
return false
}
if isIncreasing {
if l[i] <= l[i-1] {
return false
}
} else {
if l[i] >= l[i-1] {
return false
}
}
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var prevDiff = abs(l[1] - l[0])
for i in 1..<l.count {
let diff = abs(l[i] - l[i-1])
if diff!= prevDiff {
return false
}
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// The difference between any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var prevDiff = abs(l[1] - l[0])
for i in 1..<l.count {
let diff = abs(l[i] - l[i-1])
if diff!= prevDiff {
return false
}
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// The difference between any two neighboring elements is the same.
// The array must be strictly monotonically increasing or decreasing.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
var prevDiff = abs(l[1] - l[0])
for i in 1..<l.count {
let diff = abs(l[i] - l[i-1])
if diff!= prevDiff {
return false
}
if isIncreasing {
if l[i] <= l[i-1] {
return false
}
} else {
if l[i] >= l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// The difference between any two neighboring elements is the same.
// The array must be strictly monotonically increasing or decreasing.
// monotone(l: [1, 2, 4, 20]) == true
// mon
var isIncreasing = l[0] < l[1] // variable 'isIncreasing' was never mutated; consider changing to 'let' constant
if diff!= prevDiff { // '=' must have consistent whitespace on both sides
if diff!= prevDiff { // cannot force unwrap value of non-optional type 'Int'
if diff!= prevDiff { // use of '=' in a boolean context, did you mean '=='?
func monotone(l: [Int]) -> Bool { // invalid redeclaration of 'monotone(l:)'
if diff!= prevDiff { // cannot force unwrap value of non-optional type 'Int'
if diff!= prevDiff { // use of '=' in a boolean context, did you mean '=='?
if diff!= prevDiff { // '=' must have consistent whitespace on both sides
func monotonic(l: [Int]) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
func monotone_increasing_decreasing(l: [Int]) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
func min_difference(l: [Int], min_diff: Int) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
// the difference between any two neighboring elements is the same.
// monotone_increasing_decreasing(l: [1, 2, 4, 20]) == true
// monotone_increasing_decreasing(l: [1, 20, 4, 10]) == false
// monotone_increasing_decreasing(l: [4, 1, 0, -10]) == false
func monotone_increasing_decreasing(l: [Int]) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
// the difference between any two neighboring elements is greater than or equal to
// a specified minimum difference.
// min_difference(l: [1, 2, 4, 20], min_diff: 1) == true
// min_difference(l: [1, 20, 4, 10], min_diff: 1) == false
// min_difference(l: [4, 1, 0, -10], min_diff: 1) == true
func min_difference(l: [Int], min_diff: Int) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and
// the difference between any two neighboring elements is less than or equal to
// a specified maximum difference.
// max_difference(l: [1, 2, 4, 20], max_diff: 1) == true
// max_difference(l: [1, 20, 4, 10], max_diff: 1) == true
// max_difference(l: [4, 1, 0, -10], max_diff: 1) == false
func max_difference(l: [Int], max_diff: Int) -> Bool {
if l.count < 2 {
return true
}
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i-1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i-1] >= l[j] {
i = j + 1
} else {
return false
}
} else
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i - 1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i - 1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i - 1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i - 1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i - 1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i - 1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i - 1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i - 1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i - 1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i - 1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var (i, j) = (1, 2)
while j < l.count {
if l[i] > l[j] {
if l[i - 1] <= l[j] {
i = j + 1
} else {
return false
}
} else if l[i] < l[j] {
if l[i - 1] >= l[j] {
i = j + 1
} else {
return false
}
} else {
i = j + 1
}
j += 1
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between
// any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
func monotone(l: [Int]) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
func monotone(l: [Int], by: Int) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is the same.
// monotone(l: [1, 2, 4, 20]) == true
// monotone(l: [1, 20, 4, 10]) == false
// monotone(l: [4, 1, 0, -10]) == false
func monotone(l: [Int]) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given value.
// monotone(l: [1, 2, 4, 20], by: 2) == true
// monotone(l: [1, 20, 4, 10], by: 2) == false
// monotone(l: [4, 1, 0, -10], by: 2) == false
func monotone(l: [Int], by: Int) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given value.
// monotone(l: [1, 2, 4, 20], by: 2) == true
// monotone(l: [1, 20, 4, 10], by: 2) == false
// monotone(l: [4, 1, 0, -10], by: 2) == false
func monotone(l: [Int], by: Int) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements is greater than or equal to given value.
// monotone(l: [1, 2, 4, 20], by: 2) == true
// monotone(l: [1, 20, 4, 10], by: 2) == false
// monotone(l: [4, 1, 0, -10], by: 2) == false
func monotone(l: [Int], by: Int) -> Bool {
if l.count < 3 { return true }
var i = 1
while i < l.count && l[i - 1] <= l[i] { i += 1 }
if i == l.count { return true }
while i < l.count && l[i - 1] >= l[i] { i += 1 }
return i == l.count
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two neighboring elements
func monotonic(l: [Int]) -> Bool {
if l.count < 3 {
return true
}
var isIncreasing = l[1] > l[0]
for i in 2..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
func has_close_elements(l: [Int], threshold: Int) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
if abs(l[i] - l[i+1]) >= threshold {
return true
}
}
return false
}
func has_close_elements_generic<T: FloatingPoint>(l: [T], threshold: T) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
if abs(l[i] - l[i+1]) >= threshold {
return true
}
}
return false
}
func has_close_elements_generic_with_error<T: FloatingPoint>(l: [T], threshold: T) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
let diff = abs(l[i] - l[i+1])
if diff >= threshold {
return true
} else if diff > 0 && diff / threshold > 10 {
return true
}
}
return false
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
if l.count < 3 {
return true
}
var isIncreasing = l[1] > l[0]
for i in 2..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between any two
// consecutive elements is greater than or equal to the given threshold.
// has_close_elements(l: [1, 2, 4, 20], threshold: 5) == true
// has_close_elements(l: [1, 20, 4, 10], threshold: 10) == false
// has_close_elements(l: [4, 1, 0, -10], threshold: 5) == false
func has_close_elements(l: [Int], threshold: Int) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
if abs(l[i] - l[i+1]) >= threshold {
return true
}
}
return false
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between any two
// consecutive elements is greater than or equal to the given threshold.
// has_close_elements(l: [1, 2, 4, 20], threshold: 5) == true
// has_close_elements(l: [1, 20, 4, 10], threshold: 10) == false
// has_close_elements(l: [4, 1, 0, -10], threshold: 5) == false
func has_close_elements_generic<T: FloatingPoint>(l: [T], threshold: T) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
if abs(l[i] - l[i+1]) >= threshold {
return true
}
}
return false
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between any two
// consecutive elements is greater than or equal to the given threshold.
// has_close_elements(l: [1, 2, 4, 20], threshold: 5) == true
// has_close_elements(l: [1, 20, 4, 10], threshold: 10) == false
// has_close_elements(l: [4, 1, 0, -10], threshold: 5) == false
func has_close_elements_generic_with_error<T: FloatingPoint>(l: [T], threshold: T) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
let diff = abs(l[i] - l[i+1])
if diff >= threshold {
return true
} else if diff > 0 && diff / threshold > 10 {
return true
}
}
return false
}
// Return true if array elements are monotonically increasing or decreasing, and the difference between any two
// consecutive elements is greater than or equal to the given threshold.
// has_close_elements(l: [1, 2, 4, 20], threshold: 5) == true
// has_close_elements(l: [1, 20, 4, 10], threshold: 10) == false
// has_close_elements(l: [4, 1, 0, -10], threshold: 5) == false
func has_close_elements_generic_with_error_and_abs<T: FloatingPoint>(l: [T], threshold: T) -> Bool {
if l.count < 2 {
return false
}
for i in 0..<l.count - 1 {
let diff = abs(l[i] - l[i+1])
if diff >= threshold {
return true
} else if diff > 0 && diff / threshold > 10 {
return true
} else if diff ==
var isIncreasing = l[1] > l[0] // variable 'isIncreasing' was never mutated; consider changing to 'let' constant
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
func hasCloseElements(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
for i in 0..<l.count {
for j in (i+1)..<l.count {
if abs(l[i] - l[j]) >= threshold {
return true
}
}
}
return false
}
func hasCloseElements2(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
var previous = l[0]
for i in 1..<l.count {
if abs(l[i] - previous) >= threshold {
return true
}
previous = l[i]
}
return false
}
func hasCloseElements3(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
var previous = l[0]
for i in 1..<l.count {
if abs(l[i] - previous) >= threshold {
return true
}
previous = l[i]
}
return false
}
func hasCloseElements4(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
for i in 0..<l.count {
for j in (i+1)..<l.count {
if abs(l[i] - l[j]) >= threshold {
return true
}
}
}
return false
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
guard l.count > 1 else { return true }
var isIncreasing = l[0] < l[1]
for i in 1..<l.count {
if isIncreasing {
if l[i] < l[i-1] {
return false
}
} else {
if l[i] > l[i-1] {
return false
}
}
}
return true
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two consecutive elements is greater than or equal to given threshold.
// hasCloseElements(l: [1, 2, 4, 20], threshold: 5) == true
// hasCloseElements(l: [1, 20, 4, 10], threshold: 5) == false
// hasCloseElements(l: [4, 1, 0, -10], threshold: 5) == true
func hasCloseElements(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
for i in 0..<l.count {
for j in (i+1)..<l.count {
if abs(l[i] - l[j]) >= threshold {
return true
}
}
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two consecutive elements is greater than or equal to given threshold.
// hasCloseElements(l: [1, 2, 4, 20], threshold: 5) == true
// hasCloseElements(l: [1, 20, 4, 10], threshold: 5) == false
// hasCloseElements(l: [4, 1, 0, -10], threshold: 5) == true
func hasCloseElements2(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
var previous = l[0]
for i in 1..<l.count {
if abs(l[i] - previous) >= threshold {
return true
}
previous = l[i]
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two consecutive elements is greater than or equal to given threshold.
// hasCloseElements(l: [1, 2, 4, 20], threshold: 5) == true
// hasCloseElements(l: [1, 20, 4, 10], threshold: 5) == false
// hasCloseElements(l: [4, 1, 0, -10], threshold: 5) == true
func hasCloseElements3(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
var previous = l[0]
for i in 1..<l.count {
if abs(l[i] - previous) >= threshold {
return true
}
previous = l[i]
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two consecutive elements is greater than or equal to given threshold.
// hasCloseElements(l: [1, 2, 4, 20], threshold: 5) == true
// hasCloseElements(l: [1, 20, 4, 10], threshold: 5) == false
// hasCloseElements(l: [4, 1, 0, -10], threshold: 5) == true
func hasCloseElements4(l: [Int], threshold: Int) -> Bool {
guard l.count > 1 else { return true }
for i in 0..<l.count {
for j in (i+1)..<l.count {
if abs(l[i] - l[j]) >= threshold {
return true
}
}
}
return false
}
// Return true if array elements are monotonically increasing or decreasing,
// and the difference between any two consecutive elements is greater than or equal to given threshold.
// hasCloseElements(l: [1, 2, 4, 20], threshold: 5) == true
// hasCloseElements(l: [1, 20, 4, 1
var isIncreasing = l[0] < l[1] // variable 'isIncreasing' was never mutated; consider changing to 'let' constant
func common(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// 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 set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// 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 set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// 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 set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// 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 set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique common elements
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
func common2(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
func common3(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
func common4(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
```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 set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
// 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 common2(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
// 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 common3(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
// 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 common4(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
// 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 common5(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if
func common(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
func common2(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted()
}
func common3(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
func common4(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
```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 set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// 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 common2(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted()
}
// 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 common3(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
// 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 common4(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result.sorted(by: <)
}
// 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 common5(l1: [Int], l2: [Int]) -> [Int] {
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
var result = [Int]()
for i in set1 {
if set2.contains(i) {
result.
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l3 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l3 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l4 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
return result
}
// Return sorted unique common elements for three arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [5, 3, 2, 8]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [5, 3, 2, 8]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l3 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
return result
}
// Return sorted unique common elements for four arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [5, 3, 2, 8], l4: [5, 3, 2, 8]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [5, 3, 2, 8], l4: [5, 3, 2, 8]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l3 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l4 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
return result
}
// Return sorted unique common elements for five arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [5, 3, 2, 8], l4: [5, 3, 2, 8], l5: [5, 3, 2, 8]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [5, 3, 2, 8], l4: [5, 3, 2, 8], l5: [5, 3, 2, 8]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int], l5: [Int]) -> [Int] {
var result = [Int]()
var m = [Int: Bool]()
for i in l1 {
m[i] = true
}
for i in l2 {
if m[i]!= nil {
m[i] = false
result.append(i)
}
}
for i in l3 {
if m
if m[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if m[i]!= nil { // '=' must have consistent whitespace on both sides
if m[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if m[i]!= nil { // '=' must have consistent whitespace on both sides
if m[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if m[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if m[i]!= nil { // '=' must have consistent whitespace on both sides
if m[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if m[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if m[i]!= nil { // '=' must have consistent whitespace on both sides
if m[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if m[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if m[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if m[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if m[i]!= nil { // '=' must have consistent whitespace on both sides
if m[i]!= nil { // '=' must have consistent whitespace on both sides
if m[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if m[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
}
}
return result
}
func common2(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
l1Dict[i] = nil
}
}
return result
}
func common3(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
}
}
return result.sorted()
}
func common4(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
l1Dict[i] = nil
}
}
return result.sorted(by: <)
}
func common5(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
l1Dict[i] = nil
}
}
return result.sorted(by: <)
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
}
}
return result
}
// 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 common2(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
l1Dict[i] = nil
}
}
return result
}
// 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 common3(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
}
}
return result.sorted()
}
// 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 common4(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
l1Dict[i] = nil
}
}
return result.sorted(by: <)
}
// 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 common5(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1Dict = [Int: Bool]()
for i in l1 {
l1Dict[i] = true
}
for i in l2 {
if l1Dict[i]!= nil {
result.append(i)
l1Dict[i] = nil
}
}
return result.sorted(by: <)
}
// 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
if l1Dict[i]!= nil { // '=' must have consistent whitespace on both sides
if l1Dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if l1Dict[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if l1Dict[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if l1Dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if l1Dict[i]!= nil { // '=' must have consistent whitespace on both sides
if l1Dict[i]!= nil { // '=' must have consistent whitespace on both sides
if l1Dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if l1Dict[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if l1Dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if l1Dict[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if l1Dict[i]!= nil { // '=' must have consistent whitespace on both sides
if l1Dict[i]!= nil { // use of '=' in a boolean context, did you mean '=='?
if l1Dict[i]!= nil { // 'nil' cannot be assigned to type 'Bool'
if l1Dict[i]!= nil { // '=' must have consistent whitespace on both sides
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l4 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
// Return sorted unique common elements for three arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [1, 5, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [1, 2, 3]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
// Return sorted unique common elements for four arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [1, 5, 653, 121], l4: [5, 653]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [1, 2, 3], l4: [1, 2, 3, 4]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l4 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
// Return sorted unique common elements for five arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [1, 5, 653, 121], l4: [5, 653], l5: [1, 5, 653]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [1, 2, 3], l4: [1, 2, 3, 4], l5: [1, 2, 3, 4, 5]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int], l5: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
func common2(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
func common3(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
func common4(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// 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 common2(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// 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 common3(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// 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 common4(l1: [Int], l2: [Int]) -> [Int] {
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
var result = [Int]()
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 1
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l4 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
// Return sorted unique common elements for three arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [1, 5, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [1, 2, 3]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
// Return sorted unique common elements for four arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [1, 5, 653, 121], l4: [1, 5, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [1, 2, 3], l4: [1, 2, 3]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l4 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
return result
}
// Return sorted unique common elements for five arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [1, 5, 653, 121], l4: [1, 5, 653, 121], l5: [1, 5, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [1, 2, 3], l4: [1, 2, 3], l5: [1, 2, 3]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int], l5: [Int]) -> [Int] {
var result = [Int]()
var set = Set<Int>()
for i in l1 {
set.insert(i)
}
for i in l2 {
if set.contains(i) {
result.append(i)
set.remove(i)
}
}
for i in l3 {
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
var set3 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in l3 {
set3.insert(i)
}
for i in set1 {
if set2.contains(i) && set3.contains(i) {
result.append(i)
}
}
return result
}
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
var set3 = Set<Int>()
var set4 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in l3 {
set3.insert(i)
}
for i in l4 {
set4.insert(i)
}
for i in set1 {
if set2.contains(i) && set3.contains(i) && set4.contains(i) {
result.append(i)
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in set1 {
if set2.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique common elements for three arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [5, 3, 2, 8]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2], l3: [3, 2, 1]) == [2, 3]
func common(l1: [Int], l2: [Int], l3: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
var set3 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in l3 {
set3.insert(i)
}
for i in set1 {
if set2.contains(i) && set3.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique common elements for four arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [5, 3, 2, 8], l4: [3, 2, 1]) == [1, 5, 653]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
var set3 = Set<Int>()
var set4 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in l3 {
set3.insert(i)
}
for i in l4 {
set4.insert(i)
}
for i in set1 {
if set2.contains(i) && set3.contains(i) && set4.contains(i) {
result.append(i)
}
}
return result
}
// Return sorted unique common elements for five arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121], l3: [5, 3, 2, 8], l4: [3, 2, 1], l5: [3, 1, 2]) == [1, 5, 653]
func common(l1: [Int], l2: [Int], l3: [Int], l4: [Int], l5: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>()
var set2 = Set<Int>()
var set3 = Set<Int>()
var set4 = Set<Int>()
var set5 = Set<Int>()
for i in l1 {
set1.insert(i)
}
for i in l2 {
set2.insert(i)
}
for i in l3 {
set3.insert(i)
}
for i in l4 {
set4.insert(i)
}
for i in l5 {
set5.insert(i)
}
for i in set1 {
if set2.contains(i) && set3.contains(i) && set4.contains(i) &&
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func sumOfEvensOnly(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum
}
func sumOfSquares(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i * i
}
return sum
}
func differenceBetweenSumOfSquaresAndSquareOfSums(n: Int) -> Int {
return squareOfSums(n: n) - sumOfSquares(n: n)
}
func productOfSums(n: Int) -> Int {
return sumOfNaturalNumbers(n: n) * sumOfNaturalNumbers(n: n)
}
func productOfSumsOfSquares(n: Int) -> Int {
return sumOfSquares(n: n) * sumOfNaturalNumbers(n: n)
}
func differenceBetweenProductOfSumOfSquaresAndSumOfSquares(n: Int) -> Int {
return productOfSumsOfSquares(n: n) - sumOfSquares(n: n)
}
func sumOfOddEvenNumbers(n: Int) -> Int {
return sumOfEvensOnly(n: n) + sumOfOddsOnly(n: n)
}
func sumOfNaturalNumbers(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// Return the sum of all the numbers between 1 and n, excluding any even numbers.
// sumOfEvensOnly(10) == 2 + 8
// sumOfEvensOnly(5) == 2 + 4
func sumOfEvensOnly(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 2 == 0 {
sum += i
}
}
return sum
}
// Return the sum of all the squares from 1 to n.
// sumOfSquares(10) == 1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2 + 10^2 == 385
// sumOfSquares(1) == 1
func sumOfSquares(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i * i
}
return sum
}
// Return the difference between the sum of the squares of the first n natural numbers and the square of the sum.
// differenceBetweenSumOfSquaresAndSquareOfSums(10) == 2640
// differenceBetweenSumOfSquaresAndSquareOfSums(1) == 1
func differenceBetweenSumOfSquaresAndSquareOfSums(n: Int) -> Int {
return squareOfSums(n: n) - sumOfSquares(n: n)
}
// Return the result of multiplying the sum of the first n natural numbers by the sum of the first n natural numbers.
// productOfSums(10) == 55
// productOfSums(1) == 1
func productOfSums(n: Int) -> Int {
return sumOfNaturalNumbers(n: n) * sumOfNaturalNumbers(n: n)
}
// Return the result of multiplying the sum of the squares of the first n natural numbers by the sum of the first n natural numbers.
// productOfSumsOfSquares(10) == 330280
// productOfSumsOfSquares(1) == 1
func productOfSumsOfSquares(n: Int) -> Int {
return sumOfSquares(n: n) * sumOfNaturalNumbers(n: n)
}
// Return the difference between the product of the sum of the squares of the first n natural numbers and the sum of the squares of the first n natural numbers and the product of the first n natural numbers by the sum of the first n natural numbers.
// differenceBetweenProductOfSumOfSquaresAndSumOfSquares(10) == 2640
// differenceBetweenProductOfSumOfSquaresAndSumOfSquares(1) == 0
func differenceBetweenProductOfSumOfSquaresAndSumOfSquares(n: Int) -> Int {
return productOfSumsOfSquares(n: n) - sumOfSquares(n: n)
}
// Return the result of adding the sum of the even numbers to the sum of the odd numbers within the first n natural numbers.
// sumOfOddEvenNumbers(10) == 30
// sumOfOddEvenNumbers(1) == 0
func sumOfOddEvenNumbers(n: Int) -> Int {
return sumOfEvensOnly(n: n) + sumOfOddsOnly(n: n)
}
// Return the sum of the first n natural numbers.
// sumOfNaturalNumbers(10) == 55
// sumOfNaturalNumbers(1) == 1
func sumOfNaturalNumbers(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
// Return the sum of the first n odd numbers.
// sumOfOddsOnly(10) == 15
// sumOfOddsOnly(1) == 1
func sumOfOddsOnly(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 2 == 1 {
sum += i
}
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
return squareOfSums(n: n) - sumOfSquares(n: n) // cannot find 'squareOfSums' in scope
return sumOfEvensOnly(n: n) + sumOfOddsOnly(n: n) // cannot find 'sumOfOddsOnly' in scope
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the result.
return 0
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the result.
return 0
}
// Test the function
assert(largestPrimeFactor(n: 13195) == 29)
assert(largestPrimeFactor(n: 2048) == 2)
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i <= n / i {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func sumOfOddCubes(n: Int) -> Int {
(1...n).filter { $0 % 2 == 1 }.map { $0 * $0 * $0 }.reduce(0, +)
}
func sumOfMultiples(n: Int) -> Int {
(1...n).filter { $0 % 7 == 0 || $0 % 13 == 0 }.reduce(0, +)
}
func differenceBetweenSumOfSquaresAndSquareOfSum(n: Int) -> Int {
let sumOfSquares = (1...n).map { $0 * $0 }.reduce(0, +)
let squareOfSum = (1...n).reduce(0, +) * (1...n).reduce(0, +)
return squareOfSum - sumOfSquares
}
func greatestCommonDivisor(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b!= 0 {
(a, b) = (b, a % b)
}
return a
}
func leastCommonMultiple(_ a: Int, _ b: Int) -> Int {
return a / greatestCommonDivisor(a, b) * b
}
func raiseToPower(_ num: Int, _ exponent: Int, _ mod: Int) -> Int {
var result = 1
for _ in 0..<exponent {
result = (result * num) % mod
}
return result
}
func addWithoutPlus(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b!= 0 {
(a, b) = (a ^ b, (a & b) << 1)
}
return a
}
func multiplyWithoutMultiply(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b!= 0 {
if (b & 1)!= 0 {
a = addWithoutPlus(a, a)
}
b >>= 1
a <<= 1
}
return a >> 1
}
```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 <= n / i {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// Return the sum of all the numbers between 1 and n, excluding any even numbers.
// sumOfOddCubes(n: 5) == 36
// sumOfOddCubes(n: 10) == 72
func sumOfOddCubes(n: Int) -> Int {
(1...n).filter { $0 % 2 == 1 }.map { $0 * $0 * $0 }.reduce(0, +)
}
// Return the sum of all the multiples of 7 or 13 below n.
// sumOfMultiples(n: 1000) == 233168
func sumOfMultiples(n: Int) -> Int {
(1...n).filter { $0 % 7 == 0 || $0 % 13 == 0 }.reduce(0, +)
}
// Return the difference between the sum of the squares of the first one hundred natural numbers and
// the square of the sum.
// differenceBetweenSumOfSquaresAndSquareOfSum(100) == 2640
func differenceBetweenSumOfSquaresAndSquareOfSum(n: Int) -> Int {
let sumOfSquares = (1...n).map { $0 * $0 }.reduce(0, +)
let squareOfSum = (1...n).reduce(0, +) * (1...n).reduce(0, +)
return squareOfSum - sumOfSquares
}
// Return the greatest common divisor of a and b.
// greatestCommonDivisor(20, 12) == 4
// greatestCommonDivisor(7, 15) == 1
func greatestCommonDivisor(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b!= 0 {
(a, b) = (b, a % b)
}
return a
}
// Return the least common multiple of a and b.
// leastCommonMultiple(20, 12) == 480
// leastCommonMultiple(7, 15) == 35
func leastCommonMultiple(_ a: Int, _ b: Int) -> Int {
return a / greatestCommonDivisor(a, b) * b
}
// Return the result of raising num to the power of exponent modulo mod.
// raiseToPower(2, 10, 1000) == 1024
// raiseToPower(3, 50, 1000) == 1
func raiseToPower(_ num: Int, _ exponent: Int, _ mod: Int) -> Int {
var result = 1
for _ in 0..<exponent {
result = (result * num) % mod
}
return result
}
// Return the result of adding two numbers without using the "+" operator.
// addWithoutPlus(5, 7) == 12
// addWithoutPlus(10, 12) == 22
func addWithoutPlus(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b!= 0 {
(a, b) = (a ^ b, (a & b) << 1)
}
return a
}
// Return the result of multiplying two numbers without using the "*" operator.
// multiplyWithoutMultiply(5, 7) == 35
// multiplyWithoutMultiply(10, 12) == 140
func multiplyWithoutMultiply(_ a: Int, _ b: Int) -> Int {
var a = a, b = b
while b!= 0 {
if (b & 1)!= 0 {
a = addWithoutPlus(a, a)
}
b >>= 1
a <<= 1
}
return a >> 1
}
// Return the result of raising num to the power of exponent without using any built-in mathematical
// functions or operators.
// raiseToPowerWithoutOperator(2, 10) == 1024
// raiseToPowerWithoutOperator(3, 50) == 99468134454
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
if (b & 1)!= 0 { // use of '=' in a boolean context, did you mean '=='?
if (b & 1)!= 0 { // '=' must have consistent whitespace on both sides
if (b & 1)!= 0 { // cannot force unwrap value of non-optional type 'Int'
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the result.
return 0
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the result.
return 0
}
// Test the function with the given example
largestPrimeFactor(n: 13195)
largestPrimeFactor(n: 2048)
// Test the function with additional cases
largestPrimeFactor(n: 600851475143)
largestPrimeFactor(n: 13)
largestPrimeFactor(n: 17)
largestPrimeFactor(n: 19)
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i <= n / i {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func sumOfAllNumbers(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 2 == 1 {
sum += i
}
}
return sum
}
func sumOfSquares(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i * i > n {
break
} else {
sum += i * i
}
}
return sum
}
func difference(n: Int) -> Int {
return sumOfSquares(n: n) - sumOfAllNumbers(n: n)
}
func printLargestPrimeFactor(n: Int) {
print("The largest prime factor of \(n) is \(largestPrimeFactor(n: n)).")
print("The sum of all numbers between 1 and \(n) is \(sumOfAllNumbers(n: n)).")
print("The difference between the sum of the squares and the sum of the numbers between 1 and \(n) is \(difference(n: 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 <= n / i {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// Return the sum of all the numbers between 1 and n, excluding any even numbers.
// sumOfAllNumbers(n: 10) == 2 + 8 + 3 + 5 + 1 + 7 + 9 + 4 + 6 + 10
func sumOfAllNumbers(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 2 == 1 {
sum += i
}
}
return sum
}
// Return the sum of all the squares between 1 and n, excluding any perfect squares.
// sumOfSquares(n: 10) == 1 + 4 + 9 + 16 + 25 + 36 + 49 + 64 + 81 + 100
func sumOfSquares(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i * i > n {
break
} else {
sum += i * i
}
}
return sum
}
// Return the difference between the sum of the squares and the sum of the numbers between 1 and n.
// difference(n: 10) == 361
func difference(n: Int) -> Int {
return sumOfSquares(n: n) - sumOfAllNumbers(n: n)
}
// Print the largest prime factor of n, the sum of all numbers between 1 and n, and the difference between
// the sum of the squares and the sum of the numbers between 1 and n.
func printLargestPrimeFactor(n: Int) {
print("The largest prime factor of \(n) is \(largestPrimeFactor(n: n)).")
print("The sum of all numbers between 1 and \(n) is \(sumOfAllNumbers(n: n)).")
print("The difference between the sum of the squares and the sum of the numbers between 1 and \(n) is \(difference(n: n)).")
}
// Test the function with n = 1000.
printLargestPrimeFactor(n: 1000)
```
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the result.
return 0
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the result.
return 0
}
// Test the function with the given example
largestPrimeFactor(n: 13195)
largestPrimeFactor(n: 2048)
// Test the function with additional cases
largestPrimeFactor(n: 600851475143)
largestPrimeFactor(n: 13195)
largestPrimeFactor(n: 644)
largestPrimeFactor(n: 2048)
```
// XCTAssertTrue failed
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func sumOfOddNumbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
func sumOfSquares(n: Int) -> Int {
return (n * (n + 1) * (2 * n + 1)) / 6
}
func differenceBetweenSumOfSquaresAndSquareOfSum(n: Int) -> Int {
return squareOfSum(n: n) - sumOfSquares(n: n)
}
func productOfSumOfFirstNaturalNumbers(n: Int) -> Int {
return sumOfFirstNaturalNumbers(n: n) * sumOfFirstNaturalNumbers(n: n)
}
func productOfSumOfSquaresAndSquareOfSum(n: Int) -> Int {
return sumOfSquares(n: n) * squareOfSum(n: n)
}
func differenceBetweenProductOfSumOfSquaresAndSquareOfSumAndProductOfSumAndSumOfSquares(n: Int) -> Int {
return productOfSumOfSquaresAndSquareOfSum(n: n) - productOfSumOfFirstNaturalNumbers(n: n) * (sumOfFirstNaturalNumbers(n: n) * sumOfSquares(n: n))
}
func smallestLargestPrimeFactorDifference(n: Int) -> Int {
return largestPrimeFactor(n: n) - smallestPrimeFactor(n: n)
}
func smallestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// Return the sum of all the numbers between 1 and n, excluding any even numbers.
// sumOfOddNumbers(n: 10) == 25
// sumOfOddNumbers(n: 5) == 10
func sumOfOddNumbers(n: Int) -> Int {
return (n * (n + 1)) / 2
}
// Return the sum of all the squares between 1 and n, excluding any perfect squares.
// sumOfSquares(n: 10) == 385
// sumOfSquares(n: 5) == 5
func sumOfSquares(n: Int) -> Int {
return (n * (n + 1) * (2 * n + 1)) / 6
}
// Return the difference between the sum of the squares of the first n natural numbers and
// the square of the sum.
// differenceBetweenSumOfSquaresAndSquareOfSum(n: 10) == 2640
// differenceBetweenSumOfSquaresAndSquareOfSum(n: 5) == 8
func differenceBetweenSumOfSquaresAndSquareOfSum(n: Int) -> Int {
return squareOfSum(n: n) - sumOfSquares(n: n)
}
// Return the result of multiplying the sum of the first n natural numbers by the
// sum of the first n natural numbers.
// productOfSumOfFirstNaturalNumbers(n: 10) == 3628800
// productOfSumOfFirstNaturalNumbers(n: 5) == 120
func productOfSumOfFirstNaturalNumbers(n: Int) -> Int {
return sumOfFirstNaturalNumbers(n: n) * sumOfFirstNaturalNumbers(n: n)
}
// Return the result of multiplying the sum of the squares of the first n natural numbers by
// the square of the sum of the first n natural numbers.
// productOfSumOfSquaresAndSquareOfSum(n: 10) == 99016000
// productOfSumOfSquaresAndSquareOfSum(n: 5) == 15625
func productOfSumOfSquaresAndSquareOfSum(n: Int) -> Int {
return sumOfSquares(n: n) * squareOfSum(n: n)
}
// Return the difference between the product of the sum of the squares of the first n natural
// numbers and the square of the sum of the first n natural numbers and the product of the
// sum of the first n natural numbers and the sum of the squares of the first n natural numbers.
// differenceBetweenProductOfSumOfSquaresAndSquareOfSumAndProductOfSumAndSumOfSquares(n: 10) == 225
// differenceBetweenProductOfSumOfSquaresAndSquareOfSumAndProductOfSumAndSumOfSquares(n: 5) == -130
func differenceBetweenProductOfSumOfSquaresAndSquareOfSumAndProductOfSumAndSumOfSquares(n: Int) -> Int {
return productOfSumOfSquaresAndSquareOfSum(n: n) - productOfSumOfFirstNaturalNumbers(n: n) * (sumOfFirstNaturalNumbers(n: n) * sumOfSquares(n: n))
}
// Return the result of adding the largest prime factor of n to the smallest prime factor of n.
// smallestLargestPrimeFactorDifference(n: 600851475143) == 6857
func smallestLargestPrimeFactorDifference(n: Int) -> Int {
return largestPrimeFactor(n: n) - smallestPrimeFactor(n: n)
}
// Return the smallest prime factor of n. Assume n > 1 and is not a prime.
// smallestPrimeFactor(n: 600851475143) == 3187
func smallestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
} else {
i += 1
}
}
return n
}
// Return the sum of all
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
return squareOfSum(n: n) - sumOfSquares(n: n) // cannot find 'squareOfSum' in scope
return sumOfFirstNaturalNumbers(n: n) * sumOfFirstNaturalNumbers(n: n) // cannot find 'sumOfFirstNaturalNumbers' in scope
return sumOfFirstNaturalNumbers(n: n) * sumOfFirstNaturalNumbers(n: n) // cannot find 'sumOfFirstNaturalNumbers' in scope
return sumOfSquares(n: n) * squareOfSum(n: n) // cannot find 'squareOfSum' in scope
return productOfSumOfSquaresAndSquareOfSum(n: n) - productOfSumOfFirstNaturalNumbers(n: n) * (sumOfFirstNaturalNumbers(n: n) * sumOfSquares(n: n)) // cannot find 'sumOfFirstNaturalNumbers' in scope
func largestPrimeFactor(n: Int) -> Int {
// TODO: Implement the function according to the suggested steps in the output,
// and return the largest prime factor of the given number.
// The steps are as follows:
// 1. Divide the given number by 2 until it is no longer divisible by 2.
// 2. Check if the given number is divisible by any odd number from 3 to the square root of the given number,
// incrementing the divisor by 2 in each iteration (i.e. check only odd numbers).
// 3. If the given number is still divisible by a number, it is not a prime number.
// 4. If the given number is not divisible by any number, it is a prime number.
// 5. Find the largest prime factor that is less than or equal to the given number.
// 6. Return the largest prime factor.
//
// Note: You can assume that the input number will always be greater than 1 and less than or equal to 10^12.
// Also, you should not use any built-in functions or libraries that directly solve this problem.
var n = n
while n % 2 == 0 {
n /= 2
}
var i = 3
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 2
}
}
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 {
// TODO: Implement the function according to the suggested steps in the output,
// and return the largest prime factor of the given number.
// The steps are as follows:
// 1. Divide the given number by 2 until it is no longer divisible by 2.
// 2. Check if the given number is divisible by any odd number from 3 to the square root of the given number,
// incrementing the divisor by 2 in each iteration (i.e. check only odd numbers).
// 3. If the given number is still divisible by a number, it is not a prime number.
// 4. If the given number is not divisible by any number, it is a prime number.
// 5. Find the largest prime factor that is less than or equal to the given number.
// 6. Return the largest prime factor.
//
// Note: You can assume that the input number will always be greater than 1 and less than or equal to 10^12.
// Also, you should not use any built-in functions or libraries that directly solve this problem.
var n = n
while n % 2 == 0 {
n /= 2
}
var i = 3
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 2
}
}
return n
}
// Test the function
print(largestPrimeFactor(n: 13195)) // Output: 29
print(largestPrimeFactor(n: 600851475143)) // Output: 6857
```
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func sumOfPrimes(n: Int) -> Int {
var sum = 0
var i = 2
while i <= n {
if isPrime(i) {
sum += i
}
i += 1
}
return sum
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
func fibonacci(n: Int) -> Int {
if n <= 0 {
return 0
}
if n == 1 {
return 1
}
var a = 0
var b = 1
var i = 2
while i <= n {
let temp = b
b = a + b
a = temp
i += 1
}
return b
}
func primeFibonacci(n: Int) -> Int {
var i = 0
var fib = 0
while i < n {
fib = fibonacci(i)
if isPrime(fib) {
i += 1
} else {
i += 1
while!isPrime(fib) {
fib = fibonacci(i)
i += 1
}
}
}
return fib
}
func sumOfPrimeFibonacci(n: Int) -> Int {
var i = 0
var fib = 0
while i < n {
fib = fibonacci(i)
if isPrime(fib) {
i += 1
} else {
i += 1
while!isPrime(fib) {
fib = fibonacci(i)
i += 1
}
}
}
var fib2 = fibonacci(i - 1)
while!isPrime(fib2 + fib) {
fib2 = fibonacci(i - 2)
i += 1
}
return fib2 + fib
}
func fibonacciSequence(n: Int) -> [Int] {
if n <= 0 {
return [Int]()
}
if n == 1 {
return [0, 1]
}
var sequence = [0, 1]
while sequence.count < n {
let next = sequence[sequence.count - 1] + sequence[sequence.count - 2]
sequence.append(next)
}
return sequence
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// Return the sum of the first n prime numbers.
// sumOfPrimes(n: 5) == 28
func sumOfPrimes(n: Int) -> Int {
var sum = 0
var i = 2
while i <= n {
if isPrime(i) {
sum += i
}
i += 1
}
return sum
}
// Return true if n is prime, false otherwise.
// isPrime(7) == true
// isPrime(12) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n <= 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
// Return the nth Fibonacci number.
// fibonacci(0) == 0
// fibonacci(1) == 1
// fibonacci(6) == 8
func fibonacci(n: Int) -> Int {
if n <= 0 {
return 0
}
if n == 1 {
return 1
}
var a = 0
var b = 1
var i = 2
while i <= n {
let temp = b
b = a + b
a = temp
i += 1
}
return b
}
// Return the nth prime Fibonacci number.
// primeFibonacci(1) == 2
// primeFibonacci(2) == 3
// primeFibonacci(5) == 13
func primeFibonacci(n: Int) -> Int {
var i = 0
var fib = 0
while i < n {
fib = fibonacci(i)
if isPrime(fib) {
i += 1
} else {
i += 1
while!isPrime(fib) {
fib = fibonacci(i)
i += 1
}
}
}
return fib
}
// Return the nth Fibonacci number that is also the sum of two prime Fibonacci numbers.
// sumOfPrimeFibonacci(1) == 5
// sumOfPrimeFibonacci(2) == 8
// sumOfPrimeFibonacci(5) == 21
func sumOfPrimeFibonacci(n: Int) -> Int {
var i = 0
var fib = 0
while i < n {
fib = fibonacci(i)
if isPrime(fib) {
i += 1
} else {
i += 1
while!isPrime(fib) {
fib = fibonacci(i)
i += 1
}
}
}
var fib2 = fibonacci(i - 1)
while!isPrime(fib2 + fib) {
fib2 = fibonacci(i - 2)
i += 1
}
return fib2 + fib
}
// Return the nth value of the Fibonacci sequence.
// fibonacciSequence(0) == [0]
// fibonacciSequence(1) == [0, 1]
// fibonacciSequence(6) == [0, 1, 1, 2, 3, 5, 8]
func fibonacciSequence(n: Int) -> [Int] {
if n <= 0 {
return [Int]()
}
if n == 1 {
return [0, 1]
}
var sequence = [0, 1]
while sequence.count < n {
let next = sequence[sequence.count - 1] + sequence[sequence.count - 2]
sequence.append(next)
}
return sequence
}
// Return the nth value of the Fibonacci sequence that is the sum of two prime Fibonacci numbers.
// sumOfFibonacciPrimes(1)
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
if isPrime(i) { // missing argument label 'n:' in call
fib = fibonacci(i) // missing argument label 'n:' in call
if isPrime(fib) { // missing argument label 'n:' in call
while!isPrime(fib) { // expected expression, var, or let in 'while' condition
fib = fibonacci(i) // missing argument label 'n:' in call
if isPrime(fib) { // missing argument label 'n:' in call
while!isPrime(fib) { // expected expression, var, or let in 'while' condition
var fib2 = fibonacci(i - 1) // missing argument label 'n:' in call
while!isPrime(fib2 + fib) { // expected expression, var, or let in 'while' condition
func largestPrimeFactor(n: Int) -> Int {
var i = 2
while i <= n / i {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func sumOfOddCubes(n: Int) -> Int {
return (1...n).filter { $0 % 2 == 1 }.map { $0 * $0 * $0 }.reduce(0, +)
}
func sumOfSquares(n: Int) -> Int {
return (1...n).filter {!isPerfectSquare($0 * $0) }.map { $0 * $0 }.reduce(0, +)
}
func differenceBetweenSumOfSquaresAndSquareOfSum(n: Int) -> Int {
return squareOfSum(n: n) - sumOfSquares(n: n)
}
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = abs(a)
var b = abs(b)
while b!= 0 {
(a, b) = (b, a % b)
}
return a
}
func leastCommonMultiple(a: Int, b: Int) -> Int {
return abs(a * b) / greatestCommonDivisor(a: a, b: b)
}
func power(n: Int, p: Int, m: Int) -> Int {
if p > Int.bitWidth {
print("Warning: Potential overflow")
}
return Int(pow(Double(n), Double(p))) % m
}
func binaryPower(n: Int, m: Int) -> Int {
if n > Int.bitWidth {
print("Warning: Potential overflow")
}
return Int(pow(2.0, Double(n))) % m
}
```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 <= n / i {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
// Return the sum of all the numbers between 1 and n, excluding any even numbers.
// sumOfOddCubes(n: 5) == 36
// sumOfOddCubes(n: 10) == 72
func sumOfOddCubes(n: Int) -> Int {
return (1...n).filter { $0 % 2 == 1 }.map { $0 * $0 * $0 }.reduce(0, +)
}
// Return the sum of all the squares between 1 and n, excluding any perfect squares.
// sumOfSquares(n: 5) == 5
// sumOfSquares(n: 10) == 225
func sumOfSquares(n: Int) -> Int {
return (1...n).filter {!isPerfectSquare($0 * $0) }.map { $0 * $0 }.reduce(0, +)
}
// Return the difference between the sum of the squares of the first n natural numbers and
// the square of the sum.
// differenceBetweenSumOfSquaresAndSquareOfSum(n: 5) == 2640
// differenceBetweenSumOfSquaresAndSquareOfSum(n: 10) == 22720
func differenceBetweenSumOfSquaresAndSquareOfSum(n: Int) -> Int {
return squareOfSum(n: n) - sumOfSquares(n: n)
}
// Return the greatest common divisor of a and b.
// greatestCommonDivisor(a: 20, b: 12) == 4
// greatestCommonDivisor(a: 7, b: 15) == 1
func greatestCommonDivisor(a: Int, b: Int) -> Int {
var a = abs(a)
var b = abs(b)
while b!= 0 {
(a, b) = (b, a % b)
}
return a
}
// Return the least common multiple of a and b.
// leastCommonMultiple(a: 20, b: 12) == 480
// leastCommonMultiple(a: 7, b: 15) == 35
func leastCommonMultiple(a: Int, b: Int) -> Int {
return abs(a * b) / greatestCommonDivisor(a: a, b: b)
}
// Return the result of raising n to the power of p modulo m.
// Raises a warning if p is greater than the number of bits in Int.
// power(n: 2, p: 100, m: 10) == 1024
// power(n: 3, p: 1000, m: 10) == 27
func power(n: Int, p: Int, m: Int) -> Int {
if p > Int.bitWidth {
print("Warning: Potential overflow")
}
return Int(pow(Double(n), Double(p))) % m
}
// Return the result of raising 2 to the power of n modulo m.
// Raises a warning if n is greater than the number of bits in Int.
// binaryPower(n: 100, m: 10) == 1024
// binaryPower(n: 1000, m: 10) == 27
func binaryPower(n: Int, m: Int) -> Int {
if n > Int.bitWidth {
print("Warning: Potential overflow")
}
return Int(pow(2.0, Double(n))) % m
}
// Return the result of raising 3 to the power of n modulo m using an iterative approach.
// Raises a warning if n is greater than the number of bits in Int.
// triplePower(n: 100, m: 10) == 1024
// triplePower(n: 1000, m: 10) == 27
func triplePower(n: Int, m: Int) -> Int {
if n > Int.bitWidth {
print("
n /= i // left side of mutating operator isn't mutable: 'n' is a 'let' constant
return (1...n).filter {!isPerfectSquare($0 * $0) }.map { $0 * $0 }.reduce(0, +) // cannot find 'isPerfectSquare' in scope
return squareOfSum(n: n) - sumOfSquares(n: n) // cannot find 'squareOfSum' in scope
while b!= 0 { // cannot force unwrap value of non-optional type 'Int'
while b!= 0 { // '=' must have consistent whitespace on both sides
while b!= 0 { // use of '=' in a boolean context, did you mean '=='?
func sumToN(n: Int) -> Int {
return (n * (n + 1)) / 2
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func nthPrime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(num) {
count += 1
}
num += 1
}
return num - 1
}
func sumOfPrimes(n: Int) -> Int {
return nthPrime(n: n) * (n - nthPrime(n: n)) / 2
}
func nthFibonacci(n: Int) -> Int {
var a = 0
var b = 1
for _ in 2...n {
(a, b) = (b, a + b)
}
return a
}
func sumOfFibonacci(n: Int) -> Int {
return nthFibonacci(n: n) * (n - nthFibonacci(n: n)) / 2
}
func nthLucas(n: Int) -> Int {
var a = 2
var b = 1
for _ in 2...n {
(a, b) = (b, a + b)
}
return a
}
func sumOfLucas(n: Int) -> Int {
return nthLucas(n: n) * (n - nthLucas(n: n)) / 2
}
func nthPell(n: Int) -> Int {
var a = 3
var b = 1
for _ in 2...n {
(a, b) = (2 * b, a + b)
}
return a
}
```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 {
return (n * (n + 1)) / 2
}
// is_prime is a function that checks if a number is prime.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(4) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
// nth_prime is a function that finds the nth prime number.
// nthPrime(1) == 2
// nthPrime(2) == 3
// nthPrime(6) == 13
func nthPrime(n: Int) -> Int {
var count = 0
var num = 2
while count < n {
if isPrime(num) {
count += 1
}
num += 1
}
return num - 1
}
// sum_of_primes is a function that sums all prime numbers from 1 to n.
// sumOfPrimes(1) == 0
// sumOfPrimes(10) == 17
// sumOfPrimes(20) == 77
func sumOfPrimes(n: Int) -> Int {
return nthPrime(n: n) * (n - nthPrime(n: n)) / 2
}
// nth_fibonacci is a function that finds the nth Fibonacci number.
// nthFibonacci(1) == 0
// nthFibonacci(2) == 1
// nthFibonacci(6) == 5
func nthFibonacci(n: Int) -> Int {
var a = 0
var b = 1
for _ in 2...n {
(a, b) = (b, a + b)
}
return a
}
// sum_of_fibonacci is a function that sums all Fibonacci numbers from 1 to n.
// sumOfFibonacci(1) == 0
// sumOfFibonacci(10) == 143
// sumOfFibonacci(20) == 60696
func sumOfFibonacci(n: Int) -> Int {
return nthFibonacci(n: n) * (n - nthFibonacci(n: n)) / 2
}
// nth_lucas is a function that finds the nth Lucas number.
// nthLucas(1) == 2
// nthLucas(2) == 1
// nthLucas(6) == 9
func nthLucas(n: Int) -> Int {
var a = 2
var b = 1
for _ in 2...n {
(a, b) = (b, a + b)
}
return a
}
// sum_of_lucas is a function that sums all Lucas numbers from 1 to n.
// sumOfLucas(1) == 2
// sumOfLucas(10) == 29
// sumOfLucas(20) == 1296
func sumOfLucas(n: Int) -> Int {
return nthLucas(n: n) * (n - nthLucas(n: n)) / 2
}
// nth_pell is a function that finds the nth Pell number.
// nthPell(1) == 3
// nthPell(2) == 1
// nthPell(6) == 10
func nthPell(n: Int) -> Int {
var a = 3
var b = 1
for _ in 2...n {
(a, b) = (2 * b, a + b)
}
return a
}
// sum_of_pell is a function that sums all Pell numbers from 1 to n.
// sumOfPell(1) == 3
// sumOfPell(10) == 126
// sumOfPell(20) == 660
func sumOfPell(n: Int) -> Int {
return nthPell(n: n) * (n - nth
if isPrime(num) { // missing argument label 'n:' in call
func sumToN(n: Int) -> Int {
return (n * (n + 1)) / 2
}
func sumOfSquares(n: Int) -> Int {
return (n * (n + 1) * (2 * n + 1)) / 6
}
func difference(n: Int) -> Int {
return sumToN(n: n) - sumOfSquares(n: n)
}
func nthFibonacci(n: Int) -> Int {
if n <= 1 {
return n
}
return nthFibonacci(n: n - 1) + nthFibonacci(n: n - 2)
}
func isPerfectSquare(n: Int) -> Bool {
let sqrtN = Int(sqrt(Double(n)))
return sqrtN * sqrtN == n
}
func isFibonacci(n: Int) -> Bool {
return isPerfectSquare(n: difference(n: n))
}
func nthFibonacciPrime(n: Int) -> Int {
var i = 1
while true {
if isPrime(n: i) && isFibonacci(n: i) {
if n == 1 {
return i
}
n -= 1
}
i += 1
}
}
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// 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 {
return (n * (n + 1)) / 2
}
// sum_of_squares is a function that sums the squares of numbers from 1 to n.
// sumOfSquares(n: 30) == 5425
// sumOfSquares(n: 100) == 338350
// sumOfSquares(n: 5) == 55
// sumOfSquares(n: 10) == 385
// sumOfSquares(n: 1) == 1
func sumOfSquares(n: Int) -> Int {
return (n * (n + 1) * (2 * n + 1)) / 6
}
// difference is a function that subtracts the sum of squares from the sum of numbers from 1 to n.
// difference(n: 30) == 135
// difference(n: 100) == 17850
// difference(n: 5) == 7
// difference(n: 10) == 94
// difference(n: 1) == 0
func difference(n: Int) -> Int {
return sumToN(n: n) - sumOfSquares(n: n)
}
// nth_fibonacci is a function that returns the nth number in the Fibonacci sequence.
// The first Fibonacci number is 1.
// nthFibonacci(6) == 8
// nthFibonacci(10) == 55
// nthFibonacci(1) == 1
func nthFibonacci(n: Int) -> Int {
if n <= 1 {
return n
}
return nthFibonacci(n: n - 1) + nthFibonacci(n: n - 2)
}
// is_perfect_square is a function that returns true if a number is a perfect square, and false otherwise.
// isPerfectSquare(16) == true
// isPerfectSquare(25) == true
// isPerfectSquare(30) == false
// isPerfectSquare(1) == true
func isPerfectSquare(n: Int) -> Bool {
let sqrtN = Int(sqrt(Double(n)))
return sqrtN * sqrtN == n
}
// is_fibonacci is a function that returns true if a number is a Fibonacci number, and false otherwise.
// isFibonacci(8) == true
// isFibonacci(10) == false
// isFibonacci(1) == true
func isFibonacci(n: Int) -> Bool {
return isPerfectSquare(n: difference(n: n))
}
// nth_fibonacci_prime is a function that returns the nth Fibonacci number that is also a prime number.
// The first Fibonacci number that is also a prime number is 1.
// nthFibonacciPrime(6) == 8
// nthFibonacciPrime(10) == 13
// nthFibonacciPrime(1) == 1
func nthFibonacciPrime(n: Int) -> Int {
var i = 1
while true {
if isPrime(n: i) && isFibonacci(n: i) {
if n == 1 {
return i
}
n -= 1
}
i += 1
}
}
// is_prime is a function that returns true if a number is a prime number, and false otherwise.
// isPrime(2) == true
// isPrime(4) == false
// isPrime(17) == true
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
// sum_of_primes is a function that sums all prime numbers from 1 to n.
// sumOfPrimes(10) == 17
// sumOfPrimes(20) == 77
// sumOfPrimes(1) == 1
func sumOfPrimes(n: Int)
n -= 1 // left side of mutating operator isn't mutable: 'n' is a 'let' constant
func sumToN(n: Int) -> Int {
return (1...n).reduce(0, +)
}
```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 {
return (1...n).reduce(0, +)
}
// Tests
assert(sumToN(n: 30) == 465)
assert(sumToN(n: 100) == 5050)
assert(sumToN(n: 5) == 15)
assert(sumToN(n: 10) == 55)
assert(sumToN(n: 1) == 1)
```
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
func sumToNWithDuplicates(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
if i % 3 == 0 {
sum += i
}
}
return sum
}
func sumToNWithDuplicatesAndConditions(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
if i % 3 == 0 && i % 5 == 0 {
sum += i
}
}
return sum
}
func sumToNWithDuplicatesAndConditionsAndPrimes(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
if i % 3 == 0 && i % 5 == 0 {
sum += i
if isPrime(i) {
sum += i
}
}
}
return sum
}
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
```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_with_duplicates is a function that sums numbers from 1 to n, including duplicates.
// sumToNWithDuplicates(n: 30) == 1050
// sumToNWithDuplicates(n: 100) == 3150
// sumToNWithDuplicates(n: 5) == 15
// sumToNWithDuplicates(n: 10) == 55
// sumToNWithDuplicates(n: 1) == 1
func sumToNWithDuplicates(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
if i % 3 == 0 {
sum += i
}
}
return sum
}
// sum_to_n_with_duplicates_and_conditions is a function that sums numbers from 1 to n, including duplicates,
// but only if the number is divisible by both 3 and 5.
// sumToNWithDuplicatesAndConditions(n: 30) == 1050
// sumToNWithDuplicatesAndConditions(n: 100) == 3150
// sumToNWithDuplicatesAndConditions(n: 5) == 15
// sumToNWithDuplicatesAndConditions(n: 10) == 55
// sumToNWithDuplicatesAndConditions(n: 1) == 1
func sumToNWithDuplicatesAndConditions(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
if i % 3 == 0 && i % 5 == 0 {
sum += i
}
}
return sum
}
// sum_to_n_with_duplicates_and_conditions_and_primes is a function that sums numbers from 1 to n, including duplicates,
// but only if the number is divisible by both 3 and 5, and the number is also prime.
// sumToNWithDuplicatesAndConditionsAndPrimes(n: 30) == 1050
// sumToNWithDuplicatesAndConditionsAndPrimes(n: 100) == 3150
// sumToNWithDuplicatesAndConditionsAndPrimes(n: 5) == 15
// sumToNWithDuplicatesAndConditionsAndPrimes(n: 10) == 55
// sumToNWithDuplicatesAndConditionsAndPrimes(n: 1) == 1
func sumToNWithDuplicatesAndConditionsAndPrimes(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
if i % 3 == 0 && i % 5 == 0 {
sum += i
if isPrime(i) {
sum += i
}
}
}
return sum
}
// is_prime is a function that checks if a number is prime.
// isPrime(1) == true
// isPrime(2) == true
// isPrime(4) == false
func isPrime(_ number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
// sum_to_n_with_duplicates_and_conditions_and_primes_and_strings is a function that sums numbers from 1 to n, including duplicates,
// but only if the number is divisible by both 3 and 5, the number is also prime, and the number is a palindrome.
// sumToNWithDuplicatesAndConditionsAndPrimesAndStrings(n: 30) == 1050
// sumToNWithDuplicatesAndConditionsAndPrimesAndStrings(n: 100) == 3150
// sumToNWithDuplicatesAndConditionsAndPrimesAndStrings(n: 5) == 15
// sumToNWithDuplicatesAndConditionsAndPrimesAndStrings(n: 10) == 55
// sumToNWithDuplicatesAndConditionsAndPrimesAndStrings(n: 1) == 1
func sum
func sumToN(n: Int) -> Int {
return (n * (n + 1)) / 2
}
func sumToNWithCancellation(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 5 == 0 {
sum += i + (i + 1)
} else {
sum += i
}
}
return sum
}
func sumToNWithCancellationAndDuplicates(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 5 == 0 {
sum += i + (i + 1)
} else if i % 3 == 0 {
sum += i + (i + 1) + (i + 2)
} else {
sum += i
}
}
return sum
}
func sumToNWithDecimals(n: Int) -> Double {
return (Double(n) * (Double(n) + 1.0)) / 2.0
}
func sumToNWithNegatives(n: Int) -> Int {
return (n * (n + 1)) / 2 * -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 {
return (n * (n + 1)) / 2
}
// sum_to_n_with_cancellation is a function that sums numbers from 1 to n,
// but if the number is divisible by 5, it cancels out with the next number.
// sumToNWithCancellation(n: 30) == 465
// sumToNWithCancellation(n: 100) == 5500
// sumToNWithCancellation(n: 5) == 15
// sumToNWithCancellation(n: 10) == 55
// sumToNWithCancellation(n: 1) == 1
func sumToNWithCancellation(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 5 == 0 {
sum += i + (i + 1)
} else {
sum += i
}
}
return sum
}
// sum_to_n_with_cancellation_and_duplicates is a function that sums numbers from 1 to n,
// but if the number is divisible by 5, it cancels out with the next number.
// It also includes numbers that are divisible by both 3 and 5.
// sumToNWithCancellationAndDuplicates(n: 30) == 465
// sumToNWithCancellationAndDuplicates(n: 100) == 5500
// sumToNWithCancellationAndDuplicates(n: 5) == 15
// sumToNWithCancellationAndDuplicates(n: 10) == 55
// sumToNWithCancellationAndDuplicates(n: 1) == 1
func sumToNWithCancellationAndDuplicates(n: Int) -> Int {
var sum = 0
for i in 1...n {
if i % 5 == 0 {
sum += i + (i + 1)
} else if i % 3 == 0 {
sum += i + (i + 1) + (i + 2)
} else {
sum += i
}
}
return sum
}
// sum_to_n_with_decimals is a function that sums numbers from 1.0 to n.
// sumToNWithDecimals(n: 30) == 157.5
// sumToNWithDecimals(n: 100) == 5050.0
// sumToNWithDecimals(n: 5) == 15.0
// sumToNWithDecimals(n: 10) == 55.0
// sumToNWithDecimals(n: 1) == 1.0
func sumToNWithDecimals(n: Int) -> Double {
return (Double(n) * (Double(n) + 1.0)) / 2.0
}
// sum_to_n_with_negatives is a function that sums numbers from -1 to n.
// sumToNWithNegatives(n: 30) == -94
// sumToNWithNegatives(n: 100) == -5050
// sumToNWithNegatives(n: 5) == -15
// sumToNWithNegatives(n: 10) == -55
// sumToNWithNegatives(n: 1) == -1
func sumToNWithNegatives(n: Int) -> Int {
return (n * (n + 1)) / 2 * -1
}
// sum_to_n_with_negatives_and_duplicates is a function that sums numbers from -1 to n,
// but also includes numbers that are divisible by both 3 and 5.
// sumToNWithNegativesAndDuplicates(n: 30) == -94
// sumToNWithNegativesAndDuplicates(n: 100) == -5050
// sumToNWithNegativesAndDuplicates(n: 5) == -15
// sumToNWithNegativesAndDuplicates(n: 10) == -55
// sumToNWithNegativesAndDuplicates(n: 1) == -1
func sumToNWithNegativesAndDuplicates(n: Int)
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
func sumToNTail(n: Int, current: Int = 1, total: Int = 0) -> Int {
if current == n {
return total + current
} else {
return sumToNTail(n: n, current: current + 1, total: total + current)
}
}
func sumToNLoop(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
func sumToNLoop2(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
func sumToNLoop3(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
func sumToNLoop4(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
func sumToNLoop5(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToN(n: n - 1)
}
}
// sum_to_n_tail is a tail-recursive function that sums numbers from 1 to n.
// sumToNTail(n: 30) == 465
// sumToNTail(n: 100) == 5050
// sumToNTail(n: 5) == 15
// sumToNTail(n: 10) == 55
// sumToNTail(n: 1) == 1
func sumToNTail(n: Int, current: Int = 1, total: Int = 0) -> Int {
if current == n {
return total + current
} else {
return sumToNTail(n: n, current: current + 1, total: total + current)
}
}
// sum_to_n_loop is a loop function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 100) == 5050
// sumToNLoop(n: 5) == 15
// sumToNLoop(n: 10) == 55
// sumToNLoop(n: 1) == 1
func sumToNLoop(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
// sum_to_n_loop is a loop function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 100) == 5050
// sumToNLoop(n: 5) == 15
// sumToNLoop(n: 10) == 55
// sumToNLoop(n: 1) == 1
func sumToNLoop2(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
// sum_to_n_loop is a loop function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 100) == 5050
// sumToNLoop(n: 5) == 15
// sumToNLoop(n: 10) == 55
// sumToNLoop(n: 1) == 1
func sumToNLoop3(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
// sum_to_n_loop is a loop function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 100) == 5050
// sumToNLoop(n: 5) == 15
// sumToNLoop(n: 10) == 55
// sumToNLoop(n: 1) == 1
func sumToNLoop4(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
// sum_to_n_loop is a loop function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 100) == 5050
// sumToNLoop(n: 5) == 15
// sumToNLoop(n: 10) == 55
// sumToNLoop(n: 1) == 1
func sumToNLoop5(n: Int) -> Int {
var total = 0
for i in 1...n {
total += i
}
return total
}
// sum_to_n_loop is a loop function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 1
func sumToN(n: Int) -> Int {
return (1...n).reduce(0, +)
}
func sumOfSquares(n: Int) -> Int {
return (1...n).map { $0*$0 }.reduce(0, +)
}
func sumOfCubes(n: Int) -> Int {
return (1...n).map { $0*$0*$0 }.reduce(0, +)
}
func isPerfectSquare(number: Int) -> Bool {
let root = sqrt(Double(number))
return root * root == Double(number)
}
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
func nthPrime(nthPrime: Int) -> Int {
var primes: [Int] = [2, 3]
var i = 1
while primes.count < nthPrime {
i += 1
if isPrime(i) {
primes.append(i)
}
}
return primes.last!
}
func sumOfPrimes(n: Int) -> Int {
return (1...n).filter { isPrime($0) }.reduce(0, +)
}
func fibonacciSequence(n: Int) {
var sequence = [1, 1]
while sequence.count < n {
let nextNumber = sequence[sequence.count - 1] + sequence[sequence.count - 2]
sequence.append(nextNumber)
}
print(sequence)
}
```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 {
return (1...n).reduce(0, +)
}
// sum_of_squares is a function that sums the squares of numbers from 1 to n.
// sumOfSquares(n: 30) == 328350
// sumOfSquares(n: 100) == 33557600
// sumOfSquares(n: 5) == 55
// sumOfSquares(n: 10) == 385
// sumOfSquares(n: 1) == 1
func sumOfSquares(n: Int) -> Int {
return (1...n).map { $0*$0 }.reduce(0, +)
}
// sum_of_cubes is a function that sums the cubes of numbers from 1 to n.
// sumOfCubes(n: 30) == 2102160
// sumOfCubes(n: 100) == 313476800
// sumOfCubes(n: 5) == 125
// sumOfCubes(n: 10) == 3134
// sumOfCubes(n: 1) == 1
func sumOfCubes(n: Int) -> Int {
return (1...n).map { $0*$0*$0 }.reduce(0, +)
}
// is_perfect_square is a function that checks if a number is a perfect square.
// isPerfectSquare(16) == true
// isPerfectSquare(25) == true
// isPerfectSquare(30) == false
// isPerfectSquare(1) == true
// isPerfectSquare(0) == true
func isPerfectSquare(number: Int) -> Bool {
let root = sqrt(Double(number))
return root * root == Double(number)
}
// is_prime is a function that checks if a number is prime.
// isPrime(1) == false
// isPrime(2) == true
// isPrime(4) == false
// isPrime(17) == true
func isPrime(number: Int) -> Bool {
if number <= 1 {
return false
}
for i in 2...Int(sqrt(Double(number))) {
if number % i == 0 {
return false
}
}
return true
}
// nth_prime is a function that finds the nth prime number.
// nthPrime(1) == 2
// nthPrime(2) == 3
// nthPrime(6) == 13
func nthPrime(nthPrime: Int) -> Int {
var primes: [Int] = [2, 3]
var i = 1
while primes.count < nthPrime {
i += 1
if isPrime(i) {
primes.append(i)
}
}
return primes.last!
}
// sum_of_primes is a function that sums all prime numbers from 1 to n.
// sumOfPrimes(10) == 17
// sumOfPrimes(20) == 77
// sumOfPrimes(100) == 22997008800
func sumOfPrimes(n: Int) -> Int {
return (1...n).filter { isPrime($0) }.reduce(0, +)
}
// fibonacci_sequence is a function that prints the first n numbers of the Fibonacci sequence.
// The first two numbers of the sequence are 1 and 1.
// fibonacciSequence(1) prints: 1
// fibonacciSequence(2) prints: 1, 1
// fibonacciSequence(5) prints: 1, 1, 2, 3, 5
func fibonacciSequence(n: Int) {
var sequence = [1, 1]
while sequence.count < n {
let nextNumber = sequence[sequence.count - 1] + sequence[sequence.count - 2]
sequence.append(nextNumber)
}
print(sequence)
}
// is_fibonacci is a function that checks if a number is a Fibonacci number.
// isFibonacci(8) == true
// isFibon
if isPrime(i) { // missing argument label 'number:' in call
return (1...n).filter { isPrime($0) }.reduce(0, +) // missing argument label 'number:' in call
func sumToN(n: Int) -> Int {
return (1...n).reduce(0, +)
}
```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 {
return (1...n).reduce(0, +)
}
// Tests
assert(sumToN(n: 30) == 465)
assert(sumToN(n: 100) == 5050)
assert(sumToN(n: 5) == 15)
assert(sumToN(n: 10) == 55)
assert(sumToN(n: 1) == 1)
```
func sumToN(n: Int) -> Int {
return (1...n).reduce(0, +)
}
func sumToNRecursive(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToNRecursive(n: n - 1)
}
}
func sumToNNailRecursive(n: Int, _ sum: Int = 0) -> Int {
if n == 1 {
return sum + 1
} else {
return sumToNNailRecursive(n: n - 1, sum + n)
}
}
func sumToNLoop(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
func sumToNArray(n: Int) -> Int {
return (1...n).reduce(0, +)
}
func sumToNArray2(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
func sumToNArray3(n: Int) -> Int {
var sum = 0
(1...n).forEach { sum += $0 }
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 {
return (1...n).reduce(0, +)
}
// sum_to_n_recursive is a function that sums numbers from 1 to n.
// sumToNRecursive(n: 30) == 465
// sumToNRecursive(n: 100) == 5050
// sumToNRecursive(n: 5) == 15
// sumToNRecursive(n: 10) == 55
// sumToNRecursive(n: 1) == 1
func sumToNRecursive(n: Int) -> Int {
if n == 1 {
return 1
} else {
return n + sumToNRecursive(n: n - 1)
}
}
// sum_to_n_tail_recursive is a function that sums numbers from 1 to n.
// sumToNNailRecursive(n: 30) == 465
// sumToNNailRecursive(n: 100) == 5050
// sumToNNailRecursive(n: 5) == 15
// sumToNNailRecursive(n: 10) == 55
// sumToNNailRecursive(n: 1) == 1
func sumToNNailRecursive(n: Int, _ sum: Int = 0) -> Int {
if n == 1 {
return sum + 1
} else {
return sumToNNailRecursive(n: n - 1, sum + n)
}
}
// sum_to_n_loop is a function that sums numbers from 1 to n.
// sumToNLoop(n: 30) == 465
// sumToNLoop(n: 100) == 5050
// sumToNLoop(n: 5) == 15
// sumToNLoop(n: 10) == 55
// sumToNLoop(n: 1) == 1
func sumToNLoop(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
// sum_to_n_array is a function that sums numbers from 1 to n.
// sumToNArray(n: 30) == 465
// sumToNArray(n: 100) == 5050
// sumToNArray(n: 5) == 15
// sumToNArray(n: 10) == 55
// sumToNArray(n: 1) == 1
func sumToNArray(n: Int) -> Int {
return (1...n).reduce(0, +)
}
// sum_to_n_array_2 is a function that sums numbers from 1 to n.
// sumToNArray2(n: 30) == 465
// sumToNArray2(n: 100) == 5050
// sumToNArray2(n: 5) == 15
// sumToNArray2(n: 10) == 55
// sumToNArray2(n: 1) == 1
func sumToNArray2(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
// sum_to_n_array_3 is a function that sums numbers from 1 to n.
// sumToNArray3(n: 30) == 465
// sumToNArray3(n: 100) == 5050
// sumToNArray3(n: 5) == 15
// sumToNArray3(n: 10) == 55
// sumToNArray3(n: 1) == 1
func sumToNArray3(n: Int) -> Int {
var sum = 0
(1...n).forEach { sum += $0 }
return sum
}
// sum_to_n_array_4 is a function that sums numbers from 1 to n.
// sumToNArray4(n: 30) == 465
// sumToNArray4(n: 100) == 5050
// sumToNArray4(
func sumToN(n: Int) -> Int {
return (1...n).reduce(0, +)
}
func sumToSquaredN(n: Int) -> Int {
return (1...n).map { $0 * $0 }.reduce(0, +)
}
func sumToN(n: Int) -> Int {
return (1...n).map { $0 * $0 * $0 }.reduce(0, +)
}
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((3 * n) - 1)) / 2 }.reduce(0, +)
}
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((2 * n) - 1)) }.reduce(0, +)
}
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((5 * n) - 3) / 2) }.reduce(0, +)
}
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((3 * n) - 2)) }.reduce(0, +)
}
```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 {
return (1...n).reduce(0, +)
}
// sum_to_n_squared is a function that sums numbers from 1 to n squared.
// sumToSquaredN(n: 30) == 1950
// sumToSquaredN(n: 100) == 328350
// sumToSquaredN(n: 5) == 55
// sumToSquaredN(n: 10) == 385
// sumToSquaredN(n: 1) == 1
func sumToSquaredN(n: Int) -> Int {
return (1...n).map { $0 * $0 }.reduce(0, +)
}
// sum_to_n_cubes is a function that sums numbers from 1 to n cubed.
// sumToN(n: 30) == 3375
// sumToN(n: 100) == 10562500
// sumToN(n: 5) == 125
// sumToN(n: 10) == 1025
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return (1...n).map { $0 * $0 * $0 }.reduce(0, +)
}
// sum_to_n_pentagons is a function that sums numbers from 1 to n in pentagonal form.
// sumToN(n: 30) == 1050
// sumToN(n: 100) == 354224848179261908320
// sumToN(n: 5) == 15
// sumToN(n: 10) == 75
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((3 * n) - 1)) / 2 }.reduce(0, +)
}
// sum_to_n_hexagons is a function that sums numbers from 1 to n in hexagonal form.
// sumToN(n: 30) == 210
// sumToN(n: 100) == 152088
// sumToN(n: 5) == 10
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((2 * n) - 1)) }.reduce(0, +)
}
// sum_to_n_heptagons is a function that sums numbers from 1 to n in heptagonal form.
// sumToN(n: 30) == 350
// sumToN(n: 100) == 57028
// sumToN(n: 5) == 15
// sumToN(n: 10) == 85
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((5 * n) - 3) / 2) }.reduce(0, +)
}
// sum_to_n_octagons is a function that sums numbers from 1 to n in octagonal form.
// sumToN(n: 30) == 425
// sumToN(n: 100) == 165104
// sumToN(n: 5) == 15
// sumToN(n: 10) == 105
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return (1...n).map { (n * ((3 * n) - 2)) }.reduce(0, +)
}
// sum_to_n_nonagons is a function that sums numbers from 1 to n in nonagonal form.
// sumToN(n: 30) == 515
// sumToN
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func addBrackets(brackets: String) -> String {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return "NOT VALID"
}
stack.removeLast()
}
}
var newString = String()
for char in brackets {
if char == "(" {
newString.append(")")
} else {
newString.append(char)
}
}
for char in stack {
newString.append(")")
}
return newString
}
func validBrackets(brackets: String) -> [String] {
var stack = [Character]()
var validStrings = [String]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
}
}
for char in stack {
validStrings.append(addBrackets(brackets: brackets))
}
return validStrings
}
func validBracketsCount(brackets: String) -> Int {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return 0
}
stack.removeLast()
}
}
return stack.count + 1
}
func validBracketsCountRecursive(brackets: String) -> Int {
if correctBracketing(brackets: brackets) {
return 1
}
var count = 0
for validString in validBrackets(brackets: brackets) {
count += validBracketsCountRecursive(brackets: validString)
}
return count
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return a string with each open bracket replaced with a close bracket.
// if the string is not bracketed correctly, return the string "NOT VALID".
// addBrackets(brackets: "(") == ")"
// addBrackets(brackets: "()") == "())"
// addBrackets(brackets: "()(())") == "()()()"
// addBrackets(brackets: ")(()") == "NOT VALID"
func addBrackets(brackets: String) -> String {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return "NOT VALID"
}
stack.removeLast()
}
}
var newString = String()
for char in brackets {
if char == "(" {
newString.append(")")
} else {
newString.append(char)
}
}
for char in stack {
newString.append(")")
}
return newString
}
// brackets is a string of "(" and ")".
// return an array of all the possible strings of brackets that can be added to the end of brackets
// to balance it.
// validBrackets(brackets: "(") == ["(())"]
// validBrackets(brackets: "()") == ["(())", "()()"]
// validBrackets(brackets: "()(())") == ["(())", "()()()", "(())()", "()(())", "()()()"]
// validBrackets(brackets: ")(())") == []
func validBrackets(brackets: String) -> [String] {
var stack = [Character]()
var validStrings = [String]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
}
}
for char in stack {
validStrings.append(addBrackets(brackets: brackets))
}
return validStrings
}
// brackets is a string of "(" and ")".
// return the number of possible strings of brackets that can be added to the end of brackets
// to balance it.
// validBracketsCount(brackets: "(") == 5
// validBracketsCount(brackets: "()") == 5
// validBracketsCount(brackets: "()(())") == 1
// validBracketsCount(brackets: ")(())") == 0
func validBracketsCount(brackets: String) -> Int {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return 0
}
stack.removeLast()
}
}
return stack.count + 1
}
// brackets is a string of "(" and ")".
// return the number of valid strings of brackets that can be created from brackets.
// validBracketsCountRecursive(brackets: "(") == 5
// validBracketsCountRecursive(brackets: "()") == 5
// validBracketsCountRecursive(brackets: "()(())") == 1
// validBracketsCountRecursive(brackets: ")(())") == 0
func validBracketsCountRecursive(brackets: String) -> Int {
if correctBracketing(brackets: brackets) {
return 1
}
var count = 0
for validString in validBrackets(brackets: brackets) {
count += validBracketsCountRecursive(brackets: validString)
}
return count
}
// brackets is a string of "(" and ")".
// return the number of valid strings of brackets that can be created from brackets.
// validBracketsCountDynamic(brackets: "(") == 5
// validBracketsCountDynamic(brackets: "()") == 5
// validBracketsCountDynamic(
for char in stack { // immutable value 'char' was never used; consider replacing with '_' or removing it
for char in stack { // immutable value 'char' was never used; consider replacing with '_' or removing it
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
//: [Next](@next)
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return false
} else {
stack.removeLast()
}
}
}
return stack.count == 0
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else if char == ")" {
if stack.count == 0 {
return false
} else {
stack.removeLast()
}
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "")) // true
assert(correctBracketing(brackets: "(")) // false
assert(correctBracketing(brackets: "()")) // true
assert(correctBracketing(brackets: "(()())")) // true
assert(correctBracketing(brackets: ")(()")) // false
assert(correctBracketing(brackets: ")(()(")) // false
assert(correctBracketing(brackets: ")(()()")) // false
assert(correctBracketing(brackets: ")(()()(")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing(brackets: ")(()(((((")) // false
assert(correctBracketing
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func unmatchedClosingBrackets(brackets: String) -> Int {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return 1
}
stack.removeLast()
}
}
return stack.count
}
func unmatchedOpeningBrackets(brackets: String) -> Int {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return 1
}
stack.removeLast()
}
}
return stack.count
}
func balancedBrackets(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func unbalancedBrackets(brackets: String) -> Int {
var stack = [Character]()
var count = 0
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
count += 1
} else {
stack.removeLast()
}
}
}
return count + stack.count
}
func unbalancedBrackets2(brackets: String) -> Int {
var stack = [Character]()
var count = 0
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
count += 1
} else {
stack.removeLast()
}
}
}
return count + stack.count
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return the number of ")" that don't have a corresponding "(".
// unmatchedClosingBrackets(brackets: "(") == 1
// unmatchedClosingBrackets(brackets: "()") == 0
// unmatchedClosingBrackets(brackets: "(()())") == 0
// unmatchedClosingBrackets(brackets: ")(()") == 2
func unmatchedClosingBrackets(brackets: String) -> Int {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return 1
}
stack.removeLast()
}
}
return stack.count
}
// brackets is a string of "(" and ")".
// return the number of "(" that don't have a corresponding ")"
// unmatchedOpeningBrackets(brackets: "(") == 0
// unmatchedOpeningBrackets(brackets: "()") == 0
// unmatchedOpeningBrackets(brackets: "(()())") == 0
// unmatchedOpeningBrackets(brackets: ")(()") == 1
func unmatchedOpeningBrackets(brackets: String) -> Int {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return 1
}
stack.removeLast()
}
}
return stack.count
}
// brackets is a string of "(" and ")".
// return true if there are the same number of "(" and ")".
// balancedBrackets(brackets: "(") == false
// balancedBrackets(brackets: "()") == true
// balancedBrackets(brackets: "(()())") == true
// balancedBrackets(brackets: ")(()") == false
func balancedBrackets(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return the number of "(" and ")" that don't have a corresponding "(" or ")".
// unbalancedBrackets(brackets: "(") == 1
// unbalancedBrackets(brackets: "()") == 0
// unbalancedBrackets(brackets: "(()())") == 0
// unbalancedBrackets(brackets: ")(()") == 2
func unbalancedBrackets(brackets: String) -> Int {
var stack = [Character]()
var count = 0
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
count += 1
} else {
stack.removeLast()
}
}
}
return count + stack.count
}
// brackets is a string of "(" and ")".
// return the number of "(" and ")" that don't have a corresponding "(" or ")".
// unbalancedBrackets(brackets: "(") == 1
// unbalancedBrackets(brackets: "()") == 0
// unbalancedBrackets(brackets: "(()())") == 0
// unbalancedBrackets(brackets: ")(()") == 2
func unbalancedBrackets2(brackets: String) -> Int {
var stack = [Character]()
var count = 0
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
count += 1
} else {
stack.removeLast()
}
}
}
return count + stack.count
}
//
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
//: [Next](@next)
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "")) // true
assert(correctBracketing(brackets: "(")) // false
assert(correctBracketing(brackets: "()")) // true
assert(correctBracketing(brackets: "(()())")) // true
assert(correctBracketing(brackets: ")(()")) // false
assert(correctBracketing(brackets: ")(()(")) // false
assert(correctBracketing(brackets: ")(()()")) // false
assert(correctBracketing(brackets: ")(()()(")) // false
assert(correctBracketing(brackets: ")(()()()(")) // false
assert(correctBracketing(brackets: ")(()()()(((()))(")) // false
assert(correctBracketing(brackets: ")(()()()(((()))()(")) // false
assert(correctBracketing(brackets: ")(()()()(((()))()(()))(")) // false
assert(correctBracketing(brackets: ")(()()()(((()))()(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()
//: [Next](@next)
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func mismatchedBrackets(brackets: String) -> [Int] {
var stack = [Int]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append(index)
} else {
if stack.count == 0 {
return [index]
}
stack.removeLast()
}
}
return stack
}
func correctedBrackets(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
stack.removeLast()
}
}
}
result += String(stack.reversed())
return result
}
func correctedBrackets2(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
stack.removeLast()
}
}
}
result += String(stack.reversed())
return result
}
func correctedBrackets3(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
stack.removeLast()
}
}
}
result += String(stack.reversed())
return result
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return the number of indices where the brackets are mismatched.
// mismatchedBrackets(brackets: "(") == [0]
// mismatchedBrackets(brackets: "()") == []
// mismatchedBrackets(brackets: "(()())") == []
// mismatchedBrackets(brackets: ")(()") == [0, 1, 2, 3]
func mismatchedBrackets(brackets: String) -> [Int] {
var stack = [Int]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append(index)
} else {
if stack.count == 0 {
return [index]
}
stack.removeLast()
}
}
return stack
}
// brackets is a string of "(" and ")".
// return a string containing the brackets in the correct order.
// correctedBrackets(brackets: "(") == "()"
// correctedBrackets(brackets: "()") == "()"
// correctedBrackets(brackets: "(()())") == "()()"
// correctedBrackets(brackets: ")(()") == "()()"
func correctedBrackets(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
stack.removeLast()
}
}
}
result += String(stack.reversed())
return result
}
// brackets is a string of "(" and ")".
// return a string containing the brackets in the correct order.
// correctedBrackets(brackets: "(") == "()"
// correctedBrackets(brackets: "()") == "()"
// correctedBrackets(brackets: "(()())") == "()()"
// correctedBrackets(brackets: ")(()") == "()()"
func correctedBrackets2(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
stack.removeLast()
}
}
}
result += String(stack.reversed())
return result
}
// brackets is a string of "(" and ")".
// return a string containing the brackets in the correct order.
// correctedBrackets(brackets: "(") == "()"
// correctedBrackets(brackets: "()") == "()"
// correctedBrackets(brackets: "(()())") == "()()"
// correctedBrackets(brackets: ")(()") == "()()"
func correctedBrackets3(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
stack.removeLast()
}
}
}
result += String(stack.reversed())
return result
}
// brackets is a string of "(" and ")".
// return a string containing the brackets in the correct order.
// correctedBrackets(brackets: "(") == "()"
// correctedBrackets(brackets: "()") == "()"
// correctedBrackets(brackets: "(()())") == "()()"
// correctedBrackets(brackets: ")(()") == "()()"
func correctedBrackets4(brackets: String) -> String {
var stack = [Character]()
var result = ""
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else {
if stack.count == 0 {
result += ")"
} else {
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// Test cases
assert(correctBracketing(brackets: "")) // true
assert(correctBracketing(brackets: "(")) // false
assert(correctBracketing(brackets: "()")) // true
assert(correctBracketing(brackets: "(()())")) // true
assert(correctBracketing(brackets: ")(()")) // false
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func correctBracketing2(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
if stack.removeLast()!= "(" {
return false
}
}
}
return stack.count == 0
}
func correctBracketing3(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
if stack.removeLast()!= "(" {
return false
}
}
}
return stack.count == 0
}
func correctBracketing4(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
if stack.removeLast()!= "(" {
return false
}
}
}
return stack.count == 0
}
func correctBracketing5(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func correctBracketing6(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing2(brackets: "(") == false
// correctBracketing2(brackets: "()") == true
// correctBracketing2(brackets: "(()())") == true
// correctBracketing2(brackets: ")(()") == false
func correctBracketing2(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
if stack.removeLast()!= "(" {
return false
}
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing3(brackets: "(") == false
// correctBracketing3(brackets: "()") == true
// correctBracketing3(brackets: "(()())") == true
// correctBracketing3(brackets: ")(()") == false
func correctBracketing3(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
if stack.removeLast()!= "(" {
return false
}
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing4(brackets: "(") == false
// correctBracketing4(brackets: "()") == true
// correctBracketing4(brackets: "(()())") == true
// correctBracketing4(brackets: ")(()") == false
func correctBracketing4(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
if stack.removeLast()!= "(" {
return false
}
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing5(brackets: "(") == false
// correctBracketing5(brackets: "()") == true
// correctBracketing5(brackets: "(()())") == true
// correctBracketing5(brackets: ")(()") == false
func correctBracketing5(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing6(brackets: "(") == false
// correctBracketing6(brackets: "()") == true
// correctBracketing6(brackets: "(()())") == true
// correctBracketing6(brackets: ")(()") == false
func correctBracketing6(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing7(brackets: "(") == false
// correctBracketing7(brackets: "()") == true
// correct
if stack.removeLast()!= "(" { // cannot force unwrap value of non-optional type 'Character'
if stack.removeLast()!= "(" { // '=' must have consistent whitespace on both sides
if stack.removeLast()!= "(" { // use of '=' in a boolean context, did you mean '=='?
if stack.removeLast()!= "(" { // use of '=' in a boolean context, did you mean '=='?
if stack.removeLast()!= "(" { // cannot force unwrap value of non-optional type 'Character'
if stack.removeLast()!= "(" { // '=' must have consistent whitespace on both sides
if stack.removeLast()!= "(" { // cannot force unwrap value of non-optional type 'Character'
if stack.removeLast()!= "(" { // '=' must have consistent whitespace on both sides
if stack.removeLast()!= "(" { // use of '=' in a boolean context, did you mean '=='?
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
func correctedBrackets(brackets: String) -> String {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.count == 0 {
return ""
}
stack.removeLast()
}
}
return String(stack.reversed())
}
func openingBrackets(brackets: String) -> [Int] {
var stack = [Int]()
var openingBrackets = [Int]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append(index)
} else if bracket == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
}
}
return stack
}
func closingBrackets(brackets: String) -> [Int] {
var stack = [Int]()
var closingBrackets = [Int]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append(index)
} else if bracket == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
closingBrackets.append(index)
}
}
return closingBrackets
}
func openingAndClosingBrackets(brackets: String) -> [[Int]] {
var stack = [[Int]]()
var openingAndClosingBrackets = [[Int]]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append([index, index])
} else if bracket == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
openingAndClosingBrackets.append([stack.last![0], index])
}
}
return openingAndClosingBrackets
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
// brackets is a string of "(" and ")".
// return a string with each open bracket replaced with a closing bracket.
// if no closing bracket can be found, return an empty string.
// correctedBrackets(brackets: "(") == ")"
// correctedBrackets(brackets: "()") == ")"
// correctedBrackets(brackets: "(()())") == ")))"
// correctedBrackets(brackets: ")(()") == ""
func correctedBrackets(brackets: String) -> String {
var stack = [Character]()
for bracket in brackets {
if bracket == "(" {
stack.append(bracket)
} else if bracket == ")" {
if stack.count == 0 {
return ""
}
stack.removeLast()
}
}
return String(stack.reversed())
}
// brackets is a string of "(" and ")".
// return an array of the indexes of the opening brackets.
// openingBrackets(brackets: "(") == [0]
// openingBrackets(brackets: "()") == [0, 1]
// openingBrackets(brackets: "(()())") == [0, 1, 3, 5]
// openingBrackets(brackets: ")(()") == [1, 3]
func openingBrackets(brackets: String) -> [Int] {
var stack = [Int]()
var openingBrackets = [Int]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append(index)
} else if bracket == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
}
}
return stack
}
// brackets is a string of "(" and ")".
// return an array of the indexes of the closing brackets.
// closingBrackets(brackets: "(") == []
// closingBrackets(brackets: "()") == [1]
// closingBrackets(brackets: "(()())") == [7, 5]
// closingBrackets(brackets: ")(()") == [3, 1]
func closingBrackets(brackets: String) -> [Int] {
var stack = [Int]()
var closingBrackets = [Int]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append(index)
} else if bracket == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
closingBrackets.append(index)
}
}
return closingBrackets
}
// brackets is a string of "(" and ")".
// return an array of the indexes of the opening and closing brackets.
// openingAndClosingBrackets(brackets: "(") == [[0, 0]]
// openingAndClosingBrackets(brackets: "()") == [[0, 0], [1, 1]]
// openingAndClosingBrackets(brackets: "(()())") == [[0, 0], [1, 1], [3, 3], [5, 5]]
// openingAndClosingBrackets(brackets: ")(()") == [[1, 1], [3, 3]]
func openingAndClosingBrackets(brackets: String) -> [[Int]] {
var stack = [[Int]]()
var openingAndClosingBrackets = [[Int]]()
for (index, bracket) in brackets.enumerated() {
if bracket == "(" {
stack.append([index, index])
} else if bracket == ")" {
if stack.count == 0 {
return []
}
stack.removeLast()
openingAndClosingBrackets.append([stack.last![0], index])
}
}
return openingAndClosingBrackets
}
// brackets is a string of "(" and ")".
// return an array of the indexes of the opening and closing brackets.
// openingAndClosingBrackets(brackets: "(") == [[
var openingBrackets = [Int]() // initialization of variable 'openingBrackets' was never used; consider replacing with assignment to '_' or removing it
func derivative(xs: [Int]) -> [Int] {
var ys = [Int]()
for i in 0..<xs.count {
if i > 0 {
ys.append(xs[i] * i)
}
}
return ys
}
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func evaluate(xs: [Int]) -> Int {
return xs[0] + evaluate(xs: Array(xs[1...]), x: 1)
}
func add(xs: [Int], ys: [Int], x: Int) -> Int {
return evaluate(xs: xs, x: x) + evaluate(xs: ys, x: x)
}
func add(xs: [Int], ys: [Int]) -> Int {
return evaluate(xs: xs) + evaluate(xs: ys)
}
func subtract(xs: [Int], ys: [Int], x: Int) -> Int {
return evaluate(xs: xs, x: x) - evaluate(xs: ys, x: x)
}
func subtract(xs: [Int], ys: [Int]) -> Int {
return evaluate(xs: xs) - evaluate(xs: ys)
}
func multiply(xs: [Int], ys: [Int], x: Int) -> Int {
return add(
xs: add(
xs: multiply(xs: xs, ys: ys, x: x),
ys: multiply(xs: ys, ys: derivative(xs: xs), x: x)
),
ys: multiply(xs: xs, ys: derivative(xs: ys), x: x)
)
}
func multiply(xs: [Int], ys: [Int]) -> Int {
return add(
xs: add(
xs: multiply(xs: xs, ys: ys),
ys: multiply(xs: ys, ys: derivative(xs: xs))
),
ys: multiply(xs: xs, ys: derivative(xs: ys))
)
}
func divide(xs: [Int], ys: [Int], x: Int) -> Int {
return multiply(
xs: subtract(
xs: xs,
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: x)))
),
ys: ys,
x: x
)
}
func divide(xs: [Int], ys: [Int]) -> Int {
return multiply(
xs: subtract(
xs: xs,
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: xs)))
),
ys: ys
)
}
```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 ys = [Int]()
for i in 0..<xs.count {
if i > 0 {
ys.append(xs[i] * i)
}
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `x`.
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int]) -> Int {
return xs[0] + evaluate(xs: Array(xs[1...]), x: 1)
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of a polynomial.
// Return value of the polynomial `xs + ys` evaluated at `x`.
func add(xs: [Int], ys: [Int], x: Int) -> Int {
return evaluate(xs: xs, x: x) + evaluate(xs: ys, x: x)
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of a polynomial.
// Return value of the polynomial `xs + ys` evaluated at `xs`.
func add(xs: [Int], ys: [Int]) -> Int {
return evaluate(xs: xs) + evaluate(xs: ys)
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of a polynomial.
// Return value of the polynomial `xs - ys` evaluated at `x`.
func subtract(xs: [Int], ys: [Int], x: Int) -> Int {
return evaluate(xs: xs, x: x) - evaluate(xs: ys, x: x)
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of a polynomial.
// Return value of the polynomial `xs - ys` evaluated at `xs`.
func subtract(xs: [Int], ys: [Int]) -> Int {
return evaluate(xs: xs) - evaluate(xs: ys)
}
// xs and ys represent coefficients of two polynomials.
// Return value of the polynomial `xs * ys` evaluated at `x`.
func multiply(xs: [Int], ys: [Int], x: Int) -> Int {
return add(
xs: add(
xs: multiply(xs: xs, ys: ys, x: x),
ys: multiply(xs: ys, ys: derivative(xs: xs), x: x)
),
ys: multiply(xs: xs, ys: derivative(xs: ys), x: x)
)
}
// xs and ys represent coefficients of two polynomials.
// Return value of the polynomial `xs * ys` evaluated at `xs`.
func multiply(xs: [Int], ys: [Int]) -> Int {
return add(
xs: add(
xs: multiply(xs: xs, ys: ys),
ys: multiply(xs: ys, ys: derivative(xs: xs))
),
ys: multiply(xs: xs, ys: derivative(xs: ys))
)
}
// xs and ys represent coefficients of two polynomials.
// Return value of the polynomial `xs / ys` evaluated at `x`.
func divide(xs: [Int], ys: [Int], x: Int) -> Int {
return multiply(
xs: subtract(
xs: xs,
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: x)))
),
ys: ys,
x: x
)
}
// xs and ys represent coefficients of two polynomials.
// Return value of the polynomial `xs / ys` evaluated at `xs`.
func divide(xs: [Int], ys: [Int]) -> Int {
return multiply(
xs: subtract(
xs: xs,
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: xs)))
),
ys: ys
)
}
// xs and ys represent coefficients of two polynomials.
// Return value of the polynomial `xs % ys` evaluated at `xs`.
func modulo(xs: [Int], ys: [Int]) ->
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
xs: add( // cannot convert value of type 'Int' to expected argument type '[Int]'
xs: multiply(xs: xs, ys: ys, x: x), // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: derivative(xs: xs), x: x) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: xs, ys: derivative(xs: ys), x: x) // cannot convert value of type 'Int' to expected argument type '[Int]'
xs: add( // cannot convert value of type 'Int' to expected argument type '[Int]'
xs: multiply(xs: xs, ys: ys), // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: derivative(xs: xs)) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: xs, ys: derivative(xs: ys)) // cannot convert value of type 'Int' to expected argument type '[Int]'
xs: subtract( // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: x))) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: x))) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: x))) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: x))) // cannot convert value of type 'Int' to expected argument type '[Int]'
xs: subtract( // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: xs))) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: xs))) // cannot convert value of type 'Int' to expected argument type '[Int]'
ys: multiply(xs: ys, ys: subtract(xs: xs, ys: multiply(xs: ys, ys: xs))) // cannot convert value of type 'Int' to expected argument type '[Int]'
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count - 1 {
result.append(xs[i] * (i + 1))
}
return result
}
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func callEvaluate(xs: [Int], x: Int) -> Int {
return evaluate(xs: xs, x: x)
}
func add(xs1: [Int], xs2: [Int], x: Int) -> Int {
return evaluate(xs: xs1, x: x) + evaluate(xs: xs2, x: x)
}
func callAdd(xs1: [Int], xs2: [Int], x: Int) -> Int {
return add(xs1: xs1, xs2: xs2, x: x)
}
func subtract(xs1: [Int], xs2: [Int], x: Int) -> Int {
return evaluate(xs: xs1, x: x) - evaluate(xs: xs2, x: x)
}
func callSubtract(xs1: [Int], xs2: [Int], x: Int) -> Int {
return subtract(xs1: xs1, xs2: xs2, x: x)
}
func multiply(xs1: [Int], xs2: [Int], x: Int) -> Int {
var result = [Int]()
for i in 0...xs1.count + xs2.count - 2 {
var sum = 0
for j in 0...min(i, xs2.count - 1) {
if j < xs1.count {
sum += xs1[j] * xs2[i - j]
}
}
result.append(sum)
}
return result[0]
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<xs.count - 1 {
result.append(xs[i] * (i + 1))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at x.
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at x.
// This is the same as evaluate(xs: xs, x: x)
func callEvaluate(xs: [Int], x: Int) -> Int {
return evaluate(xs: xs, x: x)
}
// xs1 and xs2 represent coefficients of two polynomials.
// xs1[0] + xs1[1] * x + xs1[2] * x^2 +....
// xs2[0] + xs2[1] * x + xs2[2] * x^2 +....
// Return value of the polynomial evaluated at x.
func add(xs1: [Int], xs2: [Int], x: Int) -> Int {
return evaluate(xs: xs1, x: x) + evaluate(xs: xs2, x: x)
}
// xs1 and xs2 represent coefficients of two polynomials.
// xs1[0] + xs1[1] * x + xs1[2] * x^2 +....
// xs2[0] + xs2[1] * x + xs2[2] * x^2 +....
// Return value of the polynomial evaluated at x.
func callAdd(xs1: [Int], xs2: [Int], x: Int) -> Int {
return add(xs1: xs1, xs2: xs2, x: x)
}
// xs1 and xs2 represent coefficients of two polynomials.
// xs1[0] + xs1[1] * x + xs1[2] * x^2 +....
// xs2[0] + xs2[1] * x + xs2[2] * x^2 +....
// Return value of the polynomial evaluated at x.
func subtract(xs1: [Int], xs2: [Int], x: Int) -> Int {
return evaluate(xs: xs1, x: x) - evaluate(xs: xs2, x: x)
}
// xs1 and xs2 represent coefficients of two polynomials.
// xs1[0] + xs1[1] * x + xs1[2] * x^2 +....
// xs2[0] + xs2[1] * x + xs2[2] * x^2 +....
// Return value of the polynomial evaluated at x.
func callSubtract(xs1: [Int], xs2: [Int], x: Int) -> Int {
return subtract(xs1: xs1, xs2: xs2, x: x)
}
// xs1 and xs2 represent coefficients of two polynomials.
// xs1[0] + xs1[1] * x + xs1[2] * x^2 +....
// xs2[0] + xs2[1] * x + xs2[2] * x^2 +....
// Return value of the polynomial evaluated at x.
func multiply(xs1: [Int], xs2: [Int], x: Int) -> Int {
var result = [Int]()
for i in 0...xs1.count + xs2.count - 2 {
var sum = 0
for j in 0...min(i, xs2.count - 1) {
if j < xs1.count {
sum += xs1[j] * xs2[i - j]
}
}
result.append(sum)
}
return result[0]
}
// xs1 and xs2 represent coefficients of two polynomials.
// xs1[0] + xs1[1] * x + xs1[2] * x^2 +....
// xs2[0] + xs2[1] * x + xs2[2] * x^2 +....
//
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
func derivative(xs: [Int]) -> [Int] {
guard xs.count > 0 else {
return []
}
var ys = [Int](repeating: 0, count: xs.count - 1)
for i in 0..<ys.count {
ys[i] = xs[i + 1] * (i + 1)
}
return ys
}
func evaluate(xs: [Int], at x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * Int(pow(Double(x), Double(i)))
}
return result
}
func evaluate(xs: [Int], ys: [Int], at x: Int) -> Int {
return evaluate(xs, at: x) - evaluate(ys, at: x)
}
func evaluate(xs: [Int], ys: [Int], at x: Double) -> Double {
return Double(evaluate(xs, ys: ys, at: Int(x)))
}
func evaluate(xs: [Int], ys: [Int], at x: Float) -> Float {
return Float(evaluate(xs, ys: ys, at: Int(x)))
}
func evaluate(xs: [Int], ys: [Int], at x: CGFloat) -> CGFloat {
return CGFloat(evaluate(xs, ys: ys, at: Int(x)))
}
func evaluate(xs: [Int], ys: [Int], at x: Decimal) -> Decimal {
return Decimal(evaluate(xs, ys: ys, at: Int(x)))
}
func evaluate(xs: [Int], ys: [Int], at x: Rational) -> Rational {
return Rational(evaluate(xs, ys: ys, at: Int(x)))
}
func evaluate(xs: [Int], ys: [Int], at x: Complex<Int>) -> Complex<Int> {
return Complex<Int>(evaluate(xs, ys: ys, at: Int(x)))
}
func evaluate(xs: [Int], ys: [Int], at x: Complex<Float>) -> Complex<Float> {
return Complex<Float>(evaluate(xs, ys: ys, at: Float(x)))
}
```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] {
guard xs.count > 0 else {
return []
}
var ys = [Int](repeating: 0, count: xs.count - 1)
for i in 0..<ys.count {
ys[i] = xs[i + 1] * (i + 1)
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], at x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * Int(pow(Double(x), Double(i)))
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Int) -> Int {
return evaluate(xs, at: x) - evaluate(ys, at: x)
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Double) -> Double {
return Double(evaluate(xs, ys: ys, at: Int(x)))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Float) -> Float {
return Float(evaluate(xs, ys: ys, at: Int(x)))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: CGFloat) -> CGFloat {
return CGFloat(evaluate(xs, ys: ys, at: Int(x)))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Decimal) -> Decimal {
return Decimal(evaluate(xs, ys: ys, at: Int(x)))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Rational) -> Rational {
return Rational(evaluate(xs, ys: ys, at: Int(x)))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Complex<Int>) -> Complex<Int> {
return Complex<Int>(evaluate(xs, ys: ys, at: Int(x)))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// ys[0] + ys[1] * x + ys[2] * x^2 +....
// Return value of the polynomial evaluated at the given point x.
func evaluate(xs: [Int], ys: [Int], at x: Complex<Float>) -> Complex<Float> {
return Complex<Float>(evaluate(xs, ys: ys, at: Float(x)))
}
return evaluate(xs, at: x) - evaluate(ys, at: x) // missing argument label 'xs:' in call
return evaluate(xs, at: x) - evaluate(ys, at: x) // missing argument label 'xs:' in call
return Double(evaluate(xs, ys: ys, at: Int(x))) // missing argument label 'xs:' in call
return Float(evaluate(xs, ys: ys, at: Int(x))) // missing argument label 'xs:' in call
return CGFloat(evaluate(xs, ys: ys, at: Int(x))) // missing argument label 'xs:' in call
return Decimal(evaluate(xs, ys: ys, at: Int(x))) // initializer 'init(_:)' requires that 'Decimal' conform to 'BinaryInteger'
return Decimal(evaluate(xs, ys: ys, at: Int(x))) // missing argument label 'xs:' in call
func evaluate(xs: [Int], ys: [Int], at x: Rational) -> Rational { // cannot find type 'Rational' in scope
func evaluate(xs: [Int], ys: [Int], at x: Rational) -> Rational { // cannot find type 'Rational' in scope
func evaluate(xs: [Int], ys: [Int], at x: Complex<Int>) -> Complex<Int> { // cannot find type 'Complex' in scope
func evaluate(xs: [Int], ys: [Int], at x: Complex<Int>) -> Complex<Int> { // cannot find type 'Complex' in scope
func evaluate(xs: [Int], ys: [Int], at x: Complex<Float>) -> Complex<Float> { // cannot find type 'Complex' in scope
func evaluate(xs: [Int], ys: [Int], at x: Complex<Float>) -> Complex<Float> { // cannot find type 'Complex' in scope
func derivative(xs: [Int]) -> [Int] {
guard xs.count > 0 else {
return []
}
var ys = [Int](repeating: 0, count: xs.count - 1)
for i in 1..<xs.count {
ys[i - 1] = xs[i] * i
}
return ys
}
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func evaluate(xs: [Int]) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(i, xs.count - 1)
}
return result
}
func multiply(xs: [Int], ys: [Int]) -> [Int] {
var zs = [Int](repeating: 0, count: xs.count + ys.count - 1)
for i in 0..<xs.count {
for j in 0..<ys.count {
zs[i + j] += xs[i] * ys[j]
}
}
return zs
}
func add(xs: [Int], ys: [Int]) -> [Int] {
var zs = [Int](repeating: 0, count: max(xs.count, ys.count))
for i in 0..<zs.count {
if i < xs.count {
zs[i] += xs[i]
}
if i < ys.count {
zs[i] += ys[i]
}
}
return zs
}
func subtract(xs: [Int], ys: [Int]) -> [Int] {
return add(xs, ys: ys.map({ -$0 }))
}
func divide(xs: [Int], ys: [Int]) -> (quotient: [Int], remainder: [Int]) {
guard xs.count >= ys.count else {
return ([], xs)
}
var quotient = [Int](repeating: 0, count: xs.count - ys.count + 1)
var remainder = [Int](xs)
for i in (0..<quotient.count).reversed() {
quotient[i] = remainder[i] / ys[0]
let ys_scaled = ys.map({ $0 * quotient[i] })
remainder = subtract(remainder, ys: ys_scaled)
}
return (quotient, remainder)
}
func modulo(xs: [Int], ys: [Int]) -> [Int] {
let (q, _) = divide(xs, ys: ys)
return q
}
```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] {
guard xs.count > 0 else {
return []
}
var ys = [Int](repeating: 0, count: xs.count - 1)
for i in 1..<xs.count {
ys[i - 1] = xs[i] * i
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `x`.
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int]) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(i, xs.count - 1)
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of another polynomial.
// Return value of the polynomial represented by `xs`
// multiplied by the polynomial represented by `ys`.
func multiply(xs: [Int], ys: [Int]) -> [Int] {
var zs = [Int](repeating: 0, count: xs.count + ys.count - 1)
for i in 0..<xs.count {
for j in 0..<ys.count {
zs[i + j] += xs[i] * ys[j]
}
}
return zs
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of another polynomial.
// Return value of the polynomial represented by `xs`
// added to the polynomial represented by `ys`.
func add(xs: [Int], ys: [Int]) -> [Int] {
var zs = [Int](repeating: 0, count: max(xs.count, ys.count))
for i in 0..<zs.count {
if i < xs.count {
zs[i] += xs[i]
}
if i < ys.count {
zs[i] += ys[i]
}
}
return zs
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of another polynomial.
// Return value of the polynomial represented by `xs`
// subtracted from the polynomial represented by `ys`.
func subtract(xs: [Int], ys: [Int]) -> [Int] {
return add(xs, ys: ys.map({ -$0 }))
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of another polynomial.
// Return value of the polynomial represented by `xs`
// divided by the polynomial represented by `ys`.
func divide(xs: [Int], ys: [Int]) -> (quotient: [Int], remainder: [Int]) {
guard xs.count >= ys.count else {
return ([], xs)
}
var quotient = [Int](repeating: 0, count: xs.count - ys.count + 1)
var remainder = [Int](xs)
for i in (0..<quotient.count).reversed() {
quotient[i] = remainder[i] / ys[0]
let ys_scaled = ys.map({ $0 * quotient[i] })
remainder = subtract(remainder, ys: ys_scaled)
}
return (quotient, remainder)
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of another polynomial.
// Return value of the polynomial represented by `xs`
// modulo the polynomial represented by `ys`.
func modulo(xs: [Int], ys: [Int]) -> [Int] {
let (q, _) = divide(xs, ys: ys)
return q
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of another polynomial.
// Return value of the polynomial represented by `xs`
// raised to the power of `ys`.
func power(xs: [Int], ys: [Int]) -> [Int] {
guard xs.count > 0 else {
return []
}
guard ys.count > 0 else {
return
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += xs[i] * pow(i, xs.count - 1) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(i, xs.count - 1) // cannot convert value of type 'Decimal' to expected argument type 'Int'
return add(xs, ys: ys.map({ -$0 })) // missing argument label 'xs:' in call
remainder = subtract(remainder, ys: ys_scaled) // missing argument label 'xs:' in call
let (q, _) = divide(xs, ys: ys) // missing argument label 'xs:' in call
func derivative(xs: [Int]) -> [Int] {
var ys = [Int]()
for i in 0..<xs.count - 1 {
ys.append(xs[i] * (i + 1))
}
return ys
}
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: Decimal) -> Decimal {
var result = Decimal()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: RationalNumber) -> RationalNumber {
var result = RationalNumber()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: ComplexNumber) -> ComplexNumber {
var result = ComplexNumber()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: BigFloat) -> BigFloat {
var result = BigFloat()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: BigDouble) -> BigDouble {
var result = BigDouble()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
func evaluate(xs: [Int], x: Decimal128) -> Decimal128 {
var result = Decimal128()
for i in 0..<xs.count {
result += xs[i] * x.power(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 ys = [Int]()
for i in 0..<xs.count - 1 {
ys.append(xs[i] * (i + 1))
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: Decimal) -> Decimal {
var result = Decimal()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: RationalNumber) -> RationalNumber {
var result = RationalNumber()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: ComplexNumber) -> ComplexNumber {
var result = ComplexNumber()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: BigFloat) -> BigFloat {
var result = BigFloat()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: BigDouble) -> BigDouble {
var result = BigDouble()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial for the given value of x.
func evaluate(xs: [Int], x: Decimal128) -> Decimal128 {
var result = Decimal128()
for i in 0..<xs.count {
result += xs[i] * x.power(i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1
result += xs[i] * x.power(i) // value of type 'Int' has no member 'power'
result += Double(xs[i]) * x.power(i) // value of type 'Double' has no member 'power'
result += Float(xs[i]) * x.power(i) // value of type 'Float' has no member 'power'
result += Float(xs[i]) * x.power(i) // cannot convert value of type 'Float' to expected argument type 'Double'
result += Float(xs[i]) * x.power(i) // cannot convert value of type 'Float' to expected argument type 'Double'
return result // cannot convert return expression of type 'Double' to return type 'Float'
result += xs[i] * x.power(i) // value of type 'Decimal' has no member 'power'
result += xs[i] * x.power(i) // referencing operator function '+=' on 'RangeReplaceableCollection' requires that 'Decimal' conform to 'RangeReplaceableCollection'
func evaluate(xs: [Int], x: RationalNumber) -> RationalNumber { // cannot find type 'RationalNumber' in scope
func evaluate(xs: [Int], x: RationalNumber) -> RationalNumber { // cannot find type 'RationalNumber' in scope
var result = RationalNumber() // cannot find 'RationalNumber' in scope
func evaluate(xs: [Int], x: ComplexNumber) -> ComplexNumber { // cannot find type 'ComplexNumber' in scope
func evaluate(xs: [Int], x: ComplexNumber) -> ComplexNumber { // cannot find type 'ComplexNumber' in scope
var result = ComplexNumber() // cannot find 'ComplexNumber' in scope
func evaluate(xs: [Int], x: BigFloat) -> BigFloat { // cannot find type 'BigFloat' in scope
func evaluate(xs: [Int], x: BigFloat) -> BigFloat { // cannot find type 'BigFloat' in scope
var result = BigFloat() // cannot find 'BigFloat' in scope
func evaluate(xs: [Int], x: BigDouble) -> BigDouble { // cannot find type 'BigDouble' in scope
func evaluate(xs: [Int], x: BigDouble) -> BigDouble { // cannot find type 'BigDouble' in scope
var result = BigDouble() // cannot find 'BigDouble' in scope
func evaluate(xs: [Int], x: Decimal128) -> Decimal128 { // cannot find type 'Decimal128' in scope
func evaluate(xs: [Int], x: Decimal128) -> Decimal128 { // cannot find type 'Decimal128' in scope
var result = Decimal128() // cannot find 'Decimal128' in scope
func derivative(xs: [Int]) -> [Int] {
var ys = [Int]()
for i in 0..<xs.count - 1 {
ys.append(xs[i] * (i + 1))
}
return ys
}
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func value(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * pow(x, Double(i))
}
return result
}
func value(xs: [Double], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Double(i))
}
return result
}
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * pow(x, Float(i))
}
return result
}
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Float(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 ys = [Int]()
for i in 0..<xs.count - 1 {
ys.append(xs[i] * (i + 1))
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 2 * 2 + 4 * 2^2 + 5 * 2^3
func value(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * pow(x, Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 2 * 2 + 4 * 2^2 + 5 * 2^3
func value(xs: [Double], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 2 * 2 + 4 * 2^2 + 5 * 2^3
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * pow(x, Float(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 2 * 2 + 4 * 2^2 + 5 * 2^3
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 2 * 2 + 4 * 2^2 + 5 * 2^3
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Float(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 2 * 2 + 4
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += Float(xs[i]) * pow(x, Float(i)) // cannot convert value of type 'Float' to expected argument type 'Double'
return result // cannot convert return expression of type 'Double' to return type 'Float'
func value(xs: [Float], x: Float) -> Float { // invalid redeclaration of 'value(xs:x:)'
result += xs[i] * pow(x, Float(i)) // cannot convert value of type 'Float' to expected argument type 'Double'
return result // cannot convert return expression of type 'Double' to return type 'Float'
func derivative(xs: [Int]) -> [Int] {
var ys = [Int]()
for i in 0..<xs.count {
if i > 0 {
ys.append(xs[i] * i)
}
}
return ys
}
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func value(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * pow(x, Double(i))
}
return result
}
func value(xs: [Double], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Double(i))
}
return result
}
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * pow(x, Float(i))
}
return result
}
func value(xs: [CGFloat], x: CGFloat) -> CGFloat {
var result = CGFloat(0)
for i in 0..<xs.count {
result += xs[i] * pow(x, CGFloat(i))
}
return result
}
func value(xs: [Complex<Double>], x: Double) -> Complex<Double> {
var result = Complex<Double>(0, 0)
for i in 0..<xs.count {
result += xs[i] * pow(Complex<Double>(x, 0), Double(i))
}
return result
}
func value(xs: [Complex<Float>], x: Float) -> Complex<Float> {
var result = Complex<Float>(0, 0)
for i in 0..<xs.count {
result += xs[i] * pow(Complex<Float>(x, 0), Float(i))
}
return result
}
func value(xs: [Complex<CGFloat>], x: CGFloat) -> Complex<CGFloat> {
var result = Complex<CGFloat>(0, 0)
for i in 0..<xs.count {
result += xs[i] * pow(Complex<CGFloat>(x, 0), CGFloat(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 ys = [Int]()
for i in 0..<xs.count {
if i > 0 {
ys.append(xs[i] * i)
}
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * pow(x, Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Double], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * pow(x, Float(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [CGFloat], x: CGFloat) -> CGFloat {
var result = CGFloat(0)
for i in 0..<xs.count {
result += xs[i] * pow(x, CGFloat(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Complex<Double>], x: Double) -> Complex<Double> {
var result = Complex<Double>(0, 0)
for i in 0..<xs.count {
result += xs[i] * pow(Complex<Double>(x, 0), Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Complex<Float>], x: Float) -> Complex<Float> {
var result = Complex<Float>(0, 0)
for i in 0..<xs.count {
result += xs[i] * pow(Complex<Float>(x, 0), Float(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Complex<CGFloat>], x: CGFloat) -> Complex<CGFloat> {
var result = Complex<CGFloat>(0, 0)
for i in 0..<xs.count {
result += xs[i] * pow(Complex<CGFloat>(x, 0), CGFloat(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is the specified value.
func value(xs: [Complex
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += Float(xs[i]) * pow(x, Float(i)) // cannot convert value of type 'Float' to expected argument type 'Double'
return result // cannot convert return expression of type 'Double' to return type 'Float'
func value(xs: [Complex<Double>], x: Double) -> Complex<Double> { // cannot find type 'Complex' in scope
func value(xs: [Complex<Double>], x: Double) -> Complex<Double> { // cannot find type 'Complex' in scope
var result = Complex<Double>(0, 0) // cannot find 'Complex' in scope
func value(xs: [Complex<Float>], x: Float) -> Complex<Float> { // cannot find type 'Complex' in scope
func value(xs: [Complex<Float>], x: Float) -> Complex<Float> { // cannot find type 'Complex' in scope
var result = Complex<Float>(0, 0) // cannot find 'Complex' in scope
func value(xs: [Complex<CGFloat>], x: CGFloat) -> Complex<CGFloat> { // cannot find type 'Complex' in scope
func value(xs: [Complex<CGFloat>], x: CGFloat) -> Complex<CGFloat> { // cannot find type 'Complex' in scope
var result = Complex<CGFloat>(0, 0) // cannot find 'Complex' in scope
func derivative(xs: [Int]) -> [Int] {
var ys = [Int]()
for i in 0..<xs.count {
if i > 0 {
ys.append(xs[i] * i)
}
}
return ys
}
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func value(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * pow(x, Double(i))
}
return result
}
func value(xs: [Double], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Double(i))
}
return result
}
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * pow(x, Float(i))
}
return result
}
func value(xs: [CGFloat], x: CGFloat) -> CGFloat {
var result = CGFloat(0)
for i in 0..<xs.count {
result += xs[i] * pow(x, CGFloat(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 ys = [Int]()
for i in 0..<xs.count {
if i > 0 {
ys.append(xs[i] * i)
}
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 1 * 2 + 2 * 2^2 + 4 * 2^3 + 5 * 2^4
func value(xs: [Int], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += Double(xs[i]) * pow(x, Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 1 * 2 + 2 * 2^2 + 4 * 2^3 + 5 * 2^4
func value(xs: [Double], x: Double) -> Double {
var result = 0.0
for i in 0..<xs.count {
result += xs[i] * pow(x, Double(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 1 * 2 + 2 * 2^2 + 4 * 2^3 + 5 * 2^4
func value(xs: [Float], x: Float) -> Float {
var result = 0.0
for i in 0..<xs.count {
result += Float(xs[i]) * pow(x, Float(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 1 * 2 + 2 * 2^2 + 4 * 2^3 + 5 * 2^4
func value(xs: [CGFloat], x: CGFloat) -> CGFloat {
var result = CGFloat(0)
for i in 0..<xs.count {
result += xs[i] * pow(x, CGFloat(i))
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
// value(xs: [3, 1, 2, 4, 5], x: 2) == 3 + 1 * 2 + 2 * 2^2 + 4 * 2^3 + 5 * 2^4
func value(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial when x is specified.
// value(xs
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += Float(xs[i]) * pow(x, Float(i)) // cannot convert value of type 'Float' to expected argument type 'Double'
return result // cannot convert return expression of type 'Double' to return type 'Float'
func derivative(xs: [Int]) -> [Int] {
guard xs.count > 0 else { return [] }
var ys = Array(repeating: 0, count: xs.count - 1)
for i in 0..<ys.count {
ys[i] = xs[i + 1] * (i + 1)
}
return ys
}
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[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] {
guard xs.count > 0 else { return [] }
var ys = Array(repeating: 0, count: xs.count - 1)
for i in 0..<ys.count {
ys[i] = xs[i + 1] * (i + 1)
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `x`.
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[i])
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[i])
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[i])
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[i])
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[i])
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(n, ys[i])
}
return result
}
// xs represent coefficients of a polynomial.
// ys represent coefficients of the derivative of the polynomial.
// Assume that xs and ys have the same degree.
// Return value of the polynomial evaluated at `x` after `n` steps.
func evaluate(xs: [Int], ys: [Int], x: Int, n: Int) -> Int {
var result = 0
for i in 0..<xs
result += xs[i] * pow(x, i) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += xs[i] * pow(x, i) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(x, i) * pow(n, ys[i]) // cannot convert value of type 'Decimal' to expected argument type 'Int'
result += xs[i] * pow(x, i) * pow(n, ys[i]) // binary operator '+=' cannot be applied to two 'Int' operands
result += xs[i] * pow(x, i) * pow(n, ys[i]) // cannot convert value of type 'Int' to expected argument type 'Decimal'
result += xs[i] * pow(x, i) * pow(n, ys[i]) // binary operator '*' cannot be applied to operands of type 'Int' and 'Decimal'
result += xs[i] * pow(x, i) * pow(n, ys[i]) // cannot convert value of type 'Int' to expected argument type 'Decimal'
func derivative(xs: [Int]) -> [Int] {
guard xs.count > 0 else { return [] }
var ys = Array(repeating: 0, count: xs.count - 1)
for i in 0..<ys.count {
ys[i] = xs[i + 1] * (i + 1)
}
return ys
}
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
func evaluate(xs: [Int], xs_: [Int]) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i]
}
return result
}
func evaluate(xs: [Int], xs_: [Int], xs__:[Int]) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * xs__[i]
}
return result
}
func evaluate(xs: [Int], x: Int, x_: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(x_, i)
}
return result
}
func evaluate(xs: [Int], xs_: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * pow(x, i)
}
return result
}
func evaluate(xs: [Int], xs_: [Int], xs__:[Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * xs__[i] * pow(x, i)
}
return result
}
func evaluate(xs: [Int], x: Int, x_: Int, x__: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(x_, i) * pow(x__, i)
}
return result
}
func evaluate(xs: [Int], xs_: [Int], x: Int, x_: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * pow(x, i) * pow(x_, 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] {
guard xs.count > 0 else { return [] }
var ys = Array(repeating: 0, count: xs.count - 1)
for i in 0..<ys.count {
ys[i] = xs[i + 1] * (i + 1)
}
return ys
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `x`.
func evaluate(xs: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int], xs_: [Int]) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i]
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int], xs_: [Int], xs__:[Int]) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * xs__[i]
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `x`.
func evaluate(xs: [Int], x: Int, x_: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(x_, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int], xs_: [Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int], xs_: [Int], xs__:[Int], x: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * xs__[i] * pow(x, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `x`.
func evaluate(xs: [Int], x: Int, x_: Int, x__: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * pow(x, i) * pow(x_, i) * pow(x__, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func evaluate(xs: [Int], xs_: [Int], x: Int, x_: Int) -> Int {
var result = 0
for i in 0..<xs.count {
result += xs[i] * xs_[i] * pow(x, i) * pow(x_, i)
}
return result
}
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 +....
// Return value of the polynomial evaluated at `xs`.
func
func fibfib(n: Int) -> Int {
if n <= 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fib1 = 0
var fib2 = 1
var fib3 = 1
for _ in 3...n {
fib3 = fib1 + fib2 + fib1
fib1 = fib2
fib2 = fib3
}
return fib3
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n <= 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
var fib1 = 0
var fib2 = 1
var fib3 = 1
for _ in 3...n {
fib3 = fib1 + fib2 + fib1
fib1 = fib2
fib2 = fib3
}
return fib3
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
//: [Next](@next)
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n <= 1 {
return n
} 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 <= 1 {
return n
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
//: [Next](@next)
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n <= 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n <= 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
// fibfib(n: 13) == 233
// fibfib(n: 21) == 1597
// fibfib(n: 34) == 102334155
// fibfib(n: 55) == 354224848179261908320
// fibfib(n: 89) == 223372036854775805
// fibfib(n: 144) == 1493035223860440110933
// fibfib(n: 233) == 358221615288675212758
// fibfib(n: 377) == 1074158322928170710954
// fibfib(n: 610) == 276740158778809174553
// fibfib(n: 987) == 552587890684914945504
// fibfib(n: 1597) == 326765096549692755523
// fibfib(n: 2584) == 106102098577201905863
// fibfib(n: 4181) == 285121993844845752129
// fibfib(n: 6765) == 533481765590804953413
// fibfib(n: 10946) == 1559152353868899069439
// fibfib(n: 17711) == 361201460700884985551
// fibfib(n: 28657) == 102334155476269551725
// fibfib(n: 46368) == 253623111088675854341
// fibfib(n: 75025) == 546271035353990061021
// fibfib(n: 121393) == 1594323176442297525854
// fibfib(n: 196418) == 4782
// fibfib(n: 317811) == 10946
// fibfib(n: 514229) == 354224848179261908320
// fibfib(n: 832040) == 102334155
// fibfib(n: 1302653) == 358221615288675212758
// fibfib(n: 2176679) == 1074158322928170710954
// fibfib(n: 3524578) == 276740158778809174553
func fibfib(n: Int) -> Int {
return 0
}
```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 {
return 0
}
fibfib(n: 1) // 0
fibfib(n: 5) // 4
fibfib(n: 8) // 24
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
// fibfib(n: 1) == 0
// fibfib(n: 2) == 1
// fibfib(n: 3) == 1
// fibfib(n: 4) == 2
// fibfib(n: 5) == 3
// fibfib(n: 6) == 5
// fibfib(n: 7) == 8
// fibfib(n: 8) == 13
// fibfib(n: 9) == 21
// fibfib(n: 10) == 34
// fibfib(n: 11) == 55
// fibfib(n: 12) == 89
// fibfib(n: 13) == 144
// fibfib(n: 14) == 233
// fibfib(n: 15) == 377
// fibfib(n: 16) == 610
// fibfib(n: 17) == 987
// fibfib(n: 18) == 1597
// fibfib(n: 19) == 2584
// fibfib(n: 20) == 4181
// fibfib(n: 21) == 6765
// fibfib(n: 22) == 10946
// fibfib(n: 23) == 17711
// fibfib(n: 24) == 28657
// fibfib(n: 25) == 46368
// fibfib(n: 26) == 75025
// fibfib(n: 27) == 121393
// fibfib(n: 28) == 196418
// fibfib(n: 29) == 317811
// fibfib(n: 30) == 514229
// fibfib(n: 31) == 832040
// fibfib(n: 32) == 1303855
// fibfib(n: 33) == 2114898
// fibfib(n: 34) == 3415500
// fibfib(n: 35) == 5527977
// fibfib(n: 36) == 8944397
// fibfib(n: 37) == 14472332
// fibfib(n: 38) == 23348889
// fibfib(n: 39) == 37728062
// fibfib(n: 40) == 61030894
// fibfib(n: 41) == 98765432
// fibfib(n: 42) == 159722651
// fibfib(n: 43) == 258401458
// fibfib(n: 44) == 4181
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
//: [Next](@next)
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
// fibfib(n: 1) == 0
// fibfib(n: 2) == 1
// fibfib(n: 3) == 1
// fibfib(n: 4) == 2
// fibfib(n: 5) == 3
// fibfib(n: 6) == 5
// fibfib(n: 7) == 8
// fibfib(n: 8) == 13
// fibfib(n: 9) == 21
// fibfib(n: 10) == 34
// fibfib(n: 11) == 55
// fibfib(n: 12) == 89
// fibfib(n: 13) == 144
// fibfib(n: 14) == 233
// fibfib(n: 15) == 377
// fibfib(n: 16) == 610
// fibfib(n: 17) == 987
// fibfib(n: 18) == 1597
// fibfib(n: 19) == 2584
// fibfib(n: 20) == 4181
// fibfib(n: 21) == 6765
// fibfib(n: 22) == 10946
// fibfib(n: 23) == 17711
// fibfib(n: 24) == 28657
// fibfib(n: 25) == 46368
// fibfib(n: 26) == 75025
// fibfib(n: 27) == 121393
// fibfib(n: 28) == 196418
// fibfib(n: 29) == 317811
// fibfib(n: 30) == 514229
// fibfib(n: 31) == 832040
// fibfib(n: 32) == 1303855
// fibfib(n: 33) == 2114898
// fibfib(n: 34) == 3415500
// fibfib(n: 35) == 5527987
// fibfib(n: 36) == 8944394
// fibfib(n: 37) == 14472386
// fibfib(n: 38) == 23348890
// fibfib(n: 39) == 37728062
// fibfib(n: 40) == 61030894
// fibfib(n: 41) == 98765432
// fibfib(n: 42) == 159722691
// fibfib(n: 43) == 258401605
// fibfib(n: 44) == 418107978
// fibfib(n: 45) == 676505871
// fibfib(n: 46) == 1094603120
// fibfib(n: 47) == 1771178001
// fibfib(n: 48) == 2865782534
// fibfib(n: 49) == 4636858657
// fibfib(n: 50) == 7502597488
// fibfib(n: 51) == 1
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1)
fibfib(n: 5)
fibfib(n: 8)
//: [Next](@next)
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
func 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 fiblike(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else if n == 2 {
return 1
} else if n == 3 {
return 2
} else if n == 4 {
return 3
} else {
return fiblike(n: n-1) + fiblike(n: n-2) + fiblike(n: n-3) + fiblike(n: n-4) + fiblike(n: n-5)
}
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 0
} else if n == 2 {
return 1
} else {
return fibfib(n: n-1) + fibfib(n: n-2) + fibfib(n: n-3)
}
}
fibfib(n: 1) // 0
fibfib(n: 5) // 4
fibfib(n: 8) // 24
// The Fibonacci sequence is defined as follows:
// fib(0) == 0
// fib(1) == 1
// fib(n) == fib(n-1) + fib(n-2)
// Please write a function to efficiently compute the n-th element of the Fibonacci sequence.
// fib(n: 1) == 1
// fib(n: 5) == 5
// 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)
}
}
fib(n: 1) // 1
fib(n: 5) // 5
fib(n: 8) // 21
// The Fibonacci-like sequence is defined as follows:
// fiblike(0) == 0
// fiblike(1) == 1
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3)
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3) + fiblike(n-4) + fiblike(n-5)
// Please write a function to efficiently compute the n-th element of the Fibonacci-like sequence.
// fiblike(n: 1) == 1
// fiblike(n: 5) == 5
// fiblike(n: 8) == 21
func fiblike(n: Int) -> Int {
if n == 0 {
return 0
} else if n == 1 {
return 1
} else if n == 2 {
return 1
} else if n == 3 {
return 2
} else if n == 4 {
return 3
} else {
return fiblike(n: n-1) + fiblike(n: n-2) + fiblike(n: n-3) + fiblike(n: n-4) + fiblike(n: n-5)
}
}
fiblike(n: 1) // 1
fiblike(n: 5) // 5
fiblike(n: 8) // 21
// The Fibonacci-like sequence is defined as follows:
// fiblike(0) == 0
// fiblike(1) == 1
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3)
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3) + fiblike(n-4) + fiblike(n-5)
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3) + fiblike(n-4) + fiblike(n-5)
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3) + fiblike(n-4) + fiblike(n-5)
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3) + fiblike(n-4) + fiblike(n-5)
// fiblike(n) == fiblike(n-1) + fiblike(n-2) + fiblike(n-3) + fiblike(n-4) + fiblike(n-5)
// Please write a function to efficiently compute the n-th element of the Fibonacci-like sequence.
// fiblike(n: 1) == 1
// fiblike
func fibfib(n: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```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 {
// TODO: Write - Your - Code
return 0
}
fibfib(n: 1) == 0
fibfib(n: 5) == 4
fibfib(n: 8) == 24
//: [Next](@next)
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if s.last == char {
count += 1
}
default:
break
}
}
return count
}
func reverseVowels(s: String) -> String {
var vowels = [Character]()
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
vowels.append(char)
case "y":
if s.last == char {
vowels.append(char)
}
default:
break
}
}
vowels.reverse()
var result = ""
var vowelIndex = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
result.append(vowels[vowelIndex])
vowelIndex += 1
case "y":
if s.last == char {
result.append(vowels[vowelIndex])
vowelIndex += 1
} else {
result.append(char)
}
default:
result.append(char)
}
}
return result
}
func toUpperCase(s: String) -> String {
var result = ""
for char in s {
if String(char).lowercased()!= String(char).uppercased() {
result.append(String(char).uppercased())
} else {
result.append(char)
}
}
return result
}
func toTitleCase(s: String) -> String {
var result = ""
var capitalizeNext = true
for char in s {
if capitalizeNext {
if String(char).lowercased()!= String(char).uppercased() {
result.append(String(char).uppercased())
capitalizeNext = false
} else {
result.append(char)
}
} else {
if String(char).lowercased() == String(char).uppercased() {
result.append(char)
capitalizeNext = true
} else {
result.append(String(char).lowercased())
}
}
}
return result
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if s.last == char {
count += 1
}
default:
break
}
}
return count
}
// Write a function reverse_vowels which takes a string as input
// and reverses the order 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:
// reverseVowels(s: "hello") == "holle"
// reverseVowels(s: "leetcode") == "leotcede"
func reverseVowels(s: String) -> String {
var vowels = [Character]()
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
vowels.append(char)
case "y":
if s.last == char {
vowels.append(char)
}
default:
break
}
}
vowels.reverse()
var result = ""
var vowelIndex = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
result.append(vowels[vowelIndex])
vowelIndex += 1
case "y":
if s.last == char {
result.append(vowels[vowelIndex])
vowelIndex += 1
} else {
result.append(char)
}
default:
result.append(char)
}
}
return result
}
// Write a function to_uppercase which takes a string as input and
// returns a copy of the string in which all lowercase letters are
// converted to their corresponding uppercase letters.
// Example:
// toUpperCase(s: "hello") == "HELLO"
// toUpperCase(s: "leetcode") == "LEETCODE"
func toUpperCase(s: String) -> String {
var result = ""
for char in s {
if String(char).lowercased()!= String(char).uppercased() {
result.append(String(char).uppercased())
} else {
result.append(char)
}
}
return result
}
// Write a function to_title_case which takes a string as input and
// returns a copy of the string in which every word starts with an
// uppercase letter and the rest of the word is in lowercase.
// All words in the string should be separated by a single space.
// Example:
// toTitleCase(s: "hello world") == "Hello World"
// toTitleCase(s: "this is a test") == "This Is A Test"
func toTitleCase(s: String) -> String {
var result = ""
var capitalizeNext = true
for char in s {
if capitalizeNext {
if String(char).lowercased()!= String(char).uppercased() {
result.append(String(char).uppercased())
capitalizeNext = false
} else {
result.append(char)
}
} else {
if String(char).lowercased() == String(char).uppercased() {
result.append(char)
capitalizeNext = true
} else {
result.append(String(char).lowercased())
}
}
}
return result
}
// Write a function palindrome_permutation which takes a string as input
// and returns true if the string can be written as the sum of
// a palindrome and a non-palindrome.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward.
// A non-palindrome is a word, phrase, number, or other sequence of
// characters that reads the same forward but not backward.
// Example:
// palindromePermutation(s: "taco cat") == true
// palindromePermutation(s: "hello") == false
func palindromePermutation(s: String) -> Bool {
var charCount = [Character: Int]()
for char in s {
if String(char).lowercased()!= String(char).uppercased() { // cannot force unwrap value of non-optional type 'String'
if String(char).lowercased()!= String(char).uppercased() { // use of '=' in a boolean context, did you mean '=='?
if String(char).lowercased()!= String(char).uppercased() { // '=' must have consistent whitespace on both sides
if String(char).lowercased()!= String(char).uppercased() { // cannot force unwrap value of non-optional type 'String'
if String(char).lowercased()!= String(char).uppercased() { // use of '=' in a boolean context, did you mean '=='?
if String(char).lowercased()!= String(char).uppercased() { // '=' must have consistent whitespace on both sides
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
continue
}
}
return count
}
func reverseString(s: String) -> String {
return String(s.reversed())
}
func longestCommonPrefix(strs: [String]) -> String {
guard!strs.isEmpty else { return "" }
var prefix = strs[0]
for i in 1..<strs.count {
while!strs[i].hasPrefix(prefix) {
prefix = String(prefix.prefix(prefix.count - 1))
if prefix.isEmpty {
return ""
}
}
}
return prefix
}
func mergeStrings(_ s1: String, _ s2: String) -> String {
var result = ""
for c in s1 {
result.append(c)
}
for c in s2 {
result.append(c)
}
return result
}
func isAnagram(_ s1: String, _ s2: String) -> Bool {
guard!s1.isEmpty &&!s2.isEmpty else { return false }
let s1 = s1.lowercased()
let s2 = s2.lowercased()
var dict: [Character: Int] = [:]
for c in s1 {
dict[c, default: 0] += 1
}
for c in s2 {
dict[c, default: 0] -= 1
}
return dict.values.allSatisfy { $0 == 0 }
}
```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 c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
continue
}
}
return count
}
// Write a function reverse_string which takes a string as input and
// returns the string reversed.
// Example:
// reverse_string(s: "hello") == "olleh"
func reverseString(s: String) -> String {
return String(s.reversed())
}
// Write a function longest_common_prefix which takes a list of strings
// as input and returns the longest common prefix string.
// Example:
// longest_common_prefix(strs: ["flower", "flow", "flight"]) == "fl"
func longestCommonPrefix(strs: [String]) -> String {
guard!strs.isEmpty else { return "" }
var prefix = strs[0]
for i in 1..<strs.count {
while!strs[i].hasPrefix(prefix) {
prefix = String(prefix.prefix(prefix.count - 1))
if prefix.isEmpty {
return ""
}
}
}
return prefix
}
// Write a function merge_strings which takes two strings and returns
// a new string which contains all the characters from both the input
// strings. The function should handle cases where either or both of
// the input strings are empty.
// Example:
// merge_strings(s1: "hello", s2: "world") == "helloworld"
// merge_strings(s1: "hello", s2: "") == "hello"
// merge_strings(s1: "", s2: "world") == "world"
// merge_strings(s1: "", s2: "") == ""
func mergeStrings(_ s1: String, _ s2: String) -> String {
var result = ""
for c in s1 {
result.append(c)
}
for c in s2 {
result.append(c)
}
return result
}
// Write a function is_anagram which takes two strings as input and
// returns true if the strings are anagrams. An anagram is a word or
// phrase formed by rearranging the letters of a different word or phrase,
// typically using all the original letters exactly once. The function
// should be case-insensitive, meaning that 'A' and 'a' are considered
// the same character. The function should return false if either of the
// input strings is empty.
// Example:
// is_anagram(s1: "listen", s2: "silent") == true
// is_anagram(s1: "hello", s2: "world") == false
// is_anagram(s1: "AaBbCc", s2: "aAbBcC") == true
func isAnagram(_ s1: String, _ s2: String) -> Bool {
guard!s1.isEmpty &&!s2.isEmpty else { return false }
let s1 = s1.lowercased()
let s2 = s2.lowercased()
var dict: [Character: Int] = [:]
for c in s1 {
dict[c, default: 0] += 1
}
for c in s2 {
dict[c, default: 0] -= 1
}
return dict.values.allSatisfy { $0 == 0 }
}
// Write a function is_palindrome which takes a string as input and
// returns true if the string is a palindrome. A palindrome is a word,
// phrase, number, or other sequence of characters that reads the same
// forward and backward, disregarding spaces, punctuation, and capitalization.
// The function should be case-insensitive, meaning that 'A' and 'a' are
// considered the same character. The function should return false if the
// input string is empty.
// Example:
// is_palindrome(s: "A man, a plan, a canal, Panama!") == true
// is_palindrome(s: "hello world") == false
func isPalindrome(_ s: String) -> Bool {
guard!s.isEmpty else { return false }
let s = s.lowercased()
var left = 0
guard!strs.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
while!strs[i].hasPrefix(prefix) { // expected expression, var, or let in 'while' condition
guard!s1.isEmpty &&!s2.isEmpty else { return false } // expected expression, var, let or case in 'guard' condition
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
break
}
}
return count
}
func reverse(s: String) -> String {
var chars = [Character]()
for c in s {
chars.insert(c, at: 0)
}
return String(chars)
}
func swapPairs(s: String) -> String {
var chars = [Character]()
for (i, c) in s.enumerated() {
if i % 2 == 1 {
chars.append(c)
} else {
chars.insert(c, at: i + 1)
}
}
return String(chars)
}
func longestPalindrome(s: String) -> Int {
var longest = 0
for i in 0..<s.count {
for j in i..<s.count {
let substring = String(s[i..<j])
if substring == String(substring.reversed()) {
longest = max(longest, j - i)
}
}
}
return longest
}
func removePunctuation(s: String) -> String {
var chars = [Character]()
for c in s {
if CharacterSet.alphanumerics.contains(c) {
chars.append(c)
}
}
return String(chars)
}
func uniqueWords(s: String) -> [String] {
var words = [String]()
var currentWord = ""
for c in s {
if c == " " {
if!words.contains(currentWord) {
words.append(currentWord)
}
currentWord = ""
} else {
currentWord.append(c)
}
}
if!words.contains(currentWord) {
words.append(currentWord)
}
return words.sorted(by: >)
}
```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 c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
break
}
}
return count
}
// Write a function which takes a string as input and returns the
// string in reversed order.
// Example:
// reverse(s: "hello") == "olleh"
// reverse(s: "world") == "dlrow"
func reverse(s: String) -> String {
var chars = [Character]()
for c in s {
chars.insert(c, at: 0)
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with the characters at even positions swapped with their
// corresponding characters at odd positions.
// Example:
// swap_pairs(s: "hello") == "holle"
// swap_pairs(s: "world") == "dlrow"
func swapPairs(s: String) -> String {
var chars = [Character]()
for (i, c) in s.enumerated() {
if i % 2 == 1 {
chars.append(c)
} else {
chars.insert(c, at: i + 1)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// length of the longest palindromic substring.
// Example:
// longest_palindrome(s: "racecar") == 7
// longest_palindrome(s: "bananas") == 3
func longestPalindrome(s: String) -> Int {
var longest = 0
for i in 0..<s.count {
for j in i..<s.count {
let substring = String(s[i..<j])
if substring == String(substring.reversed()) {
longest = max(longest, j - i)
}
}
}
return longest
}
// Write a function which takes a string as input and returns the
// string with all punctuation marks and special characters removed.
// Example:
// remove_punctuation(s: "Hello, world!") == "Hello world"
// remove_punctuation(s: "I love programming!") == "I love programming"
func removePunctuation(s: String) -> String {
var chars = [Character]()
for c in s {
if CharacterSet.alphanumerics.contains(c) {
chars.append(c)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns a
// list of all the unique words in the string, sorted in reverse
// alphabetical order. You may assume that the input string will
// only contain words separated by spaces and that words with the
// same reverse alphabetical order will be considered the same word.
// Example:
// unique_words(s: "Hello world hello again") == ["again", "hello", "world"]
// unique_words(s: "Python is great!") == ["great", "is", "python"]
func uniqueWords(s: String) -> [String] {
var words = [String]()
var currentWord = ""
for c in s {
if c == " " {
if!words.contains(currentWord) {
words.append(currentWord)
}
currentWord = ""
} else {
currentWord.append(c)
}
}
if!words.contains(currentWord) {
words.append(currentWord)
}
return words.sorted(by: >)
}
// Write a function which takes a string as input and returns a
// list of all the words in the string, sorted in reverse
// alphabetical order. You may assume that the input string will
// only contain words separated by spaces.
// Example:
// reverse_alpha(s: "Hello world hello again") == ["again", "hello", "world"]
// reverse_alpha(s: "Python is great!") == ["great", "is", "python"]
func reverseAlpha(s: String) -> [String] {
var words = [String]()
var currentWord = ""
for c in s {
if c == " " {
words.append(currentWord)
currentWord =
let substring = String(s[i..<j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if CharacterSet.alphanumerics.contains(c) { // cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'
if!words.contains(currentWord) { // expected expression, var, or let in 'if' condition
if!words.contains(currentWord) { // expected expression, var, or let in 'if' condition
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if s.last == char {
count += 1
}
default:
break
}
}
return count
}
func reverseVowels(s: String) -> String {
var vowels = [Character]()
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
vowels.append(char)
case "y":
if s.last == char {
vowels.append(char)
}
default:
break
}
}
vowels.reverse()
var result = ""
var vowelIndex = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
result.append(vowels[vowelIndex])
vowelIndex += 1
case "y":
if s.last == char {
result.append(vowels[vowelIndex])
vowelIndex += 1
} else {
result.append(char)
}
default:
result.append(char)
}
}
return result
}
func toUpperCase(s: String) -> String {
return s.uppercased()
}
func toLowerCase(s: String) -> String {
return s.lowercased()
}
func toTitleCase(s: String) -> String {
return s.titlecased()
}
func palindromeCheck(s: String) -> Bool {
return s == String(s.reversed())
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if s.last == char {
count += 1
}
default:
break
}
}
return count
}
// Write a function reverse_vowels which takes a string as input and
// reverses the order 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:
// reverseVowels(s: "hello") == "holle"
// reverseVowels(s: "leetcode") == "leotcede"
func reverseVowels(s: String) -> String {
var vowels = [Character]()
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
vowels.append(char)
case "y":
if s.last == char {
vowels.append(char)
}
default:
break
}
}
vowels.reverse()
var result = ""
var vowelIndex = 0
for char in s {
switch String(char).lowercased() {
case "a", "e", "i", "o", "u":
result.append(vowels[vowelIndex])
vowelIndex += 1
case "y":
if s.last == char {
result.append(vowels[vowelIndex])
vowelIndex += 1
} else {
result.append(char)
}
default:
result.append(char)
}
}
return result
}
// Write a function to_uppercase which takes a string as input and
// returns the string in upper case.
// Example:
// toUpperCase(s: "hello") == "HELLO"
// toUpperCase(s: "leetcode") == "LEETCODE"
func toUpperCase(s: String) -> String {
return s.uppercased()
}
// Write a function to_lowercase which takes a string as input and
// returns the string in lower case.
// Example:
// toLowerCase(s: "Hello") == "hello"
// toLowerCase(s: "LeetCode") == "leetcode"
func toLowerCase(s: String) -> String {
return s.lowercased()
}
// Write a function to_titlecase which takes a string as input and
// returns the string in title case.
// Example:
// toTitleCase(s: "hello world") == "Hello World"
// toTitleCase(s: "the quick brown fox") == "The Quick Brown Fox"
func toTitleCase(s: String) -> String {
return s.titlecased()
}
// Write a function palindrome_check which takes a string as input and
// returns true if the string is a palindrome and false otherwise.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward, disregarding spaces, punctuation,
// and capitalization.
// Example:
// palindromeCheck(s: "racecar") == true
// palindromeCheck(s: "hello") == false
func palindromeCheck(s: String) -> Bool {
return s == String(s.reversed())
}
// Write a function is_valid_url which takes a string as input and
// returns true if the string is a valid URL and false otherwise.
// A valid URL is a string that starts with a protocol name followed by
// a colon, followed by a double-slash, followed by the domain name,
// followed by a path. The domain name can have multiple subdomains separated
// by dots, and the path can have multiple directories separated by forward
// slashes. The protocol name can be either "http" or "https". The path can
// be empty but cannot start with a forward slash.
// Example:
// is_valid_url(url: "https://www.example.com") == true
// is_valid_url(url: "ftp://www.example.com") == false
func is_valid
return s.titlecased() // value of type 'String' has no member 'titlecased'
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
switch String(c).lowercased() {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if c == s.last {
count += 1
}
default:
continue
}
}
return count
}
func reverse(s: String) -> String {
var chars = [Character]()
for c in s {
chars.insert(c, at: 0)
}
return String(chars)
}
func swap_even_odd(s: String) -> String {
var chars = [Character]()
for (i, c) in s.enumerated() {
if i % 2 == 0 {
chars.append(c)
} else {
chars.insert(c, at: 0)
}
}
return String(chars)
}
func remove_duplicates(s: String) -> String {
var chars = [Character]()
for c in s {
if!chars.contains(c) {
chars.append(c)
}
}
return String(chars)
}
func remove_punctuation(s: String) -> String {
var chars = [Character]()
for c in s {
if c.isLetter || c.isNumber {
chars.append(c)
}
}
return String(chars)
}
func remove_consecutive_duplicates(s: String) -> String {
var chars = [Character]()
var prev = ""
for c in s {
if c!= prev {
chars.append(c)
prev = c
}
}
return String(chars)
}
func remove_whitespace(s: String) -> String {
var chars = [Character]()
for c in s {
if!c.isWhitespace {
chars.append(c)
}
}
return String(chars)
}
func remove_special_chars(s: String) -> String {
var chars = [Character]()
for c in s {
if c.isLetter || c.isNumber {
chars.append(c)
}
}
return String(chars)
}
```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 c in s {
switch String(c).lowercased() {
case "a", "e", "i", "o", "u":
count += 1
case "y":
if c == s.last {
count += 1
}
default:
continue
}
}
return count
}
// Write a function which takes a string as input and returns the
// string in reversed order.
// Example:
// reverse(s: "hello") == "olleh"
// reverse(s: "world") == "dlrow"
func reverse(s: String) -> String {
var chars = [Character]()
for c in s {
chars.insert(c, at: 0)
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with the characters at even positions swapped with the
// characters at odd positions.
// Example:
// swap_even_odd(s: "hello") == "holle"
// swap_even_odd(s: "world") == "dlrow"
func swap_even_odd(s: String) -> String {
var chars = [Character]()
for (i, c) in s.enumerated() {
if i % 2 == 0 {
chars.append(c)
} else {
chars.insert(c, at: 0)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with duplicate characters removed.
// Example:
// remove_duplicates(s: "hello") == "helo"
// remove_duplicates(s: "world") == "world"
func remove_duplicates(s: String) -> String {
var chars = [Character]()
for c in s {
if!chars.contains(c) {
chars.append(c)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with all punctuation marks and special characters removed.
// Example:
// remove_punctuation(s: "hello, world!") == "hello world"
// remove_punctuation(s: "I am #1") == "I am 1"
func remove_punctuation(s: String) -> String {
var chars = [Character]()
for c in s {
if c.isLetter || c.isNumber {
chars.append(c)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with all consecutive duplicate characters removed.
// Example:
// remove_consecutive_duplicates(s: "abbbccdddeee") == "abbccddee"
// remove_consecutive_duplicates(s: "hello, world!") == "hello world"
func remove_consecutive_duplicates(s: String) -> String {
var chars = [Character]()
var prev = ""
for c in s {
if c!= prev {
chars.append(c)
prev = c
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with all whitespace characters removed.
// Example:
// remove_whitespace(s: "hello, world!") == "hello,world!"
// remove_whitespace(s: "I am #1") == "Iam#1"
func remove_whitespace(s: String) -> String {
var chars = [Character]()
for c in s {
if!c.isWhitespace {
chars.append(c)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with all special characters removed.
// Example:
// remove_special_chars(s: "hello, world!") == "hello world"
// remove_special_chars(s: "I am #1") == "I am 1"
func remove_special_chars(s: String) -> String {
var chars = [Character]()
for c in s {
if c.isLetter || c.isNumber {
chars.append(c)
}
}
return String(chars)
}
// Write a function which takes a string as input and returns the
// string with all punctuation marks and whitespace characters removed.
// Example:
// remove_all_punctuation(s: "hello, world
if!chars.contains(c) { // expected expression, var, or let in 'if' condition
if c!= prev { // '=' must have consistent whitespace on both sides
if c!= prev { // cannot force unwrap value of non-optional type 'Character'
if c!= prev { // cannot assign value of type 'String' to type 'Character'
if c!= prev { // use of '=' in a boolean context, did you mean '=='?
prev = c // cannot assign value of type 'Character' to type 'String'
if!c.isWhitespace { // expected expression, var, or let in 'if' condition
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
continue
}
}
return count
}
func reverseString(s: String) -> String {
var chars = [Character]()
for c in s {
chars.insert(c, at: 0)
}
return String(chars)
}
func isPalindrome(s: String) -> Bool {
return s == reverseString(s: s)
}
func longestCommonPrefix(strs: [String]) -> String {
guard!strs.isEmpty else { return "" }
var prefix = strs[0]
for i in 1..<strs.count {
while!strs[i].hasPrefix(prefix) {
prefix = String(prefix.prefix(prefix.count - 1))
if prefix.isEmpty {
return ""
}
}
}
return prefix
}
func mergeSort(arr: [Int]) -> [Int] {
guard arr.count > 1 else { return arr }
let mid = arr.count / 2
let left = mergeSort(arr: Array(arr[0..<mid]))
let right = mergeSort(arr: Array(arr[mid..<arr.count]))
return merge(left: left, right: right)
}
func merge(left: [Int], right: [Int]) -> [Int] {
var merged = [Int]()
var i = 0
var j = 0
while i < left.count && j < right.count {
if left[i] <= right[j] {
merged.append(left[i])
i += 1
} else {
merged.append(right[j])
j += 1
}
}
while i < left.count {
merged.append(left[i])
i += 1
}
while j < right.count {
merged.append(right[j])
j += 1
}
return merged
}
```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 c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
continue
}
}
return count
}
// Write a function reverse_string which takes a string as input and
// returns the string reversed.
// Example:
// reverse_string(s: "Hello, World!") == "!dlroW,olleH"
func reverseString(s: String) -> String {
var chars = [Character]()
for c in s {
chars.insert(c, at: 0)
}
return String(chars)
}
// Write a function is_palindrome which takes a string as input and
// returns true if the string is a palindrome and false otherwise.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward.
// Example:
// is_palindrome(s: "racecar") == true
// is_palindrome(s: "hello") == false
func isPalindrome(s: String) -> Bool {
return s == reverseString(s: s)
}
// Write a function longest_common_prefix which takes a list of strings
// as input and returns the longest common prefix string.
// A common prefix is a sequence of characters that appears at the beginning
// of every string in the list.
// Example:
// longest_common_prefix(strs: ["flower", "flow", "flight"]) == "fl"
// longest_common_prefix(strs: ["dog", "racecar", "car"]) == ""
func longestCommonPrefix(strs: [String]) -> String {
guard!strs.isEmpty else { return "" }
var prefix = strs[0]
for i in 1..<strs.count {
while!strs[i].hasPrefix(prefix) {
prefix = String(prefix.prefix(prefix.count - 1))
if prefix.isEmpty {
return ""
}
}
}
return prefix
}
// Write a function merge_sort which takes a list of integers as input
// and sorts the list in ascending order using the merge sort algorithm.
// The merge sort algorithm has a time complexity of O(n log n).
// Example:
// merge_sort(arr: [5, 2, 1, 8, 4, 7, 6, 3]) == [1, 2, 3, 4, 5, 6, 7, 8]
func mergeSort(arr: [Int]) -> [Int] {
guard arr.count > 1 else { return arr }
let mid = arr.count / 2
let left = mergeSort(arr: Array(arr[0..<mid]))
let right = mergeSort(arr: Array(arr[mid..<arr.count]))
return merge(left: left, right: right)
}
func merge(left: [Int], right: [Int]) -> [Int] {
var merged = [Int]()
var i = 0
var j = 0
while i < left.count && j < right.count {
if left[i] <= right[j] {
merged.append(left[i])
i += 1
} else {
merged.append(right[j])
j += 1
}
}
while i < left.count {
merged.append(left[i])
i += 1
}
while j < right.count {
merged.append(right[j])
j += 1
}
return merged
}
// Write a function bubble_sort which takes a list of integers as input
// and sorts the list in ascending order using the bubble sort algorithm.
// The bubble sort algorithm has a time complexity of O(n^2).
// Example:
// bubble_sort(arr: [5, 2, 1, 8, 4, 7, 6, 3]) == [1, 2, 3, 4, 5, 6, 7, 8]
func bubbleSort(arr: [Int]) -> [Int] {
var sorted = arr
var swapped = true
while swapped {
swapped = false
for i in 1..
guard!strs.isEmpty else { return "" } // expected expression, var, let or case in 'guard' condition
while!strs[i].hasPrefix(prefix) { // expected expression, var, or let in 'while' condition
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" {
count += 1
}
}
return count
}
func reverseString(s: String) -> String {
var result = ""
for i in (0..<s.count).reversed() {
result += String(s[s.index(s.startIndex, offsetBy: i)])
}
return result
}
func isPalindrome(s: String) -> Bool {
return s == reverseString(s: s)
}
func longestCommonPrefix(strs: [String]) -> String {
if strs.count == 0 {
return ""
}
var result = ""
for i in 0..<strs[0].count {
let c = strs[0][strs[0].index(strs[0].startIndex, offsetBy: i)]
for j in 1..<strs.count {
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c {
return result
}
}
result += String(c)
}
return result
}
func mergeSort(arr: [Int]) -> [Int] {
if arr.count <= 1 {
return arr
}
let mid = arr.count / 2
let left = mergeSort(arr: Array(arr[0..<mid]))
let right = mergeSort(arr: Array(arr[mid..<arr.count]))
return merge(left: left, right: right)
}
```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 c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" {
count += 1
}
}
return count
}
// Write a function reverse_string which takes a string as input and
// returns the string reversed.
// Example:
// reverse_string(s: "hello") == "olleh"
// reverse_string(s: "world") == "dlrow"
func reverseString(s: String) -> String {
var result = ""
for i in (0..<s.count).reversed() {
result += String(s[s.index(s.startIndex, offsetBy: i)])
}
return result
}
// Write a function is_palindrome which takes a string as input and
// returns true if the string is a palindrome and false otherwise.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward.
// Example:
// is_palindrome(s: "racecar") == true
// is_palindrome(s: "hello") == false
func isPalindrome(s: String) -> Bool {
return s == reverseString(s: s)
}
// Write a function longest_common_prefix which takes a list of strings
// as input and returns the longest common prefix string.
// A common prefix is a sequence of characters that is shared by all
// strings in the input list.
// Example:
// longest_common_prefix(strs: ["flower", "flow", "flight"]) == "fl"
// longest_common_prefix(strs: ["dog", "racecar", "car"]) == ""
func longestCommonPrefix(strs: [String]) -> String {
if strs.count == 0 {
return ""
}
var result = ""
for i in 0..<strs[0].count {
let c = strs[0][strs[0].index(strs[0].startIndex, offsetBy: i)]
for j in 1..<strs.count {
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c {
return result
}
}
result += String(c)
}
return result
}
// Write a function merge_sort which takes an array of integers as input
// and sorts the array in ascending order using a modified version of the
// merge sort algorithm.
// The merge sort algorithm has a time complexity of O(n log n).
// Here, we have modified the merge sort algorithm to recursively sort
// the subarrays until the base case is reached, which is when the array
// has only one element (as in the case of the sorted array).
// The base case is when the subarray has two elements, and in this case,
// we simply compare the two elements and swap them if they are in the wrong
// order.
// Example:
// merge_sort([9, 7, 10, 2, 6, 3, 1, 2, 10, 6, 9]) == [1, 2, 2, 3, 6, 6, 7, 9, 9, 10, 10]
func mergeSort(arr: [Int]) -> [Int] {
if arr.count <= 1 {
return arr
}
let mid = arr.count / 2
let left = mergeSort(arr: Array(arr[0..<mid]))
let right = mergeSort(arr: Array(arr[mid..<arr.count]))
return merge(left: left, right: right)
}
func merge(left: [Int], right: [Int]) -> [Int] {
var result = [Int]()
var i = 0
var j = 0
while i < left.count && j < right.count {
if left[i] < right[j] {
result.append(left[i])
i += 1
} else {
result.append(right[j])
j += 1
}
}
while i < left.count {
result.append(left[i])
i += 1
}
while j < right.count {
result.append(right[j])
j
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c { // cannot convert value of type 'Character' to expected argument type 'Bool'
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c { // '=' must have consistent whitespace on both sides
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c { // use of '=' in a boolean context, did you mean '=='?
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c { // cannot force unwrap value of non-optional type 'Character'
if i == strs[j].count || strs[j][strs[j].index(strs[j].startIndex, offsetBy: i)]!= c { // expression is not assignable: '||' returns immutable value
return merge(left: left, right: right) // cannot find 'merge' in scope
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
break
}
}
return count
}
func isPalindrome(s: String) -> Bool {
let filtered = s.filter { $0.isLetterOrDigit }
let lowercased = filtered.lowercased()
return lowercased == String(lowercased.reversed())
}
func longestCommonPalindromeSubsequence(s1: String, s2: String) -> Int {
let n = s1.count
let m = s2.count
var dp = (0...n).map { Array(repeating: 0, count: m + 1) }
for i in 1...n {
for j in 1...m {
if s1[i - 1] == s2[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[n][m]
}
func longestCommonSubsequence(s1: String, s2: String) -> Int {
let n = s1.count
let m = s2.count
var dp = (0...n).map { Array(repeating: 0, count: m + 1) }
for i in 1...n {
for j in 1...m {
if s1[i - 1] == s2[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[n][m]
}
```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 c in s {
switch String(c).uppercased() {
case "A", "E", "I", "O", "U":
count += 1
case "Y":
if s.last == c {
count += 1
}
default:
break
}
}
return count
}
// Write a function is_palindrome which takes a string as input and
// returns true if the string is a palindrome and false otherwise.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward.
// Example:
// isPalindrome(s: "racecar") == true
// isPalindrome(s: "hello") == false
func isPalindrome(s: String) -> Bool {
let filtered = s.filter { $0.isLetterOrDigit }
let lowercased = filtered.lowercased()
return lowercased == String(lowercased.reversed())
}
// Write a function longest_common_palindrome_subsequence which takes two
// strings as input and returns the length of the longest common subsequence
// between them. A subsequence is a sequence that can be derived from another
// sequence by deleting some or no elements without changing the order of the
// remaining elements. The common subsequence need not be longest among all
// subsequences.
// Example:
// longestCommonPalindromeSubsequence(s1: "abac", s2: "baba") == 3
// longestCommonPalindromeSubsequence(s1: "hello", s2: "world") == 1
func longestCommonPalindromeSubsequence(s1: String, s2: String) -> Int {
let n = s1.count
let m = s2.count
var dp = (0...n).map { Array(repeating: 0, count: m + 1) }
for i in 1...n {
for j in 1...m {
if s1[i - 1] == s2[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[n][m]
}
// Write a function longest_common_subsequence which takes two strings as
// input and returns the length of the longest common subsequence between
// them. A subsequence is a sequence that can be derived from another
// sequence by deleting some or no elements without changing the order of the
// remaining elements. The common subsequence need not be longest among all
// subsequences.
// Example:
// longestCommonSubsequence(s1: "abac", s2: "baba") == 3
// longestCommonSubsequence(s1: "hello", s2: "world") == 1
func longestCommonSubsequence(s1: String, s2: String) -> Int {
let n = s1.count
let m = s2.count
var dp = (0...n).map { Array(repeating: 0, count: m + 1) }
for i in 1...n {
for j in 1...m {
if s1[i - 1] == s2[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[n][m]
}
// Write a function longest_common_subsequence_list which takes two
// lists as input and returns the length of the longest common subsequence
// between them. A subsequence is a sequence that can be derived from another
// sequence by deleting some or no elements without changing the order of the
// remaining elements. The common subsequence need not be longest among all
// subsequences.
// Example:
// longestCommonSubsequenceList([1, 3, 5, 7, 9, 11], [2, 4, 6, 8, 10, 12]) == 3
// longestCommonSubsequenceList([1, 2, 3,
let filtered = s.filter { $0.isLetterOrDigit } // value of type 'String.Element' (aka 'Character') has no member 'isLetterOrDigit'
var dp = (0...n).map { Array(repeating: 0, count: m + 1) } // contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
if s1[i - 1] == s2[j - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s1[i - 1] == s2[j - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
var dp = (0...n).map { Array(repeating: 0, count: m + 1) } // contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
if s1[i - 1] == s2[j - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if s1[i - 1] == s2[j - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
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
} else if char == "y" && s.last == "y" {
count += 1
}
}
return count
}
func wordLengths(words: [String]) -> [Int] {
var lengths = [Int]()
for word in words {
lengths.append(word.count)
}
return lengths
}
func longestWord(words: [String]) -> String {
var longest = ""
for word in words {
if word.count > longest.count {
longest = word
}
}
return longest
}
func reverseWords(s: String) -> String {
var words = [String]()
var word = ""
for char in s {
if char == " " || char == "!" || char == "." || char == "," {
words.append(word)
word = ""
} else {
word += String(char)
}
}
words.append(word)
var reversed = ""
for i in (0...words.count - 1).reversed() {
reversed += words[i] + " "
}
return reversed
}
func isPalindrome(s: String) -> Bool {
var reversed = ""
for char in s {
reversed = String(char) + reversed
}
return reversed == s
}
func countWords(s: String) -> Int {
var words = 0
var word = ""
for char in s {
if char == " " || char == "!" || char == "." || char == "," {
words += 1
word = ""
} else {
word += String(char)
}
}
words += 1
return words
}
func printPyramid(height: Int) {
for i in 1...height {
var line = ""
for j in 1...i {
line += "*"
}
print(line)
}
}
```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
} else if char == "y" && s.last == "y" {
count += 1
}
}
return count
}
// Write a function word_lengths which takes a list of words as input
// and returns a list of integers representing the lengths of the words.
// Example:
// wordLengths(["apple", "banana", "cherry"]) == [5, 6, 6]
func wordLengths(words: [String]) -> [Int] {
var lengths = [Int]()
for word in words {
lengths.append(word.count)
}
return lengths
}
// Write a function longest_word which takes a list of words as input
// and returns the longest word in the list.
// Example:
// longestWord(["apple", "banana", "cherry"]) == "banana"
func longestWord(words: [String]) -> String {
var longest = ""
for word in words {
if word.count > longest.count {
longest = word
}
}
return longest
}
// Write a function reverse_words which takes a string as input and
// returns a string where the words are reversed. A word is defined
// to be a sequence of characters surrounded by spaces or punctuation
// marks.
// Example:
// reverseWords("The quick brown fox jumps over the lazy dog") == "dog lazy the over jumps fox brown quick The"
func reverseWords(s: String) -> String {
var words = [String]()
var word = ""
for char in s {
if char == " " || char == "!" || char == "." || char == "," {
words.append(word)
word = ""
} else {
word += String(char)
}
}
words.append(word)
var reversed = ""
for i in (0...words.count - 1).reversed() {
reversed += words[i] + " "
}
return reversed
}
// Write a function is_palindrome which takes a string as input and
// returns true if the string is a palindrome and false otherwise.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward.
// Example:
// isPalindrome("A man, a plan, a canal, Panama!") == true
func isPalindrome(s: String) -> Bool {
var reversed = ""
for char in s {
reversed = String(char) + reversed
}
return reversed == s
}
// Write a function count_words which takes a string as input and
// returns the number of words in the string. A word is defined to be
// a sequence of characters surrounded by spaces or punctuation marks.
// Example:
// countWords("The quick brown fox jumps over the lazy dog") == 4
func countWords(s: String) -> Int {
var words = 0
var word = ""
for char in s {
if char == " " || char == "!" || char == "." || char == "," {
words += 1
word = ""
} else {
word += String(char)
}
}
words += 1
return words
}
// Write a function print_pyramid which takes an integer as input
// and prints an ascii pyramid of stars with a height given by the
// input. The width of the pyramid should be calculated dynamically
// based on the input.
// Example:
// printPyramid(5)
// *
// **
// ***
// ****
// *****
func printPyramid(height: Int) {
for i in 1...height {
var line = ""
for j in 1...i {
line += "*"
}
print(line)
}
}
// Write a function is_prime which takes an integer as input and
// returns true if the input is a prime number and false otherwise.
// A prime number is a whole number greater than 1 that cannot be formed
// by multiplying two smaller whole numbers.
// Example:
// isPrime(7) == true
// isPrime(12) == false
func isPrime(n: Int) -> Bool {
if n <=
for j in 1...i { // immutable value 'j' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
} else if char == "y" && s.last == "y" {
vowels += 1
}
}
return vowels
}
func reverseString(s: String) -> String {
var chars = [Character]()
for char in s {
chars.insert(char, at: 0)
}
return String(chars)
}
func longestCommonPrefix(strs: [String]) -> String {
if strs.count == 0 {
return ""
}
if strs.count == 1 {
return strs[0]
}
var prefix = ""
var index = 0
while true {
var found = false
for string in strs {
if index >= string.count {
return prefix
}
if index == 0 {
prefix += String(string[string.startIndex])
} else if prefix[index]!= string[string.index(string.startIndex, offsetBy: index)] {
return prefix
} else {
found = true
}
}
if found {
index += 1
} else {
return prefix
}
}
}
func mergeStrings(s1: String, s2: String) -> String {
return s1 + " " + s2
}
func isPalindrome(s: String) -> Bool {
var i = 0
var j = s.count - 1
while i < j {
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: j)] {
return false
}
i += 1
j -= 1
}
return true
}
func caesarCipher(s: String, rotation: Int) -> String {
var chars = [Character]()
for char in s {
if char.isLetter {
if char.isUppercase {
chars.append(Character(UnicodeScalar(UInt8(char.asciiValue! - 65 + rotation) % 26 + 65)!))
} else {
chars.append(Character(UnicodeScalar(UInt8(char.asciiValue! - 97 + rotation) % 26 + 97)!))
}
} else {
chars.append(char)
}
}
return String(chars)
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
} else if char == "y" && s.last == "y" {
vowels += 1
}
}
return vowels
}
// Write a function reverse_string which takes a string as input and
// returns the string reversed.
// Example:
// reverse_string(s: "hello") == "olleh"
func reverseString(s: String) -> String {
var chars = [Character]()
for char in s {
chars.insert(char, at: 0)
}
return String(chars)
}
// Write a function longest_common_prefix which takes a list of strings
// as input and returns the longest common prefix string.
// Example:
// longest_common_prefix(strs: ["flower", "flow", "flight"]) == "fl"
// longest_common_prefix(strs: ["dog", "racecar", "car"]) == ""
func longestCommonPrefix(strs: [String]) -> String {
if strs.count == 0 {
return ""
}
if strs.count == 1 {
return strs[0]
}
var prefix = ""
var index = 0
while true {
var found = false
for string in strs {
if index >= string.count {
return prefix
}
if index == 0 {
prefix += String(string[string.startIndex])
} else if prefix[index]!= string[string.index(string.startIndex, offsetBy: index)] {
return prefix
} else {
found = true
}
}
if found {
index += 1
} else {
return prefix
}
}
}
// Write a function merge_strings which takes two strings and returns
// a new string containing the first and second string with a space
// between them.
// Example:
// merge_strings(s1: "hello", s2: "world") == "hello world"
func mergeStrings(s1: String, s2: String) -> String {
return s1 + " " + s2
}
// Write a function is_palindrome which takes a string as input and
// returns true if the string is a palindrome and false otherwise.
// A palindrome is a word, phrase, number, or other sequence of characters
// that reads the same forward and backward.
// Example:
// is_palindrome(s: "racecar") == true
// is_palindrome(s: "hello") == false
func isPalindrome(s: String) -> Bool {
var i = 0
var j = s.count - 1
while i < j {
if s[s.index(s.startIndex, offsetBy: i)]!= s[s.index(s.startIndex, offsetBy: j)] {
return false
}
i += 1
j -= 1
}
return true
}
// Write a function caesar_cipher which takes a string and an integer
// rotation as input and returns a new string where each character in the
// original string is rotated by the given rotation. The rotation can be
// positive or negative. The function should use only basic string
// manipulation techniques and not use any built-in string rotation
// functions.
// Example:
// caesar_cipher(s: "hello", rotation: 2) == "llohe"
// caesar_cipher(s: "world", rotation: -3) == "dlrow"
func caesarCipher(s: String, rotation: Int) -> String {
var chars = [Character]()
for char in s {
if char.isLetter {
if char.isUppercase {
chars.append(Character(UnicodeScalar(UInt8(char.asciiValue! - 65 + rotation) % 26 + 65)!))
} else {
chars.append(Character(UnicodeScalar(UInt8(char.asciiValue! - 97 + rotation) % 26 + 97)!))
}
} else {
chars.append(char)
}
}
return String(chars)
}
// Write a function is_valid_hexadecimal which takes a string as input
// and returns true if the string is a
func circularShift(x: Int, shift: Int) -> String {
var x = x
let numberOfDigits = Int(floor(log10(Double(abs(x))))) + 1
if shift > numberOfDigits {
shift = shift % numberOfDigits
}
if shift == 0 {
return String(x)
}
let shifted = x / Int(pow(10, Double(numberOfDigits - shift))) % 10
return String(shifted) + circularShift(x: x % Int(pow(10, Double(numberOfDigits - shift))), shift: shift - 1)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var x = x
let numberOfDigits = Int(floor(log10(Double(abs(x))))) + 1
if shift > numberOfDigits {
shift = shift % numberOfDigits
}
if shift == 0 {
return String(x)
}
let shifted = x / Int(pow(10, Double(numberOfDigits - shift))) % 10
return String(shifted) + circularShift(x: x % Int(pow(10, Double(numberOfDigits - shift))), shift: shift - 1)
}
// Test the function
print(circularShift(x: 123, shift: 2)) // Output: "312"
print(circularShift(x: 100, shift: 4)) // Output: "0100"
print(circularShift(x: 12345, shift: 6)) // Output: "34512"
print(circularShift(x: 123456789, shift: 4)) // Output: "567891234"
```
shift = shift % numberOfDigits // cannot assign to value: 'shift' is a 'let' constant
func circularShift(x: Int, shift: Int) -> String {
var x = x
let digits = String(x).count
if shift > digits {
x = x.reversed()
return String(x)
}
let shifted = x.digits.dropFirst(shift).appended(x.digits.prefix(shift))
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 {
var x = x
let digits = String(x).count
if shift > digits {
x = x.reversed()
return String(x)
}
let shifted = x.digits.dropFirst(shift).appended(x.digits.prefix(shift))
return String(shifted.reversed())
}
// Test the function
let x = 12345
let shift = 3
print("Original number: \(x)")
print("Shifted number: \(circularShift(x: x, shift: shift))")
```
x = x.reversed() // value of type 'Int' has no member 'reversed'
let shifted = x.digits.dropFirst(shift).appended(x.digits.prefix(shift)) // value of type 'Int' has no member 'digits'
let shifted = x.digits.dropFirst(shift).appended(x.digits.prefix(shift)) // value of type 'Int' has no member 'digits'
func circularShift(x: Int, shift: Int) -> String {
var x = x
var shift = shift
var result = ""
while x > 0 {
result = String(x % 10) + result
x /= 10
}
if shift > result.count {
shift = shift % result.count
}
return String(result.suffix(result.count - shift)) + String(result.prefix(shift))
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var x = x
var shift = shift
var result = ""
while x > 0 {
result = String(x % 10) + result
x /= 10
}
if shift > result.count {
shift = shift % result.count
}
return String(result.suffix(result.count - shift)) + String(result.prefix(shift))
}
// Test the function
print(circularShift(x: 123, shift: 2)) // Output: "312"
print(circularShift(x: 123, shift: 0)) // Output: "123"
print(circularShift(x: 123, shift: 4)) // Output: "231"
print(circularShift(x: 123, shift: 7)) // Output: "312"
print(circularShift(x: 123, shift: 3)) // Output: "123"
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let shiftedDigits = shifted(digits, shift)
return String(shiftedDigits.map { String($0) })
}
func shifted(_ digits: [Int], _ shift: Int) -> [Int] {
guard shift > 0 else { return digits.reversed() }
let shiftedDigits = digits.dropFirst(shift) + digits.prefix(shift)
return 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 shiftedDigits = shifted(digits, shift)
return String(shiftedDigits.map { String($0) })
}
func shifted(_ digits: [Int], _ shift: Int) -> [Int] {
guard shift > 0 else { return digits.reversed() }
let shiftedDigits = digits.dropFirst(shift) + digits.prefix(shift)
return shiftedDigits
}
// Test the function
print(circularShift(x: 123, shift: 1)) // Output: "213"
print(circularShift(x: 123, shift: 2)) // Output: "123"
print(circularShift(x: 123, shift: 3)) // Output: "132"
print(circularShift(x: 123, shift: 4)) // Output: "213"
print(circularShift(x: 123, shift: 5)) // Output: "321"
print(circularShift(x: 123, shift: 6)) // Output: "231"
print(circularShift(x: 123, shift: 7)) // Output: "321"
print(circularShift(x: 123, shift: 8)) // Output: "213"
print(circularShift(x: 123, shift: 9)) // Output: "123"
print(circularShift(x: 123, shift: 10)) // Output: "213"
print(circularShift(x: 123, shift: 0)) // Output: "123"
print(circularShift(x: 123, shift: -1)) // Output: "213"
print(circularShift(x: 123, shift: -2)) // Output: "123"
print(circularShift(x: 123, shift: -3)) // Output: "132"
print(circularShift(x: 123, shift: -4)) // Output: "213"
print(circularShift(x: 123, shift: -5)) // Output: "321"
print(circularShift(x: 123, shift: -6)) // Output: "231"
print(circularShift(x: 123, shift: -7)) // Output: "321"
print(circularShift(x: 123, shift: -8)) // Output: "213"
print(circularShift(x: 123, shift: -9)) // Output: "123"
print(circularShift(x: 123, shift: -10))// Output: "213"
print(circularShift(x: 123, shift: -11))// Output: "123"
print(circularShift(x: 123, shift: -12))// Output: "213"
print(circularShift(x: 123, shift: -13))// Output: "123"
print(circularShift(x: 123, shift: -14))// Output: "213"
print(circularShift(x: 123, shift: -15))// Output: "123"
print(circularShift(x: 123, shift: -16))// Output: "213"
print(circularShift(x: 123, shift: -17))// Output: "123"
print(circularShift(x: 123, shift: -18))// Output: "213"
print(circularShift(x: 123, shift: -19))// Output: "123"
print(circularShift(x: 123, shift: -20))// Output: "213"
print(circularShift(x: 123, shift: -21))// Output: "123"
print(circularShift(x: 123, shift: -22))// Output: "213"
print(circularShift(x: 123, shift: -23))// Output: "12
return String(shiftedDigits.map { String($0) }) // no exact matches in call to initializer
return shiftedDigits // cannot convert return expression of type 'Array<Int>.SubSequence' (aka 'ArraySlice<Int>') to return type '[Int]'
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
// Test the function
print(circularShift(x: 123, shift: 2)) // Output: "312"
print(circularShift(x: 123, shift: 0)) // Output: "123"
print(circularShift(x: 123, shift: 5)) // Output: "312"
print(circularShift(x: 123, shift: 3)) // Output: "213"
print(circularShift(x: 123, shift: 1)) // Output: "231"
```
guard shift > 0 else { return String(digits.reversed()) } // no exact matches in call to initializer
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) } // no exact matches in call to initializer
return String(digits.dropFirst(shift) + digits.prefix(shift)) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift).reversed() + digits.prefix(shift))
}
func getProductsOfAllOtherElements(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var leftProduct = 1
for i in 0..<input.count {
result.append(leftProduct)
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
result[i] *= rightProduct
rightProduct *= input[i]
}
return result
}
func getProductsOfAllOtherElementsNoDivision(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var runningProduct = 1
for i in 0..<input.count {
result.append(runningProduct)
runningProduct *= input[i]
}
runningProduct = 1
for i in (0..<input.count).reversed() {
result[i] *= runningProduct
runningProduct *= input[i]
}
return result
}
func getDifferenceOfProducts(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var leftProduct = 1
for i in 0..<input.count {
result.append(leftProduct)
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
result[i] = leftProduct * rightProduct - result[i]
rightProduct *= input[i]
}
return result
}
func getDifferenceOfProductsNoDivision(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var runningProduct = 1
for i in 0..<input.count {
result.append(runningProduct)
runningProduct *= input[i]
}
runningProduct = 1
for i in (0..<input.count).reversed() {
result[i] = runningProduct * input[i] - result[i]
runningProduct *= input[i]
}
return result
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift).reversed() + digits.prefix(shift))
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our
// input was [3, 2, 1], the expected output would be [2, 3, 6].
func getProductsOfAllOtherElements(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var leftProduct = 1
for i in 0..<input.count {
result.append(leftProduct)
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
result[i] *= rightProduct
rightProduct *= input[i]
}
return result
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Solve it without division.
func getProductsOfAllOtherElementsNoDivision(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var runningProduct = 1
for i in 0..<input.count {
result.append(runningProduct)
runningProduct *= input[i]
}
runningProduct = 1
for i in (0..<input.count).reversed() {
result[i] *= runningProduct
runningProduct *= input[i]
}
return result
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the difference between the product of all the numbers in the original array except the one at i,
// and the product of all the numbers in the original array except the one at the index at i.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be:
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
func getDifferenceOfProducts(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var leftProduct = 1
for i in 0..<input.count {
result.append(leftProduct)
leftProduct *= input[i]
}
var rightProduct = 1
for i in (0..<input.count).reversed() {
result[i] = leftProduct * rightProduct - result[i]
rightProduct *= input[i]
}
return result
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the difference between the product of all the numbers in the original array except the one at i,
// and the product of all the numbers in the original array except the one at the index at i.
// Solve it without division.
func getDifferenceOfProductsNoDivision(in input: [Int]) -> [Int] {
var result = [Int]()
guard input.count > 0 else { return result }
var runningProduct = 1
for i in 0..<input.count {
result.append(runningProduct)
runningProduct *= input[i]
}
runningProduct = 1
for i in (0..<input.count).reversed() {
result[i] = runningProduct * input[i] - result[i]
runningProduct *= input[i]
}
return result
}
// Given an array of integers, return a new array such that each element at index i of the new array
//
guard shift > 0 else { return String(digits.reversed()) } // no exact matches in call to initializer
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) } // no exact matches in call to initializer
return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
func circularShift(x: Int, shift: Int) -> Int {
return Int(circularShift(x: x, shift: shift))!
}
func sumOfIntegers(_ x: String, _ y: String) -> String {
let x = Int(x)!
let y = Int(y)!
let sum = x + y
return String(sum)
}
func sumOfIntegers(_ x: Int, _ y: Int) -> Int {
return Int(sumOfIntegers(String(x), String(y)))!
}
func productOfIntegers(_ x: String, _ y: String) -> String {
let x = Int(x)!
let y = Int(y)!
let product = x * y
return String(product)
}
func productOfIntegers(_ x: Int, _ y: Int) -> Int {
return Int(productOfIntegers(String(x), String(y)))!
}
func differenceOfIntegers(_ x: String, _ y: String) -> String {
let x = Int(x)!
let y = Int(y)!
let difference = x - y
return String(difference)
}
func differenceOfIntegers(_ x: Int, _ y: Int) -> Int {
return Int(differenceOfIntegers(String(x), String(y)))!
}
```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 n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as an integer.
// 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) -> Int {
return Int(circularShift(x: x, shift: shift))!
}
// Return the sum of two integers, x and y, as a string.
// The function returns the result as a string containing only digits.
// sumOfIntegers("123", "456") == "579"
// sumOfIntegers("999", "1") == "1000"
func sumOfIntegers(_ x: String, _ y: String) -> String {
let x = Int(x)!
let y = Int(y)!
let sum = x + y
return String(sum)
}
// Return the sum of two integers, x and y, as an integer.
// The function returns the result as an integer.
// sumOfIntegers(123, 456) == 579
// sumOfIntegers(999, 1) == 1000
func sumOfIntegers(_ x: Int, _ y: Int) -> Int {
return Int(sumOfIntegers(String(x), String(y)))!
}
// Return the product of two integers, x and y, as a string.
// The function returns the result as a string containing only digits.
// productOfIntegers("123", "456") == "56088"
// productOfIntegers("999", "1") == "998001"
func productOfIntegers(_ x: String, _ y: String) -> String {
let x = Int(x)!
let y = Int(y)!
let product = x * y
return String(product)
}
// Return the product of two integers, x and y, as an integer.
// The function returns the result as an integer.
// productOfIntegers(123, 456) == 56088
// productOfIntegers(999, 1) == 998001
func productOfIntegers(_ x: Int, _ y: Int) -> Int {
return Int(productOfIntegers(String(x), String(y)))!
}
// Return the difference between two integers, x and y, as a string.
// The function returns the result as a string containing only digits.
// differenceOfIntegers("123", "456") == "-333"
// differenceOfIntegers("999", "1") == "998"
func differenceOfIntegers(_ x: String, _ y: String) -> String {
let x = Int(x)!
let y = Int(y)!
let difference = x - y
return String(difference)
}
// Return the difference between two integers, x and y, as an integer.
// The function returns the result as an integer.
// differenceOfIntegers(123, 456) == -333
// differenceOfIntegers(999, 1) == 998
func differenceOfIntegers(_ x: Int, _ y: Int) -> Int {
return Int(differenceOfIntegers(String(x), String(y)))!
}
// Return the quotient of two integers, x and y, as a string.
// The function returns the result as a string containing only digits.
// quotientOfIntegers("123", "456") == "0"
// quotientOfIntegers("999", "1") == "999"
func quotientOfIntegers
guard shift > 0 else { return String(digits.reversed()) } // no exact matches in call to initializer
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) } // no exact matches in call to initializer
return String(digits.dropFirst(shift) + digits.prefix(shift)) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
// Test the function
print(circularShift(x: 123, shift: 2)) // Output: "312"
print(circularShift(x: 123, shift: 0)) // Output: "123"
print(circularShift(x: 123, shift: 5)) // Output: "312"
print(circularShift(x: 123, shift: 3)) // Output: "213"
print(circularShift(x: 123, shift: 1)) // Output: "231"
```
guard shift > 0 else { return String(digits.reversed()) } // no exact matches in call to initializer
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) } // no exact matches in call to initializer
return String(digits.dropFirst(shift) + digits.prefix(shift)) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) }
return String(digits.dropFirst(shift) + digits.prefix(shift))
}
// Test the function
print(circularShift(x: 123, shift: 2)) // Output: "312"
print(circularShift(x: 123, shift: 0)) // Output: "123"
print(circularShift(x: 123, shift: 5)) // Output: "312"
print(circularShift(x: 123, shift: 3)) // Output: "213"
print(circularShift(x: 123, shift: 1)) // Output: "231"
```
guard shift > 0 else { return String(digits.reversed()) } // no exact matches in call to initializer
guard shift < n else { return String(digits.dropFirst(shift).reversed() + digits.prefix(shift)) } // no exact matches in call to initializer
return String(digits.dropFirst(shift) + digits.prefix(shift)) // no exact matches in call to initializer
func circularShift(x: Int, shift: Int) -> String {
let digits = String(x).map { Int(String($0))! }
let n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits[shift...(n-1)]) + String(digits[0...(shift-1)]) }
return String(digits[shift...(n-1)] + digits[0...(shift-1)])
}
```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 n = digits.count
guard shift > 0 else { return String(digits.reversed()) }
guard shift < n else { return String(digits[shift...(n-1)]) + String(digits[0...(shift-1)]) }
return String(digits[shift...(n-1)] + digits[0...(shift-1)])
}
// Test the function
print(circularShift(x: 123, shift: 2)) // Output: "312"
print(circularShift(x: 123, shift: 0)) // Output: "123"
print(circularShift(x: 123, shift: 5)) // Output: "312"
print(circularShift(x: 123, shift: 3)) // Output: "213"
print(circularShift(x: 123, shift: 1)) // Output: "231"
print(circularShift(x: 123, shift: 4)) // Output: "321"
```
guard shift > 0 else { return String(digits.reversed()) } // no exact matches in call to initializer
guard shift < n else { return String(digits[shift...(n-1)]) + String(digits[0...(shift-1)]) } // no exact matches in call to initializer
guard shift < n else { return String(digits[shift...(n-1)]) + String(digits[0...(shift-1)]) } // no exact matches in call to initializer
return String(digits[shift...(n-1)] + digits[0...(shift-1)]) // no exact matches in call to initializer
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
func mixedSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
} else {
sum += Int(char.asciiValue! - 32)
}
}
return sum
}
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isNumber {
sum += Int(char.asciiValue!)
}
}
return sum
}
func sumOddDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isNumber && Int(char.asciiValue!) % 2!= 0 {
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
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
// Task
// Write a function that takes a string as input and returns the sum of the upper and lower characters'
// ASCII codes.
// Examples:
// mixedSum(s: "") == 0
// mixedSum(s: "abAB") == 131
// mixedSum(s: "abcCd") == 84
// mixedSum(s: "helloE") == 74
// mixedSum(s: "woArBld") == 131
// mixedSum(s: "aAaaaXa") == 153
func mixedSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
} else {
sum += Int(char.asciiValue! - 32)
}
}
return sum
}
// Tests
assert(mixedSum(s: "") == 0)
assert(mixedSum(s: "abAB") == 131)
assert(mixedSum(s: "abcCd") == 84)
assert(mixedSum(s: "helloE") == 74)
assert(mixedSum(s: "woArBld") == 131)
assert(mixedSum(s: "aAaaaXa") == 153)
// Task
// Write a function that takes a string as input and returns the sum of the digits of the ASCII codes.
// Examples:
// sumDigits(s: "") == 0
// sumDigits(s: "abAB") == 0
// sumDigits(s: "abc123") == 6
// sumDigits(s: "helloE") == 3
// sumDigits(s: "woArBld") == 0
// sumDigits(s: "aAaaaXa") == 6
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isNumber {
sum += Int(char.asciiValue!)
}
}
return sum
}
// Tests
assert(sumDigits(s: "") == 0)
assert(sumDigits(s: "abAB") == 0)
assert(sumDigits(s: "abc123") == 6)
assert(sumDigits(s: "helloE") == 3)
assert(sumDigits(s: "woArBld") == 0)
assert(sumDigits(s: "aAaaaXa") == 6)
// Task
// Write a function that takes a string as input and returns the sum of the odd digits of the ASCII codes.
// Examples:
// sumOddDigits(s: "") == 0
// sumOddDigits(s: "abAB") == 0
// sumOddDigits(s: "abc123") == 0
// sumOddDigits(s: "helloE") == 5
// sumOddDigits(s: "woArBld") == 0
// sumOddDigits(s: "aAaaaXa") == 9
func sumOddDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isNumber && Int(char.asciiValue!) % 2!= 0 {
sum += Int(char.asciiValue!)
}
}
return sum
}
// Tests
assert(sumOddDigits(s: "") == 0)
assert(sumOddDigits(s: "abAB") == 0)
assert(sumOddDigits(s: "abc123") == 0)
assert(sumOddDigits(s: "helloE") == 5)
assert(sumOddDigits(s: "woArBld") == 0)
if char.isNumber && Int(char.asciiValue!) % 2!= 0 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if char.isNumber && Int(char.asciiValue!) % 2!= 0 { // cannot force unwrap value of non-optional type 'Int'
if char.isNumber && Int(char.asciiValue!) % 2!= 0 { // use of '=' in a boolean context, did you mean '=='?
if char.isNumber && Int(char.asciiValue!) % 2!= 0 { // expression is not assignable: '&&' returns immutable value
if char.isNumber && Int(char.asciiValue!) % 2!= 0 { // '=' must have consistent whitespace on both sides
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
// Tests
digitSum(s: "") // 0
digitSum(s: "abAB") // 131
digitSum(s: "abcCd") // 67
digitSum(s: "helloE") // 69
digitSum(s: "woArBld") // 131
digitSum(s: "aAaaaXa") // 153
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char >= "A" && char <= "Z" {
sum += Int(char.asciiValue! - 55)
}
}
return sum
}
func digitSumBonus(s: String) -> Int {
var sum = 0
var isPreviousUppercase = false
for char in s {
if char >= "A" && char <= "Z" {
if isPreviousUppercase {
sum += Int(char.asciiValue! - 55)
}
isPreviousUppercase = true
} else {
isPreviousUppercase = false
}
}
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! - 55)
}
}
return sum
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
// Bonus
// Time and Space complexity: O(n)
// 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 digitSumBonus(s: String) -> Int {
var sum = 0
var isPreviousUppercase = false
for char in s {
if char >= "A" && char <= "Z" {
if isPreviousUppercase {
sum += Int(char.asciiValue! - 55)
}
isPreviousUppercase = true
} else {
isPreviousUppercase = false
}
}
return sum
}
// Tests
assert(digitSumBonus(s: "") == 0)
assert(digitSumBonus(s: "abAB") == 131)
assert(digitSumBonus(s: "abcCd") == 67)
assert(digitSumBonus(s: "helloE") == 69)
assert(digitSumBonus(s: "woArBld") == 131)
assert(digitSumBonus(s: "aAaaaXa") == 153)
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char >= "A" && char <= "Z" {
sum += Int(char.asciiValue! - 55)
}
}
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! - 55)
}
}
return sum
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
```
// 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
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
```
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
func letterSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
}
}
return sum
}
func oddSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
} else if char.isNumber {
sum += Int(char.asciiValue! - 57)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
// Task
// Write a function that takes a string as input and returns the sum of the upper and lower characters'
// ASCII codes.
// Examples:
// letterSum(s: "") == 0
// letterSum(s: "abAB") == 186
// letterSum(s: "abcCd") == 143
// letterSum(s: "helloE") == 143
// letterSum(s: "woArBld") == 186
// letterSum(s: "aAaaaXa") == 208
func letterSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
}
}
return sum
}
// Tests
assert(letterSum(s: "") == 0)
assert(letterSum(s: "abAB") == 186)
assert(letterSum(s: "abcCd") == 143)
assert(letterSum(s: "helloE") == 143)
assert(letterSum(s: "woArBld") == 186)
assert(letterSum(s: "aAaaaXa") == 208)
// Task
// Write a function that takes a string as input and returns the sum of the odd characters' ASCII codes.
// Examples:
// oddSum(s: "") == 0
// oddSum(s: "abAB") == 98
// oddSum(s: "abcCd") == 98
// oddSum(s: "helloE") == 101
// oddSum(s: "woArBld") == 98
// oddSum(s: "aAaaaXa") == 105
func oddSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
} else if char.isNumber {
sum += Int(char.asciiValue! - 57)
}
}
return sum
}
// Tests
assert(oddSum(s: "") == 0)
assert(oddSum(s: "abAB") == 98)
assert(oddSum(s: "abcCd") == 98)
assert(oddSum(s: "helloE") == 101)
assert(oddSum(s: "woArBld") == 98)
assert(oddSum(s: "aAaaaXa") == 105)
// Task
// Write a function that takes a string as input and returns the sum of the even characters' ASCII codes.
// Examples:
// evenSum(s: "") == 0
// evenSum(s: "abAB") == 100
// evenSum(s: "abcCd") == 100
// evenSum(s: "helloE") == 100
// evenSum(s: "woArBld") == 100
// evenSum(s: "aAaaaXa") == 100
func evenSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
} else if char.isNumber {
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
```swift
// Task
// Write a function that takes a string as input and returns the sum of the upper characters only'
// ASCII codes.
// Examples:
// digitSum(s: "") == 0
// digitSum(s: "abAB") == 131
// digitSum(s: "abcCd") == 67
// digitSum(s: "helloE") == 69
// digitSum(s: "woArBld") == 131
// digitSum(s: "aAaaaXa") == 153
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
}
}
return sum
}
// Test cases
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
// Additional test cases
assert(digitSum(s: "12345") == 15)
assert(digitSum(s: "1234567890") == 51)
assert(digitSum(s: "1234567890!@#$%") == 54)
assert(digitSum(s: "1234567890!@#$%abcdef") == 54)
assert(digitSum(s: "1234567890!@#$%abcdefg") == 57)
assert(digitSum(s: "1234567890!@#$%abcdefgh") == 60)
assert(digitSum(s: "1234567890!@#$%abcdefghi") == 63)
assert(digitSum(s: "1234567890!@#$%abcdefghij") == 66)
assert(digitSum(s: "1234567890!@#$%abcdefghijk") == 69)
assert(digitSum(s: "1234567890!@#$%abcdefghijkl") == 72)
assert(digitSum(s: "1234567890!@#$%abcdefghijklm") == 75)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmn") == 78)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmno") == 81)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnop") == 84)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopq") == 87)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqr") == 90)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrs") == 93)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrst") == 96)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrstu") == 99)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrstuv") == 102)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrstuvw") == 105)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrstuvwx") == 108)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrstuvwxy") == 111)
assert(digitSum(s: "1234567890!@#$%abcdefghijklmnopqrstuvwxyz") == 114)
assert(digitSum(s: "1234567890!@#
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char >= "A" && char <= "Z" {
sum += Int(char.asciiValue! - 55)
}
}
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! - 55)
}
}
return sum
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
}
}
return sum
}
func mixedSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 32)
}
}
return sum
}
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 55)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 97)
}
}
return sum
}
func sumDigits2(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
}
}
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
}
// Tests
assert(digitSum(s: "") == 0)
assert(digitSum(s: "abAB") == 131)
assert(digitSum(s: "abcCd") == 67)
assert(digitSum(s: "helloE") == 69)
assert(digitSum(s: "woArBld") == 131)
assert(digitSum(s: "aAaaaXa") == 153)
// Bonus
// Write a function that takes a string as input and returns the sum of the upper and lower characters
// only' ASCII codes.
// Examples:
// mixedSum(s: "") == 0
// mixedSum(s: "abAB") == 153
// mixedSum(s: "abcCd") == 84
// mixedSum(s: "helloE") == 74
// mixedSum(s: "woArBld") == 153
// mixedSum(s: "aAaaaXa") == 186
func mixedSum(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue!)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 32)
}
}
return sum
}
// Tests
assert(mixedSum(s: "") == 0)
assert(mixedSum(s: "abAB") == 153)
assert(mixedSum(s: "abcCd") == 84)
assert(mixedSum(s: "helloE") == 74)
assert(mixedSum(s: "woArBld") == 153)
assert(mixedSum(s: "aAaaaXa") == 186)
// Bonus 2
// Write a function that takes a string as input and returns the sum of the digits of the ASCII codes
// of the upper and lower characters only.
// Examples:
// sumDigits(s: "") == 0
// sumDigits(s: "abAB") == 15
// sumDigits(s: "abcCd") == 6
// sumDigits(s: "helloE") == 5
// sumDigits(s: "woArBld") == 15
// sumDigits(s: "aAaaaXa") == 18
func sumDigits(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 55)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 97)
}
}
return sum
}
// Tests
assert(sumDigits(s: "") == 0)
assert(sumDigits(s: "abAB") == 15)
assert(sumDigits(s: "abcCd") == 6)
assert(sumDigits(s: "helloE") == 5)
assert(sumDigits(s: "woArBld") == 15)
assert(sumDigits(s: "aAaaaXa") == 18)
// Bonus 3
// Write a function that takes a string as input and returns the sum of the digits of the ASCII codes
// of the upper and lower characters only.
// Examples:
// sumDigits2(s: "") == 0
// sumDigits2(s: "abAB") == 15
// sumDigits2(s: "abcCd") == 6
// sumDigits2(s: "helloE") == 5
// sumDigits2(s: "woArBld") == 15
// sumDigits2(s: "aAaaaXa") == 18
func sumDigits2(s: String) -> Int {
var sum = 0
for char in s {
if char.isUppercase {
sum += Int(char.asciiValue! - 64)
} else if char.isLowercase {
sum += Int(char.asciiValue! - 96)
}
}
return sum
}
// Tests
assert(sumDigits2(s: "") == 0)
assert
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ").map { Int($0)! }
let apples = arr[0]
let oranges = arr[1]
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ").map { Int($0)! }
let apples = arr[0]
let oranges = arr[1]
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ").map { Int($0)! }
let apples = fruits[0]
let oranges = fruits[1]
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: " ").map { Int($0)! }
let apples = fruits[0]
let oranges = fruits[1]
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ").map { Int($0)! }
let apples = fruits[0]
let oranges = fruits[1]
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: " ").map { Int($0)! }
let apples = fruits[0]
let oranges = fruits[1]
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let appleOrange = s.split(separator: " ").map { Int($0)! }
let apples = appleOrange[0]
let oranges = appleOrange[1]
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 appleOrange = s.split(separator: " ").map { Int($0)! }
let apples = appleOrange[0]
let oranges = appleOrange[1]
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangoes = n - apples - oranges
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let fruits = s.components(separatedBy: " ").map { Int($0)! }
let apples = fruits[0]
let oranges = fruits[1]
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: " ").map { Int($0)! }
let apples = fruits[0]
let oranges = fruits[1]
let mangoes = n - apples - oranges
return mangoes
}
fruitDistribution(s: "5 apples and 6 oranges", n: 19)
fruitDistribution(s: "0 apples and 1 oranges", n: 3)
fruitDistribution(s: "2 apples and 3 oranges", n: 100)
fruitDistribution(s: "100 apples and 1 oranges", n: 120)
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangos = n - apples - oranges
return mangos
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let mangos = n - apples - oranges
return mangos
}
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
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let total = apples + oranges
let mangoes = n - total
return mangoes
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let apples = Int(s.components(separatedBy: " ").first!)!
let oranges = Int(s.components(separatedBy: " ").last!)!
let total = apples + oranges
let mangoes = n - total
return mangoes
}
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
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
let smallestEvenValue = evenValues.min()
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1
return [smallestEvenValue?? 0, 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] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
let smallestEvenValue = evenValues.min()
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1
return [smallestEvenValue?? 0, smallestEvenValueIndex]
}
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]
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]) == [0, 1]
pluck(arr: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]) == [0, 1]
pluck(arr: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49, 51, 53, 55, 57, 59, 61, 63, 65, 67, 69, 71, 73, 75, 77, 79, 81, 83, 85, 87, 89, 91, 93, 95, 97, 99, 101]) == [100,
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // missing argument for parameter 'where' in call
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // extra arguments at positions #1, #2 in call
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // cannot use optional chaining on non-optional value of type 'Int'
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // integer literal is unused
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // cannot use optional chaining on non-optional value of type 'Array<Int>.Index' (aka 'Int')
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // consecutive statements on a line must be separated by ';'
let smallestEvenValueIndex = evenValues.firstIndex(of: smallestEvenValue?? 0)?? -1 // expected ',' separator
return [smallestEvenValue?? 0, smallestEvenValueIndex] // cannot convert value of type 'Int?' to expected element type 'Int'
return [smallestEvenValue?? 0, smallestEvenValueIndex] // expected ',' separator
return [smallestEvenValue?? 0, smallestEvenValueIndex] // cannot use optional chaining on non-optional value of type 'Int'
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
guard!evenValues.isEmpty else { return [] }
evenValues.sort()
return [evenValues.first!, arr.firstIndex(of: evenValues.first!)!]
}
```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] {
guard!arr.isEmpty else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
guard!evenValues.isEmpty else { return [] }
evenValues.sort()
return [evenValues.first!, arr.firstIndex(of: evenValues.first!)!]
}
pluck(arr: [4, 2, 3])
pluck(arr: [1, 2, 3])
pluck(arr: [])
pluck(arr: [5, 0, 3, 0, 4, 2])
```
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!evenValues.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
return arr.sorted { $0 < $1 }.filter { $0 % 2 == 0 }.first.map { [$0, arr.firstIndex(of: $0)!] }?? []
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
return arr.sorted { $0 < $1 }.filter { $0 % 2 == 0 }.first.map { [$0, arr.firstIndex(of: $0)!] }?? []
}
pluck(arr: [4, 2, 3])
pluck(arr: [1, 2, 3])
pluck(arr: [])
pluck(arr: [5, 0, 3, 0, 4, 2])
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100])
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
return arr.sorted { $0 < $1 }.filter { $0 % 2 == 0 }.first.map { [$0, arr.firstIndex(of: $0)!] }?? [] // missing argument for parameter #1 in subscript
return arr.sorted { $0 < $1 }.filter { $0 % 2 == 0 }.first.map { [$0, arr.firstIndex(of: $0)!] }?? [] // cannot use optional chaining on non-optional value of type '[_]'
func pluck(arr: [Int]) -> [Int] {
var even = [Int]()
var odd = [Int]()
var zero = [Int]()
for i in arr {
if i % 2 == 0 {
even.append(i)
} else if i == 0 {
zero.append(i)
} else {
odd.append(i)
}
}
if even.count > 0 {
return [even.min()!, even.firstIndex(of: even.min()!)!]
} else if zero.count > 0 {
return [zero.min()!, zero.firstIndex(of: zero.min()!)!]
} else {
return [odd.min()!, odd.firstIndex(of: odd.min()!)!]
}
}
```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 even = [Int]()
var odd = [Int]()
var zero = [Int]()
for i in arr {
if i % 2 == 0 {
even.append(i)
} else if i == 0 {
zero.append(i)
} else {
odd.append(i)
}
}
if even.count > 0 {
return [even.min()!, even.firstIndex(of: even.min()!)!]
} else if zero.count > 0 {
return [zero.min()!, zero.firstIndex(of: zero.min()!)!]
} else {
return [odd.min()!, odd.firstIndex(of: odd.min()!)!]
}
}
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]
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
if evenValues.isEmpty { return [] }
let minValue = evenValues.min()?? 0
let minIndex = arr.firstIndex(of: minValue)?? -1
return [minValue, minIndex]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
if evenValues.isEmpty { return [] }
let minValue = evenValues.min()?? 0
let minIndex = arr.firstIndex(of: minValue)?? -1
return [minValue, minIndex]
}
pluck(arr: [4, 2, 3])
pluck(arr: [1, 2, 3])
pluck(arr: [])
pluck(arr: [5, 0, 3, 0, 4, 2])
```
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
let minValue = evenValues.min()?? 0 // consecutive statements on a line must be separated by ';'
let minValue = evenValues.min()?? 0 // integer literal is unused
let minValue = evenValues.min()?? 0 // cannot use optional chaining on non-optional value of type 'Int'
let minIndex = arr.firstIndex(of: minValue)?? -1 // integer literal is unused
let minIndex = arr.firstIndex(of: minValue)?? -1 // consecutive statements on a line must be separated by ';'
let minIndex = arr.firstIndex(of: minValue)?? -1 // cannot use optional chaining on non-optional value of type 'Array<Int>.Index' (aka 'Int')
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
let even = arr.filter { $0 % 2 == 0 }
let min = even.min()
let index = arr.firstIndex(of: min!)!
return [min!, index]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
let even = arr.filter { $0 % 2 == 0 }
let min = even.min()
let index = arr.firstIndex(of: min!)!
return [min!, index]
}
pluck(arr: [4, 2, 3])
pluck(arr: [1, 2, 3])
pluck(arr: [])
pluck(arr: [5, 0, 3, 0, 4, 2])
```
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
var evenValue = arr.filter { $0 % 2 == 0 }
guard!evenValue.isEmpty else { return [] }
var minValue = evenValue.min()
guard let index = evenValue.firstIndex(of: minValue!) else { return [] }
return [minValue!, index]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
var evenValue = arr.filter { $0 % 2 == 0 }
guard!evenValue.isEmpty else { return [] }
var minValue = evenValue.min()
guard let index = evenValue.firstIndex(of: minValue!) else { return [] }
return [minValue!, index]
}
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]
```
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!evenValue.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
let even = arr.filter { $0 % 2 == 0 }
let min = even.min()
let index = arr.firstIndex(of: min!)
return [min!, index!]
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.filter({ $0 % 2 == 0 }).count > 0 else { return [] }
let even = arr.filter { $0 % 2 == 0 }
let min = even.min()
let index = arr.firstIndex(of: min!)
return [min!, index!]
}
pluck(arr: [4, 2, 3])
pluck(arr: [1, 2, 3])
pluck(arr: [])
pluck(arr: [5, 0, 3, 0, 4, 2])
```
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
guard arr.count > 1 else { return [arr[0], 0] }
var evenValues = arr.filter { $0 % 2 == 0 }
guard!evenValues.isEmpty else { return [] }
let minEvenValue = evenValues.min()
guard let minEvenValueIndex = evenValues.firstIndex(of: minEvenValue) else { return [] }
return [minEvenValue, minEvenValueIndex]
}
```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] {
guard!arr.isEmpty else { return [] }
guard arr.count > 1 else { return [arr[0], 0] }
var evenValues = arr.filter { $0 % 2 == 0 }
guard!evenValues.isEmpty else { return [] }
let minEvenValue = evenValues.min()
guard let minEvenValueIndex = evenValues.firstIndex(of: minEvenValue) else { return [] }
return [minEvenValue, minEvenValueIndex]
}
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]
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [2, 1]
pluck(arr: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]) == [10, 0]
pluck(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]) == [2, 1]
pluck(arr: [100, 99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, 79, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, 63, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 2
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!evenValues.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard let minEvenValueIndex = evenValues.firstIndex(of: minEvenValue) else { return [] } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return [minEvenValue, minEvenValueIndex] // cannot convert value of type 'Int?' to expected element type 'Int'
func pluck(arr: [Int]) -> [Int] {
guard!arr.isEmpty else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
guard!evenValues.isEmpty else { return [] }
evenValues.sort()
return [evenValues.first!, arr.firstIndex(of: evenValues.first!)!]
}
```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] {
guard!arr.isEmpty else { return [] }
var evenValues = arr.filter { $0 % 2 == 0 }
guard!evenValues.isEmpty else { return [] }
evenValues.sort()
return [evenValues.first!, arr.firstIndex(of: evenValues.first!)!]
}
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]
```
guard!arr.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
guard!evenValues.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func search(lst: [Int]) -> Int {
var frequency = [Int: Int]()
for number in lst {
frequency[number, default: 0] += 1
}
for number in lst {
if frequency[number]?? 0 >= number {
return number
}
}
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 frequency = [Int: Int]()
for number in lst {
frequency[number, default: 0] += 1
}
for number in lst {
if frequency[number]?? 0 >= number {
return number
}
}
return -1
}
// Tests
assert(search(lst: [4, 1, 2, 2, 3, 1]) == 2)
assert(search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3)
assert(search(lst: [5, 5, 4, 4, 4]) == -1)
```
if frequency[number]?? 0 >= number { // expected '{' after 'if' condition
if frequency[number]?? 0 >= number { // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
for i in lst {
if i > max {
max = i
maxCount = 1
} else if i == max {
maxCount += 1
}
}
if maxCount == 1 {
return max
} else {
return -1
}
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
for i in lst {
if i > max {
max = i
maxCount = 1
} else if i == max {
maxCount += 1
}
}
if maxCount == 1 {
return max
} else {
return -1
}
}
search(lst: [4, 1, 2, 2, 3, 1])
search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])
search(lst: [5, 5, 4, 4, 4])
//: [Next](@next)
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var count = [Int: Int]()
for num in lst {
count[num, default: 0] += 1
}
for num in lst {
if count[num]?? 0 >= num {
return num
}
}
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 count = [Int: Int]()
for num in lst {
count[num, default: 0] += 1
}
for num in lst {
if count[num]?? 0 >= num {
return num
}
}
return -1
}
// Tests
print(search(lst: [4, 1, 2, 2, 3, 1])) // 2
print(search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])) // 3
print(search(lst: [5, 5, 4, 4, 4])) // -1
if count[num]?? 0 >= num { // cannot use optional chaining on non-optional value of type 'Int'
if count[num]?? 0 >= num { // expected '{' after 'if' condition
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var maxIndex = -1
for i in 0..<lst.count {
var count = 0
for j in 0..<lst.count {
if lst[j] == lst[i] {
count += 1
}
}
if count > maxCount {
max = lst[i]
maxCount = count
maxIndex = i
}
}
return maxIndex == -1? -1 : max
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var maxIndex = -1
for i in 0..<lst.count {
var count = 0
for j in 0..<lst.count {
if lst[j] == lst[i] {
count += 1
}
}
if count > maxCount {
max = lst[i]
maxCount = count
maxIndex = i
}
}
return maxIndex == -1? -1 : max
}
search(lst: [4, 1, 2, 2, 3, 1])
search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])
search(lst: [5, 5, 4, 4, 4])
//: [Next](@next)
return maxIndex == -1? -1 : max // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return maxIndex == -1? -1 : max // cannot use optional chaining on non-optional value of type 'Int'
return maxIndex == -1? -1 : max // consecutive statements on a line must be separated by ';'
return maxIndex == -1? -1 : max // cannot convert return expression of type 'Bool' to return type 'Int'
return maxIndex == -1? -1 : max // integer literal is unused
return maxIndex == -1? -1 : max // consecutive statements on a line must be separated by ';'
return maxIndex == -1? -1 : max // expected expression
func search(lst: [Int]) -> Int {
var max = -1
var count = 0
for i in lst {
if i > 0 && i == lst.filter({$0 == i}).count {
if i > max {
max = i
}
count += 1
}
}
return count == 0? -1 : max
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = -1
var count = 0
for i in lst {
if i > 0 && i == lst.filter({$0 == i}).count {
if i > max {
max = i
}
count += 1
}
}
return count == 0? -1 : max
}
// Tests
print(search(lst: [4, 1, 2, 2, 3, 1])) // 2
print(search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])) // 3
print(search(lst: [5, 5, 4, 4, 4])) // -1
return count == 0? -1 : max // consecutive statements on a line must be separated by ';'
return count == 0? -1 : max // cannot convert return expression of type 'Bool' to return type 'Int'
return count == 0? -1 : max // expected expression
return count == 0? -1 : max // consecutive statements on a line must be separated by ';'
return count == 0? -1 : max // integer literal is unused
return count == 0? -1 : max // cannot use optional chaining on non-optional value of type 'Int'
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if j == i {
count += 1
}
}
if count >= i && count > maxCount {
max = i
maxCount = count
result = max
}
}
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if j == i {
count += 1
}
}
if count >= i && count > maxCount {
max = i
maxCount = count
result = max
}
}
}
return result
}
search(lst: [4, 1, 2, 2, 3, 1])
search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])
search(lst: [5, 5, 4, 4, 4])
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
max = i
maxCount = count
}
}
}
if maxCount > 0 {
result = max
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
max = i
maxCount = count
}
}
}
if maxCount > 0 {
result = max
}
return result
}
// Tests
print(search(lst: [4, 1, 2, 2, 3, 1])) // 2
print(search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])) // 3
print(search(lst: [5, 5, 4, 4, 4])) // -1
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if j == i {
count += 1
}
}
if count >= i && count > maxCount {
max = i
maxCount = count
result = max
}
}
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if j == i {
count += 1
}
}
if count >= i && count > maxCount {
max = i
maxCount = count
result = max
}
}
}
return result
}
// Test cases
let lst1 = [4, 1, 2, 2, 3, 1]
let lst2 = [1, 2, 2, 3, 3, 3, 4, 4, 4]
let lst3 = [5, 5, 4, 4, 4]
// Print results
print(search(lst: lst1)) // 2
print(search(lst: lst2)) // 3
print(search(lst: lst3)) // -1
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
max = i
maxCount = count
}
}
}
if maxCount > 0 {
result = max
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var max = 0
var maxCount = 0
var result = -1
for i in lst {
if i > 0 {
var count = 0
for j in lst {
if i == j {
count += 1
}
}
if count > maxCount {
max = i
maxCount = count
}
}
}
if maxCount > 0 {
result = max
}
return result
}
// Tests
print(search(lst: [4, 1, 2, 2, 3, 1])) // 2
print(search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4])) // 3
print(search(lst: [5, 5, 4, 4, 4])) // -1
```
// XCTAssertTrue failed
func search(lst: [Int]) -> Int {
var frequency = [Int: Int]()
for number in lst {
if let count = frequency[number] {
frequency[number] = count + 1
} else {
frequency[number] = 1
}
}
for number in lst {
if frequency[number] == number {
return number
}
}
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 frequency = [Int: Int]()
for number in lst {
if let count = frequency[number] {
frequency[number] = count + 1
} else {
frequency[number] = 1
}
}
for number in lst {
if frequency[number] == number {
return number
}
}
return -1
}
print(search(lst: [4, 1, 2, 2, 3, 1]))
print(search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]))
print(search(lst: [5, 5, 4, 4, 4]))
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard!lst.isEmpty else { return [] }
var sortedList = lst
for i in 0..<sortedList.count {
let minIndex = sortedList.indices.min(by: { sortedList[$0] < sortedList[$1] })!
let maxIndex = sortedList.indices.max(by: { sortedList[$0] < sortedList[$1] })!
sortedList.swapAt(minIndex, maxIndex)
}
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] {
guard!lst.isEmpty else { return [] }
var sortedList = lst
for i in 0..<sortedList.count {
let minIndex = sortedList.indices.min(by: { sortedList[$0] < sortedList[$1] })!
let maxIndex = sortedList.indices.max(by: { sortedList[$0] < sortedList[$1] })!
sortedList.swapAt(minIndex, maxIndex)
}
return sortedList
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [20, 1, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [1, 30, 2, 29, 3, 28, 4, 27, 5, 26, 6, 25, 7, 24, 8, 23, 9, 22, 10, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
assert(strangeSortList(lst: [20, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [20, 1, 2, 19, 3, 18, 4
guard!lst.isEmpty else { return [] } // expected expression, var, let or case in 'guard' condition
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedList = lst
var min = sortedList[0]
var max = sortedList[0]
for number in sortedList {
if number < min {
min = number
} else if number > max {
max = number
}
}
var result = [Int]()
var current = min
while result.count < sortedList.count {
if let index = sortedList.firstIndex(of: current) {
result.append(current)
sortedList.remove(at: index)
}
current = max
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedList = lst
var min = sortedList[0]
var max = sortedList[0]
for number in sortedList {
if number < min {
min = number
} else if number > max {
max = number
}
}
var result = [Int]()
var current = min
while result.count < sortedList.count {
if let index = sortedList.firstIndex(of: current) {
result.append(current)
sortedList.remove(at: index)
}
current = max
}
return result
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [100, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [100, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [1000, 100, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1000, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 100])
assert(strangeSortList(lst: [10000, 1000, 100, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10000, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6, 100, 1000])
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedList = lst
var min = sortedList[0]
var max = sortedList[0]
for i in 1..<sortedList.count {
if sortedList[i] < min {
min = sortedList[i]
}
if sortedList[i] > max {
max = sortedList[i]
}
}
var result = [Int]()
var current = min
while result.count < sortedList.count {
if let index = sortedList.firstIndex(of: current) {
result.append(sortedList[index])
sortedList.remove(at: index)
}
current = max
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedList = lst
var min = sortedList[0]
var max = sortedList[0]
for i in 1..<sortedList.count {
if sortedList[i] < min {
min = sortedList[i]
}
if sortedList[i] > max {
max = sortedList[i]
}
}
var result = [Int]()
var current = min
while result.count < sortedList.count {
if let index = sortedList.firstIndex(of: current) {
result.append(sortedList[index])
sortedList.remove(at: index)
}
current = max
}
return result
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [100, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [100, 1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [100, 100, 10, 9, 9, 8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1]) == [100, 100, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 100])
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
let min = lst.min()!
let max = lst.max()!
let minMaxRange = max - min + 1
var buckets = [Int](repeating: 0, count: minMaxRange)
for num in lst {
buckets[num - min] += 1
}
var result = [Int]()
for i in 0..<minMaxRange {
for _ in 0..<buckets[i] {
result.append(i + min)
}
}
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 }
let min = lst.min()!
let max = lst.max()!
let minMaxRange = max - min + 1
var buckets = [Int](repeating: 0, count: minMaxRange)
for num in lst {
buckets[num - min] += 1
}
var result = [Int]()
for i in 0..<minMaxRange {
for _ in 0..<buckets[i] {
result.append(i + min)
}
}
return result
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [1, 30, 2, 29, 3, 28, 4, 27, 5, 26, 6, 25, 7, 24, 8, 23, 9, 22, 10, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
assert(strangeSortList(lst: [20, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var min = lst[0]
var max = lst[0]
for i in 1..<lst.count {
if lst[i] < min {
min = lst[i]
}
if lst[i] > max {
max = lst[i]
}
}
var result = [Int]()
var current = min
while result.count < lst.count {
if lst.contains(current) {
result.append(current)
lst.remove(at: lst.firstIndex(of: current)!)
}
current = max
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var min = lst[0]
var max = lst[0]
for i in 1..<lst.count {
if lst[i] < min {
min = lst[i]
}
if lst[i] > max {
max = lst[i]
}
}
var result = [Int]()
var current = min
while result.count < lst.count {
if lst.contains(current) {
result.append(current)
lst.remove(at: lst.firstIndex(of: current)!)
}
current = max
}
return result
}
let test1 = [1, 2, 3, 4]
let test2 = [5, 5, 5, 5]
let test3: [Int] = []
assert(strangeSortList(lst: test1) == [1, 4, 2, 3])
assert(strangeSortList(lst: test2) == [5, 5, 5, 5])
assert(strangeSortList(lst: test3) == [])
print("Tests done!")
//: [Next](@next)
lst.remove(at: lst.firstIndex(of: current)!) // cannot use mutating member on immutable value: 'lst' is a 'let' constant
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedList = lst
var minValue = sortedList.min()!
var maxValue = sortedList.max()!
while minValue!= maxValue {
for index in 0..<sortedList.count {
if sortedList[index] == minValue {
sortedList[index] = maxValue
} else {
sortedList[index] = minValue
}
}
minValue = sortedList.min()!
maxValue = sortedList.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] {
guard lst.count > 1 else { return lst }
var sortedList = lst
var minValue = sortedList.min()!
var maxValue = sortedList.max()!
while minValue!= maxValue {
for index in 0..<sortedList.count {
if sortedList[index] == minValue {
sortedList[index] = maxValue
} else {
sortedList[index] = minValue
}
}
minValue = sortedList.min()!
maxValue = sortedList.max()!
}
return sortedList
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [1, 30, 2, 29, 3, 28, 4, 27, 5, 26, 6, 25, 7, 24, 8, 23, 9, 22, 10, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
assert(strangeSortList(lst: [20, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [1,
while minValue!= maxValue { // cannot force unwrap value of non-optional type 'Int'
while minValue!= maxValue { // '=' must have consistent whitespace on both sides
while minValue!= maxValue { // use of '=' in a boolean context, did you mean '=='?
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedLst = lst
var min = sortedLst.min()!
var max = sortedLst.max()!
while min < max {
for i in 0..<sortedLst.count {
if sortedLst[i] == min {
sortedLst[i] = max
max -= 1
} else if sortedLst[i] == max {
sortedLst[i] = min
min += 1
}
}
}
return sortedLst
}
```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 sortedLst = lst
var min = sortedLst.min()!
var max = sortedLst.max()!
while min < max {
for i in 0..<sortedLst.count {
if sortedLst[i] == min {
sortedLst[i] = max
max -= 1
} else if sortedLst[i] == max {
sortedLst[i] = min
min += 1
}
}
}
return sortedLst
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [1, 30, 2, 29, 3, 28, 4, 27, 5, 26, 6, 25, 7, 24, 8, 23, 9, 22, 10, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]) == [1, 40, 2, 39, 3, 38, 4, 37, 5, 36, 6, 35, 7, 34, 8, 33, 9, 32, 10, 31, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
let min = lst.min()!
let max = lst.max()!
let minMaxRange = max - min + 1
var buckets = Array(repeating: [Int](), count: minMaxRange)
for num in lst {
let index = num - min
buckets[index].append(num)
}
return buckets.flatMap { $0 }
}
```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 }
let min = lst.min()!
let max = lst.max()!
let minMaxRange = max - min + 1
var buckets = Array(repeating: [Int](), count: minMaxRange)
for num in lst {
let index = num - min
buckets[index].append(num)
}
return buckets.flatMap { $0 }
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sortedLst = lst
for i in 0..<sortedLst.count {
let minIndex = sortedLst.indices.min(by: { sortedLst[$0] < sortedLst[$1] })!
let maxIndex = sortedLst.indices.max(by: { sortedLst[$0] < sortedLst[$1] })!
if i % 2 == 0 {
(sortedLst[i], sortedLst[minIndex]) = (sortedLst[minIndex], sortedLst[i])
(sortedLst[i + 1], sortedLst[maxIndex]) = (sortedLst[maxIndex], sortedLst[i + 1])
} else {
(sortedLst[i], sortedLst[maxIndex]) = (sortedLst[maxIndex], sortedLst[i])
(sortedLst[i + 1], sortedLst[minIndex]) = (sortedLst[minIndex], sortedLst[i + 1])
}
}
return sortedLst
}
```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 sortedLst = lst
for i in 0..<sortedLst.count {
let minIndex = sortedLst.indices.min(by: { sortedLst[$0] < sortedLst[$1] })!
let maxIndex = sortedLst.indices.max(by: { sortedLst[$0] < sortedLst[$1] })!
if i % 2 == 0 {
(sortedLst[i], sortedLst[minIndex]) = (sortedLst[minIndex], sortedLst[i])
(sortedLst[i + 1], sortedLst[maxIndex]) = (sortedLst[maxIndex], sortedLst[i + 1])
} else {
(sortedLst[i], sortedLst[maxIndex]) = (sortedLst[maxIndex], sortedLst[i])
(sortedLst[i + 1], sortedLst[minIndex]) = (sortedLst[minIndex], sortedLst[i + 1])
}
}
return sortedLst
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [20, 1, 19, 2, 18, 3, 17, 4, 16, 5, 15, 6, 14, 7, 13, 8, 12, 9, 11, 10])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [1, 30, 2, 29, 3, 28, 4, 27, 5, 26, 6, 25, 7, 24, 8, 23, 9, 22, 10, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
// Fatal error: Index out of range
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 1 else { return lst }
var sorted = lst
for i in 0..<sorted.count {
let min = sorted.min()!
let index = sorted.firstIndex(of: min)!
sorted.remove(at: index)
sorted.append(min)
}
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 = lst
for i in 0..<sorted.count {
let min = sorted.min()!
let index = sorted.firstIndex(of: min)!
sorted.remove(at: index)
sorted.append(min)
}
return sorted
}
// Tests
assert(strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3])
assert(strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5])
assert(strangeSortList(lst: []) == [])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == [1, 10, 2, 9, 3, 8, 4, 7, 5, 6])
assert(strangeSortList(lst: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]) == [10, 1, 9, 2, 8, 3, 7, 4, 6, 5])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]) == [1, 20, 2, 19, 3, 18, 4, 17, 5, 16, 6, 15, 7, 14, 8, 13, 9, 12, 10, 11])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]) == [1, 30, 2, 29, 3, 28, 4, 27, 5, 26, 6, 25, 7, 24, 8, 23, 9, 22, 10, 21, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])
assert(strangeSortList(lst: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]) == [1, 40, 2, 39, 3, 38, 4, 37, 5, 36, 6, 35, 7, 34, 8, 33, 9, 32, 10, 31, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30])
assert(strangeSortList(lst: [1, 2,
for i in 0..<sorted.count { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
// Calculate the semi-perimeter
let s = (Double)(a + b + c) / 2
// Calculate and return the area using Heron's formula, rounded to 2 decimal places
return round((s * (s - Double(a)) * (s - Double(b)) * (s - Double(c))) * 100) / 100
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
// Calculate the semi-perimeter
let s = (Double)(a + b + c) / 2
// Calculate and return the area using Heron's formula, rounded to 2 decimal places
return round((s * (s - Double(a)) * (s - Double(b)) * (s - Double(c))) * 100) / 100
}
// Test cases
assert(triangleArea(a: 3, b: 4, c: 5) == 6.0)
assert(triangleArea(a: 1, b: 2, c: 10) == -1)
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
triangleArea(a: 3, b: 4, c: 5) == 6.0
triangleArea(a: 1, b: 2, c: 10) == -1
```
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
triangleArea(a: 3, b: 4, c: 5) // 6.0
triangleArea(a: 1, b: 2, c: 10) // -1
```
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
func longestSubarray(arr: [Int]) -> Int {
var longest = 0
var current = 0
var zeros = 0
var ones = 0
for i in arr {
if i == 0 {
zeros += 1
} else {
ones += 1
}
if zeros == ones {
longest = max(longest, current + 1)
} else {
current = 0
}
current += 1
}
return longest
}
func longestAlternatingSubarray(arr: [Int]) -> Int {
var longest = 0
var current = 0
var zeros = 0
var ones = 0
for i in arr {
if i == 0 {
zeros += 1
} else {
ones += 1
}
if zeros == ones {
longest = max(longest, current + 1)
} else {
current = 0
}
current += 1
}
return longest
}
func longestAlternatingSubarray2(arr: [Int]) -> Int {
var longest = 0
var current = 0
var previous = arr[0]
for i in arr {
if previous == i {
current += 1
} else {
longest = max(longest, current)
current = 1
}
previous = i
}
return max(longest, current)
}
func longestAlternatingSubarray3(arr: [Int]) -> Int {
var longest = 0
var current = 0
var previous = arr[0]
for i in arr {
if previous == i {
current += 1
} else {
longest = max(longest, current)
current = 1
}
previous = i
}
return max(longest, current)
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2
return sqrt(s * (s - a) * (s - b) * (s - c))
}
// Given an array of integers, return the length of the longest subarray
// that has an equal number of 0s and 1s.
// Example:
// longestSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 1]) == 6
// longestSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 0]) == 5
func longestSubarray(arr: [Int]) -> Int {
var longest = 0
var current = 0
var zeros = 0
var ones = 0
for i in arr {
if i == 0 {
zeros += 1
} else {
ones += 1
}
if zeros == ones {
longest = max(longest, current + 1)
} else {
current = 0
}
current += 1
}
return longest
}
// Given an array of integers, return the length of the longest subarray
// that has an equal number of 0s and 1s.
// Example:
// longestAlternatingSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 1]) == 6
// longestAlternatingSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 0]) == 5
func longestAlternatingSubarray(arr: [Int]) -> Int {
var longest = 0
var current = 0
var zeros = 0
var ones = 0
for i in arr {
if i == 0 {
zeros += 1
} else {
ones += 1
}
if zeros == ones {
longest = max(longest, current + 1)
} else {
current = 0
}
current += 1
}
return longest
}
// Given an array of integers, return the length of the longest subarray
// that has an equal number of 0s and 1s.
// Example:
// longestAlternatingSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 1]) == 6
// longestAlternatingSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 0]) == 5
func longestAlternatingSubarray2(arr: [Int]) -> Int {
var longest = 0
var current = 0
var previous = arr[0]
for i in arr {
if previous == i {
current += 1
} else {
longest = max(longest, current)
current = 1
}
previous = i
}
return max(longest, current)
}
// Given an array of integers, return the length of the longest subarray
// that has an equal number of 0s and 1s.
// Example:
// longestAlternatingSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 1]) == 6
// longestAlternatingSubarray(arr: [0, 1, 1, 0, 1, 1, 1, 0, 0, 0]) == 5
func longestAlternatingSubarray3(arr: [Int]) -> Int {
var longest = 0
var current = 0
var previous = arr[0]
for i in arr {
if previous == i {
current += 1
} else {
longest = max(longest, current)
current = 1
}
previous = i
}
return max(longest, current)
}
// Given an array of integers, return the length of the longest subarray
// that has an equal number of 0s and 1s.
//
return sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
// Calculate the semi-perimeter
let s = (a + b + c) / 2.0
// Calculate and return the area using Heron's formula, rounded to 2 decimal places
return round((s * (s - Double(a)) * (s - Double(b)) * (s - Double(c))) * 100) / 100
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
// Calculate the semi-perimeter
let s = (a + b + c) / 2.0
// Calculate and return the area using Heron's formula, rounded to 2 decimal places
return round((s * (s - Double(a)) * (s - Double(b)) * (s - Double(c))) * 100) / 100
}
// Test cases
assert(triangleArea(a: 3, b: 4, c: 5) == 6.0)
assert(triangleArea(a: 1, b: 2, c: 10) == -1)
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
// Compute the area using Heron's formula
let s = (a + b + c) / 2.0
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return Double(round(100 * area)/100)
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
// Compute the area using Heron's formula
let s = (a + b + c) / 2.0
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return Double(round(100 * area)/100)
}
// Test cases
assert(triangleArea(a: 3, b: 4, c: 5) == 6.0)
assert(triangleArea(a: 1, b: 2, c: 10) == -1)
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
}
triangleArea(a: 3, b: 4, c: 5) == 6.0
triangleArea(a: 1, b: 2, c: 10) == -1
triangleArea(a: 3, b: 4, c: 7) == 2.0
triangleArea(a: 5, b: 12, c: 13) == 4.47213595499958
triangleArea(a: 1, b: 1, c: 5) == -1
triangleArea(a: 3, b: 4, c: 6) == 5.0
triangleArea(a: 1000000000, b: 1000000000, c: 1000000000) == 500000000000000.0
triangleArea(a: 1000000000, b: 1000000000, c: 900000000) == 3141592653.589793
triangleArea(a: 1, b: 1, c: 1) == -1
triangleArea(a: 1, b: 1, c: 0) == -1
triangleArea(a: 1, b: 1, c: -1) == -1
triangleArea(a: 1, b: 1, c: 2) == -1
triangleArea(a: 1, b: 2, c: 1) == -1
triangleArea(a: 2, b: 1, c: 1) == -1
triangleArea(a: 1, b: 2, c: 3) == -1
triangleArea(a: 3, b: 2, c: 1) == -1
triangleArea(a: 1, b: 3, c: 2) == -1
triangleArea(a: 2, b: 3, c: 1) == -1
triangleArea(a: 1, b: 2, c: 1000000000) == -1
triangleArea(a: 1000000000, b: 1, c: 2) == -1
triangleArea(a: 1000000000, b: 2, c: 1) == -1
triangleArea(a: 2, b: 1000000000, c: 1) == -1
triangleArea(a: 1000000000, b: 2, c: 1000000000) == -1
triangleArea(a: 1000000000, b: 1000000000, c: 1) == -1
triangleArea(a: 1000000000, b: 1000000000, c: 1000000000) == -1
triangleArea(a: 1000000000, b: 1000000000, c: 900000000) == -1
triangleArea(a: 900000000, b: 1000000000, c: 1000000000) == -1
triangleArea(a: 1000000000, b: 900000000, c: 1000000000) == -1
triangleArea(a: 1000000000, b: 1000000000, c: 800000000) == -1
triangleArea(a:
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
// Compute the area using Heron's formula
let s = (a + b + c) / 2.0
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return Double(round(100 * area)/100)
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
// Check if the triangle is valid
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
// Compute the area using Heron's formula
let s = (a + b + c) / 2.0
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return Double(round(100 * area)/100)
}
// Test cases
assert(triangleArea(a: 3, b: 4, c: 5) == 6.0)
assert(triangleArea(a: 1, b: 2, c: 10) == -1)
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
}
triangleArea(a: 3, b: 4, c: 5) == 6.0
triangleArea(a: 1, b: 2, c: 10) == -1
triangleArea(a: 3, b: 4, c: 7) == 2.0
triangleArea(a: 5, b: 12, c: 13) == 4.472135955
triangleArea(a: 1, b: 1, c: 5) == -1
triangleArea(a: 3, b: 4, c: 6) == 5.0
triangleArea(a: 1000000000, b: 1000000000, c: 1000000000) == 5000000000000000000.0
triangleArea(a: 1000000000, b: 1000000000, c: 900000000) == 4503599627370496.0
triangleArea(a: 1000000000, b: 900000000, c: 1000000000) == 4503599627370496.0
triangleArea(a: 900000000, b: 1000000000, c: 1000000000) == 4503599627370496.0
triangleArea(a: 1000000000, b: 1000000000, c: 800000000) == 36028797018963968.0
triangleArea(a: 800000000, b: 1000000000, c: 1000000000) == 36028797018963968.0
triangleArea(a: 1000000000, b: 800000000, c: 1000000000) == 36028797018963968.0
triangleArea(a: 800000000, b: 1000000000, c: 800000000) == 32212254726356128.0
triangleArea(a: 800000000, b: 800000000, c: 1000000000) == 32212254726356128.0
triangleArea(a: 1000000000, b: 800000000, c: 800000000) == 32212254726356128.0
triangleArea(a: 800000000, b: 1000000000, c: 700000000) == 2824730347078056.0
triangleArea(a: 700000000, b: 1000000000, c: 1000000000) == 2824730347078056.0
triangleArea(a: 1000000000, b
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || b + c <= a || a + c <= b {
return -1
}
let s = (a + b + c) / 2.0
return sqrt(s * (s - a) * (s - b) * (s - c))
}
triangleArea(a: 3, b: 4, c: 5) == 6.0
triangleArea(a: 1, b: 2, c: 10) == -1
triangleArea(a: 3, b: 4, c: 7) == 2.0
triangleArea(a: 5, b: 12, c: 13) == 42.0
triangleArea(a: 1, b: 1, c: 5) == -1
triangleArea(a: 1000000000, b: 1000000000, c: 1000000000) == 4294967296.0
triangleArea(a: 1, b: 2, c: 3) == 0.5
triangleArea(a: 1, b: 2, c: 1) == 0.0
triangleArea(a: 1, b: 1, c: 1) == -1
triangleArea(a: 1, b: 1, c: 0) == -1
triangleArea(a: 1, b: 1, c: -1) == -1
triangleArea(a: -1, b: 2, c: 1) == -1
triangleArea(a: 1, b: -2, c: 1) == -1
triangleArea(a: 1, b: 2, c: -1) == -1
triangleArea(a: -1, b: -2, c: 1) == -1
triangleArea(a: -1, b: 2, c: -1) == -1
triangleArea(a: 1, b: -2, c: -1) == -1
triangleArea(a: -1, b: -2, c: -1) == -1
triangleArea(a: 1, b: 1000000000, c: 1000000000) == 4294967296.0
triangleArea(a: 1000000000, b: 1, c: 1000000000) == 4294967296.0
triangleArea(a: 1000000000, b: 1000000000, c: 1) == 4294967296.0
triangleArea(a: 1000000000, b: 1000000000, c: 1000000000) == 4294967296.0
triangleArea(a: 2, b: 2, c: 1) == 0.5
triangleArea(a: 2, b: 2, c: 2) == 1.0
triangleArea(a: 2, b: 2, c: 3) == 1.5
triangleArea(a: 2, b: 2, c: 4) == 2.0
triangleArea(a: 2, b: 2, c: 5) == 2.5
triangleArea(a: 2, b: 2, c: 10) == 5.0
triangleArea(a: 2, b: 2, c: 100) == 50.0
triangleArea(a: 2, b: 2, c: 1000) == 500.0
triangleArea(a: 2, b: 2, c: 10000) == 5000.0
triangleArea(a: 2, b: 2, c: 100000) == 50000.0
triangleArea(a: 2, b: 2, c: 1000000) == 500
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
func willItFly2(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func willItFly3(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
// 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 willItFly2(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
// 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 willItFly3(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
// 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 willItFly4(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <=
func isPalindrome(_ array: [Int]) -> Bool { // invalid redeclaration of 'isPalindrome'
if array[left]!= array[right] { // use of '=' in a boolean context, did you mean '=='?
if array[left]!= array[right] { // '=' must have consistent whitespace on both sides
if array[left]!= array[right] { // cannot force unwrap value of non-optional type 'Int'
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && sum(q) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
return array.reduce(0, +)
}
func willItFly(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && sum(p) <= w
}
func willItFly(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && sum(r) <= w
}
func willItFly(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && sum(s) <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && sum(q) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
return array.reduce(0, +)
}
// Write a function that returns true if the object p will fly, and false otherwise.
// The object p 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(p: [1, 2], w: 5) == false
// willItFly(p: [3, 2, 3], w: 1) == false
// willItFly(p: [3, 2, 3], w: 9) == true
// willItFly(p: [3], w: 5) == true
func willItFly(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && sum(p) <= w
}
// Write a function that returns true if the object r will fly, and false otherwise.
// The object r 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(r: [1, 2], w: 5) == false
// willItFly(r: [3, 2, 3], w: 1) == false
// willItFly(r: [3, 2, 3], w: 9) == true
// willItFly(r: [3], w: 5) == true
func willItFly(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && sum(r) <= w
}
// Write a function that returns true if the object s will fly, and false otherwise.
// The object s 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(s: [1, 2], w: 5) == false
// willItFly(s: [3, 2, 3], w: 1) == false
// willItFly(s: [3, 2, 3], w: 9) == true
// willItFly(s: [3], w: 5) == true
func willItFly(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && sum(s) <= w
}
// Write a function that returns true if the object t will fly, and false otherwise.
// The object t 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
if array[left]!= array[right] { // cannot force unwrap value of non-optional type 'Int'
if array[left]!= array[right] { // use of '=' in a boolean context, did you mean '=='?
if array[left]!= array[right] { // '=' must have consistent whitespace on both sides
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
func willItCrash(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && p.reduce(0, +) >= w
}
func willItCrash(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && r.reduce(0, +) <= w
}
func willItCrash(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && s.reduce(0, +) >= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
// Write a function that returns true if the object p will crash, and false otherwise.
// The object p will crash if it is balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is more than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is more than the minimum possible weight, and it's balanced.
// # 3 is more than the minimum possible weight, and it's balanced.
// willItCrash(p: [1, 2], w: 5) == false
// willItCrash(p: [3, 2, 3], w: 1) == false
// willItCrash(p: [3, 2, 3], w: 9) == true
// willItCrash(p: [3], w: 5) == true
func willItCrash(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && p.reduce(0, +) >= w
}
// Write a function that returns true if the object r will crash, and false otherwise.
// The object r will crash if it is balanced (it is a palindromic array) and the sum of its elements is less than or equal to 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.
// willItCrash(r: [1, 2], w: 5) == false
// willItCrash(r: [3, 2, 3], w: 1) == false
// willItCrash(r: [3, 2, 3], w: 9) == true
// willItCrash(r: [3], w: 5) == true
func willItCrash(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && r.reduce(0, +) <= w
}
// Write a function that returns true if the object s will crash, and false otherwise.
// The object s will crash if it is balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is more than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is more than the minimum possible weight, and it's balanced.
// # 3 is more than the minimum possible weight, and it's balanced.
// willItCrash(s: [1, 2], w: 5) == false
// willItCrash(s: [3, 2, 3], w: 1) == false
// willItCrash(s: [3, 2, 3], w: 9) == true
// willItCrash(s: [3], w: 5) == true
func willItCrash(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && s.reduce(0, +) >= w
}
// Write a function that returns true if the object t will crash, and false otherwise.
// The object t will crash if it is balanced (it is a palindromic array) and the sum of its elements is less than or equal to 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,
func willItFly(q: [Int], w: Int) -> Bool {
let isPalindrome = q.sorted() == q.reversed().sorted()
let sum = q.reduce(0, +)
return isPalindrome && sum <= w
}
func willItCrash(p: [Int], w: Int) -> Bool {
let isPalindrome = p.sorted() == p.reversed().sorted()
let sum = p.reduce(0, +)
return isPalindrome && sum >= w
}
func willItCrash(r: [Int], w: Int) -> Bool {
let isPalindrome = r.sorted() == r.reversed().sorted()
let sum = r.reduce(0, +)
return isPalindrome && sum <= w
}
func willItCrash(s: [Int], w: Int) -> Bool {
let isPalindrome = s.sorted() == s.reversed().sorted()
let sum = s.reduce(0, +)
return isPalindrome && sum >= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let isPalindrome = q.sorted() == q.reversed().sorted()
let sum = q.reduce(0, +)
return isPalindrome && sum <= w
}
// Write a function that returns true if the object p will crash, and false otherwise.
// The object p will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(p: [1, 2], w: 5) == false
// willItCrash(p: [3, 2, 3], w: 1) == false
// willItCrash(p: [3, 2, 3], w: 9) == true
// willItCrash(p: [3], w: 5) == true
func willItCrash(p: [Int], w: Int) -> Bool {
let isPalindrome = p.sorted() == p.reversed().sorted()
let sum = p.reduce(0, +)
return isPalindrome && sum >= w
}
// Write a function that returns true if the object r will crash, and false otherwise.
// The object r will crash if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal to 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.
// willItCrash(r: [1, 2], w: 5) == false
// willItCrash(r: [3, 2, 3], w: 1) == false
// willItCrash(r: [3, 2, 3], w: 9) == true
// willItCrash(r: [3], w: 5) == true
func willItCrash(r: [Int], w: Int) -> Bool {
let isPalindrome = r.sorted() == r.reversed().sorted()
let sum = r.reduce(0, +)
return isPalindrome && sum <= w
}
// Write a function that returns true if the object s will crash, and false otherwise.
// The object s will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(s: [1, 2], w: 5) == false
// willItCrash(s: [3, 2, 3], w: 1) == false
// willItCrash(s: [3, 2, 3], w: 9) == true
// willItCrash(s: [3], w: 5) == true
func willItCrash(s: [Int], w: Int) -> Bool {
let isPalindrome = s.sorted() == s.reversed().sorted()
let sum = s.reduce(0, +)
return isPalindrome && sum >= w
}
// Write a function that returns true if the object q will crash, and false otherwise.
// The object q will crash if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal to the maximum possible weight w.
// Example:
// # 1
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(q)
let sum = q.reduce(0, +)
return isBalanced && sum <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
func willItCrash(p: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(p)
let sum = p.reduce(0, +)
return isBalanced && sum >= w
}
func willItRotate(r: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(r)
let sum = r.reduce(0, +)
return isBalanced && sum <= w
}
func willItSink(s: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(s)
let sum = s.reduce(0, +)
return isBalanced && sum >= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(q)
let sum = q.reduce(0, +)
return isBalanced && sum <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
// Write a function that returns true if the object p will crash, and false otherwise.
// The object p will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater 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.
// willItCrash(p: [1, 2], w: 5) == false
// willItCrash(p: [3, 2, 3], w: 1) == true
// willItCrash(p: [3, 2, 3], w: 9) == false
// willItCrash(p: [3], w: 5) == false
func willItCrash(p: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(p)
let sum = p.reduce(0, +)
return isBalanced && sum >= w
}
// Write a function that returns true if the object r will rotate, and false otherwise.
// The object r will rotate 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.
// willItRotate(r: [1, 2], w: 5) == false
// willItRotate(r: [3, 2, 3], w: 1) == false
// willItRotate(r: [3, 2, 3], w: 9) == true
// willItRotate(r: [3], w: 5) == false
func willItRotate(r: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(r)
let sum = r.reduce(0, +)
return isBalanced && sum <= w
}
// Write a function that returns true if the object s will sink, and false otherwise.
// The object s will sink if it's balanced (it is a palindromic array) and the sum of its elements is greater 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.
// willItSink(s: [1, 2], w: 5) == false
// willItSink(s: [3, 2, 3], w: 1) == false
// willItSink(s: [3, 2, 3], w: 9) == false
// willItSink(s: [3], w: 5) == true
func willItSink(s: [Int], w: Int) -> Bool {
let isBalanced = isPalindrome(s)
let sum = s.reduce(0, +)
return isBalanced && sum >= w
}
// Write a function that returns true if the object t will float, and false otherwise.
// The object t will float if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbal
func willItFly(q: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(q)
let sum = sum(q)
return isPalindrome && sum <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
var sum = 0
for i in array {
sum += i
}
return sum
}
func willItFly(p: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(p)
let sum = sum(p)
return isPalindrome && sum <= w
}
func willItFly(r: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(r)
let sum = sum(r)
return isPalindrome && sum <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(q)
let sum = sum(q)
return isPalindrome && sum <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
var sum = 0
for i in array {
sum += i
}
return sum
}
// Write a function that returns true if the object p will fly, and false otherwise.
// The object p 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(p: [1, 2], w: 5) == false
// willItFly(p: [3, 2, 3], w: 1) == false
// willItFly(p: [3, 2, 3], w: 9) == true
// willItFly(p: [3], w: 5) == true
func willItFly(p: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(p)
let sum = sum(p)
return isPalindrome && sum <= w
}
// Write a function that returns true if the object r will fly, and false otherwise.
// The object r 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(r: [1, 2], w: 5) == false
// willItFly(r: [3, 2, 3], w: 1) == false
// willItFly(r: [3, 2, 3], w: 9) == true
// willItFly(r: [3], w: 5) == true
func willItFly(r: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(r)
let sum = sum(r)
return isPalindrome && sum <= w
}
// Write a function that returns true if the object s will fly, and false otherwise.
// The object s 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(s: [1, 2], w: 5) == false
// willItFly(s: [3, 2, 3], w: 1) == false
// willItFly(s: [3, 2, 3], w: 9) == true
// willItFly(s: [3], w: 5) == true
func willItFly(s: [Int], w: Int) -> Bool {
// Write your code here
let isPalindrome = isPalindrome(s)
let sum = sum(s)
return is
if array[left]!= array[right] { // use of '=' in a boolean context, did you mean '=='?
if array[left]!= array[right] { // '=' must have consistent whitespace on both sides
if array[left]!= array[right] { // cannot force unwrap value of non-optional type 'Int'
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && sum(q) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
return array.reduce(0, +)
}
func willItCrash(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && sum(p) >= w
}
func willItRotate(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && sum(r) == w
}
func willItSink(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && sum(s) > w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && sum(q) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
return array.reduce(0, +)
}
// Write a function that returns true if the object p will crash, and false otherwise.
// The object p will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(p: [1, 2], w: 5) == false
// willItCrash(p: [3, 2, 3], w: 1) == false
// willItCrash(p: [3, 2, 3], w: 9) == true
// willItCrash(p: [3], w: 5) == true
func willItCrash(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && sum(p) >= w
}
// Write a function that returns true if the object r will rotate, and false otherwise.
// The object r will rotate if it's balanced (it is a palindromic array) and the sum of its elements is equal to the minimum possible weight w.
// Example:
// # 1+2 is equal to the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is not equal to the minimum possible weight.
// # 3+2+3 is equal to the minimum possible weight, and it's balanced.
// # 3 is equal to the minimum possible weight, and it's balanced.
// willItRotate(r: [1, 2], w: 5) == false
// willItRotate(r: [3, 2, 3], w: 1) == false
// willItRotate(r: [3, 2, 3], w: 9) == true
// willItRotate(r: [3], w: 5) == true
func willItRotate(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && sum(r) == w
}
// Write a function that returns true if the object s will sink, and false otherwise.
// The object s will sink if it's balanced (it is a palindromic array) and the sum of its elements is greater than the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItSink(s: [1, 2], w: 5) == false
// willItSink(s: [3, 2, 3], w: 1) == false
// willItSink(s: [3, 2, 3], w: 9) == true
// willItSink(s: [3], w: 5) == true
func willItSink(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && sum(s) > w
}
// Write a function that returns true if the object t will float, and false otherwise.
// The object t will float 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.
// #
if array[left]!= array[right] { // cannot force unwrap value of non-optional type 'Int'
if array[left]!= array[right] { // use of '=' in a boolean context, did you mean '=='?
if array[left]!= array[right] { // '=' must have consistent whitespace on both sides
func willItFly(q: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(q) && sum(q) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
var sum = 0
for i in array {
sum += i
}
return sum
}
func willItFly(p: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(p) && sum(p) <= w
}
func willItFly(r: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(r) && sum(r) <= w
}
func willItFly(s: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(s) && sum(s) <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(q) && sum(q) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
var left = 0
var right = array.count - 1
while left < right {
if array[left]!= array[right] {
return false
}
left += 1
right -= 1
}
return true
}
func sum(_ array: [Int]) -> Int {
var sum = 0
for i in array {
sum += i
}
return sum
}
// Write a function that returns true if the object p will fly, and false otherwise.
// The object p 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(p: [1, 2], w: 5) == false
// willItFly(p: [3, 2, 3], w: 1) == false
// willItFly(p: [3, 2, 3], w: 9) == true
// willItFly(p: [3], w: 5) == true
func willItFly(p: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(p) && sum(p) <= w
}
// Write a function that returns true if the object r will fly, and false otherwise.
// The object r 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(r: [1, 2], w: 5) == false
// willItFly(r: [3, 2, 3], w: 1) == false
// willItFly(r: [3, 2, 3], w: 9) == true
// willItFly(r: [3], w: 5) == true
func willItFly(r: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(r) && sum(r) <= w
}
// Write a function that returns true if the object s will fly, and false otherwise.
// The object s 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(s: [1, 2], w: 5) == false
// willItFly(s: [3, 2, 3], w: 1) == false
// willItFly(s: [3, 2, 3], w: 9) == true
// willItFly(s: [3], w: 5) == true
func willItFly(s: [Int], w: Int) -> Bool {
// Write your code here
return isPalindrome(s) && sum(s) <= w
}
// Write a function that returns true if the object t will fly, and false otherwise.
// The object t will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum
if array[left]!= array[right] { // cannot force unwrap value of non-optional type 'Int'
if array[left]!= array[right] { // '=' must have consistent whitespace on both sides
if array[left]!= array[right] { // use of '=' in a boolean context, did you mean '=='?
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
func willItCrash(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && p.reduce(0, +) >= w
}
func willItCrash(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && r.reduce(0, +) >= w
}
func willItCrash(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && s.reduce(0, +) <= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
return isPalindrome(q) && q.reduce(0, +) <= w
}
func isPalindrome(_ array: [Int]) -> Bool {
return array == array.reversed()
}
// Write a function that returns true if the object p will crash, and false otherwise.
// The object p will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(p: [1, 2], w: 5) == false
// willItCrash(p: [3, 2, 3], w: 1) == false
// willItCrash(p: [3, 2, 3], w: 9) == true
// willItCrash(p: [3], w: 5) == true
func willItCrash(p: [Int], w: Int) -> Bool {
return isPalindrome(p) && p.reduce(0, +) >= w
}
// Write a function that returns true if the object r will crash, and false otherwise.
// The object r will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(r: [1, 2], w: 5) == false
// willItCrash(r: [3, 2, 3], w: 1) == false
// willItCrash(r: [3, 2, 3], w: 9) == true
// willItCrash(r: [3], w: 5) == true
func willItCrash(r: [Int], w: Int) -> Bool {
return isPalindrome(r) && r.reduce(0, +) >= w
}
// Write a function that returns true if the object s will crash, and false otherwise.
// The object s will crash if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal to 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.
// willItCrash(s: [1, 2], w: 5) == false
// willItCrash(s: [3, 2, 3], w: 1) == false
// willItCrash(s: [3, 2, 3], w: 9) == true
// willItCrash(s: [3], w: 5) == true
func willItCrash(s: [Int], w: Int) -> Bool {
return isPalindrome(s) && s.reduce(0, +) <= w
}
// Write a function that returns true if the object t will crash, and false otherwise.
// The object t will crash if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal to 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,
func willItFly(q: [Int], w: Int) -> Bool {
let isPalindrome = q.map { String($0) }.joined() == String(q.reversed().map { String($0) }.joined())
let sum = q.reduce(0, +)
return isPalindrome && sum <= w
}
func willItCrash(p: [Int], w: Int) -> Bool {
let isPalindrome = p.map { String($0) }.joined() == String(p.reversed().map { String($0) }.joined())
let sum = p.reduce(0, +)
return isPalindrome && sum >= w
}
func willItCrash(r: [Int], w: Int) -> Bool {
let isPalindrome = r.map { String($0) }.joined() == String(r.reversed().map { String($0) }.joined())
let sum = r.reduce(0, +)
return isPalindrome && sum >= w
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let isPalindrome = q.map { String($0) }.joined() == String(q.reversed().map { String($0) }.joined())
let sum = q.reduce(0, +)
return isPalindrome && sum <= w
}
// Write a function that returns true if the object p will crash, and false otherwise.
// The object p will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(p: [1, 2], w: 5) == false
// willItCrash(p: [3, 2, 3], w: 1) == false
// willItCrash(p: [3, 2, 3], w: 9) == true
// willItCrash(p: [3], w: 5) == true
func willItCrash(p: [Int], w: Int) -> Bool {
let isPalindrome = p.map { String($0) }.joined() == String(p.reversed().map { String($0) }.joined())
let sum = p.reduce(0, +)
return isPalindrome && sum >= w
}
// Write a function that returns true if the object r will crash, and false otherwise.
// The object r will crash if it's balanced (it is a palindromic array) and the sum of its elements is greater than or equal to the minimum possible weight w.
// Example:
// # 1+2 is greater than the minimum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is less than the minimum possible weight.
// # 3+2+3 is greater than the minimum possible weight, and it's balanced.
// # 3 is greater than the minimum possible weight, and it's balanced.
// willItCrash(r: [1, 2], w: 5) == false
// willItCrash(r: [3, 2, 3], w: 1) == false
// willItCrash(r: [3, 2, 3], w: 9) == true
// willItCrash(r: [3], w: 5) == true
func willItCrash(r: [Int], w: Int) -> Bool {
let isPalindrome = r.map { String($0) }.joined() == String(r.reversed().map { String($0) }.joined())
let sum = r.reduce(0, +)
return isPalindrome && sum >= w
}
// Write a function that returns true if the object s will crash, and false otherwise.
// The object s will crash 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.
// willItCrash(s: [1, 2], w: 5) == false
// willItCrash(s: [3, 2, 3], w: 1) == false
// willItCrash(s: [3, 2, 3], w: 9) == true
// willItCrash(s: [3], w: 5) == true
func willItCrash(s: [Int], w: Int) -> Bool {
let isPalindrome = s.map { String($0) }.joined() == String(s.reversed().map { String($0) }.joined())
let sum = s.reduce(0, +)
return isPalindrome && sum <= w
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count/2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count/2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
print(smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]))
print(smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]))
print(smallestChange(arr: [1, 2, 3, 2, 1]))
print(smallestChange(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(smallestChange(arr: [9, 8, 7, 6, 5, 4, 3, 2, 1]))
print(smallestChange(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]))
print(smallestChange(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93
if arr[i]!= arr[arr.count - i - 1] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[arr.count - i - 1] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - i - 1] { // use of '=' in a boolean context, did you mean '=='?
arr[i] = arr[arr.count - i - 1] // cannot assign through subscript: 'arr' is a 'let' constant
arr[arr.count - i - 1] = temp // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
func largestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[i] = arr[j]
} else {
arr[j] = arr[i]
}
}
i += 1
j -= 1
}
return changes
}
func minChanges(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
func maxChanges(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[i] = arr[j]
} else {
arr[j] = arr[i]
}
}
i += 1
j -= 1
}
return changes
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
// Given an array arr of integers, find the maximum 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:
// largestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// largestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// largestChange(arr: [1, 2, 3, 2, 1]) == 0
func largestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[i] = arr[j]
} else {
arr[j] = arr[i]
}
}
i += 1
j -= 1
}
return changes
}
// 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:
// minChanges(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// minChanges(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// minChanges(arr: [1, 2, 3, 2, 1]) == 0
func minChanges(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
// Given an array arr of integers, find the maximum 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:
// maxChanges(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// maxChanges(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// maxChanges(arr: [1, 2, 3, 2, 1]) == 0
func maxChanges(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[i] = arr[j]
} else {
arr[j] = arr[i]
}
}
i += 1
j -= 1
}
return changes
}
// 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:
// minChanges(arr: [1, 2, 3, 5,
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
arr[j] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
arr[j] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
arr[j] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
arr[j] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
func largestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
func smallestChange2(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 1
}
return count
}
func largestChange2(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
// Given an array arr of integers, find the maximum 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:
// largestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 6
// largestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// largestChange(arr: [1, 2, 3, 2, 1]) == 0
func largestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - 1 - i] {
count += 1
}
}
return count
}
// 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:
// smallestChange2(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange2(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange2(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange2(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 1
}
return count
}
// Given an array arr of integers, find the maximum 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:
// largestChange2(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 6
// largestChange2(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// largestChange2(arr: [1, 2, 3, 2, 1]) == 0
func largestChange2(arr: [Int]) -> Int {
var count = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
count += 1
}
i += 1
j -= 1
}
return count
}
// 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:
// smallestChange3(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange3(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange3(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange3(arr: [Int]) -> Int {
var count = 0
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]
if arr[i]!= arr[arr.count - 1 - i] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - 1 - i] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[arr.count - 1 - i] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[arr.count - 1 - i] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - 1 - i] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[arr.count - 1 - i] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
arr[arr.count - i - 1] = arr[i]
}
}
return changes
}
func sumArray(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
func multiplyArray(arr: [Int]) -> Int {
var product = 1
for i in arr {
product *= i
}
return product
}
func multiplyUniqueArray(arr: [Int]) -> Int {
var product = 1
var uniqueMultiples: Set<Int> = []
for i in arr {
if!uniqueMultiples.contains(i) {
product *= i
uniqueMultiples.insert(i)
}
}
return product
}
func multiplyUniqueAndSortedArray(arr: [Int]) -> Int {
var product = 1
var uniqueMultiples: Set<Int> = []
var sorted = arr.sorted()
var i = 0
var j = arr.count - 1
while i < j {
if!uniqueMultiples.contains(sorted[i]) {
product *= sorted[i]
uniqueMultiples.insert(sorted[i])
}
if!uniqueMultiples.contains(sorted[j]) {
product *= sorted[j]
uniqueMultiples.insert(sorted[j])
}
i += 1
j -= 1
}
return product
}
func multiplyUniqueAndSortedArray2(arr: [Int]) -> Int {
var product = 1
var uniqueMultiples: Set<Int> = []
var sorted = arr.sorted()
var i = 0
var j = arr.count - 1
while i < j {
if!uniqueMultiples.contains(sorted[i]) {
product *= sorted[i]
uniqueMultiples.insert(sorted[i])
}
i += 1
}
while i < j {
if!uniqueMultiples.contains(sorted[j]) {
product *= sorted[j]
uniqueMultiples.insert(sorted[j])
}
j -= 1
}
return product
}
```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 changes = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
arr[arr.count - i - 1] = arr[i]
}
}
return changes
}
// Given an array of integers, return the sum of all the integers.
// For example:
// sumArray([1, 2, 3, 4, 5]) == 15
// sumArray([10, 15, 30]) == 45
func sumArray(arr: [Int]) -> Int {
var sum = 0
for i in arr {
sum += i
}
return sum
}
// Given an array of integers, return the sum of all the integers multiplied together.
// For example:
// multiplyArray([1, 2, 3, 4, 5]) == 120
// multiplyArray([10, 15, 30]) == 3600
func multiplyArray(arr: [Int]) -> Int {
var product = 1
for i in arr {
product *= i
}
return product
}
// Given an array of integers, return the sum of all the integers multiplied together.
// However, if the array contains any duplicates, only count the integer multiplied
// once.
// For example:
// multiplyUniqueArray([1, 2, 3, 4, 5]) == 120
// multiplyUniqueArray([10, 15, 30]) == 360
func multiplyUniqueArray(arr: [Int]) -> Int {
var product = 1
var uniqueMultiples: Set<Int> = []
for i in arr {
if!uniqueMultiples.contains(i) {
product *= i
uniqueMultiples.insert(i)
}
}
return product
}
// Given an array of integers, return the sum of all the integers multiplied together.
// However, if the array contains any duplicates, only count the integer multiplied
// once. Additionally, if the array is sorted in ascending order, return the
// sum of all the integers multiplied together using only addition.
// For example:
// multiplyUniqueAndSortedArray([1, 2, 3, 4, 5]) == 120
// multiplyUniqueAndSortedArray([10, 15, 30]) == 360
func multiplyUniqueAndSortedArray(arr: [Int]) -> Int {
var product = 1
var uniqueMultiples: Set<Int> = []
var sorted = arr.sorted()
var i = 0
var j = arr.count - 1
while i < j {
if!uniqueMultiples.contains(sorted[i]) {
product *= sorted[i]
uniqueMultiples.insert(sorted[i])
}
if!uniqueMultiples.contains(sorted[j]) {
product *= sorted[j]
uniqueMultiples.insert(sorted[j])
}
i += 1
j -= 1
}
return product
}
// Given an array of integers, return the sum of all the integers multiplied together.
// However, if the array contains any duplicates, only count the integer multiplied
// once. Additionally, if the array is sorted in ascending order, return the
// sum of all the integers multiplied together using only addition.
// For example:
// multiplyUniqueAndSortedArray([1, 2, 3, 4, 5]) == 120
// multiplyUniqueAndSortedArray([10, 15, 30]) == 360
func multiplyUniqueAndSortedArray2(arr: [Int]) -> Int {
var product = 1
var uniqueMultiples: Set<Int> = []
var sorted = arr.sorted()
var i = 0
var j = arr.count - 1
while i < j {
if!uniqueMultiples.contains(sorted[i]) {
product *= sorted[i]
uniqueMultiples.insert(sorted[i])
}
i += 1
}
while i < j {
if!uniqueMultiples.contains(sorted[j]) {
product *= sorted[j]
uniqueMultiples.insert(sorted[j])
}
j -= 1
}
return product
}
// Given an array of integers, return the sum of all the integers multiplied together.
// However
if arr[i]!= arr[arr.count - i - 1] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[arr.count - i - 1] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - i - 1] { // use of '=' in a boolean context, did you mean '=='?
arr[arr.count - i - 1] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
if!uniqueMultiples.contains(i) { // expected expression, var, or let in 'if' condition
if!uniqueMultiples.contains(sorted[i]) { // expected expression, var, or let in 'if' condition
if!uniqueMultiples.contains(sorted[j]) { // expected expression, var, or let in 'if' condition
if!uniqueMultiples.contains(sorted[i]) { // expected expression, var, or let in 'if' condition
if!uniqueMultiples.contains(sorted[j]) { // expected expression, var, or let in 'if' condition
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count/2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [Int]()
var leftProduct = 1
for i in 0..<nums.count {
result.append(leftProduct)
leftProduct *= nums[i]
}
var rightProduct = 1
for i in (0..<nums.count).reversed() {
result[i] = result[i] * rightProduct
rightProduct *= nums[i]
}
return result
}
func productExceptSelfNoDivision(nums: [Int]) -> [Int] {
var result = [Int]()
var leftProduct = 1
for i in 0..<nums.count {
result.append(leftProduct)
leftProduct *= nums[i]
}
var rightProduct = 1
for i in (0..<nums.count).reversed() {
result[i] = result[i] * rightProduct
rightProduct *= nums[i]
}
return result
}
func isPalindrome(_ input: String) -> Bool {
var filteredInput = input.filter { $0.isLetter }
let reversedInput = String(filteredInput.reversed())
return input == reversedInput
}
func longestPalindrome(_ input: String) -> String {
var filteredInput = input.filter { $0.isLetter }
var longestPalindrome = ""
for i in 0..<filteredInput.count {
for j in i..<filteredInput.count {
let substring = String(filteredInput[i...j])
if isPalindrome(substring) && substring.count > longestPalindrome.count {
longestPalindrome = substring
}
}
}
return longestPalindrome
}
```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 changes = 0
for i in 0..<arr.count/2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be:
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
// Follow-up: what if you can't use division?
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [Int]()
var leftProduct = 1
for i in 0..<nums.count {
result.append(leftProduct)
leftProduct *= nums[i]
}
var rightProduct = 1
for i in (0..<nums.count).reversed() {
result[i] = result[i] * rightProduct
rightProduct *= nums[i]
}
return result
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// Solve it without division.
func productExceptSelfNoDivision(nums: [Int]) -> [Int] {
var result = [Int]()
var leftProduct = 1
for i in 0..<nums.count {
result.append(leftProduct)
leftProduct *= nums[i]
}
var rightProduct = 1
for i in (0..<nums.count).reversed() {
result[i] = result[i] * rightProduct
rightProduct *= nums[i]
}
return result
}
// Given a string, determine if it makes a valid palindrome.
// A valid palindrome is a string that reads the same forwards and backwards, ignoring any
// non-alphabetic characters and considering only lowercase alphabets.
// For example, the string "abca" is a valid palindrome, while the string "abc" is not.
func isPalindrome(_ input: String) -> Bool {
var filteredInput = input.filter { $0.isLetter }
let reversedInput = String(filteredInput.reversed())
return input == reversedInput
}
// Given a string, find the longest palindromic substring in it.
// For example, the longest palindromic substring of "aabcdcb" is "bcdcb".
func longestPalindrome(_ input: String) -> String {
var filteredInput = input.filter { $0.isLetter }
var longestPalindrome = ""
for i in 0..<filteredInput.count {
for j in i..<filteredInput.count {
let substring = String(filteredInput[i...j])
if isPalindrome(substring) && substring.count > longestPalindrome.count {
longestPalindrome = substring
}
}
}
return longestPalindrome
}
// Given a string, find the longest palindromic substring in it with all distinct characters.
// For example, the longest palindromic substring of "aabcdcb" is "bcdcb". The longest palindromic
// substring of "bananas" is "anana".
func longestPalindromeAllDistinctCharacters(_ input: String) -> String {
var filteredInput = input.filter { $0.isLetter }
var longestPalindrome = ""
var distinctCharacters = Set<Character>()
for i in 0..<filteredInput.count {
for j in i..<filteredInput.count {
let substring = String(filteredInput[i...j])
if isPalindrome(substring) && substring.count > longestPalindrome.count && substring.count == distinctCharacters.count {
longestPalindrome = substring
}
distinctCharacters.insert(filteredInput
if arr[i]!= arr[arr.count - i - 1] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[arr.count - i - 1] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - i - 1] { // use of '=' in a boolean context, did you mean '=='?
arr[i] = arr[arr.count - i - 1] // cannot assign through subscript: 'arr' is a 'let' constant
arr[arr.count - i - 1] = temp // cannot assign through subscript: 'arr' is a 'let' constant
var filteredInput = input.filter { $0.isLetter } // variable 'filteredInput' was never mutated; consider changing to 'let' constant
var filteredInput = input.filter { $0.isLetter } // variable 'filteredInput' was never mutated; consider changing to 'let' constant
let substring = String(filteredInput[i...j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func smallestChange(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count {
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
for i in 0..<arr.count {
if arr[i]!= arr[arr.count - i - 1] {
count += 1
}
}
return count
}
print(smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]))
print(smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]))
print(smallestChange(arr: [1, 2, 3, 2, 1]))
print(smallestChange(arr: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]))
```
if arr[i]!= arr[arr.count - i - 1] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - i - 1] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[arr.count - i - 1] { // cannot force unwrap value of non-optional type 'Int'
func smallestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var complements = [Int: Int]()
for (index, num) in nums.enumerated() {
if let complement = complements[num] {
return [complement, index]
}
complements[target - num] = index
}
return []
}
func isPalindrome(s: String) -> Bool {
var filtered = s.filter { $0.isLetterOrDigit }
let lowercased = filtered.lowercased()
let reversed = String(lowercased.reversed())
return lowercased == reversed
}
func longestPalindrome(s: String) -> String {
if s.count == 0 {
return ""
}
var longest = ""
for i in 0..<s.count {
for j in i..<s.count {
let substring = String(s[i...j])
if isPalindrome(s: substring) && substring.count > longest.count {
longest = substring
}
}
}
return longest
}
func numSquares(n: Int) -> Int {
var squares = [Int]()
var i = 1
while i * i <= n {
squares.append(i * i)
i += 1
}
var dp = [Int](repeating: 0, count: n + 1)
for i in 1...n {
var min = Int.max
for square in squares {
if i < square {
break
}
min = min(min, dp[i - square] + 1)
}
dp[i] = min
}
return dp[n]
}
func maximumDifference(nums: [Int]) -> Int {
if nums.count < 2 {
return -1
}
var minValue = Int.max
var maxDiff = Int.min
for num in nums {
if num < minValue {
minValue = num
} else if num - minValue > maxDiff {
maxDiff = num - minValue
}
}
return maxDiff > 0? maxDiff : -1
}
```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 changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
// Given an array of integers, return the indices of the two numbers such that they add up to a specific target.
// Assume that each input has exactly one solution, and you may not use the same element twice.
// Example:
// Given nums = [2, 7, 11, 15], target = 9,
// Because nums[0] = 2 and nums[1] = 7, return [0, 1].
func twoSum(nums: [Int], target: Int) -> [Int] {
var complements = [Int: Int]()
for (index, num) in nums.enumerated() {
if let complement = complements[num] {
return [complement, index]
}
complements[target - num] = index
}
return []
}
// Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Note: For the purpose of this problem, we define empty string as valid palindrome.
// Example:
// "A man, a plan, a canal: Panama" is a palindrome.
// "race a car" is not a palindrome.
func isPalindrome(s: String) -> Bool {
var filtered = s.filter { $0.isLetterOrDigit }
let lowercased = filtered.lowercased()
let reversed = String(lowercased.reversed())
return lowercased == reversed
}
// Given a string s, find the longest palindromic substring in s.
// Example:
// The longest palindromic substring of "babad" is "bab".
// The longest palindromic substring of "cbbd" is "bb".
func longestPalindrome(s: String) -> String {
if s.count == 0 {
return ""
}
var longest = ""
for i in 0..<s.count {
for j in i..<s.count {
let substring = String(s[i...j])
if isPalindrome(s: substring) && substring.count > longest.count {
longest = substring
}
}
}
return longest
}
// Given an integer n, return the least number of squares needed to sum up to n.
// Example:
// Input: n = 13, return 2.
// Explanation: 13 = 4 + 9.
func numSquares(n: Int) -> Int {
var squares = [Int]()
var i = 1
while i * i <= n {
squares.append(i * i)
i += 1
}
var dp = [Int](repeating: 0, count: n + 1)
for i in 1...n {
var min = Int.max
for square in squares {
if i < square {
break
}
min = min(min, dp[i - square] + 1)
}
dp[i] = min
}
return dp[n]
}
// Given an array of integers, return the maximum difference between
// two elements in its sorted form.
// Example:
// Given [3, 6, 9, 1], the maximum difference between
// two corresponding elements is 3.
// Note:
// There are at least two elements in the array.
func maximumDifference(nums: [Int]) -> Int {
if nums.count < 2 {
return -1
}
var minValue = Int.max
var maxDiff = Int.min
for num in nums {
if num < minValue {
minValue = num
} else if num - minValue > maxDiff {
maxDiff = num - minValue
}
}
return maxDiff > 0? maxDiff : -1
}
// Given a string, find the length of the longest substring without repeating characters.
// Example:
// The longest substring without repeating letters for
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
arr[j] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
var filtered = s.filter { $0.isLetterOrDigit } // value of type 'String.Element' (aka 'Character') has no member 'isLetterOrDigit'
let substring = String(s[i...j]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
min = min(min, dp[i - square] + 1) // cannot call value of non-function type 'Int'
return maxDiff > 0? maxDiff : -1 // consecutive statements on a line must be separated by ';'
return maxDiff > 0? maxDiff : -1 // variable is unused
return maxDiff > 0? maxDiff : -1 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return maxDiff > 0? maxDiff : -1 // consecutive statements on a line must be separated by ';'
return maxDiff > 0? maxDiff : -1 // expected expression
return maxDiff > 0? maxDiff : -1 // cannot use optional chaining on non-optional value of type 'Int'
return maxDiff > 0? maxDiff : -1 // cannot convert return expression of type 'Bool' to return type 'Int'
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count / 2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
print(smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]))
print(smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]))
print(smallestChange(arr: [1, 2, 3, 2, 1]))
```
if arr[i]!= arr[arr.count - i - 1] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[arr.count - i - 1] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - i - 1] { // use of '=' in a boolean context, did you mean '=='?
arr[i] = arr[arr.count - i - 1] // cannot assign through subscript: 'arr' is a 'let' constant
arr[arr.count - i - 1] = temp // cannot assign through subscript: 'arr' is a 'let' constant
func smallestChange(arr: [Int]) -> Int {
var changes = 0
for i in 0..<arr.count/2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [Int]()
var runningProduct = 1
for i in 0..<nums.count {
runningProduct *= nums[i]
result.append(runningProduct)
}
runningProduct = 1
for i in (0..<nums.count).reversed() {
result[i] = runningProduct * result[i]
runningProduct *= nums[i]
}
return result
}
func maximumProduct(nums: [Int]) -> Int {
var max1 = Int.min
var max2 = Int.min
var max3 = Int.min
var min1 = Int.max
var min2 = Int.max
for num in nums {
if num > max1 {
max3 = max2
max2 = max1
max1 = num
} else if num > max2 && num!= max1 {
max3 = max2
max2 = num
} else if num > max3 && num!= max1 && num!= max2 {
max3 = num
}
if num < min1 {
min2 = min1
min1 = num
} else if num < min2 && num!= min1 {
min2 = num
}
}
return max(max1 * max2 * max3, max1 * min1 * min2)
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var complements = [Int: Int]()
for i in 0..<nums.count {
if let complementIndex = complements[target - nums[i]] {
result.append(complementIndex)
result.append(i)
break
} else {
complements[nums[i]] = i
}
}
return result
}
func twoSumTwoPassHashTable(nums: [Int], target: Int) -> [Int] {
var complements = [Int: Int]()
for i in 0..<nums.count {
if let complementIndex = complements[target - nums[i]] {
return [complementIndex, i]
} else {
complements[nums[i]] = i
}
}
return []
}
```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 changes = 0
for i in 0..<arr.count/2 {
if arr[i]!= arr[arr.count - i - 1] {
changes += 1
let temp = arr[i]
arr[i] = arr[arr.count - i - 1]
arr[arr.count - i - 1] = temp
}
}
return changes
}
// Given an array of integers, return a new array such that each element at index i of the new array
// is the product of all the numbers in the original array except the one at i.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be:
// [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
// Follow-up: what if you can't use division?
func productExceptSelf(nums: [Int]) -> [Int] {
var result = [Int]()
var runningProduct = 1
for i in 0..<nums.count {
runningProduct *= nums[i]
result.append(runningProduct)
}
runningProduct = 1
for i in (0..<nums.count).reversed() {
result[i] = runningProduct * result[i]
runningProduct *= nums[i]
}
return result
}
// Given an array of integers, return the largest product yielded from three of the integers.
// For example, if our input was [1, 2, 3, 4, 5], the expected output would be 10, since we can
// create the product 5 * 4 * 3. If our input was [1, 2, 3, 5, 10], the expected output would
// be 50, since we can create the product 10 * 5 * 1.
func maximumProduct(nums: [Int]) -> Int {
var max1 = Int.min
var max2 = Int.min
var max3 = Int.min
var min1 = Int.max
var min2 = Int.max
for num in nums {
if num > max1 {
max3 = max2
max2 = max1
max1 = num
} else if num > max2 && num!= max1 {
max3 = max2
max2 = num
} else if num > max3 && num!= max1 && num!= max2 {
max3 = num
}
if num < min1 {
min2 = min1
min1 = num
} else if num < min2 && num!= min1 {
min2 = num
}
}
return max(max1 * max2 * max3, max1 * min1 * min2)
}
// Given an array of integers, return the indices of the two numbers such that they add up to a specific target.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
func twoSum(nums: [Int], target: Int) -> [Int] {
var result = [Int]()
var complements = [Int: Int]()
for i in 0..<nums.count {
if let complementIndex = complements[target - nums[i]] {
result.append(complementIndex)
result.append(i)
break
} else {
complements[nums[i]] = i
}
}
return result
}
// Given an array of integers, return indices of the two numbers such that they add up to a specific target
// using the two-pass hash table approach.
func twoSumTwoPassHashTable(nums: [Int], target: Int) -> [Int] {
var complements = [Int: Int]()
for i in 0..<nums.count {
if let complementIndex = complements[target - nums[i]] {
return [complementIndex, i]
} else {
complements[nums[i]] = i
}
}
return []
}
// Given an array of integers, return indices of the two numbers such that they add up to a specific target
// using the hash table approach.
func twoSumOnePassHashTable(nums: [Int], target: Int) -> [Int] {
var complements = [Int: Int]()
for i in 0..<nums
if arr[i]!= arr[arr.count - i - 1] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[arr.count - i - 1] { // '=' must have consistent whitespace on both sides
if arr[i]!= arr[arr.count - i - 1] { // use of '=' in a boolean context, did you mean '=='?
arr[i] = arr[arr.count - i - 1] // cannot assign through subscript: 'arr' is a 'let' constant
arr[arr.count - i - 1] = temp // cannot assign through subscript: 'arr' is a 'let' constant
} else if num > max2 && num!= max1 { // '=' must have consistent whitespace on both sides
} else if num > max2 && num!= max1 { // use of '=' in a boolean context, did you mean '=='?
} else if num > max2 && num!= max1 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
} else if num > max2 && num!= max1 { // cannot force unwrap value of non-optional type 'Int'
} else if num > max3 && num!= max1 && num!= max2 { // use of '=' in a boolean context, did you mean '=='?
} else if num > max3 && num!= max1 && num!= max2 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
} else if num > max3 && num!= max1 && num!= max2 { // '=' must have consistent whitespace on both sides
} else if num > max3 && num!= max1 && num!= max2 { // cannot force unwrap value of non-optional type 'Int'
} else if num > max3 && num!= max1 && num!= max2 { // cannot force unwrap value of non-optional type 'Int'
} else if num > max3 && num!= max1 && num!= max2 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
} else if num > max3 && num!= max1 && num!= max2 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
} else if num > max3 && num!= max1 && num!= max2 { // '=' must have consistent whitespace on both sides
} else if num < min2 && num!= min1 { // use of '=' in a boolean context, did you mean '=='?
} else if num < min2 && num!= min1 { // cannot force unwrap value of non-optional type 'Int'
} else if num < min2 && num!= min1 { // '=' must have consistent whitespace on both sides
} else if num < min2 && num!= min1 { // type 'Int' cannot be used as a boolean; test for '!= 0' instead
func smallestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var changes = 0
var i = 0
var j = arr.count - 1
while i < j {
if arr[i]!= arr[j] {
changes += 1
if arr[i] > arr[j] {
arr[j] = arr[i]
} else {
arr[i] = arr[j]
}
}
i += 1
j -= 1
}
return changes
}
print(smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]))
print(smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]))
print(smallestChange(arr: [1, 2, 3, 2, 1]))
```
if arr[i]!= arr[j] { // cannot force unwrap value of non-optional type 'Int'
if arr[i]!= arr[j] { // use of '=' in a boolean context, did you mean '=='?
if arr[i]!= arr[j] { // '=' must have consistent whitespace on both sides
arr[j] = arr[i] // cannot assign through subscript: 'arr' is a 'let' constant
arr[i] = arr[j] // cannot assign through subscript: 'arr' is a 'let' constant
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
}
}
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
}
}
// 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 greater 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"]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == [] as [String]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
}
}
// 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 or equal to the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
}
}
// 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 greater than or equal to 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", "project"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(
if!lst1.contains(i) { // expected expression, var, or let in 'if' condition
if!lst2.contains(i) { // expected expression, var, or let in 'if' condition
func totalMatch(lst1: [String], lst2: [String]) -> [String] { // invalid redeclaration of 'totalMatch(lst1:lst2:)'
if!lst2.contains(i) { // expected expression, var, or let in 'if' condition
if!lst1.contains(i) { // expected expression, var, or let in 'if' condition
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
func countStrings(lst: [String]) -> [String: Int] {
var result = [String: Int]()
for i in 0..<lst.count {
if result[lst[i]]!= nil {
result[lst[i]]! += 1
} else {
result[lst[i]] = 1
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts an array of strings and returns a dictionary with
// each string as a key and the count of that string as the value.
// Examples
// countStrings(lst: ["hi", "hello", "hi", "hi", "hello"]) == ["hi": 3, "hello": 2]
// countStrings(lst: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]) == ["a": 1, "b": 1, "c": 1, "d": 1, "e": 1, "f": 1, "g": 1, "h": 1, "i": 1, "j": 1, "k": 1, "l": 1, "m": 1, "n": 1, "o": 1, "p": 1, "q": 1, "r": 1, "s": 1, "t": 1, "u": 1, "v": 1, "w": 1, "x": 1, "y": 1, "z": 1]
// countStrings(lst: ["apple", "banana", "cherry", "apple", "banana", "apple", "grape", "banana", "cherry"]) == ["apple": 3, "banana": 3, "cherry": 3, "grape": 1]
func countStrings(lst: [String]) -> [String: Int] {
var result = [String: Int]()
for i in 0..<lst.count {
if result[lst[i]]!= nil {
result[lst[i]]! += 1
} else {
result[lst[i]] = 1
}
}
return result
}
// Write a function that accepts an array of strings and returns a dictionary with
// each string as a key and the count of that string as the value.
// Examples
// countStrings(lst: ["hi", "hello", "hi", "hi", "hello"]) == ["hi": 3, "hello": 2]
// countStrings(lst: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]) == ["a": 1, "b": 1, "c": 1, "d": 1, "e": 1, "f": 1, "g": 1, "h": 1, "i": 1, "j": 1, "k": 1, "l": 1, "m": 1, "n": 1, "o": 1, "p": 1, "q": 1, "r": 1, "s": 1, "t": 1, "u": 1, "v": 1, "w": 1, "x": 1, "y": 1, "z": 1]
// countStrings(lst: ["apple", "banana", "cherry", "apple", "banana", "apple", "grape", "banana", "cherry"]) == ["apple": 3, "banana": 3, "cherry": 3, "grape": 1]
func countStrings(lst: [String]) -> [String: Int] {
var result = [String: Int]()
for i in 0..<lst.count {
if result[lst[i]]!= nil {
result[lst[i]]! += 1
} else {
result[lst[i]] = 1
if result[lst[i]]!= nil { // 'nil' cannot be assigned to type 'Int'
if result[lst[i]]!= nil { // '=' must have consistent whitespace on both sides
if result[lst[i]]!= nil { // use of '=' in a boolean context, did you mean '=='?
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
func sortNames(lst: [String]) -> [String] {
return lst.sorted {
$0.lowercased() < $1.lowercased()
}
}
func sortNamesReverse(lst: [String]) -> [String] {
return lst.sorted {
$1.lowercased() < $0.lowercased()
}
}
func sortByVowels(lst: [String]) -> [String] {
return lst.sorted {
$0.filter { "aeiou".contains($0) }.count < $1.filter { "aeiou".contains($0) }.count
}
}
func sortByConsonants(lst: [String]) -> [String] {
return lst.sorted {
$0.filter { "aeiou".contains($0) == false }.count < $1.filter { "aeiou".contains($0) == false }.count
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted in alphabetical order.
// Examples
// sortNames(lst: ["bob", "alice", "sam"]) == ["alice", "bob", "sam"]
// sortNames(lst: ["bob", "alice", "sam", "Alice"]) == ["alice", "bob", "sam", "Alice"]
// sortNames(lst: ["bob", "alice", "sam", "Alice", "aBc", "AbC", "abC", "abc"]) == ["alice", "bob", "AbC", "abc", "aBc", "Alice", "sam"]
func sortNames(lst: [String]) -> [String] {
return lst.sorted {
$0.lowercased() < $1.lowercased()
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted in reverse alphabetical order.
// Examples
// sortNamesReverse(lst: ["bob", "alice", "sam"]) == ["sam", "bob", "alice"]
// sortNamesReverse(lst: ["bob", "alice", "sam", "Alice"]) == ["Alice", "bob", "sam", "alice"]
// sortNamesReverse(lst: ["bob", "alice", "sam", "Alice", "aBc", "AbC", "abC", "abc"]) == ["abc", "abC", "aBc", "Alice", "sam", "bob", "alice", "AbC"]
func sortNamesReverse(lst: [String]) -> [String] {
return lst.sorted {
$1.lowercased() < $0.lowercased()
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted by the number of vowels in each string.
// Examples
// sortByVowels(lst: ["bob", "alice", "sam"]) == ["bob", "alice", "sam"]
// sortByVowels(lst: ["bob", "alice", "sam", "Alice"]) == ["alice", "bob", "Alice", "sam"]
// sortByVowels(lst: ["bob", "alice", "sam", "Alice", "aBc", "AbC", "abC", "abc"]) == ["alice", "bob", "AbC", "abc", "Alice", "abC", "aBc", "sam"]
func sortByVowels(lst: [String]) -> [String] {
return lst.sorted {
$0.filter { "aeiou".contains($0) }.count < $1.filter { "aeiou".contains($0) }.count
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted by the number of consonants in each string.
// Examples
// sortByConsonants(lst: ["bob", "alice", "sam"]) == ["bob", "alice", "sam"]
// sortByConsonants(lst: ["bob", "alice", "sam", "Alice"]) == ["alice", "bob", "Alice", "sam"]
// sortByConsonants(lst: ["bob", "alice", "sam", "Alice", "aBc", "AbC", "abC", "abc"]) == ["alice", "bob", "aBc", "AbC", "abc", "Alice", "sam", "abC"]
func sortByConsonants(lst: [String]) -> [String] {
return lst.sorted {
$0.filter { "aeiou".contains($0) == false }.count < $1.filter { "aeiou".contains($0) == false }.count
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted by the length of each string.
// Examples
// sortByLength(lst: ["bob", "alice", "sam"]) == ["bob", "alice", "sam"]
// sortBy
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
func sortNames(lst: [String]) -> [String] {
return lst.sorted { $0 < $1 }
}
func reverseNames(lst: [String]) -> [String] {
return lst.sorted { $0 > $1 }
}
func sortByVowels(lst: [String]) -> [String] {
return lst.sorted {
var count1 = 0
var count2 = 0
for char in $0 {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count1 += 1
}
}
for char in $1 {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count2 += 1
}
}
return count1 < count2
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted in alphabetical order.
// Examples
// sortNames(lst: ["Luis", "Ana", "Adam"]) == ["Ana", "Adam", "Luis"]
// sortNames(lst: ["Luis", "Ana", "Adam", "Ana"]) == ["Ana", "Ana", "Adam", "Luis"]
// sortNames(lst: ["Luis", "Ana", "Adam", "Ana", "Luis"]) == ["Ana", "Ana", "Adam", "Luis", "Luis"]
// sortNames(lst: ["Luis", "Ana", "Adam", "Ana", "Luis", "Adam"]) == ["Ana", "Ana", "Adam", "Adam", "Luis", "Luis"]
func sortNames(lst: [String]) -> [String] {
return lst.sorted { $0 < $1 }
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted in reverse alphabetical order.
// Examples
// reverseNames(lst: ["Luis", "Ana", "Adam"]) == ["Adam", "Luis", "Ana"]
// reverseNames(lst: ["Luis", "Ana", "Adam", "Ana"]) == ["Ana", "Luis", "Adam", "Ana"]
// reverseNames(lst: ["Luis", "Ana", "Adam", "Ana", "Luis"]) == ["Ana", "Luis", "Adam", "Ana", "Luis"]
// reverseNames(lst: ["Luis", "Ana", "Adam", "Ana", "Luis", "Adam"]) == ["Adam", "Ana", "Luis", "Ana", "Adam", "Luis"]
func reverseNames(lst: [String]) -> [String] {
return lst.sorted { $0 > $1 }
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted by the number of vowels in each string.
// Examples
// sortByVowels(lst: ["Luis", "Ana", "Adam"]) == ["Ana", "Luis", "Adam"]
// sortByVowels(lst: ["Luis", "Ana", "Adam", "Ana"]) == ["Ana", "Ana", "Luis", "Adam"]
// sortByVowels(lst: ["Luis", "Ana", "Adam", "Ana", "Luis"]) == ["Ana", "Ana", "Luis", "Luis", "Adam"]
// sortByVowels(lst: ["Luis", "Ana", "Adam", "Ana", "Luis", "Adam"]) == ["Ana", "Ana", "Adam", "Luis", "Luis", "Adam"]
func sortByVowels(lst: [String]) -> [String] {
return lst.sorted {
var count1 = 0
var count2 = 0
for char in $0 {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count1 += 1
}
}
for char in $1 {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
count2 += 1
}
}
return count1 < count2
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted by the number of consonants in each string.
// Examples
// sortByConsonants(lst: ["Luis", "Ana", "Adam"]) == ["Luis", "Adam", "Ana"]
// sortByConsonants(lst:
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
func longestFirst(lst: [String]) -> [String] {
var result = [String]()
var maxLength = 0
for i in 0..<lst.count {
if lst[i].count > maxLength {
maxLength = lst[i].count
result = [String]()
result.append(lst[i])
} else if lst[i].count == maxLength {
result.append(lst[i])
}
}
return result
}
func shortestFirst(lst: [String]) -> [String] {
var result = [String]()
var minLength = 100
for i in 0..<lst.count {
if lst[i].count < minLength {
minLength = lst[i].count
result = [String]()
result.append(lst[i])
} else if lst[i].count == minLength {
result.append(lst[i])
}
}
return result
}
func alphabeticalOrder(lst: [String]) -> [String] {
var result = [String]()
for i in 0..<lst.count {
for j in i+1..<lst.count {
if lst[i] > lst[j] {
let temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
}
}
}
return lst
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts an array of strings and returns the array of strings
// with the longest string first.
// Examples
// longestFirst(["hi", "hello", "goodbye"]) == ["hello", "goodbye", "hi"]
// longestFirst(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// longestFirst(["hi", "hi", "hello"]) == ["hello", "hi", "hi"]
// longestFirst(["hi", "hello", "hi"]) == ["hello", "hi", "hi"]
func longestFirst(lst: [String]) -> [String] {
var result = [String]()
var maxLength = 0
for i in 0..<lst.count {
if lst[i].count > maxLength {
maxLength = lst[i].count
result = [String]()
result.append(lst[i])
} else if lst[i].count == maxLength {
result.append(lst[i])
}
}
return result
}
// Write a function that accepts an array of strings and returns the array of strings
// with the shortest string first.
// Examples
// shortestFirst(["hi", "hello", "goodbye"]) == ["hi", "hello", "goodbye"]
// shortestFirst(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// shortestFirst(["hi", "hi", "hello"]) == ["hi", "hi", "hello"]
// shortestFirst(["hi", "hello", "hi"]) == ["hi", "hello", "hi"]
func shortestFirst(lst: [String]) -> [String] {
var result = [String]()
var minLength = 100
for i in 0..<lst.count {
if lst[i].count < minLength {
minLength = lst[i].count
result = [String]()
result.append(lst[i])
} else if lst[i].count == minLength {
result.append(lst[i])
}
}
return result
}
// Write a function that accepts an array of strings and returns the array of strings
// with the strings sorted in alphabetical order.
// Examples
// alphabeticalOrder(["hi", "hello", "goodbye"]) == ["hi", "hello", "goodbye"]
// alphabeticalOrder(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// alphabeticalOrder(["hi", "hi", "hello"]) == ["hi", "hi", "hello"]
// alphabeticalOrder(["hi", "hello", "hi"]) == ["hi", "hi", "hello"]
func alphabeticalOrder(lst: [String]) -> [String] {
var result = [String]()
for i in 0..<lst.count {
for j in i+1..<lst.count {
if lst[i] > lst[j] {
let temp = lst[i]
lst[i] = lst[j]
lst[j] = temp
}
}
}
return lst
}
// Write a function that accepts an array of strings and returns the array of strings
// with the strings sorted in reverse alphabetical order.
// Examples
// reverseAlphabeticalOrder(["hi", "hello", "goodbye"]) == ["goodbye", "hello", "hi"]
// reverseAlphabeticalOrder(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// reverseAlphabeticalOrder(["hi", "hi", "hello"]) == ["hello", "hi", "hi"]
// reverseAlphabeticalOrder(["hi", "hello", "hi"]) == ["hi", "hello", "hi"]
func reverseAlphabeticalOrder(lst: [String]) -> [String] {
var result = [String]()
for i in 0..<lst.count {
for j in i+1..<lst.count {
if lst[i] < lst[j] {
let temp = lst[i]
lst[i] = lst[j]
lst[i] = lst[j] // cannot assign through subscript: 'lst' is a 'let' constant
lst[j] = temp // cannot assign through subscript: 'lst' is a 'let' constant
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
}
}
func sortNames(lst: [String]) -> [String] {
return lst.sorted()
}
func reverseNames(lst: [String]) -> [String] {
return lst.sorted().reversed()
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in lst2 {
if!lst1.contains(i) {
result.append(i)
}
}
return result
} else {
for i in lst1 {
if!lst2.contains(i) {
result.append(i)
}
}
return result
}
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted in alphabetical order.
// Examples
// sortNames(lst: ["Bryce", "Craig", "Henry", "Jane", "John"]) == ["Bryce", "Craig", "Henry", "Jane", "John"]
// sortNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig"]) == ["Bryce", "Craig", "Henry", "Jane", "John"]
// sortNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig", "Jake"]) == ["Bryce", "Craig", "Henry", "Jane", "John", "Jake"]
// sortNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig", "Jake", "Jane"]) == ["Bryce", "Craig", "Henry", "Jane", "John", "Jake"]
func sortNames(lst: [String]) -> [String] {
return lst.sorted()
}
// Write a function that accepts an array of strings and returns the array of strings
// sorted in reverse alphabetical order.
// Examples
// reverseNames(lst: ["Bryce", "Craig", "Henry", "Jane", "John"]) == ["John", "Jane", "Henry", "Craig", "Bryce"]
// reverseNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig"]) == ["Jane", "John", "Craig", "Bryce", "Henry"]
// reverseNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig", "Jake"]) == ["Jake", "John", "Craig", "Bryce", "Henry", "Jane"]
// reverseNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig", "Jake", "Jane"]) == ["Jake", "Jane", "John", "Craig", "Bryce", "Henry"]
func reverseNames(lst: [String]) -> [String] {
return lst.sorted().reversed()
}
// Write a function that accepts an array of strings and returns a dictionary with
// each string as a key and the count of that string as the value.
// Examples
// countNames(lst: ["Bryce", "Craig", "Henry", "Jane", "John"]) == ["Bryce": 1, "Craig": 1, "Henry": 1, "Jane": 1, "John": 1]
// countNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig"]) == ["Bryce": 1, "Craig": 1, "Henry": 1, "Jane": 1, "John": 1]
// countNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig", "Jake"]) == ["Bryce": 1, "Craig": 1, "Henry": 1, "Jane": 1, "John": 1, "Jake": 1]
// countNames(lst: ["Henry", "Bryce", "Jane", "John", "Craig", "Jake", "Jane"]) == ["Bryce": 1, "Craig": 1, "Henry": 1, "Jane": 2, "John": 1]
func countNames(lst: [String]) -> [String: Int] {
var result = [String:
if!lst1.contains(i) { // expected expression, var, or let in 'if' condition
if!lst2.contains(i) { // expected expression, var, or let in 'if' condition
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
func longestFirst(lst: [String]) -> [String] {
var result = [String]()
var maxLength = 0
for i in 0..<lst.count {
if lst[i].count > maxLength {
maxLength = lst[i].count
}
}
for i in 0..<lst.count {
if lst[i].count == maxLength {
result.append(lst[i])
}
}
return result
}
func shortestFirst(lst: [String]) -> [String] {
var result = [String]()
var minLength = 100
for i in 0..<lst.count {
if lst[i].count < minLength {
minLength = lst[i].count
}
}
for i in 0..<lst.count {
if lst[i].count == minLength {
result.append(lst[i])
}
}
return result
}
func alphabeticalOrder(lst: [String]) -> [String] {
return lst.sorted()
}
func reverseAlphabeticalOrder(lst: [String]) -> [String] {
return lst.sorted().reversed()
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts an array of strings and returns the array of strings
// with the longest string first.
// Examples
// longestFirst(["hi", "admin", "project"]) == ["admin", "project", "hi"]
// longestFirst(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// longestFirst(["hi", "hi"]) == ["hi", "hi"]
// longestFirst(["a", "ab", "abc", "abcd", "abcde"]) == ["abcde", "abcd", "abc", "ab", "a"]
func longestFirst(lst: [String]) -> [String] {
var result = [String]()
var maxLength = 0
for i in 0..<lst.count {
if lst[i].count > maxLength {
maxLength = lst[i].count
}
}
for i in 0..<lst.count {
if lst[i].count == maxLength {
result.append(lst[i])
}
}
return result
}
// Write a function that accepts an array of strings and returns the array of strings
// with the shortest string first.
// Examples
// shortestFirst(["hi", "admin", "project"]) == ["hi", "admin", "project"]
// shortestFirst(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// shortestFirst(["hi", "hi"]) == ["hi"]
// shortestFirst(["a", "ab", "abc", "abcd", "abcde"]) == ["a", "ab", "abc"]
func shortestFirst(lst: [String]) -> [String] {
var result = [String]()
var minLength = 100
for i in 0..<lst.count {
if lst[i].count < minLength {
minLength = lst[i].count
}
}
for i in 0..<lst.count {
if lst[i].count == minLength {
result.append(lst[i])
}
}
return result
}
// Write a function that accepts an array of strings and returns the array of strings
// with the strings sorted in alphabetical order.
// Examples
// alphabeticalOrder(["hi", "admin", "project"]) == ["admin", "hi", "project"]
// alphabeticalOrder(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// alphabeticalOrder(["a", "ab", "abc", "abcd", "abcde"]) == ["a", "ab", "abc", "abcd", "abcde"]
func alphabeticalOrder(lst: [String]) -> [String] {
return lst.sorted()
}
// Write a function that accepts an array of strings and returns the array of strings
// with the strings sorted in reverse alphabetical order.
// Examples
// reverseAlphabeticalOrder(["hi", "admin", "project"]) == ["project", "hi", "admin"]
// reverseAlphabeticalOrder(["hi", "hi", "hi"]) == ["hi", "hi", "hi"]
// reverseAlphabeticalOrder(["a", "ab", "abc", "abcd", "abcde"]) == ["abcde", "abcd", "abc", "ab", "a"]
func reverseAlphabeticalOrder(lst: [String]) -> [String] {
return lst.sorted().reversed()
}
// Write a function that accepts an array of strings and returns the array of strings
// with duplicates removed.
// Examples
// removeDuplicates(["hi", "admin", "project"]) == ["hi", "admin", "project"]
// removeDuplicates(["hi", "hi", "hi"]) == ["hi"]
// removeDuplicates(["a", "ab", "abc", "abcd", "abcde"]) == ["a", "ab", "abc", "abcd", "abcde"]
func removeDuplicates(lst: [String]) -> [String] {
var result = [String]()
for i in 0..<lst
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
// 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
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result: [String] = []
if lst1.count == lst2.count {
return lst1
}
for i in 0..<lst1.count {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result: [String] = []
if lst1.count == lst2.count {
return lst1
}
for i in 0..<lst1.count {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
// Write a function that accepts an array of strings and returns the array of strings
// with the longest string first.
// Examples
// longestFirst(["hi", "admin", "project"]) == ["admin", "project", "hi"]
// longestFirst(["hi", "hi", "hi", "hi"]) == ["hi", "hi", "hi", "hi"]
// longestFirst(["hi", "hi", "hey"]) == ["hi", "hi", "hey"]
// longestFirst(["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100"]) == ["100", "99", "98", "97", "96", "95", "94", "93", "92", "91", "89", "88", "87", "86", "85", "84", "83", "82", "81", "79", "78", "77", "76", "75", "74", "73", "72", "71", "70", "69", "68", "67", "66", "65", "64", "63", "62", "61", "59", "58", "57", "56", "55", "54", "53", "52", "51", "50", "49", "48", "47", "46", "45", "44", "43", "42", "41", "39", "38", "37", "36", "35", "34", "33", "32", "31", "30", "29", "28", "27", "26", "25", "24", "23", "22", "21", "20", "19", "18", "17", "16", "15", "14", "13", "12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"]
func longestFirst(lst: [String]) -> [String] {
var result: [String] = []
var maxLength = 0
for i in 0..<lst.count {
if lst[i].count >
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
var result = [String]()
if lst1.count == lst2.count {
return lst1
} else if lst1.count > lst2.count {
for i in 0..<lst2.count {
result.append(lst1[i])
}
return result
} else {
for i in 0..<lst1.count {
result.append(lst2[i])
}
return result
}
}
totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"])
totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"])
totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"])
totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"])
//: [Next](@next)
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeArray = [2,3,5]
var i = 0
while i < primeArray.count {
if a % primeArray[i] == 0 {
i += 1
} else {
return false
}
}
return true
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeArray = [2,3,5]
var i = 0
while i < primeArray.count {
if a % primeArray[i] == 0 {
i += 1
} else {
return false
}
}
return true
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 25)
isMultiplyPrime(a: 100)
isMultiplyPrime(a: 101)
// 1. Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeArray = [2,3,5]
var i = 0
while i < primeArray.count {
if a % primeArray[i] == 0 {
i += 1
} else {
return false
}
}
return true
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 25)
isMultiplyPrime(a: 100)
isMultiplyPrime(a: 101)
// 2. Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeArray = [2,3,5]
var i = 0
while i < primeArray.count {
if a % primeArray[i] == 0 {
i += 1
} else {
return false
}
}
return true
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 25)
isMultiplyPrime(a: 100)
isMultiplyPrime(a: 101)
// 3. Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeArray = [2,3,5]
var i = 0
while i < primeArray.count {
if a % primeArray[i] == 0 {
i += 1
} else {
return false
}
}
return true
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 25)
isMultiplyPrime(a: 100)
isMultiplyPrime(a: 101)
// 4. Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeArray = [2,3,5]
var i = 0
while i < primeArray.count {
if a % primeArray[i] == 0 {
i += 1
} else {
return false
}
}
return true
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 25)
isMultiplyPrime(a: 100)
isMultiplyPrime(a: 101)
// 5. 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
var primeArray = [2,3,5] // variable 'primeArray' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeNumbers = [2,3,5]
var i = 0
while i < primeNumbers.count {
let number = primeNumbers[i]
if a % number == 0 {
i += 1
continue
}
return false
}
return true
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
var primeNumbers = [2,3,5]
var i = 0
while i < primeNumbers.count {
let number = primeNumbers[i]
if a % number == 0 {
i += 1
continue
}
return false
}
return true
}
print(isMultiplyPrime(a: 30)) // true
print(isMultiplyPrime(a: 100)) // false
print(isMultiplyPrime(a: 101)) // true
print(isMultiplyPrime(a: 105)) // false
print(isMultiplyPrime(a: 107)) // true
print(isMultiplyPrime(a: 110)) // false
print(isMultiplyPrime(a: 111)) // true
print(isMultiplyPrime(a: 113)) // false
print(isMultiplyPrime(a: 114)) // true
print(isMultiplyPrime(a: 115)) // false
print(isMultiplyPrime(a: 116)) // true
print(isMultiplyPrime(a: 117)) // false
print(isMultiplyPrime(a: 118)) // true
print(isMultiplyPrime(a: 119)) // false
print(isMultiplyPrime(a: 120)) // true
print(isMultiplyPrime(a: 121)) // false
print(isMultiplyPrime(a: 122)) // true
print(isMultiplyPrime(a: 123)) // false
print(isMultiplyPrime(a: 124)) // true
print(isMultiplyPrime(a: 125)) // false
print(isMultiplyPrime(a: 126)) // true
print(isMultiplyPrime(a: 127)) // false
print(isMultiplyPrime(a: 128)) // true
print(isMultiplyPrime(a: 129)) // false
print(isMultiplyPrime(a: 130)) // true
print(isMultiplyPrime(a: 131)) // false
print(isMultiplyPrime(a: 132)) // true
print(isMultiplyPrime(a: 133)) // false
print(isMultiplyPrime(a: 134)) // true
print(isMultiplyPrime(a: 135)) // false
print(isMultiplyPrime(a: 136)) // true
print(isMultiplyPrime(a: 137)) // false
print(isMultiplyPrime(a: 138)) // true
print(isMultiplyPrime(a: 139)) // false
print(isMultiplyPrime(a: 140)) // true
print(isMultiplyPrime(a: 141)) // false
print(isMultiplyPrime(a: 142)) // true
print(isMultiplyPrime(a: 143)) // false
print(isMultiplyPrime(a: 144)) // true
print(isMultiplyPrime(a: 145)) // false
print(isMultiplyPrime(a: 146)) // true
print(isMultiplyPrime(a: 147)) // false
print(isMultiplyPrime(a: 148)) // true
print(isMultiplyPrime(a: 149)) // false
print(isMultiplyPrime(a: 150)) // true
print(isMultiplyPrime(a: 151)) // false
print(isMultiplyPrime(a: 152)) // true
print(isMultiplyPrime(a: 153)) // false
print(isMultiplyPrime(a: 154)) // true
print(isMultiplyPrime(a: 155)) // false
print(isMultiplyPrime(a: 156)) // true
print(isMultiplyPrime(a: 157)) // false
print(isMultiplyPrime(a: 158)) // true
print(isMultiplyPrime(a: 159)) // false
print(isMultiplyPrime(a: 160)) // true
print(isMultiplyPrime(a: 161)) // false
print(isMultiplyPrime(a: 162)) // true
print(isMultiplyPrime(a: 163)) // false
print(isMultiplyPrime(a: 164)) // true
print(isMultiplyPrime(a:
var primeNumbers = [2,3,5] // variable 'primeNumbers' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var temp = a
for prime in primes {
while temp % prime == 0 {
temp /= prime
}
if temp == 1 {
break
} else {
result = false
break
}
}
return result
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var temp = a
for prime in primes {
while temp % prime == 0 {
temp /= prime
}
if temp == 1 {
break
} else {
result = false
break
}
}
return result
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 100)
isMultiplyPrime(a: 101)
isMultiplyPrime(a: 1000)
isMultiplyPrime(a: 10000)
isMultiplyPrime(a: 100000)
isMultiplyPrime(a: 1000000)
isMultiplyPrime(a: 10000000)
isMultiplyPrime(a: 100000000)
isMultiplyPrime(a: 1000000000)
isMultiplyPrime(a: 10000000000)
isMultiplyPrime(a: 100000000000)
isMultiplyPrime(a: 1000000000000)
isMultiplyPrime(a: 10000000000000)
isMultiplyPrime(a: 100000000000000)
isMultiplyPrime(a: 1000000000000000)
isMultiplyPrime(a: 10000000000000000)
isMultiplyPrime(a: 100000000000000000)
isMultiplyPrime(a: 1000000000000000000)
isMultiplyPrime(a: 10000000000000000000)
isMultiplyPrime(a: 100000000000000000000)
isMultiplyPrime(a: 1000000000000000000000)
isMultiplyPrime(a: 10000000000000000000000)
isMultiplyPrime(a: 100000000000000000000000)
isMultiplyPrime(a: 1000000000000000000000000)
isMultiplyPrime(a: 10000000000000000000000000)
isMultiplyPrime(a: 100000000000000000000000000)
isMultiplyPrime(a: 1000000000000000000000000000)
isMultiplyPrime(a: 10000000000000000000000000000)
isMultiplyPrime(a: 100000000000000000000000000000)
isMultiplyPrime(a: 1000000000000000000000000000000)
isMultiplyPrime(a: 10000000000000000000000000000000)
isMultiplyPrime(a: 1000000000000000000000000000000000)
isMultiplyPrime(a: 10000000000000000000000000000000000)
isMultiplyPrime(a: 100
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
let result = primes.filter { a % $0 == 0 }.count
return result == 3
}
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
let result = primes.filter { a % $0 == 0 }.count
return result == 11
}
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79]
let result = primes.filter { a % $0 == 0 }.count
return result == 13
}
func isMultiplyPrime(a: Int) -> Bool {
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 result = primes.filter { a % $0 == 0 }.count
return result == 23
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
let result = primes.filter { a % $0 == 0 }.count
return result == 3
}
isMultiplyPrime(a: 30)
isMultiplyPrime(a: 12)
isMultiplyPrime(a: 100)
// 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 1000.
// Example:
// 900 = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41 * 43 * 47
// isMultiplyPrime(a: 900) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
let result = primes.filter { a % $0 == 0 }.count
return result == 11
}
isMultiplyPrime(a: 900)
isMultiplyPrime(a: 12)
isMultiplyPrime(a: 1000)
// 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 10000.
// Example:
// 7919 = 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23 * 29 * 31 * 37 * 41 * 43 * 47 * 53 * 59 * 61 * 67 * 71 * 73 * 79
// isMultiplyPrime(a: 7919) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79]
let result = primes.filter { a % $0 == 0 }.count
return result == 13
}
isMultiplyPrime(a: 7919)
isMultiplyPrime(a: 12)
isMultiplyPrime(a: 10000)
// 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 100000.
// Example:
// 600851475143 = 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
// isMultiplyPrime(a: 600851475143) == true
func isMultiplyPrime(a: Int) -> Bool {
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 result = primes.filter { a % $0 == 0 }.count
return result == 23
}
func isMultiplyPrime(a: Int) -> Bool { // invalid redeclaration of 'isMultiplyPrime(a:)'
func isMultiplyPrime(a: Int) -> Bool { // invalid redeclaration of 'isMultiplyPrime(a:)'
func isMultiplyPrime(a: Int) -> Bool { // invalid redeclaration of 'isMultiplyPrime(a:)'
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var temp = a
for prime in primes {
while temp % prime == 0 {
temp /= prime
}
if temp == 1 {
break
} else {
result = false
break
}
}
return result
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var temp = a
for prime in primes {
while temp % prime == 0 {
temp /= prime
}
if temp == 1 {
break
} else {
result = false
break
}
}
return result
}
// Test Cases
isMultiplyPrime(a: 30) // true
isMultiplyPrime(a: 12) // false
isMultiplyPrime(a: 15) // false
isMultiplyPrime(a: 100) // false
isMultiplyPrime(a: 105) // true
isMultiplyPrime(a: 101) // true
isMultiplyPrime(a: 103) // false
isMultiplyPrime(a: 107) // true
isMultiplyPrime(a: 109) // false
isMultiplyPrime(a: 113) // true
isMultiplyPrime(a: 127) // false
isMultiplyPrime(a: 131) // true
isMultiplyPrime(a: 137) // false
isMultiplyPrime(a: 139) // true
isMultiplyPrime(a: 149) // false
isMultiplyPrime(a: 151) // true
isMultiplyPrime(a: 157) // false
isMultiplyPrime(a: 163) // true
isMultiplyPrime(a: 167) // false
isMultiplyPrime(a: 173) // true
isMultiplyPrime(a: 179) // false
isMultiplyPrime(a: 181) // true
isMultiplyPrime(a: 191) // false
isMultiplyPrime(a: 193) // true
isMultiplyPrime(a: 197) // false
isMultiplyPrime(a: 199) // true
isMultiplyPrime(a: 211) // false
isMultiplyPrime(a: 223) // true
isMultiplyPrime(a: 227) // false
isMultiplyPrime(a: 229) // true
isMultiplyPrime(a: 233) // false
isMultiplyPrime(a: 239) // true
isMultiplyPrime(a: 241) // false
isMultiplyPrime(a: 251) // true
isMultiplyPrime(a: 257) // false
isMultiplyPrime(a: 263) // true
isMultiplyPrime(a: 269) // false
isMultiplyPrime(a: 271) // true
isMultiplyPrime(a: 277) // false
isMultiplyPrime(a: 281) // true
isMultiplyPrime(a: 283) // false
isMultiplyPrime(a: 293) // true
isMultiplyPrime(a: 307) // false
isMultiplyPrime(a: 311) // true
isMultiplyPrime(a: 313) // false
isMultiplyPrime(a: 317) // true
isMultiplyPrime(a: 331) // false
isMultiplyPrime(a: 337) // true
isMultiplyPrime(a: 347) // false
isMultiplyPrime(a: 349) // true
isMultiplyPrime(a: 353) // false
isMultiplyPrime(a: 359) // true
isMultiplyPrime(a: 367) // false
isMultiplyPrime(a: 373) // true
isMultiplyPrime(a: 379) // false
isMultiplyPrime(a: 383) // true
isMultiplyPrime(a: 389) // false
isMultiplyPrime(a: 397) // true
isMultiplyPrime(a: 401) // false
isMultiplyPrime(a: 409) // true
isMultiplyPrime(a: 419) // false
isMultiplyPrime(a: 421) // true
isMultiplyPrime(a: 431) // false
isMultiplyPrime(a: 433) // true
isMultiplyPrime(a: 439) // false
isMultiplyPrime
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
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 {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
var divisor = 2
while divisor <= number {
if number % divisor == 0 {
result = false
break
}
divisor += 1
}
return result
}
// 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.
let primes = [2,3,5,7,11,13,17,19,23,29] // initialization of immutable value 'primes' was never used; consider replacing with assignment to '_' or removing it
var number = a // variable 'number' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
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 {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
return result
}
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2,3,5,7,11,13,17,19,23,29]
var result = true
var number = a
primes.forEach { (prime) in
while number % prime == 0 {
number /= prime
}
if number!= 1 {
result = false
}
}
return result
}
// 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.
if number!= 1 { // '=' must have consistent whitespace on both sides
if number!= 1 { // use of '=' in a boolean context, did you mean '=='?
if number!= 1 { // cannot force unwrap value of non-optional type 'Int'
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
primes.forEach { (prime) in
if a % prime!= 0 {
result = false
}
}
return result
}
func isSumPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var sum = 0
for i in 0..<3 {
sum += primes[i]
if a < sum {
result = false
break
}
}
return result
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
primes.forEach { (prime) in
if a % prime!= 0 {
result = false
}
}
return result
}
// Write a function that returns true if the given number is the sum of 3 consecutive prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 + 3 + 5
// isSumPrime(a: 30) == true
func isSumPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var sum = 0
for i in 0..<3 {
sum += primes[i]
if a < sum {
result = false
break
}
}
return result
}
// Write a function that returns true if the given number is the sum of 3 consecutive prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 + 3 + 5
// isSumPrime(a: 30) == true
func isSumPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var sum = 0
for i in 0..<3 {
sum += primes[i]
if a < sum {
result = false
break
}
}
return result
}
// Write a function that returns true if the given number is the sum of 3 consecutive prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 + 3 + 5
// isSumPrime(a: 30) == true
func isSumPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var sum = 0
for i in 0..<3 {
sum += primes[i]
if a < sum {
result = false
break
}
}
return result
}
// Write a function that returns true if the given number is the sum of 3 consecutive prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 + 3 + 5
// isSumPrime(a: 30) == true
func isSumPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var sum = 0
for i in 0..<3 {
sum += primes[i]
if a < sum {
result = false
break
}
}
return result
}
// Write a function that returns true if the given number is the sum of 3 consecutive prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 + 3 + 5
// isSumPrime(a: 30) == true
func isSumPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var sum = 0
for i in 0..<3 {
sum += primes[i]
if a < sum {
result = false
break
}
}
return result
}
// Write a function that returns true if the given number is the sum of 3 consecutive prime numbers
// and false otherwise.
//
if a % prime!= 0 { // '=' must have consistent whitespace on both sides
if a % prime!= 0 { // cannot force unwrap value of non-optional type 'Int'
if a % prime!= 0 { // use of '=' in a boolean context, did you mean '=='?
func isMultiplyPrime(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
func isMultipleOf3And5(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
func sumMultiples(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumMultiplesNoModulus(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumMultiplesNoModulusNoLoop(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumEvenNumbers(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumOddNumbers(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumAllNumbers(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumAllNumbersNoModulus(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumSquares(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func sumCubes(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func difference(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
// Write a function that returns true if the given number is a multiple of 3 and 5 and false otherwise.
// Example:
// 15 = 3 * 5
// isMultipleOf3And5(a: 15) == true
func isMultipleOf3And5(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
// Write a function that returns the sum of all the multiples of 3 or 5 below the given number.
// Example:
// sumMultiples(a: 10) == 23
func sumMultiples(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the multiples of 3 or 5 below the given number.
// However, you should not use the modulus operator (%) to solve this problem.
// Example:
// sumMultiplesNoModulus(a: 10) == 23
func sumMultiplesNoModulus(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the multiples of 3 or 5 below the given number.
// However, you should not use the modulus operator (%) to solve this problem.
// Additionally, you should not use any loops to solve this problem.
// Example:
// sumMultiplesNoModulusNoLoop(a: 10) == 23
func sumMultiplesNoModulusNoLoop(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the even numbers between 1 and the given number.
// Example:
// sumEvenNumbers(a: 10) == 30
func sumEvenNumbers(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the odd numbers between 1 and the given number.
// Example:
// sumOddNumbers(a: 10) == 25
func sumOddNumbers(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the numbers between 1 and the given number.
// Example:
// sumAllNumbers(a: 10) == 55
func sumAllNumbers(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the numbers between 1 and the given number.
// However, you should not use the modulus operator (%) to solve this problem.
// Example:
// sumAllNumbersNoModulus(a: 10) == 55
func sumAllNumbersNoModulus(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the squares between 1 and the given number.
// Example:
// sumSquares(a: 10) == 385
func sumSquares(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the sum of all the cubes between 1 and the given number.
// Example:
// sumCubes(a: 10) == 19335
func sumCubes(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the difference between the sum of the squares of the first 100
// natural numbers and the sum of the cubes of the first 100 natural numbers.
// Example:
// difference(a: 100) == 2297800
func difference(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that returns the difference between the sum of the squares of the first 100
// natural numbers and the sum of the cubes of the first 100 natural numbers.
// However, you should not use the modulus operator (%) to solve this problem.
// Example:
// differenceNoModulus(a: 10
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var temp = a
for prime in primes {
while temp % prime == 0 {
temp /= prime
}
if temp == 1 {
result = false
break
}
}
return result
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// Write your code here
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var result = true
var temp = a
for prime in primes {
while temp % prime == 0 {
temp /= prime
}
if temp == 1 {
result = false
break
}
}
return result
}
// Test Cases
isMultiplyPrime(a: 30) // true
isMultiplyPrime(a: 10) // false
isMultiplyPrime(a: 15) // false
isMultiplyPrime(a: 6) // false
isMultiplyPrime(a: 9) // false
```
// 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)
}
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
//: [Next](@next)
// 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)
}
// Tests
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
```
// 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)
}
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
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x == n * n || 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 * n || x == n * n * n
}
// Tests
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
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x == 1 || 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 == 1 || x % n == 0
}
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
//: [Next](@next)
// 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)
}
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
//: [Next](@next)
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n && (x == 1 || 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 == 1 || x == n) || x % n == 0 && isSimplePower(x: x / n, n: n)
}
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
//: [Next](@next)
// 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)
}
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
//: [Next](@next)
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
return x == n || x == 1 || 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 == 1 || x % n == 0 && isSimplePower(x: x / n, n: n)
}
// Tests
assert(isSimplePower(x: 1, n: 4) == true)
assert(isSimplePower(x: 2, n: 2) == true)
assert(isSimplePower(x: 8, n: 2) == true)
assert(isSimplePower(x: 3, n: 2) == false)
assert(isSimplePower(x: 3, n: 1) == false)
assert(isSimplePower(x: 5, n: 3) == false)
```
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
}
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
//: [Next](@next)
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
if a < 0 {
return false
}
let x = Int(pow(Double(a), 1.0/3.0))
return x*x*x == a
}
func nextcube(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 1
}
var x = Int(pow(Double(a), 1.0/3.0)) + 1
while!iscube(a: x*x*x) {
x += 1
}
return x*x*x
}
func prevcube(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 0
}
var x = Int(pow(Double(a), 1.0/3.0))
while!iscube(a: x*x*x) {
x -= 1
}
return x*x*x
}
func cubesmaller(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 0
}
var x = Int(pow(Double(a), 1.0/3.0))
var count = 0
while x*x*x < a {
count += 1
x += 1
}
return count
}
func cubelarger(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 0
}
var x = Int(pow(Double(a), 1.0/3.0)) + 1
var count = 0
while x*x*x > a {
count += 1
x -= 1
}
return count
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
if a < 0 {
return false
}
let x = Int(pow(Double(a), 1.0/3.0))
return x*x*x == a
}
// Write a function that takes an integer a and returns the
// smallest cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// nextcube(a: 1) == 2
// nextcube(a: 2) == 8
// nextcube(a: -1) == 1
// nextcube(a: 64) == 128
// nextcube(a: 0) == 1
// nextcube(a: 180) == 512
func nextcube(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 1
}
var x = Int(pow(Double(a), 1.0/3.0)) + 1
while!iscube(a: x*x*x) {
x += 1
}
return x*x*x
}
// Write a function that takes an integer a and returns the
// largest cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// prevcube(a: 1) == 1
// prevcube(a: 2) == 1
// prevcube(a: -1) == -1
// prevcube(a: 64) == 64
// prevcube(a: 0) == 0
// prevcube(a: 180) == 9
func prevcube(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 0
}
var x = Int(pow(Double(a), 1.0/3.0))
while!iscube(a: x*x*x) {
x -= 1
}
return x*x*x
}
// Write a function that takes an integer a and returns the
// number of cubes that are smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubesmaller(a: 1) == 0
// cubesmaller(a: 2) == 1
// cubesmaller(a: -1) == 0
// cubesmaller(a: 64) == 1
// cubesmaller(a: 0) == 0
// cubesmaller(a: 180) == 2
func cubesmaller(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 0
}
var x = Int(pow(Double(a), 1.0/3.0))
var count = 0
while x*x*x < a {
count += 1
x += 1
}
return count
}
// Write a function that takes an integer a and returns the
// number of cubes that are larger than a.
// Note: you may assume the input is always valid.
// Examples:
// cubelarger(a: 1) == 0
// cubelarger(a: 2) == 0
// cubelarger(a: -1) == 1
// cubelarger(a: 64) == 0
// cubelarger(a: 0) == 0
// cubelarger(a: 180) == 1
func cubelarger(a: Int) -> Int {
if a < 0 {
return 0
}
if a == 0 {
return 0
}
var x = Int(pow(Double(a), 1.0/3.0)) + 1
var count = 0
while x*x*x > a {
count += 1
x -= 1
}
return count
}
// Write a function that takes an integer a and returns the
// difference between the largest and the smallest cube that is
// smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubediff(a: 1) == 0
// cubediff(a: 2) == 1
while!iscube(a: x*x*x) { // expected expression, var, or let in 'while' condition
while!iscube(a: x*x*x) { // expected expression, var, or let in 'while' condition
func iscube(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.0/3.0))
}
func issquare(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 0.5))
}
func ispentagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.25))
}
func ishexagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.5))
}
func isheptagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.75))
}
func isoctagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.8))
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.0/3.0))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a square of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// issquare(a: 1) == true
// issquare(a: 2) == true
// issquare(a: -1) == false
// issquare(a: 64) == false
// issquare(a: 0) == true
// issquare(a: 180) == false
func issquare(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 0.5))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a pentagonal of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// ispentagonal(a: 1) == true
// ispentagonal(a: 2) == false
// ispentagonal(a: -1) == false
// ispentagonal(a: 64) == true
// ispentagonal(a: 0) == true
// ispentagonal(a: 180) == false
func ispentagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.25))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a hexagonal of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// ishexagonal(a: 1) == true
// ishexagonal(a: 2) == false
// ishexagonal(a: -1) == false
// ishexagonal(a: 64) == true
// ishexagonal(a: 0) == true
// ishexagonal(a: 180) == false
func ishexagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.5))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a heptagonal of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// isheptagonal(a: 1) == true
// isheptagonal(a: 2) == false
// isheptagonal(a: -1) == false
// isheptagonal(a: 64) == true
// isheptagonal(a: 0) == true
// isheptagonal(a: 180) == false
func isheptagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.75))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a octagonal of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// isoctagonal(a: 1) == true
// isoctagonal(a: 2) == false
// isoctagonal(a: -1) == false
// isoctagonal(a: 64) == true
// isoctagonal(a: 0) == true
// isoctagonal(a: 180) == false
func isoctagonal(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.8))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a nonagonal of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// isnonagonal(a: 1) == true
// isnonagonal(a: 2) == false
// isnonagonal(a: -1) == false
// isnonagonal(a: 64) == true
// isnonagonal(a: 0) == true
// isnonagonal(a: 1
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
func nextcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func prevcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubesmaller(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubebigger(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubeequal(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubesmallersum(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```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 {
// TODO: Write - Your - Code
return false
}
// Write a function that takes an integer a and returns the smallest
// cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// nextcube(a: 1) == 2
// nextcube(a: 2) == 8
// nextcube(a: -1) == 8
// nextcube(a: 64) == 128
// nextcube(a: 0) == 1
// nextcube(a: 180) == 512
func nextcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the largest
// cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// prevcube(a: 1) == 0
// prevcube(a: 2) == 1
// prevcube(a: -1) == 0
// prevcube(a: 64) == 64
// prevcube(a: 0) == -1
// prevcube(a: 180) == 96
func prevcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number
// of cubes that are smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubesmaller(a: 1) == 0
// cubesmaller(a: 2) == 1
// cubesmaller(a: -1) == 0
// cubesmaller(a: 64) == 3
// cubesmaller(a: 0) == 0
// cubesmaller(a: 180) == 5
func cubesmaller(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number
// of cubes that are larger than a.
// Note: you may assume the input is always valid.
// Examples:
// cubebigger(a: 1) == 1
// cubebigger(a: 2) == 0
// cubebigger(a: -1) == 1
// cubebigger(a: 64) == 0
// cubebigger(a: 0) == 0
// cubebigger(a: 180) == 0
func cubebigger(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number
// of cubes that are equal to a.
// Note: you may assume the input is always valid.
// Examples:
// cubeequal(a: 1) == 1
// cubeequal(a: 2) == 0
// cubeequal(a: -1) == 0
// cubeequal(a: 64) == 1
// cubeequal(a: 0) == 0
// cubeequal(a: 180) == 0
func cubeequal(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the sum
// of all cubes smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubesmallersum(a: 1) == 0
// cubesmallersum(a: 2) == 1
// cubesmallersum(a: -1) == 0
// cubesmallersum(a: 64) == 115
// cubesmallersum(a: 0) == 0
// cubesmallersum(a: 180) == 15335
func cubesmallersum(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the sum
// of all cubes bigger than a.
// Note: you may assume the input
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
if a < 0 {
return false
}
let x = Int(pow(Double(a), 1/3))
return x * x * x == a
}
func ispowerof2(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0
}
func ispowerof3(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0
}
func ispowerof4(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0
}
func ispowerof5(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0
}
func ispowerof6(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0
}
```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 {
if a < 0 {
return false
}
let x = Int(pow(Double(a), 1/3))
return x * x * x == a
}
// Write a function that takes an integer a and returns true
// if this ingeger is a power of 2.
// Note: you may assume the input is always valid.
// Examples:
// ispowerof2(a: 1) == true
// ispowerof2(a: 2) == true
// ispowerof2(a: 3) == false
// ispowerof2(a: 4) == true
// ispowerof2(a: 5) == false
func ispowerof2(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0
}
// Write a function that takes an integer a and returns true
// if this ingeger is a power of 3.
// Note: you may assume the input is always valid.
// Examples:
// ispowerof3(a: 1) == false
// ispowerof3(a: 2) == false
// ispowerof3(a: 3) == true
// ispowerof3(a: 4) == false
// ispowerof3(a: 5) == false
func ispowerof3(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0
}
// Write a function that takes an integer a and returns true
// if this ingeger is a power of 4.
// Note: you may assume the input is always valid.
// Examples:
// ispowerof4(a: 1) == false
// ispowerof4(a: 2) == false
// ispowerof4(a: 3) == false
// ispowerof4(a: 4) == true
// ispowerof4(a: 5) == false
func ispowerof4(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0
}
// Write a function that takes an integer a and returns true
// if this ingeger is a power of 5.
// Note: you may assume the input is always valid.
// Examples:
// ispowerof5(a: 1) == false
// ispowerof5(a: 2) == false
// ispowerof5(a: 3) == false
// ispowerof5(a: 4) == false
// ispowerof5(a: 5) == true
func ispowerof5(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0
}
// Write a function that takes an integer a and returns true
// if this ingeger is a power of 6.
// Note: you may assume the input is always valid.
// Examples:
// ispowerof6(a: 1) == false
// ispowerof6(a: 2) == false
// ispowerof6(a: 3) == false
// ispowerof6(a: 4) == false
// ispowerof6(a: 5) == false
// ispowerof6(a: 6) == true
func ispowerof6(a: Int) -> Bool {
if a < 0 {
return false
}
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0
}
// Write a function that takes an integer a and returns true
// if this ingeger is a power of 7.
// Note: you may assume the input is always valid.
// Examples:
// ispowerof7(a: 1) == false
// ispowerof7(a: 2) == false
// ispowerof7(a: 3) == false
// ispowerof7(a: 4) == false
// ispowerof7(a: 5) ==
return a!= 0 && (a & (a - 1)) == 0 // cannot force unwrap value of non-optional type 'Int'
return a!= 0 && (a & (a - 1)) == 0 // '=' must have consistent whitespace on both sides
return a!= 0 && (a & (a - 1)) == 0 // cannot assign value of type 'Bool' to type 'Int'
return a!= 0 && (a & (a - 1)) == 0 // use of '=' in a boolean context, did you mean '=='?
return a!= 0 && (a & (a - 1)) == 0 // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0 // '=' must have consistent whitespace on both sides
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0 // cannot assign value of type 'Bool' to type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0 // cannot force unwrap value of non-optional type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0 // use of '=' in a boolean context, did you mean '=='?
return a!= 0 && (a & (a - 1)) == 0 && (a % 3) == 0 // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0 // '=' must have consistent whitespace on both sides
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0 // cannot assign value of type 'Bool' to type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0 // cannot force unwrap value of non-optional type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0 // use of '=' in a boolean context, did you mean '=='?
return a!= 0 && (a & (a - 1)) == 0 && (a % 4) == 0 // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0 // '=' must have consistent whitespace on both sides
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0 // cannot assign value of type 'Bool' to type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0 // cannot force unwrap value of non-optional type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0 // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
return a!= 0 && (a & (a - 1)) == 0 && (a % 5) == 0 // use of '=' in a boolean context, did you mean '=='?
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0 // use of '=' in a boolean context, did you mean '=='?
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0 // integer literal value '0' cannot be used as a boolean; did you mean 'false'?
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0 // cannot force unwrap value of non-optional type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0 // cannot assign value of type 'Bool' to type 'Int'
return a!= 0 && (a & (a - 1)) == 0 && (a % 6) == 0 // '=' must have consistent whitespace on both sides
func iscube(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.0/3.0))
}
func nextcube(a: Int) -> Int {
if a < 0 {
return 1
}
if a == 0 {
return 1
}
var i = 1
while i < a {
i = i * 3 + 1
}
return i
}
func prevcube(a: Int) -> Int {
if a <= 0 {
return -1
}
if a == 0 {
return 0
}
var i = a
while i > 1 {
i = (i - 1) / 3
}
return i
}
func numcubes(a: Int) -> Int {
if a <= 0 {
return 0
}
if a == 0 {
return 0
}
var i = 1
var count = 0
while i < a {
i = i * 3 + 1
count += 1
}
return count
}
func numcubes2(a: Int) -> Int {
if a <= 0 {
return 0
}
if a == 0 {
return 0
}
var i = a
var count = 0
while i > 1 {
i = (i - 1) / 3
count += 1
}
return count
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.0/3.0))
}
// Write a function that takes an integer a and returns the smallest
// cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// nextcube(a: 1) == 2
// nextcube(a: 2) == 8
// nextcube(a: -1) == 1
// nextcube(a: 64) == 128
// nextcube(a: 0) == 1
// nextcube(a: 180) == 512
func nextcube(a: Int) -> Int {
if a < 0 {
return 1
}
if a == 0 {
return 1
}
var i = 1
while i < a {
i = i * 3 + 1
}
return i
}
// Write a function that takes an integer a and returns the largest
// cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// prevcube(a: 1) == 1
// prevcube(a: 2) == 1
// prevcube(a: -1) == -1
// prevcube(a: 64) == 64
// prevcube(a: 0) == 0
// prevcube(a: 180) == 9
func prevcube(a: Int) -> Int {
if a <= 0 {
return -1
}
if a == 0 {
return 0
}
var i = a
while i > 1 {
i = (i - 1) / 3
}
return i
}
// Write a function that takes an integer a and returns the number of
// cubes that are smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// numcubes(a: 1) == 0
// numcubes(a: 2) == 1
// numcubes(a: -1) == 0
// numcubes(a: 64) == 1
// numcubes(a: 0) == 0
// numcubes(a: 180) == 3
func numcubes(a: Int) -> Int {
if a <= 0 {
return 0
}
if a == 0 {
return 0
}
var i = 1
var count = 0
while i < a {
i = i * 3 + 1
count += 1
}
return count
}
// Write a function that takes an integer a and returns the number of
// cubes that are larger than a.
// Note: you may assume the input is always valid.
// Examples:
// numcubes(a: 1) == 1
// numcubes(a: 2) == 0
// numcubes(a: -1) == 0
// numcubes(a: 64) == 0
// numcubes(a: 0) == 0
// numcubes(a: 180) == 1
func numcubes2(a: Int) -> Int {
if a <= 0 {
return 0
}
if a == 0 {
return 0
}
var i = a
var count = 0
while i > 1 {
i = (i - 1) / 3
count += 1
}
return count
}
// Write a function that takes an integer a and returns the sum of all
// cubes that are smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubeSum(a: 1) == 0
// cubeSum(a: 2) == 3
// cubeSum(a: -1) == 0
// cubeSum(a: 64) == 512
// cubeSum(a: 0) == 0
// cubeSum(a: 180) == 15360
func cubeSum(a: Int) -> Int {
if a <= 0 {
return 0
}
if a == 0 {
return 0
}
var i = 1
var sum = 0
while i < a {
i =
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.0/3.0))
}
func nextcube(a: Int) -> Int {
if a < 0 {
return nextcube(a: -a)
}
if a == 0 {
return 1
}
var x = a + 1
while!iscube(a: x) {
x += 1
}
return x
}
func prevcube(a: Int) -> Int {
if a < 0 {
return prevcube(a: -a)
}
if a == 0 {
return 0
}
var x = a - 1
while!iscube(a: x) {
x -= 1
}
return x
}
func largetscube(a: Int, b: Int) -> Int {
if a < 0 {
return largetscube(a: -a, b: b)
}
if b < 0 {
return largetscube(a: a, b: -b)
}
if a == 0 {
return 0
}
if b == 0 {
return 0
}
if a > b {
return largetscube(a: b, b: a)
}
var x = a + 1
while x < b {
if iscube(a: x) {
return x
}
x += 1
}
return x - 1
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
return a > 0 && a == Int(pow(Double(a), 1.0/3.0))
}
// Write a function that takes an integer a and returns the smallest
// cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// nextcube(a: 1) == 2
// nextcube(a: 2) == 8
// nextcube(a: -1) == 2
// nextcube(a: 64) == 128
// nextcube(a: 0) == 1
// nextcube(a: 180) == 512
func nextcube(a: Int) -> Int {
if a < 0 {
return nextcube(a: -a)
}
if a == 0 {
return 1
}
var x = a + 1
while!iscube(a: x) {
x += 1
}
return x
}
// Write a function that takes an integer a and returns the largest
// cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// prevcube(a: 1) == 1
// prevcube(a: 2) == 1
// prevcube(a: -1) == -1
// prevcube(a: 64) == 64
// prevcube(a: 0) == 0
// prevcube(a: 180) == 9
func prevcube(a: Int) -> Int {
if a < 0 {
return prevcube(a: -a)
}
if a == 0 {
return 0
}
var x = a - 1
while!iscube(a: x) {
x -= 1
}
return x
}
// Write a function that takes two integers a and b and returns the
// smallest cube that is both larger than a and smaller than b.
// Note: you may assume the input is always valid.
// Examples:
// largetscube(a: 1, b: 2) == 2
// largetscube(a: 2, b: 8) == 8
// largetscube(a: -1, b: 2) == 2
// largetscube(a: 64, b: 128) == 128
// largetscube(a: 0, b: 1) == 0
// largetscube(a: 180, b: 512) == 512
func largetscube(a: Int, b: Int) -> Int {
if a < 0 {
return largetscube(a: -a, b: b)
}
if b < 0 {
return largetscube(a: a, b: -b)
}
if a == 0 {
return 0
}
if b == 0 {
return 0
}
if a > b {
return largetscube(a: b, b: a)
}
var x = a + 1
while x < b {
if iscube(a: x) {
return x
}
x += 1
}
return x - 1
}
// Write a function that takes two integers a and b and returns the
// largest cube that is both larger than a and smaller than b.
// Note: you may assume the input is always valid.
// Examples:
// smallestlcube(a: 1, b: 2) == 1
// smallestlcube(a: 2, b: 8) == 2
// smallestlcube(a: -1, b: 2) == -1
// smallestlcube(a: 64, b: 128) == 64
// smallestlcube(a: 0, b: 1) == 0
// smallestlcube(a: 180, b: 512) == 9
func smallestlcube(a: Int, b: Int) -> Int {
if a < 0 {
return smallestlcube(a: -a, b: b)
}
if b < 0 {
return smallestlcube(a: a, b: -b)
}
if a == 0 {
return 0
}
if b ==
while!iscube(a: x) { // expected expression, var, or let in 'while' condition
while!iscube(a: x) { // expected expression, var, or let in 'while' condition
func iscube(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
func nextcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func prevcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubesmaller(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubebigger(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubeequal(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubesmallerorequal(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```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 {
// TODO: Write - Your - Code
return false
}
// Write a function that takes an integer a and returns the smallest
// cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// nextcube(a: 1) == 2
// nextcube(a: 2) == 8
// nextcube(a: -1) == 8
// nextcube(a: 64) == 128
// nextcube(a: 0) == 1
// nextcube(a: 180) == 512
func nextcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the largest
// cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// prevcube(a: 1) == 1
// prevcube(a: 2) == 1
// prevcube(a: -1) == -1
// prevcube(a: 64) == 64
// prevcube(a: 0) == 0
// prevcube(a: 180) == 9
func prevcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number
// of cubes that are smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubesmaller(a: 1) == 0
// cubesmaller(a: 2) == 1
// cubesmaller(a: -1) == 0
// cubesmaller(a: 64) == 3
// cubesmaller(a: 0) == 0
// cubesmaller(a: 180) == 2
func cubesmaller(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number
// of cubes that are larger than a.
// Note: you may assume the input is always valid.
// Examples:
// cubebigger(a: 1) == 1
// cubebigger(a: 2) == 0
// cubebigger(a: -1) == 1
// cubebigger(a: 64) == 0
// cubebigger(a: 0) == 0
// cubebigger(a: 180) == 1
func cubebigger(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number
// of cubes that are equal to a.
// Note: you may assume the input is always valid.
// Examples:
// cubeequal(a: 1) == 1
// cubeequal(a: 2) == 0
// cubeequal(a: -1) == 0
// cubeequal(a: 64) == 1
// cubeequal(a: 0) == 0
// cubeequal(a: 180) == 0
func cubeequal(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the sum
// of all cubes smaller than or equal to a.
// Note: you may assume the input is always valid.
// Examples:
// cubesmallerorequal(a: 1) == 0
// cubesmallerorequal(a: 2) == 1
// cubesmallerorequal(a: -1) == 0
// cubesmallerorequal(a: 64) == 1728
// cubesmallerorequal(a: 0) == 0
// cubesmallerorequal(a: 180) == 57344
func cubesmallerorequal(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the sum
// of all cubes larger than or equal to a.
// Note
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
if a < 0 {
return false
}
let root = Int(sqrt(Double(a)))
return root * root == a
}
func isperfectsquare(a: Int) -> Bool {
if a < 0 {
return false
}
let root = sqrt(Double(a))
return root * root == Double(a)
}
func ispalindrome(a: Int) -> Bool {
if a < 0 {
return false
}
let str = "\(a)"
let reversed = String(str.reversed())
return str == reversed
}
func isprime(a: Int) -> Bool {
if a < 0 {
return false
}
if a == 0 || a == 1 {
return false
}
for i in 2...Int(sqrt(Double(a))) {
if a % i == 0 {
return false
}
}
return true
}
func isfibonacci(a: Int) -> Bool {
if a < 0 {
return false
}
let phi = (1 + sqrt(5)) / 2
return Double(a) / (phi * phi) == Double(Int(phi * phi))
}
func istriangular(a: Int) -> Bool {
if a < 0 {
return false
}
let root = sqrt(Double(2 * a))
return root * root == Double(2 * 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 {
if a < 0 {
return false
}
let root = Int(sqrt(Double(a)))
return root * root == a
}
// Write a function that takes an integer a and returns true
// if this ingeger is a perfect square.
// Note: you may assume the input is always valid.
// Examples:
// isperfectsquare(a: 1) == true
// isperfectsquare(a: 2) == true
// isperfectsquare(a: -1) == false
// isperfectsquare(a: 64) == true
// isperfectsquare(a: 0) == true
// isperfectsquare(a: 180) == false
func isperfectsquare(a: Int) -> Bool {
if a < 0 {
return false
}
let root = sqrt(Double(a))
return root * root == Double(a)
}
// Write a function that takes an integer a and returns true
// if this ingeger is a palindrome.
// Note: you may assume the input is always valid.
// Examples:
// ispalindrome(a: 1) == true
// ispalindrome(a: 2) == false
// ispalindrome(a: -1) == false
// ispalindrome(a: 64) == false
// ispalindrome(a: 0) == true
// ispalindrome(a: 180) == false
func ispalindrome(a: Int) -> Bool {
if a < 0 {
return false
}
let str = "\(a)"
let reversed = String(str.reversed())
return str == reversed
}
// Write a function that takes an integer a and returns true
// if this ingeger is a prime number.
// Note: you may assume the input is always valid.
// Examples:
// isprime(a: 1) == true
// isprime(a: 2) == true
// isprime(a: -1) == false
// isprime(a: 64) == false
// isprime(a: 0) == false
// isprime(a: 180) == false
func isprime(a: Int) -> Bool {
if a < 0 {
return false
}
if a == 0 || a == 1 {
return false
}
for i in 2...Int(sqrt(Double(a))) {
if a % i == 0 {
return false
}
}
return true
}
// Write a function that takes an integer a and returns true
// if this ingeger is a Fibonacci number.
// Note: you may assume the input is always valid.
// Examples:
// isfibonacci(a: 1) == true
// isfibonacci(a: 2) == true
// isfibonacci(a: -1) == false
// isfibonacci(a: 64) == false
// isfibonacci(a: 0) == false
// isfibonacci(a: 180) == false
func isfibonacci(a: Int) -> Bool {
if a < 0 {
return false
}
let phi = (1 + sqrt(5)) / 2
return Double(a) / (phi * phi) == Double(Int(phi * phi))
}
// Write a function that takes an integer a and returns true
// if this ingeger is a triangular number.
// Note: you may assume the input is always valid.
// Examples:
// istriangular(a: 1) == true
// istriangular(a: 2) == false
// istriangular(a: -1) == false
// istriangular(a: 64) == false
// istriangular(a: 0) == true
// istriangular(a: 180) == false
func istriangular(a: Int) -> Bool {
if a < 0 {
return false
}
let root = sqrt(Double(2 * a))
return root * root == Double(2 * a)
}
// Write a function that takes an integer a and returns true
// if this ingeger is a square number.
// Note: you may assume the input is always valid.
// Examples:
// issquare(
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
func cubicroot(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
func cubicroot2(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
func cubed(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
func cubed2(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
func cubed3(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
func cubed4(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
```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 {
// TODO: Write - Your - Code
return false
}
// Write a function that takes an integer a and returns the smallest
// cube root of a.
// Note: you may assume the input is always valid.
// Examples:
// cubicroot(a: 1) == 1
// cubicroot(a: 8) == 2
// cubicroot(a: 27) == 3
// cubicroot(a: 64) == 4
// cubicroot(a: 0) == 0
// cubicroot(a: 180) == -1
func cubicroot(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
// Write a function that takes an integer a and returns the largest
// cube root of a.
// Note: you may assume the input is always valid.
// Examples:
// cubicroot(a: 1) == 1
// cubicroot(a: 8) == 2
// cubicroot(a: 27) == 3
// cubicroot(a: 64) == 4
// cubicroot(a: 0) == 0
// cubicroot(a: 180) == -1
func cubicroot2(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
// Write a function that takes an integer a and returns the number of
// cubes that equal a.
// Note: you may assume the input is always valid.
// Examples:
// cubed(a: 1) == 1
// cubed(a: 8) == 1
// cubed(a: 27) == 1
// cubed(a: 64) == 1
// cubed(a: 0) == 0
// cubed(a: 180) == 3
func cubed(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
// Write a function that takes an integer a and returns the number of
// perfect cubes that are less than or equal to a.
// Note: you may assume the input is always valid.
// Examples:
// cubed(a: 1) == 1
// cubed(a: 8) == 1
// cubed(a: 27) == 1
// cubed(a: 64) == 1
// cubed(a: 0) == 0
// cubed(a: 180) == 3
func cubed2(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
// Write a function that takes an integer a and returns the number of
// perfect cubes that are greater than or equal to a.
// Note: you may assume the input is always valid.
// Examples:
// cubed(a: 1) == 1
// cubed(a: 8) == 1
// cubed(a: 27) == 1
// cubed(a: 64) == 1
// cubed(a: 0) == 0
// cubed(a: 180) == 3
func cubed3(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
// Write a function that takes an integer a and returns the number of
// cubes that equal a.
// Note: you may assume the input is always valid.
// Examples:
// cubed(a: 1) == 1
// cubed(a: 8) == 1
// cubed(a: 27) == 1
// cubed(a: 64) == 1
// cubed(a: 0) == 0
// cubed(a: 180) == 3
func cubed4(a: Int) -> Int {
// TODO: Write - Your - Code
return -1
}
// Write a function that takes an integer a and returns the number of
// cubes that equal a.
// Note: you may assume the input is always
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
// TODO: Write - Your - Code
return false
}
func nextcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func prevcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubesmaller(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubelarger(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubedelta(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
func cubediff(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
```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 {
// TODO: Write - Your - Code
return false
}
// Write a function that takes an integer a and returns the smallest
// cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// nextcube(a: 1) == 2
// nextcube(a: 2) == 8
// nextcube(a: -1) == 8
// nextcube(a: 64) == 128
// nextcube(a: 0) == 1
// nextcube(a: 180) == 512
func nextcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the largest
// cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// prevcube(a: 1) == 0
// prevcube(a: 2) == 1
// prevcube(a: -1) == 0
// prevcube(a: 64) == 64
// prevcube(a: 0) == 0
// prevcube(a: 180) == 96
func prevcube(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number of
// cubes that are smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubesmaller(a: 1) == 0
// cubesmaller(a: 2) == 1
// cubesmaller(a: -1) == 0
// cubesmaller(a: 64) == 32
// cubesmaller(a: 0) == 0
// cubesmaller(a: 180) == 16
func cubesmaller(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number of
// cubes that are larger than a.
// Note: you may assume the input is always valid.
// Examples:
// cubelarger(a: 1) == 1
// cubelarger(a: 2) == 0
// cubelarger(a: -1) == 0
// cubelarger(a: 64) == 0
// cubelarger(a: 0) == 0
// cubelarger(a: 180) == 5
func cubelarger(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the difference
// between the largest and the smallest cube that is smaller than a.
// Note: you may assume the input is always valid.
// Examples:
// cubedelta(a: 1) == 1
// cubedelta(a: 2) == 1
// cubedelta(a: -1) == 1
// cubedelta(a: 64) == 63
// cubedelta(a: 0) == 1
// cubedelta(a: 180) == 179
func cubedelta(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the difference
// between the smallest and the largest cube that is larger than a.
// Note: you may assume the input is always valid.
// Examples:
// cubediff(a: 1) == 0
// cubediff(a: 2) == 1
// cubediff(a: -1) == 2
// cubediff(a: 64) == 65
// cubediff(a: 0) == 0
// cubediff(a: 180) == 179
func cubediff(a: Int) -> Int {
// TODO: Write - Your - Code
return 0
}
// Write a function that takes an integer a and returns the number of
// cubes that are between a and b (both inclusive).
// Note: you may assume the input is always valid.
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for c in num {
if c == "0" || c == "1" || c == "2" || c == "3" || c == "4" || c == "5" || c == "6" || c == "7" || c == "8" || c == "9" {
count += 1
} else if c == "A" || c == "B" || c == "C" || c == "D" || c == "E" || c == "F" {
count += 1
} else if c == "1" || c == "3" || c == "5" || c == "7" || c == "9" || c == "B" || c == "D" || c == "F" {
count += 2
}
}
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 c in num {
if c == "0" || c == "1" || c == "2" || c == "3" || c == "4" || c == "5" || c == "6" || c == "7" || c == "8" || c == "9" {
count += 1
} else if c == "A" || c == "B" || c == "C" || c == "D" || c == "E" || c == "F" {
count += 1
} else if c == "1" || c == "3" || c == "5" || c == "7" || c == "9" || c == "B" || c == "D" || c == "F" {
count += 2
}
}
return count
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
let num = num.uppercased()
for i in num {
if i == "A" || i == "B" || i == "C" || i == "D" || i == "E" || i == "F" {
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
let num = num.uppercased()
for i in num {
if i == "A" || i == "B" || i == "C" || i == "D" || i == "E" || i == "F" {
count += 1
}
}
return count
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
var hex = [2,3,5,7,11,13]
for i in 0...5 {
if hex.contains(Int(String(num.prefix(1)))!) {
count += 1
}
num = String(num.suffix(num.count-1))
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
var hex = [2,3,5,7,11,13]
for i in 0...5 {
if hex.contains(Int(String(num.prefix(1)))!) {
count += 1
}
num = String(num.suffix(num.count-1))
}
return count
}
hexKey(num: "AB")
hexKey(num: "1077E")
hexKey(num: "ABED1A33")
hexKey(num: "123456789ABCDEF0")
hexKey(num: "2020")
//: [Next](@next)
num = String(num.suffix(num.count-1)) // cannot assign to value: 'num' is a 'let' constant
func hexKey(num: String) -> Int {
var count = 0
for i in num {
switch String(i) {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F":
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 i in num {
switch String(i) {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F":
count += 1
default:
break
}
}
return count
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for c in num {
let n = Int(String(c), radix: 16)!
if isPrime(n) {
count += 1
}
}
return count
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 { return false }
if n <= 3 { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 { return false }
i += 6
}
return true
}
```swift
// You 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 c in num {
let n = Int(String(c), radix: 16)!
if isPrime(n) {
count += 1
}
}
return count
}
func isPrime(_ n: Int) -> Bool {
if n <= 1 { return false }
if n <= 3 { return true }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 { return false }
i += 6
}
return true
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
func hexKey(num: String) -> Int {
var count = 0
for i in num {
switch String(i) {
case "2", "3", "5", "7", "11", "13":
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 i in num {
switch String(i) {
case "2", "3", "5", "7", "11", "13":
count += 1
default:
break
}
}
return count
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for i in num {
switch String(i) {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F":
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 i in num {
switch String(i) {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F":
count += 1
default:
break
}
}
return count
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var primeCount = 0
var hexNum = num.uppercased()
var hexArray = Array(hexNum)
for i in 0...hexArray.count-1 {
switch hexArray[i] {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
break
case "A", "B", "C", "D", "E", "F":
primeCount += 1
default:
break
}
}
return primeCount
}
```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 primeCount = 0
var hexNum = num.uppercased()
var hexArray = Array(hexNum)
for i in 0...hexArray.count-1 {
switch hexArray[i] {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
break
case "A", "B", "C", "D", "E", "F":
primeCount += 1
default:
break
}
}
return primeCount
}
hexKey(num: "AB")
hexKey(num: "1077E")
hexKey(num: "ABED1A33")
hexKey(num: "123456789ABCDEF0")
hexKey(num: "2020")
//: [Next](@next)
var hexNum = num.uppercased() // variable 'hexNum' was never mutated; consider changing to 'let' constant
var hexArray = Array(hexNum) // variable 'hexArray' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for char in num {
switch String(char) {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F":
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 String(char) {
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F":
count += 1
default:
break
}
}
return count
}
hexKey(num: "AB")
hexKey(num: "1077E")
hexKey(num: "ABED1A33")
hexKey(num: "123456789ABCDEF0")
hexKey(num: "2020")
//: [Next](@next)
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var count = 0
for c in num {
if ["2", "3", "5", "7", "11", "13"].contains(String(c)) {
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 c in num {
if ["2", "3", "5", "7", "11", "13"].contains(String(c)) {
count += 1
}
}
return count
}
hexKey(num: "AB") == 1
hexKey(num: "1077E") == 2
hexKey(num: "ABED1A33") == 4
hexKey(num: "123456789ABCDEF0") == 6
hexKey(num: "2020") == 2
//: [Next](@next)
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
func hexadecimalToBinary(hexadecimal: String) -> String {
// TODO: Write - Your - Code
return ""
}
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
func decimalToHexadecimal(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
func binarySqueeze(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
func reverse(string: String) -> String {
// TODO: Write - Your - Code
return ""
}
```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 {
// TODO: Write - Your - Code
return ""
}
// You will be given a binary string and your task is to convert it to decimal format.
// The function should return an integer.
// Examples:
// binaryToDecimal(binary: "1111") == 15
// binaryToDecimal(binary: "100000") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a binary string and your task is to convert it to a hexadecimal format.
// The function should return a string.
// Examples:
// binaryToHexadecimal(binary: "1101110001010100000101101000111") == "dbc3a57"
// binaryToHexadecimal(binary: "11111111111111111111111111111101") == "ffffffff"
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a hexadecimal string and your task is to convert it to binary format.
// The function should return a string.
// Examples:
// hexadecimalToBinary(hexadecimal: "Ff1A3B") == "11111111111111111110001010110011"
// hexadecimalToBinary(hexadecimal: "FFFFFFFF") == "11111111111111111111111111111111"
func hexadecimalToBinary(hexadecimal: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a hexadecimal string and your task is to convert it to decimal format.
// The function should return an integer.
// Examples:
// hexadecimalToDecimal(hexadecimal: "Ff1A3B") == 13467859
// hexadecimalToDecimal(hexadecimal: "FFFFFFFF") == 4294967295
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a decimal number and your task is to convert it to a hexadecimal format.
// The function should return a string.
// Examples:
// decimalToHexadecimal(decimal: 13467859) == "Ff1A3B"
// decimalToHexadecimal(decimal: 4294967295) == "FFFFFFFF"
func decimalToHexadecimal(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a binary string and your task is to convert it to a string that has
// only 0's and 1's.
// The function should return a string.
// Examples:
// binarySqueeze(binary: "11110000111100001111000011110000") == "111100001111"
// binarySqueeze(binary: "11111111111111111111111111111111") == "11111111111111111111111111111111"
func binarySqueeze(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a string and your task is to reverse the string.
// The function should return a string.
// Examples:
// reverse(string: "Hello, World!") == "!dlroW,olleH"
// reverse(string: "12345") == "54321"
func reverse(string: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a string and your task is to remove all duplicate characters from it.
// The function should return a string.
// Examples:
// removeDuplicates(string: "Hello, World!") == "Helo, Wr
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
func hexadecimalToBinary(hexadecimal: String) -> String {
// TODO: Write - Your - Code
return ""
}
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
func decimalToHexadecimal(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
```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 {
// TODO: Write - Your - Code
return ""
}
// You will be given a string of binary numbers and your task is to convert it to decimal format.
// The function should return a number.
// The string will only contain 0's and 1's. There will be an equal amount of 0's and 1's.
// Examples:
// binaryToDecimal(binary: "101010") == 42
// binaryToDecimal(binary: "1100110") == 102
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers and your task is to convert it to hexadecimal format.
// The function should return a string.
// The string will only contain 0's and 1's. There will be an equal amount of 0's, 1's and 'x's.
// Examples:
// binaryToHexadecimal(binary: "101010") == "2A"
// binaryToHexadecimal(binary: "1100110") == "66"
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a number in hexadecimal 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:
// hexadecimalToBinary(hexadecimal: "2A") == "db101010db"
// hexadecimalToBinary(hexadecimal: "66") == "db110011db"
func hexadecimalToBinary(hexadecimal: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a string of binary numbers and your task is to convert it to hexadecimal format.
// The function should return a string.
// The string will only contain 0's and 1's. There will be an equal amount of 0's, 1's and 'x's.
// Examples:
// binaryToHexadecimal(binary: "101010") == "2A"
// binaryToHexadecimal(binary: "1100110") == "66"
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a number in hexadecimal form and your task is to convert it to decimal format.
// The function should return a number.
// The string will only contain 0's, 1's and 'x's. There will be an equal amount of 0's, 1's and 'x's.
// Examples:
// hexadecimalToDecimal(hexadecimal: "2A") == 42
// hexadecimalToDecimal(hexadecimal: "66") == 102
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a number in decimal form and your task is to convert it to hexadecimal format.
// The function should return a string.
// The string will only contain 0's and 1's. There will be an equal amount of 0's and 1's.
// Examples:
// decimalToHexadecimal(decimal: 42) == "2A"
// decimalToHexadecimal(decimal: 102) == "66"
func decimalToHexadecimal(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a string of hexadecimal numbers and your task is to convert it to decimal format.
// The function should return a number.
// The string will only contain 0's, 1's and 'x's. There will be an equal amount of 0's, 1's and 'x's.
// Examples:
// hexadecimalToDecimal(hexadecimal: "2A") == 42
// hexadecimalToDecimal(hexadecimal: "66") == 102
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
// Write your code here
var binary = ""
var dec = decimal
while dec > 0 {
binary = String(dec % 2) + binary
dec /= 2
}
return "db" + binary + "db"
}
func binaryToDecimal(binary: String) -> Int {
// Write your code here
var decimal = 0
for (index, value) in binary.reversed().enumerated() {
decimal += Int(String(value))! * (2 ** index)
}
return decimal
}
func binaryToHexadecimal(binary: String) -> String {
// Write your code here
var hexadecimal = ""
var dec = binaryToDecimal(binary: binary)
while dec > 0 {
hexadecimal = String(hexChars[dec % 16]) + hexadecimal
dec /= 16
}
return "hd" + hexadecimal + "db"
}
func hexadecimalToBinary(hexadecimal: String) -> String {
// Write your code here
var binary = ""
var dec = 0
for char in hexadecimal {
dec = dec * 16 + Int(String(char))!
}
return "db" + binaryToDecimal(binary: String(dec)) + "db"
}
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// Write your code here
var decimal = 0
for (index, value) in hexadecimal.reversed().enumerated() {
decimal += Int(String(value))! * (16 ** index)
}
return decimal
}
```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 {
// Write your code here
var binary = ""
var dec = decimal
while dec > 0 {
binary = String(dec % 2) + binary
dec /= 2
}
return "db" + binary + "db"
}
// You will be given a number in binary form and your task is to convert it to
// decimal format. The function should return an integer.
// Examples:
// binaryToDecimal(binary: "11111") == 31
// binaryToDecimal(binary: "101010") == 42
func binaryToDecimal(binary: String) -> Int {
// Write your code here
var decimal = 0
for (index, value) in binary.reversed().enumerated() {
decimal += Int(String(value))! * (2 ** index)
}
return decimal
}
// You will be given a number in binary form and your task is to convert it to
// hexadecimal format. The function should return a string, with each character representing a
// hexadecimal number. Each character in the string will be a letter from the set ['A', 'B',
// 'C', 'D', 'E', 'F'].
// There will be an extra couple of characters 'hd' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// binaryToHexadecimal(binary: "11011101101110100101011") == "hd1A6B95Ddb"
// binaryToHexadecimal(binary: "11000000") == "hd0Cdb"
func binaryToHexadecimal(binary: String) -> String {
// Write your code here
var hexadecimal = ""
var dec = binaryToDecimal(binary: binary)
while dec > 0 {
hexadecimal = String(hexChars[dec % 16]) + hexadecimal
dec /= 16
}
return "hd" + hexadecimal + "db"
}
// You will be given a number in hexadecimal 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:
// hexadecimalToBinary(hexadecimal: "1A6B95Ddb") == "db11011101110100101011db"
// hexadecimalToBinary(hexadecimal: "0Cdb") == "db11000000db"
func hexadecimalToBinary(hexadecimal: String) -> String {
// Write your code here
var binary = ""
var dec = 0
for char in hexadecimal {
dec = dec * 16 + Int(String(char))!
}
return "db" + binaryToDecimal(binary: String(dec)) + "db"
}
// You will be given a number in hexadecimal form and your task is to convert it to
// decimal format. The function should return an integer.
// Examples:
// hexadecimalToDecimal(hexadecimal: "1A6B95Ddb") == 11011101110100101011
// hexadecimalToDecimal(hexadecimal: "0Cdb") == 1100000
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// Write your code here
var decimal = 0
for (index, value) in hexadecimal.reversed().enumerated() {
decimal += Int(String(value))! * (16 ** index)
}
return decimal
}
// You will be given a number in hexadecimal form and your task is to convert it to
// octal format. The function should return a string, with each character representing a
// octal number. Each character in the string will be a digit from the set ['0', '1', '2',
// '3', '4', '5', '6', '7'].
// There will be an extra couple of characters 'oh' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// hexadecimalToOctal(hexadecimal: "1A6B95Ddb") == "oh014
decimal += Int(String(value))! * (2 ** index) // no operator '**' is defined; did you mean 'pow(_:_:)'?
hexadecimal = String(hexChars[dec % 16]) + hexadecimal // cannot find 'hexChars' in scope
return "db" + binaryToDecimal(binary: String(dec)) + "db" // cannot convert value of type 'Int' to expected argument type 'String'
decimal += Int(String(value))! * (16 ** index) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func decimalToBinary(decimal: Int) -> String {
// Write your code here
var binary = ""
if decimal == 0 {
binary = "0"
}
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
// Write your code here
var binary = ""
if decimal == 0 {
binary = "0"
}
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
// Tests
print(decimalToBinary(decimal: 15))
print(decimalToBinary(decimal: 32))
print(decimalToBinary(decimal: 0))
print(decimalToBinary(decimal: 1))
print(decimalToBinary(decimal: 10))
print(decimalToBinary(decimal: 100))
print(decimalToBinary(decimal: 1000))
print(decimalToBinary(decimal: 10000))
print(decimalToBinary(decimal: 100000))
print(decimalToBinary(decimal: 1000000))
print(decimalToBinary(decimal: 10000000))
print(decimalToBinary(decimal: 100000000))
print(decimalToBinary(decimal: 1000000000))
print(decimalToBinary(decimal: 10000000000))
print(decimalToBinary(decimal: 100000000000))
print(decimalToBinary(decimal: 1000000000000))
print(decimalToBinary(decimal: 10000000000000))
print(decimalToBinary(decimal: 100000000000000))
print(decimalToBinary(decimal: 1000000000000000))
print(decimalToBinary(decimal: 10000000000000000))
print(decimalToBinary(decimal: 100000000000000000))
print(decimalToBinary(decimal: 1000000000000000000))
print(decimalToBinary(decimal: 10000000000000000000))
print(decimalToBinary(decimal: 100000000000000000000))
print(decimalToBinary(decimal: 1000000000000000000000))
print(decimalToBinary(decimal: 10000000000000000000000))
print(decimalToBinary(decimal: 100000000000000000000000))
print(decimalToBinary(decimal: 1000000000000000000000000))
print(decimalToBinary(decimal: 10000000000000000000000000))
print(decimalToBinary(decimal: 100000000000000000000000000))
print(decimalToBinary(decimal: 1000000000000000000000000000))
print(decimalToBinary(decimal: 10000000000000000000000000000))
print(decimalToBinary(decimal: 1000000000000000000000000000000))
print(decimalToBinary(decimal: 10000000000000000000000000000000))
print(decimalToBinary(decimal: 1000000000000000000000000000000000))
print(decimalToBinary(decimal: 10000000000000000000000
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func decimalToBinary(decimal: Int) -> String {
// Write your code here
var binary = ""
if decimal == 0 {
binary = "0"
}
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
func binaryToDecimal(binary: String) -> Int {
// Write your code here
var decimal = 0
for i in 0..<binary.count {
if binary[i] == "1" {
decimal += 2.0.pow(binary.count - i - 1)
}
}
return decimal
}
func binaryToHexadecimal(binary: String) -> String {
// Write your code here
var hexadecimal = ""
for i in stride(from: binary.count - 1, through: 0, by: -4) {
let start = i - 3 < 0? 0 : i - 3
let end = i + 1
let part = binary[start...end]
hexadecimal = hexDictionary[part]! + hexadecimal
}
return hexadecimal
}
func hexadecimalToBinary(hexadecimal: String) -> String {
// Write your code here
var binary = ""
for i in 0..<hexadecimal.count {
binary += hexDictionary[String(hexadecimal[i])]!
}
return binary
}
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// Write your code here
var decimal = 0
for i in 0..<hexadecimal.count {
decimal += Int(String(hexadecimal[i]))! * 16.0.pow(hexadecimal.count - i - 1)
}
return decimal
}
func decimalToOctal(decimal: Int) -> String {
// Write your code here
var octal = ""
if decimal == 0 {
octal = "0"
}
while decimal > 0 {
octal = String(decimal % 8) + octal
decimal /= 8
}
return octal
}
```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 {
// Write your code here
var binary = ""
if decimal == 0 {
binary = "0"
}
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
// You will be given a string in binary format and your task is to convert it to decimal format.
// The function should return an integer.
// Examples:
// binaryToDecimal(binary: "11111") == 31
// binaryToDecimal(binary: "101010") == 42
func binaryToDecimal(binary: String) -> Int {
// Write your code here
var decimal = 0
for i in 0..<binary.count {
if binary[i] == "1" {
decimal += 2.0.pow(binary.count - i - 1)
}
}
return decimal
}
// You will be given a string in binary format and your task is to convert it to hexadecimal format.
// The function should return a string.
// Examples:
// binaryToHexadecimal(binary: "110111011011100000101010") == "3AE8D28"
// binaryToHexadecimal(binary: "11111111111111111111111111111101") == "FFFFFFFFFFFFFFF"
func binaryToHexadecimal(binary: String) -> String {
// Write your code here
var hexadecimal = ""
for i in stride(from: binary.count - 1, through: 0, by: -4) {
let start = i - 3 < 0? 0 : i - 3
let end = i + 1
let part = binary[start...end]
hexadecimal = hexDictionary[part]! + hexadecimal
}
return hexadecimal
}
// You will be given a string in hexadecimal format and your task is to convert it to binary format.
// The function should return a string.
// Examples:
// hexadecimalToBinary(hexadecimal: "3AE8D28") == "110111011011100000101010"
// hexadecimalToBinary(hexadecimal: "FFFFFFFFFFFFFFF") == "11111111111111111111111111111101"
func hexadecimalToBinary(hexadecimal: String) -> String {
// Write your code here
var binary = ""
for i in 0..<hexadecimal.count {
binary += hexDictionary[String(hexadecimal[i])]!
}
return binary
}
// You will be given a string in hexadecimal format and your task is to convert it to decimal format.
// The function should return an integer.
// Examples:
// hexadecimalToDecimal(hexadecimal: "3AE8D28") == 1347483652
// hexadecimalToDecimal(hexadecimal: "FFFFFFFFFFFFFFF") == 9223372036854775807
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// Write your code here
var decimal = 0
for i in 0..<hexadecimal.count {
decimal += Int(String(hexadecimal[i]))! * 16.0.pow(hexadecimal.count - i - 1)
}
return decimal
}
// You will be given a decimal number and your task is to convert it to octal format.
// The function should return a string.
// Examples:
// decimalToOctal(decimal: 15) == "17"
// decimalToOctal(decimal: 32) == "34"
func decimalToOctal(decimal: Int) -> String {
// Write your code here
var octal = ""
if decimal == 0 {
octal = "0"
}
while decimal > 0 {
octal = String(decimal % 8) + octal
decimal /= 8
}
return octal
}
// You will be given a string in octal format and your task is to convert it to decimal format.
// The function should return an integer.
// Examples:
// octalToDecimal(octal: "17") == 15
// octalTo
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
if binary[i] == "1" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
decimal += 2.0.pow(binary.count - i - 1) // value of type 'Double' has no member 'pow'
let start = i - 3 < 0? 0 : i - 3 // consecutive statements on a line must be separated by ';'
let start = i - 3 < 0? 0 : i - 3 // consecutive statements on a line must be separated by ';'
let start = i - 3 < 0? 0 : i - 3 // expected expression
let start = i - 3 < 0? 0 : i - 3 // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
let start = i - 3 < 0? 0 : i - 3 // cannot use optional chaining on non-optional value of type 'Int'
let start = i - 3 < 0? 0 : i - 3 // integer literal is unused
hexadecimal = hexDictionary[part]! + hexadecimal // cannot find 'hexDictionary' in scope
binary += hexDictionary[String(hexadecimal[i])]! // cannot find 'hexDictionary' in scope
decimal += Int(String(hexadecimal[i]))! * 16.0.pow(hexadecimal.count - i - 1) // value of type 'Double' has no member 'pow'
decimal /= 8 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = "\(decimal % 2)" + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = "\(decimal % 2)" + binary
decimal /= 2
}
return "db" + binary + "db"
}
// Tests
print(decimalToBinary(decimal: 15))
print(decimalToBinary(decimal: 32))
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
// Write your code here
var binary = ""
if decimal == 0 {
binary = "0"
}
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
// Write your code here
var binary = ""
if decimal == 0 {
binary = "0"
}
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
// Tests
print(decimalToBinary(decimal: 15))
print(decimalToBinary(decimal: 32))
```
decimal /= 2 // left side of mutating operator isn't mutable: 'decimal' is a 'let' constant
func decimalToBinary(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
```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 {
// TODO: Write - Your - Code
return ""
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
// binaryToDecimal(binary: "db11011db") == 13
// binaryToDecimal(binary: "db1010000db") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a string of binary numbers. The string can have extra characters, but
// the characters will always be '0' or '1'. The function should return an integer.
// The string will always start with "db" and end with "db".
// Examples:
//
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
func hexadecimalToBinary(hexadecimal: String) -> String {
// TODO: Write - Your - Code
return ""
}
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
func decimalToHexadecimal(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
```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 {
// TODO: Write - Your - Code
return ""
}
// You will be given a number in binary form and your task is to convert it to
// decimal format. The function should return an integer.
// Examples:
// binaryToDecimal(binary: "1111") == 15
// binaryToDecimal(binary: "100000") == 32
func binaryToDecimal(binary: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a number in binary form and your task is to convert it to
// hexadecimal format. The function should return a string, with each character representing a
// hexadecimal number. Each character in the string will be a letter from the set ['A', 'B', 'C',
// 'D', 'E', 'F'].
// There will be an extra couple of characters 'hd' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// binaryToHexadecimal(binary: "11011101") == "hd1Ddb"
// binaryToHexadecimal(binary: "11111111111111111111111111111101") == "hdFFFFFFFFdb"
func binaryToHexadecimal(binary: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a number in hexadecimal 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:
// hexadecimalToBinary(hexadecimal: "FF") == "db111111db"
// hexadecimalToBinary(hexadecimal: "FFFFFFFF") == "db1111111111111111111111111111111db"
func hexadecimalToBinary(hexadecimal: String) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a number in hexadecimal form and your task is to convert it to
// decimal format. The function should return an integer.
// Examples:
// hexadecimalToDecimal(hexadecimal: "FF") == 255
// hexadecimalToDecimal(hexadecimal: "FFFFFFFF") == 4294967295
func hexadecimalToDecimal(hexadecimal: String) -> Int {
// TODO: Write - Your - Code
return 0
}
// You will be given a number in decimal form and your task is to convert it to
// hexadecimal format. The function should return a string, with each character representing a
// hexadecimal number. Each character in the string will be a letter from the set ['A', 'B', 'C',
// 'D', 'E', 'F'].
// There will be an extra couple of characters 'hd' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToHexadecimal(decimal: 15) == "hd0Fdb"
// decimalToHexadecimal(decimal: 4294967295) == "hdFFFFFFFFdb"
func decimalToHexadecimal(decimal: Int) -> String {
// TODO: Write - Your - Code
return ""
}
// You will be given a number in binary form and your task is to convert it to
// octal format. The function should return a string, with each character representing an octal
// number. Each character in the string will be a digit from the set ['0', '1', '2', '3', '4', '5',
// '6', '7'].
// There will be an extra couple of characters 'od' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// binaryToOctal(binary: "11111111") == "od177db"
// binaryToOctal(binary: "11111111111111111111111111111111") == "od37
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
// Convert decimal to binary
let binary = String(decimal, radix: 2)
// Add the 'db' at the beginning and end of the string
return "db" + String(binary.dropFirst()) + "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 {
// Convert decimal to binary
let binary = String(decimal, radix: 2)
// Add the 'db' at the beginning and end of the string
return "db" + String(binary.dropFirst()) + "db"
}
// Test cases
print(decimalToBinary(decimal: 15)) // db1111db
print(decimalToBinary(decimal: 32)) // db100000db
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var seen = Set<Character>()
var slow = s
var fast = s
repeat {
slow = next(s: slow)
fast = next(s: next(s: fast))
if seen.contains(slow.first!) {
return false
}
seen.insert(slow.first!)
} while slow!= fast
return true
}
func next(s: String) -> String {
var next = ""
for i in stride(from: 1, to: s.count, by: 2) {
next.append(s[i])
}
return next
}
```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 seen = Set<Character>()
var slow = s
var fast = s
repeat {
slow = next(s: slow)
fast = next(s: next(s: fast))
if seen.contains(slow.first!) {
return false
}
seen.insert(slow.first!)
} while slow!= fast
return true
}
func next(s: String) -> String {
var next = ""
for i in stride(from: 1, to: s.count, by: 2) {
next.append(s[i])
}
return next
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
} while slow!= fast // cannot force unwrap value of non-optional type 'String'
} while slow!= fast // '=' must have consistent whitespace on both sides
} while slow!= fast // use of '=' in a boolean context, did you mean '=='?
next.append(s[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
var seen = Set<Character>()
var slow = s
var fast = s
repeat {
slow = next(s: slow)
fast = next(s: next(s: fast))
print(slow)
print(fast)
} while slow!= fast &&!seen.contains(slow)
return slow == fast
}
func next(s: String) -> String {
var next = ""
for i in stride(from: 1, to: s.count, by: 3) {
next.append(s[i])
}
return next
}
```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 seen = Set<Character>()
var slow = s
var fast = s
repeat {
slow = next(s: slow)
fast = next(s: next(s: fast))
print(slow)
print(fast)
} while slow!= fast &&!seen.contains(slow)
return slow == fast
}
func next(s: String) -> String {
var next = ""
for i in stride(from: 1, to: s.count, by: 3) {
next.append(s[i])
}
return next
}
print(isHappy(s: "a"))
print(isHappy(s: "aa"))
print(isHappy(s: "abcd"))
print(isHappy(s: "aabb"))
print(isHappy(s: "adb"))
print(isHappy(s: "xyy"))
print(isHappy(s: "xxy"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(s: "xaxxx"))
print(isHappy(
} while slow!= fast &&!seen.contains(slow) // use of '=' in a boolean context, did you mean '=='?
} while slow!= fast &&!seen.contains(slow) // cannot force unwrap value of non-optional type 'String'
} while slow!= fast &&!seen.contains(slow) // consecutive statements on a line must be separated by ';'
} while slow!= fast &&!seen.contains(slow) // '=' must have consistent whitespace on both sides
} while slow!= fast &&!seen.contains(slow) // cannot find operator '&&!' in scope
next.append(s[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
var slow = 0
var fast = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast > 9 {
fast = Int(String(fast))!
}
if fast == 10 {
fast = 1
}
}
while slow!= fast {
slow = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast > 9 {
fast = Int(String(fast))!
}
if fast == 10 {
fast = 1
}
}
}
return slow == 1
}
```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 slow = 0
var fast = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast > 9 {
fast = Int(String(fast))!
}
if fast == 10 {
fast = 1
}
}
while slow!= fast {
slow = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast > 9 {
fast = Int(String(fast))!
}
if fast == 10 {
fast = 1
}
}
}
return slow == 1
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
while slow!= fast { // cannot force unwrap value of non-optional type 'Int'
while slow!= fast { // use of '=' in a boolean context, did you mean '=='?
while slow!= fast { // '=' must have consistent whitespace on both sides
func isHappy(s: String) -> Bool {
var seen = Set<Character>()
var slow = 0
var fast = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast >= 10 {
fast -= 10
}
if fast == 0 {
return false
}
if seen.contains(Character(String(fast))) {
return false
}
seen.insert(Character(String(fast)))
if fast == slow {
break
}
slow = 0
fast = 0
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var seen = Set<Character>()
var slow = 0
var fast = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast >= 10 {
fast -= 10
}
if fast == 0 {
return false
}
if seen.contains(Character(String(fast))) {
return false
}
seen.insert(Character(String(fast)))
if fast == slow {
break
}
slow = 0
fast = 0
}
return true
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for i in stride(from: 0, to: s.count, by: 3) {
if set.contains(s[i]) {
return false
}
set.insert(s[i])
if i + 1 < s.count && set.contains(s[i + 1]) {
return false
}
set.insert(s[i + 1])
if i + 2 < s.count && set.contains(s[i + 2]) {
return false
}
set.insert(s[i + 2])
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for i in stride(from: 0, to: s.count, by: 3) {
if set.contains(s[i]) {
return false
}
set.insert(s[i])
if i + 1 < s.count && set.contains(s[i + 1]) {
return false
}
set.insert(s[i + 1])
if i + 2 < s.count && set.contains(s[i + 2]) {
return false
}
set.insert(s[i + 2])
}
return true
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
if set.contains(s[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i + 1 < s.count && set.contains(s[i + 1]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i + 1]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i + 2 < s.count && set.contains(s[i + 2]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i + 2]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
var slow = 0
var fast = 0
var slowSet = Set<Int>()
var fastSet = Set<Int>()
while slowSet.insert(slow).insert(fast).insert(fast).count == 3 {
slow = 0
fast = 0
for i in 0..<s.count {
slow += Int(String(s[s.index(s.startIndex, offsetBy: i)]))! * Int(String(s[s.index(s.startIndex, offsetBy: i)]))!
fast += Int(String(s[s.index(s.startIndex, offsetBy: i)]))! * Int(String(s[s.index(s.startIndex, offsetBy: i + 1)]))!
fast += Int(String(s[s.index(s.startIndex, offsetBy: i + 1)]))! * Int(String(s[s.index(s.startIndex, offsetBy: i + 2)]))!
}
}
return slow == fast
}
```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 slow = 0
var fast = 0
var slowSet = Set<Int>()
var fastSet = Set<Int>()
while slowSet.insert(slow).insert(fast).insert(fast).count == 3 {
slow = 0
fast = 0
for i in 0..<s.count {
slow += Int(String(s[s.index(s.startIndex, offsetBy: i)]))! * Int(String(s[s.index(s.startIndex, offsetBy: i)]))!
fast += Int(String(s[s.index(s.startIndex, offsetBy: i)]))! * Int(String(s[s.index(s.startIndex, offsetBy: i + 1)]))!
fast += Int(String(s[s.index(s.startIndex, offsetBy: i + 1)]))! * Int(String(s[s.index(s.startIndex, offsetBy: i + 2)]))!
}
}
return slow == fast
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
while slowSet.insert(slow).insert(fast).insert(fast).count == 3 { // value of tuple type '(inserted: Bool, memberAfterInsert: Int)' has no member 'insert'
func isHappy(s: String) -> Bool {
var set = Set<Character>()
var count = 0
var str = s
while count < str.count {
if set.contains(str[str.index(str.startIndex, offsetBy: count)]) {
return false
} else {
set.insert(str[str.index(str.startIndex, offsetBy: count)])
}
count += 3
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var set = Set<Character>()
var count = 0
var str = s
while count < str.count {
if set.contains(str[str.index(str.startIndex, offsetBy: count)]) {
return false
} else {
set.insert(str[str.index(str.startIndex, offsetBy: count)])
}
count += 3
}
return true
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
var str = s // variable 'str' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var slow = s.first
var fast = s.first
repeat {
slow = next(slow)
fast = next(next(fast))
print(slow)
print(fast)
} while slow!= fast
return slow == nil
}
func next(_ c: Character?) -> Character? {
guard let c = c else { return nil }
var sum = 0
var c = c
repeat {
let v = Int(String(c))!
sum += v * v
c = String(c).next()!
} while c!= "-"
return Character(UnicodeScalar(sum)!)
}
```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 slow = s.first
var fast = s.first
repeat {
slow = next(slow)
fast = next(next(fast))
print(slow)
print(fast)
} while slow!= fast
return slow == nil
}
func next(_ c: Character?) -> Character? {
guard let c = c else { return nil }
var sum = 0
var c = c
repeat {
let v = Int(String(c))!
sum += v * v
c = String(c).next()!
} while c!= "-"
return Character(UnicodeScalar(sum)!)
}
isHappy(s: "a")
isHappy(s: "aa")
isHappy(s: "abcd")
isHappy(s: "aabb")
isHappy(s: "adb")
isHappy(s: "xyy")
isHappy(s: "abac")
isHappy(s: "abad")
isHappy(s: "abae")
isHappy(s: "abaf")
isHappy(s: "abag")
isHappy(s: "abah")
isHappy(s: "abai")
isHappy(s: "abaj")
isHappy(s: "abak")
isHappy(s: "abal")
isHappy(s: "abam")
isHappy(s: "aban")
isHappy(s: "abap")
isHappy(s: "abar")
isHappy(s: "abas")
isHappy(s: "abab")
isHappy(s: "abbab")
isHappy(s: "abbey")
isHappy(s: "abbot")
isHappy(s: "abets")
isHappy(s: "abhor")
isHappy(s: "abide")
isHappy(s: "abies")
isHappy(s: "abler")
isHappy(s: "ablest")
isHappy(s: "abode")
isHappy(s: "abram")
isHappy(s: "abort")
isHappy(s: "abuts")
isHappy(s: "abused")
isHappy(s: "abuser")
isHappy(s: "abuses")
isHappy(s: "acres")
isHappy(s: "acrid")
isHappy(s: "acrids")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy(s: "acridy")
isHappy(s: "acridz")
isHappy(s: "acridnes")
isHappy
print(slow) // expression implicitly coerced from 'String.Element?' (aka 'Optional<Character>') to 'Any'
print(fast) // expression implicitly coerced from 'String.Element?' (aka 'Optional<Character>') to 'Any'
} while slow!= fast // '=' must have consistent whitespace on both sides
} while slow!= fast // use of '=' in a boolean context, did you mean '=='?
} while slow!= fast // value of optional type 'String.Element?' (aka 'Optional<Character>') must be unwrapped to a value of type 'String.Element' (aka 'Character')
var c = c // invalid redeclaration of 'c'
sum += v * v // cannot convert value of type 'Duration' to expected argument type 'Int'
c = String(c).next()! // reference to member 'next' cannot be resolved without a contextual type
} while c!= "-" // '=' must have consistent whitespace on both sides
} while c!= "-" // use of '=' in a boolean context, did you mean '=='?
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for i in stride(from: 0, to: s.count, by: 3) {
if set.contains(s[i]) {
return false
}
set.insert(s[i])
if i + 1 < s.count, set.contains(s[i + 1]) {
return false
}
set.insert(s[i + 1])
if i + 2 < s.count, set.contains(s[i + 2]) {
return false
}
set.insert(s[i + 2])
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var set = Set<Character>()
for i in stride(from: 0, to: s.count, by: 3) {
if set.contains(s[i]) {
return false
}
set.insert(s[i])
if i + 1 < s.count, set.contains(s[i + 1]) {
return false
}
set.insert(s[i + 1])
if i + 2 < s.count, set.contains(s[i + 2]) {
return false
}
set.insert(s[i + 2])
}
return true
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
if set.contains(s[i]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i + 1 < s.count, set.contains(s[i + 1]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i + 1]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if i + 2 < s.count, set.contains(s[i + 2]) { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
set.insert(s[i + 2]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isHappy(s: String) -> Bool {
var seen = Set<Character>()
var slow = 0
var fast = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast >= 10 {
fast -= 10
}
if fast >= 10 {
fast -= 10
}
if seen.contains(Character(String(fast))) {
return false
}
seen.insert(Character(String(fast)))
}
return slow == fast
}
```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 seen = Set<Character>()
var slow = 0
var fast = 0
for char in s {
slow += Int(String(char))!
fast += Int(String(char))!
if fast >= 10 {
fast -= 10
}
if fast >= 10 {
fast -= 10
}
if seen.contains(Character(String(fast))) {
return false
}
seen.insert(Character(String(fast)))
}
return slow == fast
}
isHappy(s: "a") == false
isHappy(s: "aa") == false
isHappy(s: "abcd") == true
isHappy(s: "aabb") == false
isHappy(s: "adb") == true
isHappy(s: "xyy") == false
//: [Next](@next)
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
```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
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
// Test the function
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(letterGrades)
//: [Next](@next)
grades[index] = "A+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "F" // cannot assign value of type 'String' to subscript of type 'Double'
return grades // cannot convert return expression of type '[Double]' to return type '[String]'
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
```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
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(letterGrades)
// ["A+", "B", "C-", "C", "A-"]
//: [Next](@next)
grades[index] = "A+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "F" // cannot assign value of type 'String' to subscript of type 'Double'
return grades // cannot convert return expression of type '[Double]' to return type '[String]'
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
```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
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
print(numericalLetterGrade(grades: grades))
// ["A+", "B", "C-", "C", "A-"]
let grades2 = [3.8, 3.3, 2.7, 2.3, 1.8]
print(numericalLetterGrade(grades: grades2))
// ["C+", "C", "B-", "B", "F"]
let grades3 = [1.0, 1.0, 1.0, 1.0, 1.0]
print(numericalLetterGrade(grades: grades3))
// ["A", "A", "A", "A", "A"]
let grades4 = [0.0, 0.0, 0.0, 0.0, 0.0]
print(numericalLetterGrade(grades: grades4))
// ["F", "F", "F", "F", "F"]
let grades5 = [4.0, 3.0, 2.0, 1.0, 0.0]
print(numericalLetterGrade(grades: grades5))
// ["A+", "C", "D", "F", "F"]
let grades6 = [4.0, 3.0, 2.0, 1.0, 0.0, 0.0]
print(numericalLetterGrade(grades: grades6))
// ["A+", "C", "D", "F", "F", "F"]
let grades7 = [4.0, 3.0, 2.0, 1.0, 0.0, 0.0, 0.0]
print(numericalLetterGrade(grades: grades7))
// ["A+", "C", "D", "F", "F", "F", "F"]
let grades8 = [4.0, 3.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0]
print(numericalLetterGrade(grades: grades8))
// ["A+", "C", "D", "F", "F", "F", "F", "F"]
let grades9 = [4.0, 3.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]
print(numericalLetterGrade(grades: grades9))
// ["A+", "C", "D", "F", "F", "F", "F", "F", "F"]
let grades10 = [4.0, 3.0, 2.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
print(numericalLetterGrade(grades: gr
grades[index] = "A+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "F" // cannot assign value of type 'String' to subscript of type 'Double'
return grades // cannot convert return expression of type '[Double]' to return type '[String]'
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades = [String]()
for grade in grades {
if grade > 4.0 {
letterGrades.append("A+")
} else if grade > 3.7 {
letterGrades.append("A")
} else if grade > 3.3 {
letterGrades.append("A-")
} else if grade > 3.0 {
letterGrades.append("B+")
} else if grade > 2.7 {
letterGrades.append("B")
} else if grade > 2.3 {
letterGrades.append("B-")
} else if grade > 2.0 {
letterGrades.append("C+")
} else if grade > 1.7 {
letterGrades.append("C")
} else if grade > 1.3 {
letterGrades.append("C-")
} else if grade > 1.0 {
letterGrades.append("D+")
} else if grade > 0.7 {
letterGrades.append("D")
} else if grade > 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("F")
}
}
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("F")
}
}
return letterGrades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(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("F")
}
}
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("F")
}
}
return letterGrades
}
// Test the function
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(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("F")
}
}
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("F")
}
}
return letterGrades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(letterGrades)
//: [Next](@next)
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var grades = grades
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
```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
for (index, grade) in grades.enumerated() {
if grade >= 4.0 {
grades[index] = "A+"
} else if grade >= 3.7 {
grades[index] = "A"
} else if grade >= 3.3 {
grades[index] = "A-"
} else if grade >= 3.0 {
grades[index] = "B+"
} else if grade >= 2.7 {
grades[index] = "B"
} else if grade >= 2.3 {
grades[index] = "B-"
} else if grade >= 2.0 {
grades[index] = "C+"
} else if grade >= 1.7 {
grades[index] = "C"
} else if grade >= 1.3 {
grades[index] = "C-"
} else if grade >= 1.0 {
grades[index] = "D+"
} else if grade >= 0.7 {
grades[index] = "D"
} else if grade >= 0.0 {
grades[index] = "D-"
} else {
grades[index] = "F"
}
}
return grades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(letterGrades)
```
grades[index] = "A+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "A-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "B-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "C-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D+" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "D-" // cannot assign value of type 'String' to subscript of type 'Double'
grades[index] = "F" // cannot assign value of type 'String' to subscript of type 'Double'
return grades // cannot convert return expression of type '[Double]' to return type '[String]'
func numericalLetterGrade(grades: [Double]) -> [String] {
var letterGrades: [String] = []
for grade in grades {
if grade >= 4.0 {
letterGrades.append("A+")
} else if grade >= 3.7 {
letterGrades.append("A")
} else if grade >= 3.3 {
letterGrades.append("A-")
} else if grade >= 3.0 {
letterGrades.append("B+")
} else if grade >= 2.7 {
letterGrades.append("B")
} else if grade >= 2.3 {
letterGrades.append("B-")
} else if grade >= 2.0 {
letterGrades.append("C+")
} else if grade >= 1.7 {
letterGrades.append("C")
} else if grade >= 1.3 {
letterGrades.append("C-")
} else if grade >= 1.0 {
letterGrades.append("D+")
} else if grade >= 0.7 {
letterGrades.append("D")
} else if grade >= 0.0 {
letterGrades.append("D-")
} else {
letterGrades.append("F")
}
}
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("F")
}
}
return letterGrades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(letterGrades)
// ["A+", "B", "C-", "C", "A-"]
//: [Next](@next)
// 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("F")
}
}
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("F")
}
}
return letterGrades
}
let grades = [4.0, 3, 1.7, 2, 3.5]
let letterGrades = numericalLetterGrade(grades: grades)
print(letterGrades)
// ["A+", "B", "C-", "C", "A-"]
//: [Next](@next)
// 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("F")
}
}
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:
// numericalLetterGra