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 {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = sorted.count - 1
while left < right {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if diff < threshold {
return true
}
left += 1
right -= 1
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:双指针
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = sorted.count - 1
while left < right {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if diff < threshold {
return true
}
left += 1
right -= 1
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
for i in 1..<numbers.count {
if abs(sorted[i] - sorted[i - 1]) < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
var left = 0
var right = numbers.count - 1
while left < right {
if abs(sorted[left] - sorted[left + 1]) < threshold {
return true
}
left += 1
if abs(sorted[right] - sorted[right - 1]) < threshold {
return true
}
right -= 1
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
for i in 1..<numbers.count {
if abs(sorted[i] - sorted[i - 1]) < 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 {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
var left = 0
var right = numbers.count - 1
while left < right {
if abs(sorted[left] - sorted[left + 1]) < threshold {
return true
}
left += 1
if abs(sorted[right] - sorted[right - 1]) < threshold {
return true
}
right -= 1
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers
sorted.sort()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers
sorted.sort()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1)
if index != -1 && abs(sorted[index] - sorted[i]) < threshold {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int) -> Int {
var left = left
var right = numbers.count - 1
while left <= right {
let mid = left + (right - left) / 2
if numbers[mid] > target {
right = mid - 1
} else {
left = mid + 1
}
}
return left
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers
sorted.sort()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if right == sorted.count - 1 {
left += 1
right = left + 1
} else {
right += 1
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers
sorted.sort()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:二分查找
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers
sorted.sort()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1)
if index != -1 && abs(sorted[index] - sorted[i]) < threshold {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int) -> Int {
var left = left
var right = numbers.count - 1
while left <= right {
let mid = left + (right - left) / 2
if numbers[mid] > target {
right = mid - 1
} else {
left = mid + 1
}
}
return left
}
```
### 解法三:双指针
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
var sorted = numbers
sorted.sort()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if right == sorted.count - 1 {
left += 1
right = left + 1
} else {
right += 1
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
let index = binarySearch(sorted, target: sorted[i], left: i + 1) // missing argument label 'numbers:' in call
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1)
if index != nil && diff < abs(sorted[index!] - sorted[i + 1]) {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int) -> Int? {
var left = left
var right = numbers.count - 1
while left <= right {
let mid = (left + right) / 2
if numbers[mid] == target {
return mid
} else if numbers[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return nil
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if diff < abs(sorted[left] - sorted[left + 1]) {
left += 1
}
right += 1
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:二分查找
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1)
if index != nil && diff < abs(sorted[index!] - sorted[i + 1]) {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int) -> Int? {
var left = left
var right = numbers.count - 1
while left <= right {
let mid = (left + right) / 2
if numbers[mid] == target {
return mid
} else if numbers[mid] < target {
left = mid + 1
} else {
right = mid - 1
}
}
return nil
}
```
### 解法三:双指针
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if diff < abs(sorted[left] - sorted[left + 1]) {
left += 1
}
right += 1
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
let index = binarySearch(sorted, target: sorted[i], left: i + 1) // missing argument label 'numbers:' in call
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if diff > threshold {
left += 1
right = left + 1
} else {
right += 1
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1)
if index != -1 && abs(sorted[index] - sorted[i + 1]) < threshold {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int) -> Int {
var left = left
var right = numbers.count - 1
while left <= right {
let mid = (left + right) / 2
if numbers[mid] > target {
right = mid - 1
} else if numbers[mid] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:双指针
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if diff > threshold {
left += 1
right = left + 1
} else {
right += 1
}
}
return false
}
```
### 解法三:二分查找
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1)
if index != -1 && abs(sorted[index] - sorted[i + 1]) < threshold {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int) -> Int {
var left = left
var right = numbers.count - 1
while left <= right {
let mid = (left + right) / 2
if numbers[mid] > target {
right = mid - 1
} else if numbers[mid] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
let index = binarySearch(sorted, target: sorted[i], left: i + 1) // missing argument label 'numbers:' in call
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i] + threshold)
if index != -1 && abs(sorted[i] - sorted[index]) < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i] - threshold)
if index != -1 && abs(sorted[i] - sorted[index]) < threshold {
return true
}
}
return false
}
func binarySearch(_ nums: [Double], target: Double) -> Int {
var left = 0
var right = nums.count - 1
while left < right {
let mid = (left + right) / 2
if nums[mid] < target {
left = mid + 1
} else {
right = mid
}
}
return left
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:二分查找
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i] + threshold)
if index != -1 && abs(sorted[i] - sorted[index]) < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i] - threshold)
if index != -1 && abs(sorted[i] - sorted[index]) < threshold {
return true
}
}
return false
}
func binarySearch(_ nums: [Double], target: Double) -> Int {
var left = 0
var right = nums.count - 1
while left < right {
let mid = (left + right) / 2
if nums[mid] < target {
left = mid + 1
} else {
right = mid
}
}
return left
}
```
### 解法三:滑动窗口
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i] + threshold)
if index != -1 && abs(sorted[i] - sorted[index]) < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i] - threshold)
if index != -1 && abs(sorted[i] - sorted[index]) < threshold {
return true
}
}
return false
}
func binarySearch(_ nums: [Double], target: Double) -> Int {
var left = 0
var right = nums.count - 1
while left < right {
let mid = (left + right) / 2
if nums[mid] < target {
left = mid + 1
} else {
right = mid
}
}
return left
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
let index = binarySearch(sorted, target: sorted[i] - threshold) // invalid redeclaration of 'index'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let left = binarySearch(sorted, target: sorted[i], left: 0, right: i)
let right = binarySearch(sorted, target: sorted[i + 1], left: i + 1, right: sorted.count - 1)
if left != nil && right != nil {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int, right: Int) -> Double? {
if left > right {
return nil
}
let mid = (left + right) / 2
if numbers[mid] > target {
return binarySearch(numbers, target: target, left: left, right: mid - 1)
} else if numbers[mid] < target {
return binarySearch(numbers, target: target, left: mid + 1, right: right)
} else {
return numbers[mid]
}
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if left == right {
right += 1
} else {
left += 1
right += 1
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:二分查找
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let left = binarySearch(sorted, target: sorted[i], left: 0, right: i)
let right = binarySearch(sorted, target: sorted[i + 1], left: i + 1, right: sorted.count - 1)
if left != nil && right != nil {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int, right: Int) -> Double? {
if left > right {
return nil
}
let mid = (left + right) / 2
if numbers[mid] > target {
return binarySearch(numbers, target: target, left: left, right: mid - 1)
} else if numbers[mid] < target {
return binarySearch(numbers, target: target, left: mid + 1, right: right)
} else {
return numbers[mid]
}
}
```
### 解法三:双指针
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if left == right {
right += 1
} else {
left += 1
right += 1
}
}
return false
}
```
### 解法四:滑动窗口
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
var left = 0
var right = 1
while right < sorted.count {
let diff = abs(sorted[left] - sorted[right])
if diff < threshold {
return true
}
if left == right {
right += 1
} else {
left += 1
right += 1
}
}
return false
}
```
### 解法五:桶
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
let left = binarySearch(sorted, target: sorted[i], left: 0, right: i) // missing argument label 'numbers:' in call
let right = binarySearch(sorted, target: sorted[i + 1], left: i + 1, right: sorted.count - 1) // missing argument label 'numbers:' in call
return binarySearch(numbers, target: target, left: left, right: mid - 1) // missing argument label 'numbers:' in call
return binarySearch(numbers, target: target, left: mid + 1, right: right) // missing argument label 'numbers:' in call
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1, right: sorted.count - 1)
if index != -1 && diff < abs(sorted[i] - sorted[index]) {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int, right: Int) -> Int {
var left = left
var right = right
while left <= right {
let mid = left + (right - left) / 2
if numbers[mid] > target {
right = mid - 1
} else if numbers[mid] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let buckets = [Int](repeating: 0, count: 100)
for number in numbers {
let bucket = Int(number * 100)
buckets[bucket] += 1
}
for i in 0..<buckets.count - 1 {
let diff = abs(Double(i) / 100 - Double(i + 1) / 100)
if diff < threshold {
return true
}
if buckets[i] > 0 {
let count = buckets[i]
for j in 0..<count {
let index = binarySearch(buckets, target: Double(i) / 100, left: 0, right: buckets.count - 1)
if index != -1 && diff < abs(Double(i) / 100 - Double(index) / 100) {
return true
}
}
}
}
return false
}
func binarySearch(buckets: [Int], target: Double, left: Int, right: Int) -> Int {
var left = left
var right = right
while left <= right {
let mid = left + (right - left) / 2
if buckets[mid] > target {
right = mid - 1
} else if buckets[mid] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
### 解法二:二分查找
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let sorted = numbers.sorted()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
let index = binarySearch(sorted, target: sorted[i], left: i + 1, right: sorted.count - 1)
if index != -1 && diff < abs(sorted[i] - sorted[index]) {
return true
}
}
return false
}
func binarySearch(numbers: [Double], target: Double, left: Int, right: Int) -> Int {
var left = left
var right = right
while left <= right {
let mid = left + (right - left) / 2
if numbers[mid] > target {
right = mid - 1
} else if numbers[mid] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
```
### 解法三:桶排序
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
let buckets = [Int](repeating: 0, count: 100)
for number in numbers {
let bucket = Int(number * 100)
buckets[bucket] += 1
}
for i in 0..<buckets.count - 1 {
let diff = abs(Double(i) / 100 - Double(i + 1) / 100)
if diff < threshold {
return true
}
if buckets[i] > 0 {
let count = buckets[i]
for j in 0..<count {
let index = binarySearch(buckets, target: Double(i) / 100, left: 0, right: buckets.count - 1)
if index != -1 && diff < abs(Double(i) / 100 - Double(index) / 100) {
return true
}
}
}
}
return false
}
func binarySearch(buckets: [Int], target: Double, left: Int, right: Int) -> Int {
var left = left
var right = right
while left <= right {
let mid = left + (right - left) / 2
if buckets[mid] > target {
right = mid - 1
} else if buckets[mid] < target {
left = mid + 1
} else {
return mid
}
}
return -1
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
let index = binarySearch(sorted, target: sorted[i], left: i + 1, right: sorted.count - 1) // missing argument label 'numbers:' in call
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool { // invalid redeclaration of 'hasCloseElements(numbers:threshold:)'
buckets[bucket] += 1 // left side of mutating operator isn't mutable: 'buckets' is a 'let' constant
let index = binarySearch(buckets, target: Double(i) / 100, left: 0, right: buckets.count - 1) // missing argument label 'buckets:' in call
if buckets[mid] > target { // binary operator '>' cannot be applied to operands of type 'Int' and 'Double'
} else if buckets[mid] < target { // binary operator '<' cannot be applied to operands of type 'Int' and 'Double'
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
for i in 1..<numbers.count {
let diff = abs(sorted[i] - sorted[i - 1])
if diff < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
for i in 1..<numbers.count {
let diff = abs(sorted[i] - sorted[i - 1])
if diff < threshold {
return true
}
}
return false
}
```
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```swift
// Check if in given array of numbers, are any two numbers closer to each other than
// given threshold.
// hasCloseElements(numbers: [1.0, 2.0, 3.0], threshold: 0.5) == false
// hasCloseElements(numbers: [1.0, 2.8, 3.0, 4.0, 5.0, 2.0], threshold: 0.3) == true
func hasCloseElements(numbers: [Double], threshold: Double) -> Bool {
guard numbers.count > 1 else {
return false
}
var sorted = numbers
sorted.sort()
for i in 0..<sorted.count - 1 {
let diff = abs(sorted[i] - sorted[i + 1])
if diff < threshold {
return true
}
}
return false
}
```
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append("(")
} else if char == ")" {
if let last = stack.popLast() {
if last == "(" {
result.append(current)
current = ""
} else {
current += last
}
}
} else {
current += char
}
}
result.append(current)
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append("(")
} else if char == ")" {
if let last = stack.popLast() {
if last == "(" {
result.append(current)
current = ""
} else {
current += last
}
}
} else {
current += char
}
}
result.append(current)
return result
}
```
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append("(")
current += char
} else if char == ")" {
if stack.count > 0 {
stack.removeLast()
current += char
} else {
result.append(current)
current = ""
}
} else {
current += char
}
}
if current != "" {
result.append(current)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append("(")
current += char
} else if char == ")" {
if stack.count > 0 {
stack.removeLast()
current += char
} else {
result.append(current)
current = ""
}
} else {
current += char
}
}
if current != "" {
result.append(current)
}
return result
}
```
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append("(")
current += char
} else if char == ")" {
if stack.count == 0 {
result.append(current)
current = ""
} else {
stack.removeLast()
current += char
}
} else {
current += char
}
}
if current != "" {
result.append(current)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append("(")
current += char
} else if char == ")" {
if stack.count == 0 {
result.append(current)
current = ""
} else {
stack.removeLast()
current += char
}
} else {
current += char
}
}
if current != "" {
result.append(current)
}
return result
}
```
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [String]()
var current = ""
var level = 0
for char in parenString {
if char == "(" {
level += 1
current += char
} else if char == ")" {
level -= 1
current += char
if level == 0 {
result.append(current)
current = ""
}
} else {
current += char
}
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [String]()
var current = ""
var level = 0
for char in parenString {
if char == "(" {
level += 1
current += char
} else if char == ")" {
level -= 1
current += char
if level == 0 {
result.append(current)
current = ""
}
} else {
current += char
}
}
return result
}
```
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
if current.isEmpty {
current = stack.removeLast()
} else {
current += ")"
}
} else {
current += char
}
}
if !current.isEmpty {
stack.append(current)
}
while !stack.isEmpty {
result.append(stack.removeLast())
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
if current.isEmpty {
current = stack.removeLast()
} else {
current += ")"
}
} else {
current += char
}
}
if !current.isEmpty {
stack.append(current)
}
while !stack.isEmpty {
result.append(stack.removeLast())
}
return result
}
```
current += char // cannot convert value of type 'Character' to expected argument type 'String'
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
for item in stack {
result.append(item)
}
result.append(current)
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
for item in stack {
result.append(item)
}
result.append(current)
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
for str in stack {
result.append(str)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
for str in stack {
result.append(str)
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String.Element]()
for char in parenString {
if char == "(" {
stack.append(char)
} else if char == ")" {
while !stack.isEmpty && stack.last != "(" {
current.append(stack.removeLast())
}
if !stack.isEmpty && stack.last == "(" {
stack.removeLast()
result.append(current)
current = ""
}
} else {
current.append(char)
}
}
while !stack.isEmpty {
current.append(stack.removeLast())
}
result.append(current)
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String.Element]()
for char in parenString {
if char == "(" {
stack.append(char)
} else if char == ")" {
while !stack.isEmpty && stack.last != "(" {
current.append(stack.removeLast())
}
if !stack.isEmpty && stack.last == "(" {
stack.removeLast()
result.append(current)
current = ""
}
} else {
current.append(char)
}
}
while !stack.isEmpty {
current.append(stack.removeLast())
}
result.append(current)
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
stack.append(current)
for s in stack {
result.append(s)
}
return result
}
```swift
// Input to this function is a string containing multiple groups of nested parentheses. Your goal is to
// separate those group into separate strings and return the array of those.
// Separate groups are balanced (each open brace is properly closed) and not nested within each other
// Ignore any spaces in the input string.
// separateParenGroups(parenString: "( ) (( )) (( )( ))") == ["()", "(())", "(()())"]
func separateParenGroups(parenString: String) -> [String] {
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
stack.append(current)
for s in stack {
result.append(s)
}
return result
}
```
// XCTAssertTrue failed
func separateParenGroups(parenString: String) -> [String] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
for str in stack {
result.append(str)
}
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] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [String]()
var current = ""
var stack = [String]()
for char in parenString {
if char == "(" {
stack.append(current)
current = ""
} else if char == ")" {
current = stack.removeLast() + current
} else {
current += String(char)
}
}
for str in stack {
result.append(str)
}
return result
}
```
// XCTAssertTrue failed
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Double) -> Double {
return Double(Int(number))
}
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
func truncateNumber(number: Double) -> Double {
return number.floor()
}
func truncateNumber(number: Double) -> Double {
return number.rounded(.down)
}
```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))
}
```
### 解法二
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
### 解法四
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.floor()
}
```
### 解法五
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.rounded(.down)
}
```
### 解法六
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.floor()
}
```
### 解法七
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
### 解法八
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
### 解法九
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
### 解法十
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return number.floor() // value of type 'Double' has no member 'floor'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer) + (number - Double(integer))
}
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer) + (number - Double(integer))
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func tr
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer) + (number - Double(integer))
}
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer) + (number - Double(integer))
}
```
### 解法二
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法三
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法四
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法五
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法六
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法七
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法八
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法九
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
return Double(integer)
}
```
### 解法十
```swift
// Given
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
let decimal = number - integer
return decimal
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
let decimal = number - integer
return decimal
}
```
let decimal = number - integer // binary operator '-' cannot be applied to operands of type 'Double' and 'Int'
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart
}
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
return Double(integerPart)
}
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.5 ? integerPart : integerPart + 1
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart
}
```
### 解法二:
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
return Double(integerPart)
}
```
### 解法三:
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.5 ? integerPart : integerPart + 1
}
```
### 解法四:
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.5 ? integerPart : integerPart + 1
}
```
### 解法五:
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.5 ? integerPart : integerPart + 1
}
```
### 解法六:
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.5 ? integerPart : integerPart + 1
}
```
### 解法七:
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.5 ? integerPart : integerPart + 1
}
```
### 解法八:
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart < 0.
let decimalPart = number - integerPart // binary operator '-' cannot be applied to operands of type 'Double' and 'Int'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
let decimalPart = number - integerPart // binary operator '-' cannot be applied to operands of type 'Double' and 'Int'
return decimalPart < 0.5 ? integerPart : integerPart + 1 // cannot convert return expression of type 'Int' to return type 'Double'
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let integerPart = Int(number)
let decimalPart = number - integerPart
return decimalPart
}
```
let decimalPart = number - integerPart // binary operator '-' cannot be applied to operands of type 'Double' and 'Int'
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
let decimal = number - integer
return decimal
}
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
let integer = Int(number)
let decimal = number - integer
return decimal
}
```
### 解法二
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法三
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法四
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法五
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法六
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法七
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法八
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法九
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Int {
let integer = Int(number)
return integer
}
```
### 解法十
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover
let decimal = number - integer // binary operator '-' cannot be applied to operands of type 'Double' and 'Int'
func truncateNumber(number: Double) -> Double {
return number - Double(Int(number))
}
func truncateNumber(number: Double) -> Double {
return Double(Int(number))
}
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
func truncateNumber(number: Double) -> Double {
return number.floor()
}
func truncateNumber(number: Double) -> Double {
return number.rounded(.down)
}
func truncateNumber(number: Double) -> Double {
return number.rounded(.toNearest(0))
}
func truncateNumber(number: Double) -> Double {
return number.rounded(.toNearest(1))
}
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the decimal part of the number.
// truncateNumber(number: 3.5) == 0.5
func truncateNumber(number: Double) -> Double {
return number - 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.truncatingRemainder(dividingBy: 1)
}
```
### 解法四
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.floor()
}
```
### 解法五
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.rounded(.down)
}
```
### 解法六
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.rounded(.toNearest(0))
}
```
### 解法七
```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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.rounded(.toNearest(1))
}
```
### 解法八
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.rounded(.toNearest(1))
}
```
### 解法九
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
// Return the integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return number.rounded(.toNearest(1))
}
```
### 解法十
```swift
// Given a positive floating point number, it can be decomposed into
// and integer part (largest integer smaller than given number) and decimals
// (leftover part always smaller than 1).
//
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return number.floor() // value of type 'Double' has no member 'floor'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return number.rounded(.toNearest(0)) // type 'FloatingPointRoundingRule' has no member 'toNearest'
func truncateNumber(number: Double) -> Double { // invalid redeclaration of 'truncateNumber(number:)'
return number.rounded(.toNearest(1)) // type 'FloatingPointRoundingRule' has no member 'toNearest'
func truncateNumber(number: Double) -> Double {
return 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 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) -> Double {
return 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 integer part of the number.
// truncateNumber(number: 3.5) == 3
func truncateNumber(number: Double) ->
// XCTAssertTrue failed
func truncateNumber(number: Double) -> Double {
return 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 Double(Int(number))
}
```
// XCTAssertTrue failed
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for operation in operations {
balance += operation
if balance < 0 {
return true
}
}
return false
}
```
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```swift
// You're given an array of deposit and withdrawal operations on a bank account that starts with
// zero balance. Your task is to detect if at any point the balance of account fallls below zero, and
// at that point function should return true. Otherwise it should return false.
// belowZero(operations: [1, 2, 3]) == false
// belowZero(operations: [1, 2, -4, 5]) == true
func belowZero(operations: [Int]) -> Bool {
var balance = 0
for op in operations {
balance += op
if balance < 0 {
return true
}
}
return false
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
class Solution {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
let total = nums1.count + nums2.count
let mid = total / 2
let nums = nums1 + nums2
nums.sort()
if total % 2 == 0 {
return Double(nums[mid - 1] + nums[mid]) / 2
} else {
return Double(nums[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, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 代码
```swift
class Solution {
func findMedianSortedArrays(_ nums1: [Int], _ nums2: [Int]) -> Double {
let total = nums1.count + nums2.count
let mid = total / 2
let nums = nums1 + nums2
nums.sort()
if total % 2 == 0 {
return Double(nums[mid - 1] + nums[mid]) / 2
} else {
return Double(nums[mid])
}
}
}
```
nums.sort() // cannot use mutating member on immutable value: 'nums' is a 'let' constant
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
class Solution {
func findMaxAverage(_ nums: [Int], _ k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += nums[i]
}
var maxSum = sum
for i in k..<nums.count {
sum = sum - nums[i-k] + nums[i]
maxSum = max(maxSum, sum)
}
return maxSum / k
}
}
```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.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 代码
```swift
class Solution {
func findMaxAverage(_ nums: [Int], _ k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += nums[i]
}
var maxSum = sum
for i in k..<nums.count {
sum = sum - nums[i-k] + nums[i]
maxSum = max(maxSum, sum)
}
return maxSum / k
}
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.map { abs(median - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let quantile = numbers.sorted()[numbers.count / 4]
return numbers.map { abs(quantile - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let quantile = numbers.sorted()[numbers.count / 8]
return numbers.map { abs(quantile - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let quantile = numbers.sorted()[numbers.count * 3 / 4]
return numbers.map { abs(quantile - $0) }.reduce(0, +) / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法二:中位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.map { abs(median - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法三:分位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the 0.5-quantile of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (0.5-quantile in this case):
// MAD = average | x - x_0.5-quantile |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let quantile = numbers.sorted()[numbers.count / 4]
return numbers.map { abs(quantile - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法四:分位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the 0.25-quantile of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (0.25-quantile in this case):
// MAD = average | x - x_0.25-quantile |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let quantile = numbers.sorted()[numbers.count / 8]
return numbers.map { abs(quantile - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法五:分位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the 0.75-quantile of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (0.75-quantile in this case):
// MAD = average | x - x_0.75-quantile |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let quantile = numbers.sorted()[numbers.count * 3 / 4]
return numbers.map { abs(quantile - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法六:分位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the 0.9-quantile of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (0.9-quantile in this case):
// MAD = average | x - x_0.9-quantile |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDev
func meanAbsoluteDeviation(numbers: [Double]) -> Double { // invalid redeclaration of 'meanAbsoluteDeviation(numbers:)'
func meanAbsoluteDeviation(numbers: [Double]) -> Double { // invalid redeclaration of 'meanAbsoluteDeviation(numbers:)'
func meanAbsoluteDeviation(numbers: [Double]) -> Double { // invalid redeclaration of 'meanAbsoluteDeviation(numbers:)'
func meanAbsoluteDeviation(numbers: [Double]) -> Double { // invalid redeclaration of 'meanAbsoluteDeviation(numbers:)'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法二
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法三
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法四
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法五
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法六
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法七
```swift
//
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 代码
```swift
class Solution {
func calculateMKAverage(_ m: Int, _ nums: [Int]) -> Int {
guard m > 0 else {
return 0
}
guard nums.count >= m else {
return -1
}
let n = nums.count
let k = m - 1
let max = nums.max()!
let min = nums.min()!
let range = max - min + 1
let total = (range + 1) * range / 2
let sum = nums.reduce(0, +)
let sumMinusMin = sum - min * n
let sumMinusMinPlusRange = sumMinusMin + range * (n - 1)
let sumMinusMinPlusRangeDivide = sumMinusMinPlusRange / n
let sumMinusMinPlusRangeDividePlusOne = sumMinusMinPlusRangeDivide + 1
let sumMinusMinPlusRangeDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOne = sumMinusMinPlusRangeDividePlusOneDivide + 1
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOne = sumMinusMinPlusRangeDividePlusOneDividePlusOneDivide + 1
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOne = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDivide + 1
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDivide + 1
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDivide + 1
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDivide = sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne / range
let sumMinusMinPlusRangeDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOneDividePlusOne = sumMinusMinPlusRangeDivide
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs( $0 - mean ) }.reduce(0, +) / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs( $0 - mean ) }.reduce(0, +) / Double(numbers.count)
}
```
### 代码
```swift
class Solution {
func calculateMKAverage(_ m: Int, _ nums: [Int]) -> Int {
guard m > 0 else {
return 0
}
guard nums.count > m else {
return -1
}
let n = nums.count
let k = m - 1
let total = nums.reduce(0, +)
let mean = total / Double(n)
let sum = nums.map { $0 - mean }.reduce(0, +)
let min = sum / Double(n - k)
let max = sum / Double(n - k + 1)
let minIndex = nums.map { $0 - min }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - max }.reduce(0, +) / Double(n - k + 1)
let minIndex = Int(minIndex.rounded(.down))
let maxIndex = Int(maxIndex.rounded(.up))
let minValue = nums[minIndex]
let maxValue = nums[maxIndex]
let minIndex = nums.map { $0 - minValue }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - maxValue }.reduce(0, +) / Double(n - k + 1)
let minIndex = Int(minIndex.rounded(.down))
let maxIndex = Int(maxIndex.rounded(.up))
let minValue = nums[minIndex]
let maxValue = nums[maxIndex]
let minIndex = nums.map { $0 - minValue }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - maxValue }.reduce(0, +) / Double(n - k + 1)
let minIndex = Int(minIndex.rounded(.down))
let maxIndex = Int(maxIndex.rounded(.up))
let minValue = nums[minIndex]
let maxValue = nums[maxIndex]
let minIndex = nums.map { $0 - minValue }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - maxValue }.reduce(0, +) / Double(n - k + 1)
let minIndex = Int(minIndex.rounded(.down))
let maxIndex = Int(maxIndex.rounded(.up))
let minValue = nums[minIndex]
let maxValue = nums[maxIndex]
let minIndex = nums.map { $0 - minValue }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - maxValue }.reduce(0, +) / Double(n - k + 1)
let minIndex = Int(minIndex.rounded(.down))
let maxIndex = Int(maxIndex.rounded(.up))
let minValue = nums[minIndex]
let maxValue = nums[maxIndex]
let minIndex = nums.map { $0 - minValue }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - maxValue }.reduce(0, +) / Double(n - k + 1)
let minIndex = Int(minIndex.rounded(.down))
let maxIndex = Int(maxIndex.rounded(.up))
let minValue = nums[minIndex]
let maxValue = nums[maxIndex]
let minIndex = nums.map { $0 - minValue }.reduce(0, +) / Double(n - k)
let maxIndex = nums.map { $0 - maxValue
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
class Solution {
func findMaxAverage(_ nums: [Int], _ k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += nums[i]
}
var maxSum = sum
for i in k..<nums.count {
sum = sum - nums[i - k] + nums[i]
maxSum = max(maxSum, sum)
}
return maxSum / k
}
}
```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.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 代码
```swift
class Solution {
func findMaxAverage(_ nums: [Int], _ k: Int) -> Int {
var sum = 0
for i in 0..<k {
sum += nums[i]
}
var maxSum = sum
for i in k..<nums.count {
sum = sum - nums[i - k] + nums[i]
maxSum = max(maxSum, sum)
}
return maxSum / k
}
}
```
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.map { abs(median - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let bucketSize = 10
let bucketCount = Int(ceil(Double(numbers.count) / Double(bucketSize)))
var buckets = [Int]()
for i in 0..<bucketCount {
buckets.append(0)
}
for number in numbers {
let bucketIndex = Int(floor(Double(number) / Double(bucketSize)))
buckets[bucketIndex] += 1
}
var sum = 0.0
for (index, bucket) in buckets.enumerated() {
let bucketStart = Double(index) * Double(bucketSize)
let bucketEnd = Double(index + 1) * Double(bucketSize)
let bucketMean = (bucketStart + bucketEnd) / 2
let bucketAbsoluteDifference = bucket.map { abs(bucketMean - Double($0)) }.reduce(0, +)
sum += Double(bucketAbsoluteDifference) * Double(bucket.count)
}
return sum / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法二:中位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.map { abs(median - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法三:分桶
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let bucketSize = 10
let bucketCount = Int(ceil(Double(numbers.count) / Double(bucketSize)))
var buckets = [Int]()
for i in 0..<bucketCount {
buckets.append(0)
}
for number in numbers {
let bucketIndex = Int(floor(Double(number) / Double(bucketSize)))
buckets[bucketIndex] += 1
}
var sum = 0.0
for (index, bucket) in buckets.enumerated() {
let bucketStart = Double(index) * Double(bucketSize)
let bucketEnd = Double(index + 1) * Double(bucketSize)
let bucketMean = (bucketStart + bucketEnd) / 2
let bucketAbsoluteDifference = bucket.map { abs(bucketMean - Double($0)) }.reduce(0, +)
sum += Double(bucketAbsoluteDifference) * Double(bucket.count)
}
return sum / Double(numbers.count)
}
```
### 解法四:分桶 + 滑动窗口
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let bucketSize = 10
let bucketCount = Int(ceil(Double(numbers.count) / Double(bucketSize)))
var buckets = [Int]()
for i in 0..<bucketCount {
buckets.append(0)
}
for number in numbers {
let bucketIndex = Int(floor(Double(number) / Double(bucketSize)))
buckets[bucketIndex] += 1
}
var sum = 0.0
var windowStart = 0
var windowEnd = 0
while windowEnd < numbers.count {
let bucketStart = Double(windowStart)
let bucketEnd = Double(windowEnd)
let bucketMean = (bucketStart + bucketEnd) / 2
let bucketAbsoluteDifference = buckets[windowStart].map { abs(bucketMean - Double($0)) }.reduce(0, +)
sum +=
func meanAbsoluteDeviation(numbers: [Double]) -> Double { // invalid redeclaration of 'meanAbsoluteDeviation(numbers:)'
func meanAbsoluteDeviation(numbers: [Double]) -> Double { // invalid redeclaration of 'meanAbsoluteDeviation(numbers:)'
let bucketAbsoluteDifference = bucket.map { abs(bucketMean - Double($0)) }.reduce(0, +) // value of type 'Int' has no member 'map'
sum += Double(bucketAbsoluteDifference) * Double(bucket.count) // value of type 'Int' has no member 'count'
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.map { abs(median - $0) }.reduce(0, +) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let bucketSize = 10
let bucketCount = Int(ceil(Double(numbers.count) / Double(bucketSize)))
var buckets = [Int]()
for _ in 0..<bucketCount { buckets.append(0) }
for number in numbers {
let bucketIndex = Int(ceil(Double(number) / Double(bucketSize)))
buckets[bucketIndex] += 1
}
var sum = 0.0
for (index, bucket) in buckets.enumerated() {
let bucketMean = Double(index) * bucketSize + Double(index) * bucketSize / 2
let bucketAbsoluteDifference = Double(bucket) * bucketSize / 2
sum += bucketAbsoluteDifference
}
return sum / Double(numbers.count)
}
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the mean of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (mean in this case):
// MAD = average | x - x_mean |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.map { abs(mean - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法二:中位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.map { abs(median - $0) }.reduce(0, +) / Double(numbers.count)
}
```
### 解法三:分桶
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let bucketSize = 10
let bucketCount = Int(ceil(Double(numbers.count) / Double(bucketSize)))
var buckets = [Int]()
for _ in 0..<bucketCount { buckets.append(0) }
for number in numbers {
let bucketIndex = Int(ceil(Double(number) / Double(bucketSize)))
buckets[bucketIndex] += 1
}
var sum = 0.0
for (index, bucket) in buckets.enumerated() {
let bucketMean = Double(index) * bucketSize + Double(index) * bucketSize / 2
let bucketAbsoluteDifference = Double(bucket) * bucketSize / 2
sum += bucketAbsoluteDifference
}
return sum / Double(numbers.count)
}
```
### 解法四:分桶 + 滑动窗口
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let bucketSize = 10
let bucketCount = Int(ceil(Double(numbers.count) / Double(bucketSize)))
var buckets = [Int]()
for _ in 0..<bucketCount { buckets.append(0) }
for number in numbers {
let bucketIndex = Int(ceil(Double(number) / Double(bucketSize)))
buckets[bucketIndex] += 1
}
var sum = 0.0
var windowSum = 0.0
var windowStart = 0
for (index, bucket) in buckets.enumerated() {
let bucketMean = Double(index) * bucketSize + Double(index) * bucketSize / 2
let bucketAbsoluteDifference = Double(bucket) * bucketSize / 2
sum += bucketAbsoluteDifference
if index - windowStart >= 2 {
let windowMean = windowSum / Double(index - windowStart)
let windowAbsoluteDifference = Double(index - windowStart) * bucketSize / 2
sum -= windowAbsoluteDifference
windowSum -= numbers[windowStart]
windowStart += 1
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let mean = numbers.reduce(0, +) / Double(numbers.count)
return numbers.reduce(0, { abs($0 - mean) + abs($1 - mean) }) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0, { abs($0 - median) + abs($1 - median) }) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let buckets = numbers.reduce(into: [Int: [Double]]()) {
let bucket = $0[0] ?? 0
let count = $0[1] ?? 0
$0[0] = bucket + 1
$0[1] = count + 1
$0[bucket] = ($0[bucket] ?? []) + [$1]
}
let mean = buckets.reduce(0, { $0 + $1.value.reduce(0, +) / Double($1.value.count) })
return buckets.reduce(0, { $0 + $1.value.reduce(0, { abs($0 - mean) + abs($1 - mean) }) }) / Double(numbers.count)
}
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let buckets = numbers.reduce(into: [Int: [Double]]()) {
let bucket = $0[0] ?? 0
let count = $0[1] ?? 0
$0[0] = bucket + 1
$0[1] = count + 1
$0[bucket] = ($0[bucket] ?? []) + [$1]
}
let median = buckets.reduce(0, { $0 + $1.value.reduce(0, +) / Double($1.value.count) })
return buckets.reduce(0, { $0 + $1.value.reduce(0, { abs($0 - median) + abs($1 - 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, { abs($0 - mean) + abs($1 - mean) }) / Double(numbers.count)
}
```
### 解法二:中位数
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let median = numbers.sorted()[numbers.count / 2]
return numbers.reduce(0, { abs($0 - median) + abs($1 - 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 buckets = numbers.reduce(into: [Int: [Double]]()) {
let bucket = $0[0] ?? 0
let count = $0[1] ?? 0
$0[0] = bucket + 1
$0[1] = count + 1
$0[bucket] = ($0[bucket] ?? []) + [$1]
}
let mean = buckets.reduce(0, { $0 + $1.value.reduce(0, +) / Double($1.value.count) })
return buckets.reduce(0, { $0 + $1.value.reduce(0, { abs($0 - mean) + abs($1 - mean) }) }) / Double(numbers.count)
}
```
### 解法四:分桶
```swift
// For a given array of input numbers, calculate Mean Absolute Deviation
// around the median of this dataset.
// Mean Absolute Deviation is the average absolute difference between each
// element and a centerpoint (median in this case):
// MAD = average | x - x_median |
// meanAbsoluteDeviation(numbers: [1.0, 2.0, 3.0, 4.0]) == 1.0
func meanAbsoluteDeviation(numbers: [Double]) -> Double {
let buckets = numbers.reduce(into: [Int: [Double]]()) {
let bucket = $0[0] ?? 0
let count = $0[1] ?? 0
$0[0] = bucket + 1
$0[1] = count + 1
$0[bucket] = ($0[bucket] ?? []) + [$1]
}
let median = buckets.reduce(0, { $0 + $1.value.reduce(0, +) / Double($1.value.count) })
return buckets.reduce(0, { $0 + $1.value.reduce(0, { abs($0 - median) + abs($1 - 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 intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
return [numbers[0], delimeter] + intersperse(numbers: numbers[1..<numbers.count], delimeter: delimeter)
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法二:递归
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
return [numbers[0], delimeter] + intersperse(numbers: numbers[1..<numbers.count], delimeter: delimeter)
}
```
### 解法三:迭代
```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 number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法四:递归 + 迭代
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法五:迭代 + 递归
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法六:迭代 + 递归 + 迭代
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
return [numbers[0], delimeter] + intersperse(numbers: numbers[1..<numbers.count], delimeter: delimeter) // cannot convert value of type 'ArraySlice<Int>' to expected argument type '[Int]'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var result = [Int]()
result.append(numbers[0])
for number in numbers[1..<numbers.count] {
result.append(delimeter)
result.append(number)
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法二:递归
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var result = [Int]()
result.append(numbers[0])
for number in numbers[1..<numbers.count] {
result.append(delimeter)
result.append(number)
}
return result
}
```
### 解法三:迭代
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法四:递归
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var result = [Int]()
result.append(numbers[0])
for number in numbers[1..<numbers.count] {
result.append(delimeter)
result.append(number)
}
return result
}
```
### 解法五:迭代
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
return [numbers[0], delimeter] + intersperse(numbers: numbers[1..<numbers.count], delimeter: delimeter)
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var stack = [Int]()
stack.append(numbers[0])
for number in numbers[1..<numbers.count] {
stack.append(delimeter)
stack.append(number)
}
return stack
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
var i = 0
while i < numbers.count {
result.append(numbers[i])
if i < numbers.count - 1 {
result.append(delimeter)
}
i += 1
}
return result
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
var stack = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
stack.append(number)
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法二:递归
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
return [numbers[0], delimeter] + intersperse(numbers: numbers[1..<numbers.count], delimeter: delimeter)
}
```
### 解法三:递归 + 栈
```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] {
if numbers.count == 0 {
return []
}
if numbers.count == 1 {
return numbers
}
var stack = [Int]()
stack.append(numbers[0])
for number in numbers[1..<numbers.count] {
stack.append(delimeter)
stack.append(number)
}
return stack
}
```
### 解法四:迭代
```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]()
var i = 0
while i < numbers.count {
result.append(numbers[i])
if i < numbers.count - 1 {
result.append(delimeter)
}
i += 1
}
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]()
var stack = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
stack.append(number)
}
return result
}
```
### 解法六:迭代 + 数组
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func inters
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
return [numbers[0], delimeter] + intersperse(numbers: numbers[1..<numbers.count], delimeter: delimeter) // cannot convert value of type 'ArraySlice<Int>' to expected argument type '[Int]'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
guard numbers.count > 0 else {
return []
}
var result = [Int]()
for index in 0..<numbers.count {
result.append(numbers[index])
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
class Solution {
func reverseWords(_ s: String) -> String {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count > 0 {
result.append(String(str.reversed()))
}
}
return result.joined(separator: " ")
}
}
```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.count > 0 else {
return []
}
var result = [Int]()
for index in 0..<numbers.count {
result.append(numbers[index])
if index < numbers.count - 1 {
result.append(delimeter)
}
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func reverseWords(_ s: String) -> String {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count > 0 {
result.append(String(str.reversed()))
}
}
return result.joined(separator: " ")
}
}
```
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.isEmpty {
return []
}
let first = numbers.removeFirst()
return [first] + intersperse(numbers: numbers, delimeter: delimeter) + [delimeter]
}
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
var index = 0
while index < numbers.count {
result.append(numbers[index])
if index > 0 {
result.append(delimeter)
}
index += 1
}
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 number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
### 解法二:递归
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
if numbers.isEmpty {
return []
}
let first = numbers.removeFirst()
return [first] + intersperse(numbers: numbers, delimeter: delimeter) + [delimeter]
}
```
### 解法三:迭代
```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]()
var index = 0
while index < numbers.count {
result.append(numbers[index])
if index > 0 {
result.append(delimeter)
}
index += 1
}
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] {
if numbers.isEmpty {
return []
}
let first = numbers.removeFirst()
return [first] + intersperse(numbers: numbers, delimeter: delimeter) + [delimeter]
}
```
### 解法五:递归 + 迭代
```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] {
if numbers.isEmpty {
return []
}
let first = numbers.removeFirst()
return [first] + intersperse(numbers: numbers, delimeter: delimeter) + [delimeter]
}
```
### 解法六:迭代
```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]()
var index = 0
while index < numbers.count {
result.append(numbers[index])
if index > 0 {
result.append(delimeter)
}
index += 1
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
let first = numbers.removeFirst() // cannot use mutating member on immutable value: 'numbers' is a 'let' constant
func intersperse(numbers: [Int], delimeter: Int) -> [Int] { // invalid redeclaration of 'intersperse(numbers:delimeter:)'
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 && result.last! == delimeter {
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 number in numbers {
result.append(number)
if result.count > 0 && result.last! == delimeter {
result.append(delimeter)
}
}
return result
}
```
// XCTAssertTrue failed
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```swift
// Insert a number 'delimeter' between every two consecutive elements of input array `numbers'
// intersperse(numbers: [] as [Int], delimeter: 4) == [] as [Int]
// intersperse(numbers: [1, 2, 3], delimeter: 4) == [1, 4, 2, 4, 3]
func intersperse(numbers: [Int], delimeter: Int) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
if result.count > 0 {
result.append(delimeter)
}
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
let parens = parenString.map { $0 == "(" ? 1 : -1 }
var maxLevel = 0
var levels = [Int]()
for i in 0..<parens.count {
let level = parens[i] + maxLevel
if level < 0 {
maxLevel = 0
} else {
maxLevel = max(maxLevel, level)
}
levels.append(maxLevel)
}
return levels
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
let parens = parenString.map { $0 == "(" ? 1 : -1 }
var maxLevel = 0
var levels = [Int]()
for i in 0..<parens.count {
let level = parens[i] + maxLevel
if level < 0 {
maxLevel = 0
} else {
maxLevel = max(maxLevel, level)
}
levels.append(maxLevel)
}
return levels
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
switch char {
case "(":
depth += 1
if depth > maxDepth {
maxDepth = depth
}
case ")":
depth -= 1
default:
break
}
}
for _ in parenString {
result.append(maxDepth)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
switch char {
case "(":
depth += 1
if depth > maxDepth {
maxDepth = depth
}
case ")":
depth -= 1
default:
break
}
}
for _ in parenString {
result.append(maxDepth)
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxLevel = 0
var level = 0
for char in parenString {
if char == "(" {
level += 1
if level > maxLevel {
maxLevel = level
}
} else if char == ")" {
level -= 1
}
result.append(maxLevel)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxLevel = 0
var level = 0
for char in parenString {
if char == "(" {
level += 1
if level > maxLevel {
maxLevel = level
}
} else if char == ")" {
level -= 1
}
result.append(maxLevel)
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
let parenString = parenString.map { String($0) }
var maxLevel = 0
var maxLevels = [Int]()
for char in parenString {
if char == "(" {
maxLevel += 1
maxLevels.append(maxLevel)
} else {
maxLevel -= 1
}
}
return maxLevels
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
let parenString = parenString.map { String($0) }
var maxLevel = 0
var maxLevels = [Int]()
for char in parenString {
if char == "(" {
maxLevel += 1
maxLevels.append(maxLevel)
} else {
maxLevel -= 1
}
}
return maxLevels
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var result = [Int]()
var currentDepth = 0
for char in parenString {
if char == "(" {
currentDepth += 1
if currentDepth > maxDepth {
maxDepth = currentDepth
}
} else if char == ")" {
currentDepth -= 1
}
result.append(maxDepth)
}
return result
}
class Solution {
func maxDepthAfterSplit(_ seq: String) -> [Int] {
var result = [Int]()
var currentDepth = 0
for char in seq {
if char == "(" {
currentDepth += 1
result.append(currentDepth % 2)
} else {
result.append(currentDepth % 2)
currentDepth -= 1
}
}
return result
}
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var maxDepth = 0
var result = [Int]()
var currentDepth = 0
for char in parenString {
if char == "(" {
currentDepth += 1
if currentDepth > maxDepth {
maxDepth = currentDepth
}
} else if char == ")" {
currentDepth -= 1
}
result.append(maxDepth)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func maxDepthAfterSplit(_ seq: String) -> [Int] {
var result = [Int]()
var currentDepth = 0
for char in seq {
if char == "(" {
currentDepth += 1
result.append(currentDepth % 2)
} else {
result.append(currentDepth % 2)
currentDepth -= 1
}
}
return result
}
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
let parens = parenString.map { $0 == "(" ? 1 : -1 }
var maxDepth = 0
var depth = 0
var result = [Int]()
for p in parens {
depth += p
if depth > maxDepth {
maxDepth = depth
}
if p == 1 {
result.append(maxDepth)
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
let parens = parenString.map { $0 == "(" ? 1 : -1 }
var maxDepth = 0
var depth = 0
var result = [Int]()
for p in parens {
depth += p
if depth > maxDepth {
maxDepth = depth
}
if p == 1 {
result.append(maxDepth)
}
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxDepth = 0
var depth = 0
for c in parenString {
if c == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if c == ")" {
depth -= 1
}
result.append(maxDepth)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxDepth = 0
var depth = 0
for c in parenString {
if c == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if c == ")" {
depth -= 1
}
result.append(maxDepth)
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
if char == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if char == ")" {
depth -= 1
}
}
for _ in 0..<maxDepth {
result.append(maxDepth)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
if char == "(" {
depth += 1
if depth > maxDepth {
maxDepth = depth
}
} else if char == ")" {
depth -= 1
}
}
for _ in 0..<maxDepth {
result.append(maxDepth)
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
switch char {
case "(":
depth += 1
if depth > maxDepth {
maxDepth = depth
}
case ")":
depth -= 1
default:
break
}
}
for _ in parenString {
result.append(maxDepth)
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
switch char {
case "(":
depth += 1
if depth > maxDepth {
maxDepth = depth
}
case ")":
depth -= 1
default:
break
}
}
for _ in parenString {
result.append(maxDepth)
}
return result
}
```
// XCTAssertTrue failed
func parseNestedParens(parenString: String) -> [Int] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
if char == "(" {
depth += 1
} else {
depth -= 1
}
if depth > maxDepth {
maxDepth = depth
}
if depth == 0 {
result.append(maxDepth)
}
}
return result
}
```swift
// Input to this function is a string represented multiple groups for nested parentheses separated by spaces.
// For each of the group, output the deepest level of nesting of parentheses.
// E.g. (()()) has maximum two levels of nesting while ((())) has three.
// parseNestedParens(parenString: "(()()) ((())) () ((())()())") == [2, 3, 1, 3]
func parseNestedParens(parenString: String) -> [Int] {
let parenString = parenString.replacingOccurrences(of: " ", with: "")
var result = [Int]()
var maxDepth = 0
var depth = 0
for char in parenString {
if char == "(" {
depth += 1
} else {
depth -= 1
}
if depth > maxDepth {
maxDepth = depth
}
if depth == 0 {
result.append(maxDepth)
}
}
return result
}
```
// XCTAssertTrue failed
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.map { String($0) }
}
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.reduce([], +)
}
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.reduce([], +).map { String($0) }
}
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.reduce([], +).map { String($0) }.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) }
}
```
### 2. 2-way-map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
```
### 3. 2-way-map-with-filter
```swift
// Map an input array of strings to another array of strings, only for ones that contain given substring
// mapToStrings(strings: [] as [String], substring: "a") == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.map { String($0) }
}
```
### 4. 2-way-map-with-filter-and-reduce
```swift
// Map an input array of strings to another array of strings, only for ones that contain given substring
// mapToStrings(strings: [] as [String], substring: "a") == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.reduce([], +)
}
```
### 5. 2-way-map-with-filter-and-reduce-and-map
```swift
// Map an input array of strings to another array of strings, only for ones that contain given substring
// mapToStrings(strings: [] as [String], substring: "a") == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.reduce([], +).map { String($0) }
}
```
### 6. 2-way-map-with-filter-and-reduce-and-map-with-filter
```swift
// Map an input array of strings to another array of strings, only for ones that contain given substring
// mapToStrings(strings: [] as [String], substring: "a") == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func mapToStrings(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }.reduce([], +).map { String($0) }.filter { $0.contains(substring) }
}
```
### 7. 2-way-map-with-filter-and-reduce-and-map-with-filter-and-map
```swift
// Map an input array of strings to another array of strings, only for ones that contain given substring
// mapToStrings(strings: [] as [String], substring: "a") == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func mapToStrings(strings: [String
func mapToStrings(strings: [String], substring: String) -> [String] { // invalid redeclaration of 'mapToStrings(strings:substring:)'
return strings.filter { $0.contains(substring) }.reduce([], +) // operator function '+' requires the types 'String' and 'String.Element' (aka 'Character') be equivalent
func mapToStrings(strings: [String], substring: String) -> [String] { // invalid redeclaration of 'mapToStrings(strings:substring:)'
func mapToStrings(strings: [String], substring: String) -> [String] { // invalid redeclaration of 'mapToStrings(strings:substring:)'
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
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) }
}
```
### 2. 2-way map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
```
### 3. 2-way filter
```swift
// Filter an input array of strings only for ones that don't contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["bcd", "cde", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { !$0.contains(substring) }
}
```
### 4. 2-way filter
```swift
// Filter an input array of strings only for ones that don't contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["bcd", "cde", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { !$0.contains(substring) }
}
```
### 5. 2-way map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
```
### 6. 2-way map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
```
### 7. 2-way map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
```
### 8. 2-way map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) == [] as [String]
// mapToStrings(strings: ["abc", "bacd", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func mapToStrings(strings: [String]) -> [String] {
return strings.map { String($0) }
}
```
### 9. 2-way map
```swift
// Map an input array of strings to another array of strings
// mapToStrings(strings: [] as [String]) ==
func filterBySubstring(strings: [String], substring: String) -> [String] { // invalid redeclaration of 'filterBySubstring(strings:substring:)'
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```swift
// Filter an input array of strings only for ones that contain given substring
// filterBySubstring(strings: [] as [String], substring: "a") == [] as [String]
// filterBySubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == ["abc", "bacd", "array"]
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
```
### 2. 过滤器
```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) }
}
```
### 3. 过滤器
```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) }
}
```
### 4. 过滤器
```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) }
}
```
### 5. 过滤器
```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) }
}
```
### 6. 过滤器
```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) }
}
```
### 7. 过滤器
```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) }
}
```
### 8. 过滤器
```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: [
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```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) }
}
```
### 2.2.2. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.3. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.4. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.5. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.6. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.7. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.8. 过滤空字符串
```swift
// Filter an input array of strings only for ones that are not empty
// filterEmptyStrings(strings: [] as [String]) == [] as [String]
// filterEmptyStrings(strings: ["", "abc", "bacd", "", "cde", "array"]) == ["abc", "bacd", "cde", "array"]
func filterEmptyStrings(strings: [String]) -> [String] {
return strings.filter { $0.isEmpty == false }
}
```
### 2.2.
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) }
}
```
### 2. 过滤器
```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) }
}
```
### 3. 过滤器
```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) }
}
```
### 4. 过滤器
```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) }
}
```
### 5. 过滤器
```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) }
}
```
### 6. 过滤器
```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) }
}
```
### 7. 过滤器
```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) }
}
```
### 8. 过滤器
```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: [
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func sortByLength(strings: [String]) -> [String] {
return strings.sorted { $0.count > $1.count }
}
func reverseStrings(strings: [String]) -> [String] {
return strings.reversed()
}
func concatenateStrings(strings: [String]) -> String {
return strings.joined()
}
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
func replaceAllSubstrings(strings: [String], old: String, new: String) -> [String] {
return strings.map { $0.replacingOccurrences(of: old, with: new) }
}
func containsSubstring(strings: [String], substring: String) -> Bool {
return strings.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) }
}
```
### 2. 字符串排序
```swift
// Sort an array of strings by their length
// sortByLength(strings: [] as [String]) == [] as [String]
// sortByLength(strings: ["abc", "bacd", "cde", "array"]) == ["array", "abc", "bacd", "cde"]
func sortByLength(strings: [String]) -> [String] {
return strings.sorted { $0.count > $1.count }
}
```
### 3. 字符串反转
```swift
// Reverse an array of strings
// reverseStrings(strings: [] as [String]) == [] as [String]
// reverseStrings(strings: ["abc", "bacd", "cde", "array"]) == ["array", "cde", "bacd", "abc"]
func reverseStrings(strings: [String]) -> [String] {
return strings.reversed()
}
```
### 4. 字符串拼接
```swift
// Concatenate an array of strings into a single string
// concatenateStrings(strings: [] as [String]) == ""
// concatenateStrings(strings: ["abc", "bacd", "cde", "array"]) == "abc bacd cde array"
func concatenateStrings(strings: [String]) -> String {
return strings.joined()
}
```
### 5. 字符串分割
```swift
// Split an array of strings into an array of substrings by a given separator
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bacd", "cde", "array"], separator: " ") == ["abc", "bacd", "cde", "array"]
// splitStrings(strings: ["abc", "bacd", "cde", "array"], separator: "d") == ["abc", "bac", "cde", "array"]
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```
### 6. 字符串替换
```swift
// Replace all instances of a given substring in an array of strings with a new substring
// replaceAllSubstrings(strings: [] as [String], old: "", new: "") == [] as [String]
// replaceAllSubstrings(strings: ["abc", "bacd", "cde", "array"], old: "a", new: "A") == ["Abc", "Bacd", "Cde", "Array"]
func replaceAllSubstrings(strings: [String], old: String, new: String) -> [String] {
return strings.map { $0.replacingOccurrences(of: old, with: new) }
}
```
### 7. 字符串匹配
```swift
// Check if an array of strings contains a given substring
// containsSubstring(strings: [] as [String], substring: "") == false
// containsSubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == true
func containsSubstring(strings: [String], substring: String) -> Bool {
return strings.contains(substring)
}
```
### 8. 字符串匹配
```swift
// Check if an array of strings contains a given substring
// containsSubstring(strings: [] as [String], substring: "") == false
// containsSubstring(strings: ["abc", "bacd", "cde", "array"], substring: "a") == true
func containsSubstring(strings: [String], substring: String) -> Bool {
return strings.contains(substring)
}
```
### 9. 字符串匹配
```swift
// Check if an array of
return strings.split(separator: separator) // cannot convert return expression of type '[ArraySlice<String>]' to return type '[String]'
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) }
}
```
### 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
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) }
}
```
### 3. 数组中出现次数最多的元素
```swift
// Find the most frequent element in an array
// mostFrequent(numbers: []) == nil
// mostFrequent(numbers: [1, 2, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
func filterBySubstring(strings: [String], substring: String) -> [String] {
return strings.filter { $0.contains(substring) }
}
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: " ")
}
func splitString(string: String) -> [Character] {
return Array(string)
}
```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) }
}
```
### 2. 字符串数组转成字符串
```swift
// Convert an array of strings to a single string
// joinStrings(strings: [] as [String]) == ""
// joinStrings(strings: ["abc", "bacd", "cde", "array"]) == "abc bacd cde array"
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: " ")
}
```
### 3. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters
// splitString(string: "") == [] as [Character]
// splitString(string: "abc bacd cde array") == ["a", "b", "c", " ", "b", "a", "c", " ", "d", "c", "e", " ", "a", "r", "r", "a", "y"]
func splitString(string: String) -> [Character] {
return Array(string)
}
```
### 4. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters
// splitString(string: "") == [] as [Character]
// splitString(string: "abc bacd cde array") == ["a", "b", "c", " ", "b", "a", "c", " ", "d", "c", "e", " ", "a", "r", "r", "a", "y"]
func splitString(string: String) -> [Character] {
return Array(string)
}
```
### 5. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters
// splitString(string: "") == [] as [Character]
// splitString(string: "abc bacd cde array") == ["a", "b", "c", " ", "b", "a", "c", " ", "d", "c", "e", " ", "a", "r", "r", "a", "y"]
func splitString(string: String) -> [Character] {
return Array(string)
}
```
### 6. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters
// splitString(string: "") == [] as [Character]
// splitString(string: "abc bacd cde array") == ["a", "b", "c", " ", "b", "a", "c", " ", "d", "c", "e", " ", "a", "r", "r", "a", "y"]
func splitString(string: String) -> [Character] {
return Array(string)
}
```
### 7. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters
// splitString(string: "") == [] as [Character]
// splitString(string: "abc bacd cde array") == ["a", "b", "c", " ", "b", "a", "c", " ", "d", "c", "e", " ", "a", "r", "r", "a", "y"]
func splitString(string: String) -> [Character] {
return Array(string)
}
```
### 8. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters
// splitString(string: "") == [] as [Character]
// splitString(string: "abc bacd cde array") == ["a", "b", "c", " ", "b", "a", "c", " ", "d", "c", "e", " ", "a", "r", "r", "a", "y"]
func splitString(string: String) -> [Character] {
return Array(string)
}
```
### 9. 字符串数组转成
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) }
}
```
### 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2. 2.
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for num in numbers {
sum += num
product *= num
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
class Solution {
func sumProduct(_ nums: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in nums {
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)
}
```
### 解题思路
### 代码
```swift
class Solution {
func sumProduct(_ nums: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in nums {
sum += number
product *= number
}
return (sum, product)
}
}
```
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```swift
// For a given array of integers, return a tuple consisting of a sum and a product of all the integers in an array.
// Empty sum should be equal to 0 and empty product should be equal to 1.
// sumProduct(numbers: [] as [Int]) == (0, 1)
// sumProduct(numbers: [1, 2, 3, 4]) == (10, 24)
func sumProduct(numbers: [Int]) -> (Int, Int) {
var sum = 0
var product = 1
for number in numbers {
sum += number
product *= number
}
return (sum, product)
}
```
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[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]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[i]
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[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]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[i]
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 1..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var stack = [Int]()
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[0]])
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 1..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
### 解法二:单调栈
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var stack = [Int]()
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[0]])
}
return result
}
```
func rollingMax(numbers: [Int]) -> [Int] { // invalid redeclaration of 'rollingMax(numbers:)'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[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]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[i]
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
result.append(max)
max = max > numbers[i] ? max : numbers[i]
}
return result
}
class Solution {
func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
guard k > 0, nums.count > 0 else {
return []
}
var result = [Int]()
var window = [Int]()
for i in 0..<nums.count {
if i >= k && window[0] <= i - k {
window.removeFirst()
}
while !window.isEmpty && nums[i] >= nums[window.last!] {
window.removeLast()
}
window.append(i)
if i >= k - 1 {
result.append(nums[window[0]])
}
}
return result
}
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var max = numbers[0]
var result = [Int]()
for i in 0..<numbers.count {
result.append(max)
max = max > numbers[i] ? max : numbers[i]
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
guard k > 0, nums.count > 0 else {
return []
}
var result = [Int]()
var window = [Int]()
for i in 0..<nums.count {
if i >= k && window[0] <= i - k {
window.removeFirst()
}
while !window.isEmpty && nums[i] >= nums[window.last!] {
window.removeLast()
}
window.append(i)
if i >= k - 1 {
result.append(nums[window[0]])
}
}
return result
}
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[i]
}
}
return result
}
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var stack = [Int]()
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[0]])
}
return result
}
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var stack = [Int]()
stack.append(Int.max)
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[0]])
}
return result
}
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var stack = [Int]()
stack.append(Int.max)
stack.append(Int.max)
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[1]])
}
return result
}
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var stack = [Int]()
stack.append(Int.max)
stack.append(Int.max)
stack.append(Int.max)
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[2]])
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[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 stack = [Int]()
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[0]])
}
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 stack = [Int]()
stack.append(Int.max)
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[0]])
}
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 stack = [Int]()
stack.append(Int.max)
stack.append(Int.max)
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[1]])
}
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 stack = [Int]()
stack.append(Int.max)
stack.append(Int.max)
stack.append(Int.max)
for i in 0..<numbers.count {
while let top = stack.last, numbers[i] > numbers[top] {
stack.removeLast()
}
stack.append(i)
result.append(numbers[stack[2]])
}
return result
}
```
### 解法六:单调栈 + 哨兵 + 哨兵 + 哨兵 + 哨兵
```swift
// From a given array
func rollingMax(numbers: [Int]) -> [Int] { // invalid redeclaration of 'rollingMax(numbers:)'
func rollingMax(numbers: [Int]) -> [Int] { // invalid redeclaration of 'rollingMax(numbers:)'
func rollingMax(numbers: [Int]) -> [Int] { // invalid redeclaration of 'rollingMax(numbers:)'
func rollingMax(numbers: [Int]) -> [Int] { // invalid redeclaration of 'rollingMax(numbers:)'
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[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]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[i]
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[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]
for i in 0..<numbers.count {
result.append(max)
if numbers[i] > max {
max = numbers[i]
}
}
return result
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 1..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
class Solution {
func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
guard k > 0, nums.count > 0 else {
return []
}
var result = [Int]()
var max = nums[0]
for i in 0..<nums.count - k + 1 {
if i == 0 {
for j in 0..<k {
if nums[j] > max {
max = nums[j]
}
}
result.append(max)
} else {
if nums[i + k - 1] > max {
max = nums[i + k - 1]
}
result.append(max)
}
}
return result
}
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 1..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
guard k > 0, nums.count > 0 else {
return []
}
var result = [Int]()
var max = nums[0]
for i in 0..<nums.count - k + 1 {
if i == 0 {
for j in 0..<k {
if nums[j] > max {
max = nums[j]
}
}
result.append(max)
} else {
if nums[i + k - 1] > max {
max = nums[i + k - 1]
}
result.append(max)
}
}
return result
}
}
```
// Fatal error: Index out of range
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```swift
// From a given array of integers, generate an array of rolling maximum element found until given moment
// in the sequence.
// rollingMax(numbers: [1, 2, 3, 2, 3, 4, 2]) == [1, 2, 3, 3, 3, 4, 4]
func rollingMax(numbers: [Int]) -> [Int] {
var result = [Int]()
var max = numbers[0]
for i in 0..<numbers.count {
if numbers[i] > max {
max = numbers[i]
}
result.append(max)
}
return result
}
```
// Fatal error: Index out of range
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && !isPalindrome(s[0...i]) {
i -= 1
}
let prefix = s[0...i]
let suffix = Array(s.reversed()[0...i])
return prefix + String(suffix.reversed())
}
func isPalindrome(_ s: [Character]) -> Bool {
let i = s.startIndex
let j = s.endIndex - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && !isPalindrome(s[0...i]) {
i -= 1
}
let prefix = s[0...i]
let suffix = Array(s.reversed()[0...i])
return prefix + String(suffix.reversed())
}
func isPalindrome(_ s: [Character]) -> Bool {
let i = s.startIndex
let j = s.endIndex - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
```
while i >= 0 && !isPalindrome(s[0...i]) { // cannot convert value of type 'Array<String.Element>.SubSequence' (aka 'ArraySlice<Character>') to expected argument type '[Character]'
i += 1 // left side of mutating operator isn't mutable: 'i' is a 'let' constant
j -= 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
func makePalindrome(string: String) -> String {
guard string.count > 0 else {
return ""
}
let s = Array(string)
var i = s.count - 1
while i >= 0 && !isPalindrome(s[0...i]) {
i -= 1
}
if i < 0 {
return string
}
let prefix = s[0...i]
let suffix = String(s.reversed()[i+1...s.count-1])
return prefix + suffix
}
func isPalindrome(_ s: String) -> Bool {
let s = Array(s)
var i = 0, j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard string.count > 0 else {
return ""
}
let s = Array(string)
var i = s.count - 1
while i >= 0 && !isPalindrome(s[0...i]) {
i -= 1
}
if i < 0 {
return string
}
let prefix = s[0...i]
let suffix = String(s.reversed()[i+1...s.count-1])
return prefix + suffix
}
func isPalindrome(_ s: String) -> Bool {
let s = Array(s)
var i = 0, j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
```
while i >= 0 && !isPalindrome(s[0...i]) { // cannot convert value of type 'Array<String.Element>.SubSequence' (aka 'ArraySlice<Character>') to expected argument type 'String'
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && s[i] != s[0] {
i -= 1
}
let prefix = String(s[0...i])
let suffix = String(s[i...s.count - 1].reversed())
return prefix + suffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && s[i] != s[0] {
i -= 1
}
let prefix = String(s[0...i])
let suffix = String(s[i...s.count - 1].reversed())
return prefix + suffix
}
```
// Fatal error: Range requires lowerBound <= upperBound
func makePalindrome(string: String) -> String {
guard string.count > 0 else {
return ""
}
var longestPalindrome = ""
for i in 0..<string.count {
let start = string.index(string.startIndex, offsetBy: i)
let end = string.index(string.startIndex, offsetBy: string.count - i)
let subStr = string[start..<end]
if isPalindrome(string: subStr) {
longestPalindrome = subStr
}
}
let reverse = longestPalindrome.reversed()
let prefix = string.prefix(longestPalindrome.count)
return prefix + String(reverse)
}
func isPalindrome(string: String) -> Bool {
let count = string.count
for i in 0..<count / 2 {
if string[i] != string[count - i - 1] {
return false
}
}
return true
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
guard string.count > 0 else {
return ""
}
var longestPalindrome = ""
for i in 0..<string.count {
let start = string.index(string.startIndex, offsetBy: i)
let end = string.index(string.startIndex, offsetBy: string.count - i)
let subStr = string[start..<end]
if isPalindrome(string: subStr) {
longestPalindrome = subStr
}
}
let reverse = longestPalindrome.reversed()
let prefix = string.prefix(longestPalindrome.count)
return prefix + String(reverse)
}
func isPalindrome(string: String) -> Bool {
let count = string.count
for i in 0..<count / 2 {
if string[i] != string[count - i - 1] {
return false
}
}
return true
}
```
if isPalindrome(string: subStr) { // cannot convert value of type 'Substring' to expected argument type 'String'
longestPalindrome = subStr // cannot assign value of type 'Substring' to type 'String'
if string[i] != string[count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] != string[count - i - 1] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func makePalindrome(string: String) -> String {
if string.isEmpty {
return ""
}
let reversed = string.reversed()
let reversedString = reversed.dropFirst(string.count % reversed.count)
let palindrome = reversedString.compare(string) == .orderedSame ? string : string + reversedString
return palindrome
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
if string.isEmpty {
return ""
}
let reversed = string.reversed()
let reversedString = reversed.dropFirst(string.count % reversed.count)
let palindrome = reversedString.compare(string) == .orderedSame ? string : string + reversedString
return palindrome
}
```
let palindrome = reversedString.compare(string) == .orderedSame ? string : string + reversedString // cannot convert value of type 'String' to expected argument type 'Slice<ReversedCollection<String>>.Element.Compared' (aka 'Character.Compared')
let palindrome = reversedString.compare(string) == .orderedSame ? string : string + reversedString // missing argument for parameter #2 in call
let palindrome = reversedString.compare(string) == .orderedSame ? string : string + reversedString // instance method 'compare' requires that 'Slice<ReversedCollection<String>>.Element' (aka 'Character') conform to 'SortComparator'
func makePalindrome(string: String) -> String {
let reversedString = string.reversed()
let reversedStringArray = Array(reversedString)
let reversedStringArrayLength = reversedStringArray.count
let stringArray = Array(string)
let stringArrayLength = stringArray.count
// Find the longest postfix of supplied string that is a palindrome.
var longestPalindromeIndex = 0
var longestPalindromeLength = 0
for i in 0..<stringArrayLength {
let startIndex = i
let endIndex = stringArrayLength - 1 - i
var startIndex = startIndex
var endIndex = endIndex
while startIndex < endIndex && stringArray[startIndex] == reversedStringArray[endIndex] {
startIndex += 1
endIndex -= 1
}
if startIndex >= endIndex {
if longestPalindromeLength < endIndex - startIndex + 1 {
longestPalindromeLength = endIndex - startIndex + 1
longestPalindromeIndex = i
}
}
}
// Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
var result = string
if longestPalindromeLength > 0 {
let suffixStartIndex = longestPalindromeIndex + 1
let suffixEndIndex = stringArrayLength - 1 - longestPalindromeIndex
let suffix = String(stringArray[suffixStartIndex...suffixEndIndex])
let reversedSuffix = String(reversedStringArray[suffixStartIndex...suffixEndIndex])
result += reversedSuffix
}
return result
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversedString = string.reversed()
let reversedStringArray = Array(reversedString)
let reversedStringArrayLength = reversedStringArray.count
let stringArray = Array(string)
let stringArrayLength = stringArray.count
// Find the longest postfix of supplied string that is a palindrome.
var longestPalindromeIndex = 0
var longestPalindromeLength = 0
for i in 0..<stringArrayLength {
let startIndex = i
let endIndex = stringArrayLength - 1 - i
var startIndex = startIndex
var endIndex = endIndex
while startIndex < endIndex && stringArray[startIndex] == reversedStringArray[endIndex] {
startIndex += 1
endIndex -= 1
}
if startIndex >= endIndex {
if longestPalindromeLength < endIndex - startIndex + 1 {
longestPalindromeLength = endIndex - startIndex + 1
longestPalindromeIndex = i
}
}
}
// Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
var result = string
if longestPalindromeLength > 0 {
let suffixStartIndex = longestPalindromeIndex + 1
let suffixEndIndex = stringArrayLength - 1 - longestPalindromeIndex
let suffix = String(stringArray[suffixStartIndex...suffixEndIndex])
let reversedSuffix = String(reversedStringArray[suffixStartIndex...suffixEndIndex])
result += reversedSuffix
}
return result
}
```
var startIndex = startIndex // invalid redeclaration of 'startIndex'
var endIndex = endIndex // invalid redeclaration of 'endIndex'
longestPalindromeLength = endIndex - startIndex + 1 // cannot convert value of type 'Duration' to expected argument type 'Int'
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && s[i] == s[0] {
i -= 1
}
if i < 0 {
return string
}
let prefix = Array(s[0...i])
let suffix = Array(s[i...s.count - 1])
let reverseSuffix = Array(suffix.reversed())
let palindrome = Array(prefix + reverseSuffix)
return String(palindrome)
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && s[i] == s[0] {
i -= 1
}
if i < 0 {
return string
}
let prefix = Array(s[0...i])
let suffix = Array(s[i...s.count - 1])
let reverseSuffix = Array(suffix.reversed())
let palindrome = Array(prefix + reverseSuffix)
return String(palindrome)
}
```
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
if string.isEmpty {
return ""
}
let reversed = string.reversed()
let reversedString = reversed.dropFirst()
let reversedPrefix = reversed.prefix(string.count - reversedString.count)
let prefix = reversedPrefix.reversed()
return string + prefix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
if string.isEmpty {
return ""
}
let reversed = string.reversed()
let reversedString = reversed.dropFirst()
let reversedPrefix = reversed.prefix(string.count - reversedString.count)
let prefix = reversedPrefix.reversed()
return string + prefix
}
```
// XCTAssertTrue failed
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && s[i] != s[0] {
i -= 1
}
let prefix = String(s[0...i])
let suffix = String(s[i...s.count - 1].reversed())
return prefix + suffix
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let s = Array(string)
var i = s.count - 1
while i >= 0 && s[i] != s[0] {
i -= 1
}
let prefix = String(s[0...i])
let suffix = String(s[i...s.count - 1].reversed())
return prefix + suffix
}
```
// Fatal error: Range requires lowerBound <= upperBound
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let reversedString = reversed.dropFirst(string.count % 2 == 0 ? 1 : 0)
let palindrome = string + reversedString
return palindrome
}
```swift
// Find the shortest palindrome that begins with a supplied string.
// Algorithm idea is simple:
// - Find the longest postfix of supplied string that is a palindrome.
// - Append to the end of the string reverse of a string prefix that comes before the palindromic suffix.
// makePalindrome(string: "") == ""
// makePalindrome(string: "cat") == "catac"
// makePalindrome(string: "cata") == "catac"
func makePalindrome(string: String) -> String {
let reversed = string.reversed()
let reversedString = reversed.dropFirst(string.count % 2 == 0 ? 1 : 0)
let palindrome = string + reversedString
return palindrome
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
let a = a.map { $0 == "1" ? 1 : 0 }
let b = b.map { $0 == "1" ? 1 : 0 }
let result = a.zip(b).map { $0 ^ $1 }
return result.map { $0 == 1 ? "1" : "0" }.joined()
}
func stringXor(a: String, b: String) -> String {
var result = 0
for c in a.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
for c in b.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
var resultStr = ""
while result > 0 {
resultStr.append(String(result % 2))
result /= 2
}
return resultStr.reversed()
}
func stringXor(a: String, b: String) -> String {
var result = 0
for c in a.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
for c in b.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
return String(result)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = a.map { $0 == "1" ? 1 : 0 }
let b = b.map { $0 == "1" ? 1 : 0 }
let result = a.zip(b).map { $0 ^ $1 }
return result.map { $0 == 1 ? "1" : "0" }.joined()
}
```
### 解法二:位运算
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = 0
for c in a.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
for c in b.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
var resultStr = ""
while result > 0 {
resultStr.append(String(result % 2))
result /= 2
}
return resultStr.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 = 0
for c in a.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
for c in b.reversed() {
result = result << 1
result += c == "1" ? 1 : 0
}
return String(result)
}
```
let result = a.zip(b).map { $0 ^ $1 } // value of type '[Int]' has no member 'zip'
func stringXor(a: String, b: String) -> String { // invalid redeclaration of 'stringXor(a:b:)'
return resultStr.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func stringXor(a: String, b: String) -> String { // invalid redeclaration of 'stringXor(a:b:)'
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[a.index(a.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[a.index(a.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```
### 解法二
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result += String(a[a.index(a.startIndex, offsetBy: i)] != b[a.index(a.startIndex, offsetBy: i)])
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result += String(a[a.index(a.startIndex, offsetBy: i)] != b[a.index(a.startIndex, offsetBy: i)])
}
return result
}
```
// XCTAssertTrue failed
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```
func stringXor(a: String, b: String) -> String {
let a = a.map { $0 == "1" ? 1 : 0 }
let b = b.map { $0 == "1" ? 1 : 0 }
let result = a.zip(b).map { $0 ^ $1 }
return result.map { $0 == 1 ? "1" : "0" }.joined()
}
func stringXor(a: String, b: String) -> String {
var result = 0
for (i, c) in a.enumerated() {
result ^= (c == "1") ? 1 : 0
result ^= (b[i] == "1") ? 1 : 0
}
return String(result, 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 {
let a = a.map { $0 == "1" ? 1 : 0 }
let b = b.map { $0 == "1" ? 1 : 0 }
let result = a.zip(b).map { $0 ^ $1 }
return result.map { $0 == 1 ? "1" : "0" }.joined()
}
```
### 解法二:位运算
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = 0
for (i, c) in a.enumerated() {
result ^= (c == "1") ? 1 : 0
result ^= (b[i] == "1") ? 1 : 0
}
return String(result, 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 {
let a = a.map { $0 == "1" ? 1 : 0 }
let b = b.map { $0 == "1" ? 1 : 0 }
let result = a.zip(b).map { $0 ^ $1 }
return result.map { $0 == 1 ? "1" : "0" }.joined()
}
```
let result = a.zip(b).map { $0 ^ $1 } // value of type '[Int]' has no member 'zip'
func stringXor(a: String, b: String) -> String { // invalid redeclaration of 'stringXor(a:b:)'
result ^= (b[i] == "1") ? 1 : 0 // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for (a, b) in zip(a, b) {
result.append(String(Int(a.asciiValue! - 48) ^ Int(b.asciiValue! - 48)))
}
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 (a, b) in zip(a, b) {
result.append(String(Int(a.asciiValue! - 48) ^ Int(b.asciiValue! - 48)))
}
return result
}
```
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
if a.count > b.count {
for i in b.index(b.startIndex, offsetBy: b.count)..<a.count {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != "0" ? "1" : "0"))
}
} else {
for i in a.index(a.startIndex, offsetBy: a.count)..<b.count {
result.append(String(b[b.index(b.startIndex, offsetBy: i)] != "0" ? "1" : "0"))
}
}
return result
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
var result = ""
for i in 0..<min(a.count, b.count) {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != b[b.index(b.startIndex, offsetBy: i)] ? "1" : "0"))
}
if a.count > b.count {
for i in b.index(b.startIndex, offsetBy: b.count)..<a.count {
result.append(String(a[a.index(a.startIndex, offsetBy: i)] != "0" ? "1" : "0"))
}
} else {
for i in a.index(a.startIndex, offsetBy: a.count)..<b.count {
result.append(String(b[b.index(b.startIndex, offsetBy: i)] != "0" ? "1" : "0"))
}
}
return result
}
```
for i in b.index(b.startIndex, offsetBy: b.count)..<a.count { // cannot convert value of type 'String.Index' to expected argument type 'Int'
for i in a.index(a.startIndex, offsetBy: a.count)..<b.count { // cannot convert value of type 'String.Index' to expected argument type 'Int'
func stringXor(a: String, b: String) -> String {
let a = Array(a), b = Array(b)
var result = [Character]()
for i in 0..<min(a.count, b.count) {
result.append(a[i] ^ b[i])
}
if a.count > b.count {
result.append(contentsOf: a[b.count..<a.count])
} else {
result.append(contentsOf: b[a.count..<b.count])
}
return String(result)
}
```swift
// Input are two strings a and b consisting only of 1s and 0s.
// Perform binary XOR on these inputs and return result also as a string.
// stringXor(a: "010", b: "110") == "100"
func stringXor(a: String, b: String) -> String {
let a = Array(a), b = Array(b)
var result = [Character]()
for i in 0..<min(a.count, b.count) {
result.append(a[i] ^ b[i])
}
if a.count > b.count {
result.append(contentsOf: a[b.count..<a.count])
} else {
result.append(contentsOf: b[a.count..<b.count])
}
return String(result)
}
```
result.append(a[i] ^ b[i]) // binary operator '^' cannot be applied to two 'String.Element' (aka 'Character') operands
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLength = 0
var maxString: String?
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var dp = Array(repeating: 0, count: n)
var maxLength = 0
var maxString: String?
for i in 0..<n {
dp[i] = strings[i].count
if dp[i] > maxLength {
maxLength = dp[i]
maxString = strings[i]
}
}
return maxString
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
for i in 0..<n {
if strings[i].count > maxLength {
maxLength = strings[i].count
maxString = strings[i]
}
}
return maxString
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
var dp = 0
for i in 0..<n {
dp = strings[i].count
if dp > maxLength {
maxLength = dp
maxString = strings[i]
}
}
return maxString
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLength = 0
var maxString: String?
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```
### 解法二:动态规划
```swift
// Dynamic programming
// Time complexity: O(n)
// Space complexity: O(n)
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var dp = Array(repeating: 0, count: n)
var maxLength = 0
var maxString: String?
for i in 0..<n {
dp[i] = strings[i].count
if dp[i] > maxLength {
maxLength = dp[i]
maxString = strings[i]
}
}
return maxString
}
```
### 解法三:动态规划
```swift
// Dynamic programming
// Time complexity: O(n)
// Space complexity: O(1)
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
for i in 0..<n {
if strings[i].count > maxLength {
maxLength = strings[i].count
maxString = strings[i]
}
}
return maxString
}
```
### 解法四:动态规划
```swift
// Dynamic programming
// Time complexity: O(n)
// Space complexity: O(1)
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
var dp = 0
for i in 0..<n {
dp = strings[i].count
if dp > maxLength {
maxLength = dp
maxString = strings[i]
}
}
return maxString
}
```
### 解法五:动态规划
```swift
// Dynamic programming
// Time complexity: O(n)
// Space complexity: O(1)
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
var dp = 0
for i in 0..<n {
dp = strings[i].count
if dp > maxLength {
maxLength = dp
maxString = strings[i]
}
}
return maxString
}
```
### 解法六:动态规划
```swift
// Dynamic programming
// Time complexity: O(n)
// Space complexity: O(1)
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
var dp = 0
for i in 0..<n {
dp = strings[i].count
if dp > maxLength {
maxLength = dp
maxString = strings[i]
}
}
return maxString
}
```
### 解法七:动态规划
```swift
// Dynamic programming
// Time complexity: O(n)
// Space complexity: O(1)
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let n = strings.count
var maxLength = 0
var maxString: String?
var dp = 0
for i in 0..<n {
dp = strings[i].count
if dp > maxLength {
maxLength = dp
maxString
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let sorted = strings.sorted { $0.count > $1.count }
return sorted.first
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var dp = [Int](repeating: 0, count: strings.count)
var maxLen = 0
for i in 0..<strings.count {
dp[i] = strings[i].count
if i == 0 {
maxLen = dp[i]
} else {
if dp[i] > maxLen {
maxLen = dp[i]
}
}
}
return strings[strings.count - maxLen]
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLen = 0
var dp = [Int](repeating: 0, count: strings.count)
for i in 0..<strings.count {
dp[i] = strings[i].count
if i == 0 {
maxLen = dp[i]
} else {
if dp[i] > maxLen {
maxLen = dp[i]
}
}
}
return strings[strings.count - maxLen]
}
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLen = 0
var maxLenString = ""
for string in strings {
let len = string.count
if len > maxLen {
maxLen = len
maxLenString = string
}
}
return maxLenString
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
### 解法二:排序
```swift
// Sort the array of strings by length, then return the first one.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
let sorted = strings.sorted { $0.count > $1.count }
return sorted.first
}
```
### 解法三:动态规划
```swift
// Dynamic programming
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var dp = [Int](repeating: 0, count: strings.count)
var maxLen = 0
for i in 0..<strings.count {
dp[i] = strings[i].count
if i == 0 {
maxLen = dp[i]
} else {
if dp[i] > maxLen {
maxLen = dp[i]
}
}
}
return strings[strings.count - maxLen]
}
```
### 解法四:动态规划(空间优化)
```swift
// Dynamic programming
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLen = 0
var dp = [Int](repeating: 0, count: strings.count)
for i in 0..<strings.count {
dp[i] = strings[i].count
if i == 0 {
maxLen = dp[i]
} else {
if dp[i] > maxLen {
maxLen = dp[i]
}
}
}
return strings[strings.count - maxLen]
}
```
### 解法五:动态规划(空间优化)
```swift
// Dynamic programming
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLen = 0
var maxLenString = ""
for string in strings {
let len = string.count
if len > maxLen {
maxLen = len
maxLenString = string
}
}
return maxLenString
}
```
### 解法六:动态规划(空间优化)
```swift
// Dynamic programming
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var maxLen = 0
var maxLenString = ""
for string in strings {
let len = string.count
if len > maxLen {
maxLen = len
maxLenString = string
}
}
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? { // invalid redeclaration of 'longest(strings:)'
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings[1...] {
if string.count > longest.count {
longest = string
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings[1...] {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for s in strings {
if s.count > longest.count {
longest = s
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for s in strings {
if s.count > longest.count {
longest = s
}
}
return longest
}
```
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else {
return nil
}
var maxLength = 0
var maxString = ""
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else {
return nil
}
var maxLength = 0
var maxString = ""
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else { return nil }
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
}
}
return longest
}
```
```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"]) == "
func longest(strings: [String]) -> String? {
guard strings.count > 0 else {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
} else if string.count == longest.count {
longest = min(longest, string)
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard strings.count > 0 else {
return nil
}
var longest = strings[0]
for string in strings {
if string.count > longest.count {
longest = string
} else if string.count == longest.count {
longest = min(longest, string)
}
}
return longest
}
```
// XCTAssertTrue failed
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var maxLength = 0
var maxString: String?
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```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 maxLength = 0
var maxString: String?
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```
func longest(strings: [String]) -> String? {
if strings.isEmpty {
return nil
}
var maxLength = 0
var maxString = ""
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```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 maxLength = 0
var maxString = ""
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```
### 解法二
```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 maxLength = 0
var maxString = ""
for string in strings {
if string.count > maxLength {
maxLength = string.count
maxString = string
}
}
return maxString
}
```
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else {
return nil
}
var longest = strings.first!
for string in strings[1..<strings.count] {
if string.count > longest.count {
longest = string
} else if string.count == longest.count {
longest = string < longest ? string : longest
}
}
return longest
}
```swift
// Out of array of strings, return the longest one. Return the first one in case of multiple
// strings of the same length. Return nil in case the input array is empty.
// longest(strings: [] as [String]) == nil
// longest(strings: ["a", "b", "c"]) == "a"
// longest(strings: ["a", "bb", "ccc"]) == "ccc"
func longest(strings: [String]) -> String? {
guard !strings.isEmpty else {
return nil
}
var longest = strings.first!
for string in strings[1..<strings.count] {
if string.count > longest.count {
longest = string
} else if string.count == longest.count {
longest = string < longest ? string : longest
}
}
return longest
}
```
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a - b)
}
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b & -b, b: a & -a)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法二:辗转相除法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法三:欧几里得算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法四:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a - b)
}
```
### 解法五:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b & -b, b: a & -a)
}
```
### 解法六:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a - b)
}
```
### 解法七:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b & -b, b: a & -a)
}
```
### 解法八:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a - b)
}
```
### 解法九:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) ==
func greatestCommonDivisor(a: Int, b: Int) -> Int { // invalid redeclaration of 'greatestCommonDivisor(a:b:)'
func greatestCommonDivisor(a: Int, b: Int) -> Int { // invalid redeclaration of 'greatestCommonDivisor(a:b:)'
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a - b)
}
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
if a % 2 == 0 && b % 2 == 0 {
return 2 * greatestCommonDivisor(a: a / 2, b: b / 2)
}
if a % 3 == 0 && b % 3 == 0 {
return 3 * greatestCommonDivisor(a: a / 3, b: b / 3)
}
return greatestCommonDivisor(a: b, b: a % b)
}
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
if a % 2 == 0 && b % 2 == 0 {
return 2 * greatestCommonDivisor(a: a / 2, b: b / 2)
}
if a % 3 == 0 && b % 3 == 0 {
return 3 * greatestCommonDivisor(a: a / 3, b: b / 3)
}
if a % 5 == 0 && b % 5 == 0 {
return 5 * greatestCommonDivisor(a: a / 5, b: b / 5)
}
return greatestCommonDivisor(a: b, b: a % b)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法二:欧几里得算法
欧几里得算法又称辗转相除法,是求两个数的最大公约数的一种方法。
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法三:更相减损术
更相减损术是求两个数的最大公约数的一种方法。
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a - b)
}
```
### 解法四:Stein算法
Stein算法是求两个数的最大公约数的一种方法。
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
if a % 2 == 0 && b % 2 == 0 {
return 2 * greatestCommonDivisor(a: a / 2, b: b / 2)
}
if a % 3 == 0 && b % 3 == 0 {
return 3 * greatestCommonDivisor(a: a / 3, b: b / 3)
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法五:Legendre算法
Legendre算法是求两个数的最大公约数的一种方法。
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
if a % 2 == 0 && b % 2 == 0 {
return 2 * greatestCommonDivisor(a: a / 2, b: b / 2)
}
if a % 3 == 0 && b % 3 == 0 {
return 3 * greatestCommonDivisor(a: a / 3, b: b / 3)
}
if a % 5 == 0 && b % 5 == 0 {
return 5 * greatestCommonDivisor(a: a / 5, b: b / 5)
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法六:欧拉算法
欧拉算法是求
func greatestCommonDivisor(a: Int, b: Int) -> Int { // invalid redeclaration of 'greatestCommonDivisor(a:b:)'
func greatestCommonDivisor(a: Int, b: Int) -> Int { // invalid redeclaration of 'greatestCommonDivisor(a:b:)'
func greatestCommonDivisor(a: Int, b: Int) -> Int { // invalid redeclaration of 'greatestCommonDivisor(a:b:)'
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法二:辗转相除法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法三:欧几里得算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法四:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法五:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法六:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法七:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法八:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 解法九:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
class Solution {
func isUgly(_ num: Int) -> Bool {
if num <= 0 {
return false
}
var num = num
while num % 2 == 0 {
num /= 2
}
while num % 3 == 0 {
num /= 3
}
while num % 5 == 0 {
num /= 5
}
return num == 1
}
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 代码
```swift
class Solution {
func isUgly(_ num: Int) -> Bool {
if num <= 0 {
return false
}
var num = num
while num % 2 == 0 {
num /= 2
}
while num % 3 == 0 {
num /= 3
}
while num % 5 == 0 {
num /= 5
}
return num == 1
}
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法二
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法三
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法四
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法五
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法六
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法七
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b
func greatestCommonDivisor(a: Int, b: Int) -> Int {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法二:辗转相除法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法三:欧几里得算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法四:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法五:Stein's Algorithm
```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 {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法六:Stein's Algorithm
```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 {
guard a > 0, b > 0 else {
return 1
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法七:Stein's Algorithm
```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
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法二:辗转相除法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法三:欧几里得算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法四:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法五:Stein算法
```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
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法六:Stein算法
```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
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法七:Stein算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDiv
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
class Solution {
func isUgly(_ num: Int) -> Bool {
if num == 0 {
return false
}
var num = num
while num % 5 == 0 {
num /= 5
}
while num % 3 == 0 {
num /= 3
}
while num % 2 == 0 {
num /= 2
}
return num == 1
}
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a < b {
return greatestCommonDivisor(a: b, b: a)
}
if b == 0 {
return a
}
return greatestCommonDivisor(a: b, b: a % b)
}
```
### 代码
```swift
class Solution {
func isUgly(_ num: Int) -> Bool {
if num == 0 {
return false
}
var num = num
while num % 5 == 0 {
num /= 5
}
while num % 3 == 0 {
num /= 3
}
while num % 2 == 0 {
num /= 2
}
return num == 1
}
}
```
func greatestCommonDivisor(a: Int, b: Int) -> Int {
guard a > 0, b > 0 else { return 1 }
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
class Solution {
func isUgly(_ num: Int) -> Bool {
guard num > 0 else { return false }
var num = num
while num % 5 == 0 {
num /= 5
}
while num % 3 == 0 {
num /= 3
}
while num % 2 == 0 {
num /= 2
}
return num == 1
}
}
```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 {
guard a > 0, b > 0 else { return 1 }
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 代码
```swift
class Solution {
func isUgly(_ num: Int) -> Bool {
guard num > 0 else { return false }
var num = num
while num % 5 == 0 {
num /= 5
}
while num % 3 == 0 {
num /= 3
}
while num % 2 == 0 {
num /= 2
}
return num == 1
}
}
```
// XCTAssertTrue failed
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法二:辗转相除法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法三:欧几里得算法
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法四:更相减损术
```swift
// Return a greatest common divisor of two integers a and b
// greatestCommonDivisor(a: 3, b: 5) == 1
// greatestCommonDivisor(a: 25, b: 15) == 5
func greatestCommonDivisor(a: Int, b: Int) -> Int {
if a == 0 {
return b
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法五:Stein's algorithm
```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
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法六:Copeland's algorithm
```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
}
if b == 0 {
return a
}
if a > b {
return greatestCommonDivisor(a: a - b, b: b)
} else {
return greatestCommonDivisor(a: b - a, b: a)
}
}
```
### 解法七:Stein's algorithm
```swift
// Return a greatest common divisor of two integers a
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
return allPrefixesRecursive(string: string, prefixes: &prefixes)
}
func allPrefixesRecursive(string: String, prefixes: inout [String]) -> [String] {
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
return allPrefixesRecursive(string: string, prefixes: &prefixes, cache: [String: [String]]())
}
func allPrefixesRecursive(string: String, prefixes: inout [String], cache: inout [String: [String]]) -> [String] {
if let cached = cache[string] {
return cached
}
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
cache[string] = prefixes
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
```
### 解法二:动态规划
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
```
### 解法三:递归
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
return allPrefixesRecursive(string: string, prefixes: &prefixes)
}
func allPrefixesRecursive(string: String, prefixes: inout [String]) -> [String] {
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
```
### 解法四:递归 + 缓存
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
return allPrefixesRecursive(string: string, prefixes: &prefixes, cache: [String: [String]]())
}
func allPrefixesRecursive(string: String, prefixes: inout [String], cache: inout [String: [String]]) -> [String] {
if let cached = cache[string] {
return cached
}
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
cache[string] = prefixes
return prefixes
}
```
### 解法五:递归 + 缓存 + 迭代
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
return allPrefixesRecursive(string: string, prefixes: &prefixes, cache: [String: [String]]())
}
func allPrefixesRecursive(string: String, prefixes: inout [String], cache: inout [String: [String]]) -> [String] {
if let cached = cache[string] {
return cached
}
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
cache[string] = prefixes
return prefixes
}
```
### 解法六:
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
return allPrefixesRecursive(string: string, prefixes: &prefixes, cache: [String: [String]]()) // cannot pass immutable value as inout argument: function call returns immutable value
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(contentsOf: prefixes.map { $0 + String(char) })
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
### 解法二:动态规划
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var newPrefixes = [String]()
for prefix in prefixes {
newPrefixes.append(prefix + String(char))
}
prefixes.append(contentsOf: newPrefixes)
}
return prefixes
}
```
### 解法三:递归
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(contentsOf: prefixes.map { $0 + String(char) })
}
return prefixes
}
```
prefixes.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var temp = [String]()
for pre in prefixes {
temp.append(pre + String(char))
}
prefixes.append(contentsOf: temp)
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
var temp = [String]()
for pre in prefixes {
temp.append(pre + String(char))
}
prefixes.append(contentsOf: temp)
}
return prefixes
}
```
### 解法二
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法三
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法四
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法五
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法六
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法七
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法八
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append("")
for char in string {
prefixes.append(prefixes.last! + String(char))
}
return prefixes
}
```
### 解法九
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allP
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(string.suffix(i + 1))
}
return suffixes
}
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
substrings.append(string.substring(i, j + 1))
}
}
return substrings
}
func longestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(j, i + 1))
}
}
return substrings
}
func shortestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(j, i + 1))
}
}
return substrings
}
func shortestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(i, j + 1))
}
}
return substrings
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
```swift
// Return array of all suffixes from shortest to longest of the input string
// allSuffixes(string: "abc") == ["c", "bc", "ab", "abc"]
func allSuffixes(string: String) -> [String] {
var suffixes = [String]()
for i in 0..<string.count {
suffixes.append(string.suffix(i + 1))
}
return suffixes
}
```
```swift
// Return array of all substrings from shortest to longest of the input string
// allSubstrings(string: "abc") == ["a", "b", "c", "ab", "bc", "abc"]
func allSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in 0..<string.count {
substrings.append(string.substring(i, j + 1))
}
}
return substrings
}
```
```swift
// Return array of all substrings from longest to shortest of the input string
// longestSubstrings(string: "abc") == ["abc", "bc", "ab", "c"]
func longestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(j, i + 1))
}
}
return substrings
}
```
```swift
// Return array of all substrings from shortest to longest of the input string
// shortestSubstrings(string: "abc") == ["a", "ab", "abc"]
func shortestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(j, i + 1))
}
}
return substrings
}
```
```swift
// Return array of all substrings from longest to shortest of the input string
// shortestSubstrings(string: "abc") == ["abc", "bc", "ab"]
func shortestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(i, j + 1))
}
}
return substrings
}
```
```swift
// Return array of all substrings from shortest to longest of the input string
// shortestSubstrings(string: "abc") == ["a", "ab", "abc"]
func shortestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(j, i + 1))
}
}
return substrings
}
```
```swift
// Return array of all substrings from shortest to longest of the input string
// shortestSubstrings(string: "abc") == ["a", "ab", "abc"]
func shortestSubstrings(string: String) -> [String] {
var substrings = [String]()
for i in 0..<string.count {
for j in (0...i).reversed() {
substrings.append(string.substring(j, i + 1))
}
}
return substrings
}
```
```sw
prefixes.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
suffixes.append(string.suffix(i + 1)) // no exact matches in call to instance method 'append'
substrings.append(string.substring(i, j + 1)) // no exact matches in call to instance method 'substring'
substrings.append(string.substring(j, i + 1)) // no exact matches in call to instance method 'substring'
substrings.append(string.substring(j, i + 1)) // no exact matches in call to instance method 'substring'
func shortestSubstrings(string: String) -> [String] { // invalid redeclaration of 'shortestSubstrings(string:)'
substrings.append(string.substring(i, j + 1)) // no exact matches in call to instance method 'substring'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
guard strs.count > 0 else {
return ""
}
let shortest = strs.min()!
let shortestLength = shortest.count
let allPrefixes = allPrefixes(string: shortest)
for i in 0..<allPrefixes.count {
let prefix = allPrefixes[i]
for str in strs {
if !str.hasPrefix(prefix) {
return String(prefix.prefix(i))
}
}
}
return String(shortest)
}
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
```
### 代码
```swift
class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
guard strs.count > 0 else {
return ""
}
let shortest = strs.min()!
let shortestLength = shortest.count
let allPrefixes = allPrefixes(string: shortest)
for i in 0..<allPrefixes.count {
let prefix = allPrefixes[i]
for str in strs {
if !str.hasPrefix(prefix) {
return String(prefix.prefix(i))
}
}
}
return String(shortest)
}
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
}
```
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
let shortestLength = shortest.count // initialization of immutable value 'shortestLength' was never used; consider replacing with assignment to '_' or removing it
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
func allPrefixes(string: String) -> [String] {
var result = [String]()
result.append(string)
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
func allPrefixes(string: String) -> [String] {
var result = [String]()
result.append(string)
var i = 0
while i < string.count {
result.append(string.prefix(i + 1))
i += 1
}
return result
}
func allPrefixes(string: String) -> [String] {
let regex = "^(.+)"
let matches = try! regex.matches(in: string, range: Range(string.startIndex...))
var result = [String]()
for match in matches {
result.append(string[match.range])
}
return result
}
func allPrefixes(string: String) -> [String] {
let regex = "^(.+)"
let matches = regex.allMatches(in: string)
var result = [String]()
for match in matches {
result.append(string[match.range])
}
return result
}
func allPrefixes(string: String) -> [String] {
let regex = "^(.+)"
let matches = regex.allMatches(in: string)
return matches.map { string[$0.range] }
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
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]()
result.append(string)
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
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]()
result.append(string)
var i = 0
while i < string.count {
result.append(string.prefix(i + 1))
i += 1
}
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] {
let regex = "^(.+)"
let matches = try! regex.matches(in: string, range: Range(string.startIndex...))
var result = [String]()
for match in matches {
result.append(string[match.range])
}
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] {
let regex = "^(.+)"
let matches = regex.allMatches(in: string)
var result = [String]()
for match in matches {
result.append(string[match.range])
}
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] {
let regex = "^(.+)"
let matches = regex.allMatches(in: string)
return matches.map { string[$0.range] }
}
```
### 解法七:正则表达式
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
let regex = "^(.+)"
let matches = regex.allMatches(in: string)
return matches.map { string[$0.range] }
}
```
### 解法八:正则表达式
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
let regex = "^(.+)"
let matches = regex.allMatches(in: string)
return matches.map { string[$0.range] }
}
```
### 解法九:正则表达式
```swift
// Return array of all prefixes from shortest to longest of the input string
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
let matches = try! regex.matches(in: string, range: Range(string.startIndex...)) // cannot convert value of type 'PartialRangeFrom<String.Index>' to expected argument type 'NSRange' (aka '_NSRange')
let matches = try! regex.matches(in: string, range: Range(string.startIndex...)) // extra arguments at positions #1, #2 in call
let matches = try! regex.matches(in: string, range: Range(string.startIndex...)) // missing argument for parameter 'of' in call
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
let matches = regex.allMatches(in: string) // value of type 'String' has no member 'allMatches'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
let matches = regex.allMatches(in: string) // value of type 'String' has no member 'allMatches'
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
func allPrefixes(string: String) -> [String] {
var result = [String]()
result.append(string)
if string.count > 1 {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
return result
}
func allPrefixes(string: String) -> [String] {
var result = [String]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
return result
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
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]()
result.append(string)
if string.count > 1 {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
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]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
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]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
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]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
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]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
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]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
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]()
result.append(string)
for i in 1..<string.count {
result.append(contentsOf: allPrefixes(string: String(string.dropFirst())))
}
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
for i in 1..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
prefixes.append(contentsOf: allPrefixes(string: string.substring(from: 1, length: string.count - 1)))
return prefixes
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
### 解法二:动态规划
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
for i in 1..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
### 解法三:递归
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
prefixes.append(contentsOf: allPrefixes(string: string.substring(from: 1, length: string.count - 1)))
return prefixes
}
```
### 解法四:递归 + 缓存
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
prefixes.append(contentsOf: allPrefixes(string: string.substring(from: 1, length: string.count - 1)))
return prefixes
}
// 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]()
prefixes.append(string.prefix(1))
prefixes.append(contentsOf: allPrefixes(string: string.substring(from: 1, length: string.count - 1)))
return prefixes
}
```
### 解法五:迭代
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
for i in 1..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
### 解法六:迭代 + 缓存
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
for i in 1..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
### 解法七:迭代 + 缓存 + 迭代
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
prefixes.append(string.prefix(1))
for i in 1..<string.count {
prefixes.append(string.prefix(i + 1))
}
prefixes.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
prefixes.append(string.prefix(1)) // no exact matches in call to instance method 'append'
prefixes.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
func allPrefixes(string: String) -> [String] { // invalid redeclaration of 'allPrefixes(string:)'
prefixes.append(string.prefix(1)) // no exact matches in call to instance method 'append'
prefixes.append(contentsOf: allPrefixes(string: string.substring(from: 1, length: string.count - 1))) // extra argument 'length' in call
prefixes.append(contentsOf: allPrefixes(string: string.substring(from: 1, length: string.count - 1))) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
guard strs.count > 0 else {
return ""
}
let first = strs[0]
let prefixes = allPrefixes(string: first)
for str in strs {
for prefix in prefixes {
if !str.hasPrefix(prefix) {
prefixes.remove(at: prefixes.firstIndex(of: prefix)!)
}
}
}
return prefixes.last!
}
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var prefixes = [String]()
for i in 0..<string.count {
prefixes.append(string.prefix(i + 1))
}
return prefixes
}
```
### 解题思路
### 代码
```swift
class Solution {
func longestCommonPrefix(_ strs: [String]) -> String {
guard strs.count > 0 else {
return ""
}
let first = strs[0]
let prefixes = allPrefixes(string: first)
for str in strs {
for prefix in prefixes {
if !str.hasPrefix(prefix) {
prefixes.remove(at: prefixes.firstIndex(of: prefix)!)
}
}
}
return prefixes.last!
}
}
```
prefixes.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
prefixes.remove(at: prefixes.firstIndex(of: prefix)!) // cannot use mutating member on immutable value: 'prefixes' is a 'let' constant
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
class Solution {
func findSubstringInWraproundString(_ p: String) -> Int {
var dic = [Character: Int]()
var count = 0
for i in 0..<p.count {
let c = p[p.index(p.startIndex, offsetBy: i)]
if i > 0, p[p.index(p.startIndex, offsetBy: i - 1)] + 1 == c {
count += 1
} else {
count = 1
}
dic[c] = max(dic[c] ?? 0, count)
}
return dic.values.reduce(0, +)
}
}
```swift
// Return array of all prefixes from shortest to longest of the input string
// allPrefixes(string: "abc") == ["a", "ab", "abc"]
func allPrefixes(string: String) -> [String] {
var result = [String]()
for i in 0..<string.count {
result.append(string.prefix(i + 1))
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func findSubstringInWraproundString(_ p: String) -> Int {
var dic = [Character: Int]()
var count = 0
for i in 0..<p.count {
let c = p[p.index(p.startIndex, offsetBy: i)]
if i > 0, p[p.index(p.startIndex, offsetBy: i - 1)] + 1 == c {
count += 1
} else {
count = 1
}
dic[c] = max(dic[c] ?? 0, count)
}
return dic.values.reduce(0, +)
}
}
```
result.append(string.prefix(i + 1)) // no exact matches in call to instance method 'append'
if i > 0, p[p.index(p.startIndex, offsetBy: i - 1)] + 1 == c { // binary operator '==' cannot be applied to operands of type 'Int' and 'Character'
if i > 0, p[p.index(p.startIndex, offsetBy: i - 1)] + 1 == c { // cannot convert value of type 'Character' to expected argument type 'Int'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
func stringSequence(n: Int) -> String {
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```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"
}
return stringSequence(n - 1) + " " + String(n)
}
```
### 解法三:迭代
```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 = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
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 {
if n == 0 {
return "0"
}
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
func stringSequence(_ n: Int
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + String(n) // missing argument label 'n:' in call
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
func stringSequence(n: Int) -> String {
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
yield result
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
var result = [String]()
var i = 0
while i <= n {
result.append(String(i))
i += 1
}
return result.joined(separator: " ")
}
func stringSequence(n: Int) -> String {
var result = [String]()
var i = 0
while i <= n {
result.append(String(i))
yield result.joined(separator: " ")
i += 1
}
return result.joined(separator: " ")
}
func stringSequence(n: Int) -> String {
var result = [String]()
var i = 0
while i <= n {
result.append(String(i))
yield result
i += 1
}
return result.joined(separator: " ")
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
```
### 解法三:迭代
```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 = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
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 = ""
var i = 0
while i <= n {
result += String(i) + " "
yield result
i += 1
}
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 = [String]()
var i = 0
while i <= n {
result.append(String(i))
i += 1
}
return result.joined(separator: " ")
}
```
### 解法六:数组 + 生成器
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = [String]()
var i = 0
while i <= n {
result.append(String(i))
yield result.joined(separator: " ")
i += 1
}
return result.joined(separator: " ")
}
```
### 解法七:数组 + 数组生成器
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = [String]()
var i = 0
while i <= n {
result.append(String(i))
yield result
i += 1
}
return result.joined(separator: " ")
}
```
### 解法八:数组 + 数组生成器 + 数组
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + String(n) // missing argument label 'n:' in call
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
yield result // consecutive statements on a line must be separated by ';'
yield result // variable is unused
yield result // cannot find 'yield' in scope
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
yield result.joined(separator: " ") // result of call to 'joined(separator:)' is unused
yield result.joined(separator: " ") // cannot find 'yield' in scope
yield result.joined(separator: " ") // consecutive statements on a line must be separated by ';'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
yield result // consecutive statements on a line must be separated by ';'
yield result // cannot find 'yield' in scope
yield result // variable is unused
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
func stringSequence(n: Int) -> String {
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " "
stringSequence(n - 1, &result)
}
var result = ""
stringSequence(n, &result)
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```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"
}
return stringSequence(n - 1) + " " + String(n)
}
```
### 解法三:迭代
```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 = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
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 {
if n == 0 {
return "0"
}
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " "
stringSequence(n - 1, &result)
}
var result = ""
stringSequence(n, &result)
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " "
stringSequence(n - 1, &result)
}
var result = ""
stringSequence(n, &result)
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " "
stringSequence
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + String(n) // missing argument label 'n:' in call
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n: n - 1) + " " + "\(n)"
}
```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
}
```
### 解法二:递归
```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"
}
return stringSequence(n: n - 1) + " " + "\(n)"
}
```
### 解法三:迭代
```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
}
```
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
let result = stringSequence(n: n - 1)
return result + " " + String(n)
}
func stringSequence(n: Int) -> String {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
return result
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```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"
}
let result = stringSequence(n: n - 1)
return result + " " + String(n)
}
```
### 解法三:迭代
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法四:递归 + 迭代
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法五:尾递归
```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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
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 {
func stringSequence(_ n: Int, _ result: inout String) {
if n == 0 {
result += "0"
return
}
stringSequence(n - 1, &result)
result += " " + String(n)
}
var result = ""
stringSequence(n, &result)
return result
}
```
### 解法八:尾递归 + 迭代
``
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n: n - 1) + " " + String(n)
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```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"
}
return stringSequence(n: n - 1) + " " + String(n)
}
```
### 解法三:迭代
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法四:生成器
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法五:数组
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法六:数组 + 生成器
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法七:数组 + 数组
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法八:数组 + 数组 + 数组
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法九:数组 + 数组 + 数组 + 数组
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += "\(i) "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + "\(n)"
}
func stringSequence(n: Int) -> String {
return stringSequenceHelper(n, String())
}
func stringSequenceHelper(_ n: Int, _ result: String) -> String {
if n == 0 {
return result + "0"
}
return stringSequenceHelper(n - 1, result + "\(n) ")
}
```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
}
```
### 解法二:递归
```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"
}
return stringSequence(n - 1) + " " + "\(n)"
}
```
### 解法三:尾递归
```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 stringSequenceHelper(n, String())
}
func stringSequenceHelper(_ n: Int, _ result: String) -> String {
if n == 0 {
return result + "0"
}
return stringSequenceHelper(n - 1, result + "\(n) ")
}
```
### 解法四:尾递归优化
```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 stringSequenceHelper(n, String())
}
func stringSequenceHelper(_ n: Int, _ result: String) -> String {
if n == 0 {
return result + "0"
}
return stringSequenceHelper(n - 1, result + "\(n) ")
}
// 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 stringSequenceHelper(n, String())
}
func stringSequenceHelper(_ n: Int, _ result: String) -> String {
if n == 0 {
return result + "0"
}
return stringSequenceHelper(n - 1, result + "\(n) ")
}
```
### 解法五:尾递归优化
```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 stringSequenceHelper(n, String())
}
func stringSequenceHelper(_ n: Int, _ result: String) -> String {
if n == 0 {
return result + "0"
}
return stringSequenceHelper(n - 1, result + "\(n) ")
}
// 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 stringSequenceHelper(n, String())
}
func stringSequenceHelper(_ n: Int, _ result: String) -> String {
if n == 0 {
return result + "0"
}
return stringSequenceHelper(n - 1, result + "\(n) ")
}
```
### 解法六:尾递归优化
```swift
// Return a string containing space-delimited numbers starting from 0 upto
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + "\(n)" // missing argument label 'n:' in call
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
func stringSequence(n: Int) -> String {
var result = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
func stringSequence(n: Int) -> String {
var result = [String]()
for i in 0...n {
result.append(String(i))
}
return result.joined(separator: " ")
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
```
### 解法三:迭代
```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 = ""
var i = 0
while i <= n {
result += String(i) + " "
i += 1
}
return result
}
```
### 解法四:生成器
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法五:数组
```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 = [String]()
for i in 0...n {
result.append(String(i))
}
return result.joined(separator: " ")
}
```
### 解法六:数组 + reduce
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
return [0, 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
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + String(n) // missing argument label 'n:' in call
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 方法二:递归
```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"
}
return stringSequence(n - 1) + " " + String(n)
}
```
### 方法三:迭代
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + String(n) // missing argument label 'n:' in call
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
func stringSequence(n: Int) -> String {
if n == 0 {
return "0"
}
return stringSequence(n - 1) + " " + String(n)
}
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法二:递归
```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"
}
return stringSequence(n - 1) + " " + String(n)
}
```
### 解法三:循环
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法四:递归 + 循环
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法五:循环 + 递归
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法六:循环 + 循环
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法七:循环 + 递归 + 循环
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法八:循环 + 循环 + 循环
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0) == "0"
// stringSequence(n: 5) == "0 1 2 3 4 5"
func stringSequence(n: Int) -> String {
var result = ""
for i in 0...n {
result += String(i) + " "
}
return result
}
```
### 解法九:循环 + 循环 + 递归
```swift
// Return a string containing space-delimited numbers starting from 0 upto n inclusive.
// stringSequence(n: 0
func stringSequence(n: Int) -> String { // invalid redeclaration of 'stringSequence(n:)'
return stringSequence(n - 1) + " " + String(n) // missing argument label 'n:' in call
func countDistinctCharacters(string: String) -> Int {
let array = Array(string)
var set = Set<Character>()
for c in array {
set.insert(c)
}
return set.count
}
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
let array = Array(string)
var set = Set<Character>()
for c in array {
set.insert(c)
}
return set.count
}
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let array = Array(string)
var set = Set<Character>()
for c in array {
set.insert(c)
}
return set.count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
let array = Array(string)
var set = Set<Character>()
for c in array {
set.insert(c)
}
return set.count
}
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var map = [Character: Int]()
for char in string {
map[char, default: 0] += 1
}
return map.count
}
func countDistinctCharacters(string: String) -> Int {
let chars = Array(string)
chars.sort()
var prev = chars[0]
var count = 1
for char in chars[1..<chars.count] {
if char == prev {
continue
}
prev = char
count += 1
}
return count
}
func countDistinctCharacters(string: String) -> Int {
var count = [Int](repeating: 0, count: 26)
for char in string {
count[Int(char.asciiValue!) - 97] += 1
}
var result = 0
for num in count {
result += num
}
return result
}
func countDistinctCharacters(string: String) -> Int {
var mask = 0
var count = 0
for char in string {
let index = Int(char.asciiValue!) - 97
if mask & (1 << index) == 0 {
mask |= (1 << index)
count += 1
}
}
return count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var map = [Character: Int]()
for char in string {
map[char, default: 0] += 1
}
return map.count
}
```
### 解法二:排序
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let chars = Array(string)
chars.sort()
var prev = chars[0]
var count = 1
for char in chars[1..<chars.count] {
if char == prev {
continue
}
prev = char
count += 1
}
return count
}
```
### 解法三:计数
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = [Int](repeating: 0, count: 26)
for char in string {
count[Int(char.asciiValue!) - 97] += 1
}
var result = 0
for num in count {
result += num
}
return result
}
```
### 解法四:位运算
```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 mask = 0
var count = 0
for char in string {
let index = Int(char.asciiValue!) - 97
if mask & (1 << index) == 0 {
mask |= (1 << index)
count += 1
}
}
return count
}
```
### 解法五:位运算优化
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var mask = 0
var count = 0
for char in string {
let index = Int(char.asciiValue!) - 97
if mask & (1 << index) == 0 {
mask |= (1 << index)
count += 1
}
}
return count
}
```
### 解法六:位运算优化
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var mask = 0
var count = 0
for char in string {
let index = Int(char.asciiValue!) - 97
if mask & (1 << index) == 0 {
mask |= (1 << index)
count += 1
}
}
return count
}
```
### 解法七:位运算优化
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var mask = 0
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
chars.sort() // cannot use mutating member on immutable value: 'chars' is a 'let' constant
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
func countDistinctCharacters(string: String) -> Int {
let array = Array(string)
var map = [Character: Int]()
for char in array {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
let array = Array(string)
var map = [Character: Int]()
for char in array {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
let array = Array(string)
var map = [Character: Int]()
for char in array {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
let array = Array(string)
var map = [Character: Int]()
for char in array {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
}
```
// XCTAssertTrue failed
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
}
class Solution {
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
}
}
```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
}
```
### 解题思路
### 代码
```swift
class Solution {
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
}
}
```
// XCTAssertTrue failed
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
}
class Solution {
func countDistinctCharacters(_ s: String) -> Int {
var count = 0
var charSet = Set<Character>()
for char in s {
if !charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var charSet = Set<Character>()
for char in string {
if !charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countDistinctCharacters(_ s: String) -> Int {
var count = 0
var charSet = Set<Character>()
for char in s {
if !charSet.contains(char) {
charSet.insert(char)
count += 1
}
}
return count
}
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var map = [Character: Int]()
for c in string {
map[c, default: 0] += 1
}
return map.count
}
func countDistinctCharacters(string: String) -> Int {
var chars = Array(string)
chars.sort()
var prev = chars[0]
var count = 1
for c in chars[1..<chars.count] {
if c != prev {
count += 1
prev = c
}
}
return count
}
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for c in string {
map[c, default: 0] += 1
if map[c] == 1 {
count += 1
}
}
return count
}
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for c in string {
let index = Int(c.asciiValue!) - 97
if map[c, default: 0] == 0 {
count += 1
}
map[c] = 1 << index
}
return count
}
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for c in string {
let index = Int(c.asciiValue!) - 97
if map[c] == nil {
count += 1
}
map[c] = map[c]?.bitwiseOr(1 << index) ?? (1 << index)
}
return count
}
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for c in string {
let index = Int(c.asciiValue!) - 97
if map[c] == nil {
count += 1
} else if map[c]! & (1 << index) == 0 {
count += 1
}
map[c] = map[c]?.bitwiseOr(1 << index) ?? (1 << index)
}
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 map = [Character: Int]()
for c in string {
map[c, default: 0] += 1
}
return map.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 chars = Array(string)
chars.sort()
var prev = chars[0]
var count = 1
for c in chars[1..<chars.count] {
if c != prev {
count += 1
prev = c
}
}
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 map = [Character: Int]()
for c in string {
map[c, default: 0] += 1
if map[c] == 1 {
count += 1
}
}
return count
}
```
### 解法四:位运算
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for c in string {
let index = Int(c.asciiValue!) - 97
if map[c, default: 0] == 0 {
count += 1
}
map[c] = 1 << index
}
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 map = [Character: Int]()
for c in string {
let index = Int(c.asciiValue!) - 97
if map[c] == nil {
count += 1
}
map[c] = map[c]?.bitwiseOr(1 << index) ?? (1 << index)
}
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 map = [Character: Int]()
for c in string {
let index = Int(c.asciiValue!) - 97
if map[c] == nil {
count += 1
} else if map[c]! & (1 << index) == 0 {
count += 1
}
map[c] = map[c]?.bitwiseOr(1 << index) ?? (1 << index)
}
return count
}
```
### 解法七:位运算优化
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinct
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
map[c] = map[c]?.bitwiseOr(1 << index) ?? (1 << index) // value of type 'Int' has no member 'bitwiseOr'
func countDistinctCharacters(string: String) -> Int { // invalid redeclaration of 'countDistinctCharacters(string:)'
map[c] = map[c]?.bitwiseOr(1 << index) ?? (1 << index) // value of type 'Int' has no member 'bitwiseOr'
func countDistinctCharacters(string: String) -> Int {
var count = 0
var set = Set<Character>()
for char in string {
if !set.contains(char) {
count += 1
set.insert(char)
}
}
return count
}
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
let array = Array(string)
var count = 0
var set = Set<Character>()
for char in array {
if !set.contains(char) {
count += 1
set.insert(char)
}
}
return count
}
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var set = Set<Character>()
for char in string {
if !set.contains(char) {
count += 1
set.insert(char)
}
}
return count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
let array = Array(string)
var count = 0
var set = Set<Character>()
for char in array {
if !set.contains(char) {
count += 1
set.insert(char)
}
}
return count
}
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for char in string {
if map[char] == nil {
count += 1
map[char] = 1
} else {
map[char]! += 1
}
}
return count
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var count = 0
var map = [Character: Int]()
for char in string {
if map[char] == nil {
count += 1
map[char] = 1
} else {
map[char]! += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var map = [Character: Int]()
for char in string {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
class Solution {
func countDistinctCharacters(_ s: String) -> Int {
var map = [Character: Int]()
for char in s {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.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 map = [Character: Int]()
for char in string {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countDistinctCharacters(_ s: String) -> Int {
var map = [Character: Int]()
for char in s {
if map[char] == nil {
map[char] = 1
} else {
map[char]! += 1
}
}
return map.count
}
}
```
// XCTAssertTrue failed
func countDistinctCharacters(string: String) -> Int {
var charSet = Set<Character>()
for char in string {
charSet.insert(char)
}
return charSet.count
}
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
var charSet = Set<Character>()
var result = 0
for char in string {
if charSet.contains(char) {
continue
}
charSet.insert(char)
result += 1
}
return result
}
}
```swift
// Given a string, find out how many distinct characters (regardless of case) does it consist of
// countDistinctCharacters(string: "xyzXYZ") == 3
// countDistinctCharacters(string: "Jerry") == 4
func countDistinctCharacters(string: String) -> Int {
var charSet = Set<Character>()
for char in string {
charSet.insert(char)
}
return charSet.count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countDistinctCharacters(_ string: String) -> Int {
var charSet = Set<Character>()
var result = 0
for char in string {
if charSet.contains(char) {
continue
}
charSet.insert(char)
result += 1
}
return result
}
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 }
var result = [Int]()
var currentNote = 0
var currentDuration = 0
for note in notes {
switch note {
case "o":
currentDuration = 4
case "o|":
currentDuration = 2
case ".|":
currentDuration = 1
default:
break
}
currentNote += currentDuration
result.append(currentNote)
}
return result
}
class Solution {
func parseMusic(_ musicString: String) -> [Int] {
var result = [Int]()
var currentNote = 0
var currentDuration = 0
for note in musicString {
switch note {
case "o":
currentDuration = 4
case "o|":
currentDuration = 2
case ".|":
currentDuration = 1
default:
break
}
currentNote += currentDuration
result.append(currentNote)
}
return result
}
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 }
var result = [Int]()
var currentNote = 0
var currentDuration = 0
for note in notes {
switch note {
case "o":
currentDuration = 4
case "o|":
currentDuration = 2
case ".|":
currentDuration = 1
default:
break
}
currentNote += currentDuration
result.append(currentNote)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func parseMusic(_ musicString: String) -> [Int] {
var result = [Int]()
var currentNote = 0
var currentDuration = 0
for note in musicString {
switch note {
case "o":
currentDuration = 4
case "o|":
currentDuration = 2
case ".|":
currentDuration = 1
default:
break
}
currentNote += currentDuration
result.append(currentNote)
}
return result
}
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
case ".|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
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 notes = [Int]()
var note = 0
for char in musicString {
switch char {
case "o":
note = 4
case "o|":
note = 2
case ".":
note = 1
default:
break
}
notes.append(note)
}
return notes
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
var notes = [Int]()
var note = 0
for char in musicString {
switch char {
case "o":
note = 4
case "o|":
note = 2
case ".":
note = 1
default:
break
}
notes.append(note)
}
return notes
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'Character'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 }
var result = [Int]()
var current = 0
for note in notes {
current += note
result.append(current)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 }
var result = [Int]()
var current = 0
for note in notes {
current += note
result.append(current)
}
return result
}
```
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 } // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func parseMusic(musicString: String) -> [Int] {
let musicArray = Array(musicString)
var result = [Int]()
var currentLength = 0
for char in musicArray {
if char == "o" {
result.append(4)
currentLength = 4
} else if char == "o|" {
result.append(2)
currentLength = 2
} else if char == ".|" {
result.append(1)
currentLength = 1
}
currentLength -= 1
if currentLength == 0 {
currentLength = 4
}
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let musicArray = Array(musicString)
var result = [Int]()
var currentLength = 0
for char in musicArray {
if char == "o" {
result.append(4)
currentLength = 4
} else if char == "o|" {
result.append(2)
currentLength = 2
} else if char == ".|" {
result.append(1)
currentLength = 1
}
currentLength -= 1
if currentLength == 0 {
currentLength = 4
}
}
return result
}
```
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 }
var result = [Int]()
var currentLength = 0
for note in notes {
switch note {
case "o":
currentLength = 4
case "o|":
currentLength = 2
case ".|":
currentLength = 1
default:
break
}
result.append(currentLength)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 }
var result = [Int]()
var currentLength = 0
for note in notes {
switch note {
case "o":
currentLength = 4
case "o|":
currentLength = 2
case ".|":
currentLength = 1
default:
break
}
result.append(currentLength)
}
return result
}
```
case "o|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
case ".|": // expression pattern of type 'String' cannot match values of type 'String.Element' (aka 'Character')
func parseMusic(musicString: String) -> [Int] {
let musicArray = Array(musicString)
var notes = [Int]()
var note = 0
for char in musicArray {
if char == "o" {
note = 4
} else if char == "o|" {
note = 2
} else if char == ".|" {
note = 1
}
notes.append(note)
}
return notes
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let musicArray = Array(musicString)
var notes = [Int]()
var note = 0
for char in musicArray {
if char == "o" {
note = 4
} else if char == "o|" {
note = 2
} else if char == ".|" {
note = 1
}
notes.append(note)
}
return notes
}
```
} else if char == "o|" { // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
} else if char == ".|" { // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 }
var result = [Int]()
var count = 0
for note in notes {
count += note
result.append(count)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 }
var result = [Int]()
var count = 0
for note in notes {
count += note
result.append(count)
}
return result
}
```
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 } // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { String($0) }
var result = [Int]()
var currentNote = 0
var currentNoteLength = 0
for note in notes {
if note == "o" {
currentNoteLength = 4
} else if note == "o|" {
currentNoteLength = 2
} else if note == ".|" {
currentNoteLength = 1
}
currentNote += currentNoteLength
result.append(currentNote)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { String($0) }
var result = [Int]()
var currentNote = 0
var currentNoteLength = 0
for note in notes {
if note == "o" {
currentNoteLength = 4
} else if note == "o|" {
currentNoteLength = 2
} else if note == ".|" {
currentNoteLength = 1
}
currentNote += currentNoteLength
result.append(currentNote)
}
return result
}
```
// XCTAssertTrue failed
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : $0 == "." ? 1 : 0 }
var result = [Int]()
var current = 0
for note in notes {
current += note
result.append(current)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : $0 == "." ? 1 : 0 }
var result = [Int]()
var current = 0
for note in notes {
current += note
result.append(current)
}
return result
}
```
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : $0 == "." ? 1 : 0 } // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 }
var result = [Int]()
var current = 0
for note in notes {
current += note
result.append(current)
}
return result
}
```swift
// Input to this function is a string representing musical notes in a special ASCII format.
// Your task is to parse this string and return array of integers corresponding to how many beats does each
// not last.
// Here is a legend:
// 'o' - whole note, lasts four beats
// 'o|' - half note, lasts two beats
// '.|' - quater note, lasts one beat
// parseMusic(musicString: "o o| .| o| o| .| .| .| .| o o") == [4, 2, 1, 2, 2, 1, 1, 1, 1, 4, 4]
func parseMusic(musicString: String) -> [Int] {
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 }
var result = [Int]()
var current = 0
for note in notes {
current += note
result.append(current)
}
return result
}
```
let notes = musicString.map { $0 == "o" ? 4 : $0 == "o|" ? 2 : 1 } // binary operator '==' cannot be applied to operands of type 'String.Element' (aka 'Character') and 'String'
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
for i in 0..<count {
if string[i] == substring[0] {
var j = i
var k = 0
while j < count && k < subCount && string[j] == substring[k] {
j += 1
k += 1
}
if k == subCount {
count += 1
}
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
for i in 0..<count {
if string[i] == substring[0] {
var j = i
var k = 0
while j < count && k < subCount && string[j] == substring[k] {
j += 1
k += 1
}
if k == subCount {
count += 1
}
}
}
return count
}
```
var count = 0 // invalid redeclaration of 'count'
func howManyTimes(string: String, substring: String) -> Int {
guard string.count > 0, substring.count > 0 else {
return 0
}
let count = string.count - substring.count + 1
var result = 0
for i in 0..<count {
result += string[i..<i+substring.count].contains(substring) ? 1 : 0
}
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 string.count > 0, substring.count > 0 else {
return 0
}
let count = string.count - substring.count + 1
var result = 0
for i in 0..<count {
result += string[i..<i+substring.count].contains(substring) ? 1 : 0
}
return result
}
```
result += string[i..<i+substring.count].contains(substring) ? 1 : 0 // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
if string.isEmpty || substring.isEmpty {
return 0
}
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
var start = 0
while start < count {
let index = string.index(string.startIndex, offsetBy: start)
let end = string.index(index, offsetBy: subCount)
let subString = string[index..<end]
if subString == substring {
count += 1
}
start += 1
}
return count
}
class Solution {
func countSubstrings(_ s: String, _ t: String) -> Int {
if s.isEmpty || t.isEmpty {
return 0
}
let count = s.count
let subCount = t.count
if count < subCount {
return 0
}
var count = 0
var start = 0
while start < count {
let index = s.index(s.startIndex, offsetBy: start)
let end = s.index(index, offsetBy: subCount)
let subString = s[index..<end]
if subString == t {
count += 1
}
start += 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 {
if string.isEmpty || substring.isEmpty {
return 0
}
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
var start = 0
while start < count {
let index = string.index(string.startIndex, offsetBy: start)
let end = string.index(index, offsetBy: subCount)
let subString = string[index..<end]
if subString == substring {
count += 1
}
start += 1
}
return count
}
```
### 解题思路
### 代码
```swift
class Solution {
func countSubstrings(_ s: String, _ t: String) -> Int {
if s.isEmpty || t.isEmpty {
return 0
}
let count = s.count
let subCount = t.count
if count < subCount {
return 0
}
var count = 0
var start = 0
while start < count {
let index = s.index(s.startIndex, offsetBy: start)
let end = s.index(index, offsetBy: subCount)
let subString = s[index..<end]
if subString == t {
count += 1
}
start += 1
}
return count
}
}
```
var count = 0 // invalid redeclaration of 'count'
var count = 0 // invalid redeclaration of 'count'
func howManyTimes(string: String, substring: String) -> Int {
guard string.count >= substring.count else {
return 0
}
let count = string.count - substring.count + 1
var result = 0
for i in 0..<count {
if string[i..<i + substring.count] == substring {
result += 1
}
}
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 string.count >= substring.count else {
return 0
}
let count = string.count - substring.count + 1
var result = 0
for i in 0..<count {
if string[i..<i + substring.count] == substring {
result += 1
}
}
return result
}
```
if string[i..<i + substring.count] == substring { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
guard string.count >= substring.count else { return 0 }
let count = string.count - substring.count + 1
var result = 0
for i in 0..<count {
if string[i..<i + substring.count] == substring {
result += 1
}
}
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 string.count >= substring.count else { return 0 }
let count = string.count - substring.count + 1
var result = 0
for i in 0..<count {
if string[i..<i + substring.count] == substring {
result += 1
}
}
return result
}
```
if string[i..<i + substring.count] == substring { // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
for i in 0..<count-subCount+1 {
if string[i..<i+subCount] == substring {
count += 1
}
}
return count
}
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
var j = 0
let next = getNext(substring)
for i in 0..<count {
while j > 0 && string[i] != substring[j] {
j = next[j-1]
}
if string[i] == substring[j] {
j += 1
}
if j == subCount {
count += 1
j = next[j-1]
}
}
return count
}
func getNext(_ string: String) -> [Int] {
let count = string.count
var next = [Int](repeating: 0, count: count)
next[0] = 0
var j = 0
for i in 1..<count {
while j > 0 && string[i] != string[j] {
j = next[j-1]
}
if string[i] == string[j] {
j += 1
}
next[i] = j
}
return next
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
for i in 0..<count-subCount+1 {
if string[i..<i+subCount] == substring {
count += 1
}
}
return count
}
```
### 解法二:滑动窗口
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
for i in 0..<count-subCount+1 {
if string[i..<i+subCount] == substring {
count += 1
}
}
return count
}
```
### 解法三:KMP
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
var count = 0
var j = 0
let next = getNext(substring)
for i in 0..<count {
while j > 0 && string[i] != substring[j] {
j = next[j-1]
}
if string[i] == substring[j] {
j += 1
}
if j == subCount {
count += 1
j = next[j-1]
}
}
return count
}
func getNext(_ string: String) -> [Int] {
let count = string.count
var next = [Int](repeating: 0, count: count)
next[0] = 0
var j = 0
for i in 1..<count {
while j > 0 && string[i] != string[j] {
j = next[j-1]
}
if string[i] == string[j] {
j += 1
}
next[i] = j
}
return next
}
```
### 解法四:Rabin-Karp
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let count = string.count
let subCount = substring.count
if count < subCount {
return 0
}
let prime = 1000000007
let base = 31
let hashValue = getHashValue(string, subCount)
let subHashValue = getHashValue(substring, subCount)
var count = 0
for i in 0..<count-subCount+1 {
if hashValue == subHashValue && string[i..<i+subCount] == substring {
count += 1
}
if i < count-subCount {
hashValue = (hashValue * base + string[i+subCount].wholeNumber
var count = 0 // invalid redeclaration of 'count'
func howManyTimes(string: String, substring: String) -> Int { // invalid redeclaration of 'howManyTimes(string:substring:)'
var count = 0 // invalid redeclaration of 'count'
while j > 0 && string[i] != string[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
while j > 0 && string[i] != string[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] == string[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if string[i] == string[j] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func howManyTimes(string: String, substring: String) -> Int {
guard string.count >= substring.count else {
return 0
}
var count = 0
for i in 0..<string.count {
let start = string.index(string.startIndex, offsetBy: i)
let end = string.index(string.startIndex, offsetBy: string.count - substring.count + i)
let subStr = string[start..<end]
if subStr == substring {
count += 1
}
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
guard string.count >= substring.count else {
return 0
}
var count = 0
for i in 0..<string.count {
let start = string.index(string.startIndex, offsetBy: i)
let end = string.index(string.startIndex, offsetBy: string.count - substring.count + i)
let subStr = string[start..<end]
if subStr == substring {
count += 1
}
}
return count
}
```
// Fatal error: String index is out of bounds
func howManyTimes(string: String, substring: String) -> Int {
let s = Array(string)
let sub = Array(substring)
var count = 0
var i = 0
var j = 0
while i < s.count {
if s[i] == sub[j] {
if j == sub.count - 1 {
count += 1
j = 0
} else {
j += 1
}
} else {
j = 0
}
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 {
let s = Array(string)
let sub = Array(substring)
var count = 0
var i = 0
var j = 0
while i < s.count {
if s[i] == sub[j] {
if j == sub.count - 1 {
count += 1
j = 0
} else {
j += 1
}
} else {
j = 0
}
i += 1
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
let s = Array(string)
let sub = Array(substring)
var count = 0
var i = 0
var j = 0
while i < s.count {
if s[i] == sub[j] {
if j == sub.count - 1 {
count += 1
j = 0
} else {
j += 1
}
} else {
j = 0
}
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 {
let s = Array(string)
let sub = Array(substring)
var count = 0
var i = 0
var j = 0
while i < s.count {
if s[i] == sub[j] {
if j == sub.count - 1 {
count += 1
j = 0
} else {
j += 1
}
} else {
j = 0
}
i += 1
}
return count
}
```
// XCTAssertTrue failed
func howManyTimes(string: String, substring: String) -> Int {
let s = Array(string)
let sub = Array(substring)
var count = 0
var start = 0
var end = 0
while start < s.count {
end = start
while end < s.count && s[end] == sub[0] {
end += 1
}
if end - start == sub.count {
count += 1
}
start = end
}
return count
}
```swift
// Find how many times a given substring can be found in the original string. Count overlaping cases.
// howManyTimes(string: "", substring: "a") == 0
// howManyTimes(string: "aaa", substring: "a") == 3
// howManyTimes(string: "aaaa", substring: "aa") == 3
func howManyTimes(string: String, substring: String) -> Int {
let s = Array(string)
let sub = Array(substring)
var count = 0
var start = 0
var end = 0
while start < s.count {
end = start
while end < s.count && s[end] == sub[0] {
end += 1
}
if end - start == sub.count {
count += 1
}
start = end
}
return count
}
```
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0.unicodeScalars.first!.value) }
return nums.sorted().joined(separator: " ")
}
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.unicodeScalars.first!.value < $1.unicodeScalars.first!.value }).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 nums = numbers.map { String($0.unicodeScalars.first!.value) }
return nums.sorted().joined(separator: " ")
}
```
### 解法二:正则表达式
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.unicodeScalars.first!.value < $1.unicodeScalars.first!.value }).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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.unicodeScalars.first!.value < $1.unicodeScalars.first!.value }).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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.unicodeScalars.first!.value < $1.unicodeScalars.first!.value }).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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.unicodeScalars.first!.value < $1.unicodeScalars.first!.value }).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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
return nums.sorted(by: { $0 < $1 }).joined()
}
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
```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 nums = numbers.map { String($0) }
return nums.sorted(by: { $0 < $1 }).joined()
}
```
### 解法二:使用 Swift 标准库函数
```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 nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
```
### 解法三:使用 Swift 标准库函数
```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 nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
```
### 解法四:使用 Swift 标准库函数
```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 nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
```
### 解法五:使用 Swift 标准库函数
```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 nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
```
### 解法六:使用 Swift 标准库函数
```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 nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
```
### 解法七:使用 Swift 标准库函数
```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 nums = numbers.map { String($0) }
return nums.sorted(by: <).joined()
}
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
var sorted = nums.sorted()
return sorted.joined(separator: " ")
}
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
var sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 2. 排序
```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 nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```
### 3. 排序
```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 nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```
### 4. 排序
```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 nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```
### 5. 排序
```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 nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```
### 6. 排序
```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 nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```
### 7. 排序
```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 nums = numbers.map { String($0) }
return nums.sorted().joined(separator: " ")
}
```
### 8. 排序
```swift
// Input is
var sorted = nums.sorted() // variable 'sorted' was never mutated; consider changing to 'let' constant
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 2. 排序
```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 nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 3. 排序
```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 nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 4. 排序
```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 nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 5. 排序
```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 nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 6. 排序
```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 nums = numbers.map { String($0) }
let sorted = nums.sorted()
return sorted.joined(separator: " ")
}
```
### 7. 排序
```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 nums = numbers.map { String($0) }
let sorted = nums
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).joined(separator: " ")
}
```
### 2. 排序
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).joined(separator: " ")
}
```
### 3. 排序
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).joined(separator: " ")
}
```
### 4. 排序
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).joined(separator: " ")
}
```
### 5. 排序
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).joined(separator: " ")
}
```
### 6. 排序
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: <).joined(separator: " ")
}
```
### 7. 排序
```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(
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
return nums.sorted(by: { $0 < $1 }).joined()
}
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0 < $1 }).joined()
}
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.reversed() < $1.reversed() }).joined()
}
func sortNumbers(numbers: String) -> String {
let nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { Int($0) < Int($1) }).joined()
}
```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 nums = numbers.map { String($0) }
return nums.sorted(by: { $0 < $1 }).joined()
}
```
### 解法二:正则表达式
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0 < $1 }).joined()
}
```
### 解法三:正则表达式
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { $0.reversed() < $1.reversed() }).joined()
}
```
### 解法四:正则表达式
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { Int($0) < Int($1) }).joined()
}
```
### 解法五:正则表达式
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { Int($0) < Int($1) }).joined()
}
```
### 解法六:正则表达式
```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 nums = numbers.split(separator: " ").map { String($0) }
return nums.sorted(by: { Int($0) < Int($1) }).joined()
}
```
### 解法七:正则表达式
```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'.
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
return nums.sorted(by: { $0.reversed() < $1.reversed() }).joined() // binary operator '<' cannot be applied to two 'ReversedCollection<String>' operands
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
return nums.sorted(by: { Int($0) < Int($1) }).joined() // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return nums.sorted(by: { Int($0) < Int($1) }).joined() // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { Int(String($0))! }
nums.sort()
return nums.map { String($0) }.joined()
}
func sortNumbers(numbers: String) -> String {
let regex = try! NSRegularExpression(pattern: "\\d+", options: [.caseInsensitive])
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! }
nums.sort()
return nums.map { String($0) }.joined()
}
func sortNumbers(numbers: String) -> String {
let regex = try! NSRegularExpression(pattern: "\\D+", options: [.caseInsensitive])
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! }
nums.sort()
return nums.map { String($0) }.joined()
}
```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 nums = numbers.map { Int(String($0))! }
nums.sort()
return nums.map { String($0) }.joined()
}
```
### 解法二:正则表达式
```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 regex = try! NSRegularExpression(pattern: "\\d+", options: [.caseInsensitive])
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! }
nums.sort()
return nums.map { String($0) }.joined()
}
```
### 解法三:正则表达式
```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 regex = try! NSRegularExpression(pattern: "\\D+", options: [.caseInsensitive])
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! }
nums.sort()
return nums.map { String($0) }.joined()
}
```
### 解法四:正则表达式
```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 regex = try! NSRegularExpression(pattern: "\\D+", options: [.caseInsensitive])
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! }
nums.sort()
return nums.map { String($0) }.joined()
}
```
### 解法五:正则表达式
```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 regex = try! NSRegularExpression(pattern: "\\D+", options: [.caseInsensitive])
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! }
nums.sort()
return nums.map { String($0) }.joined()
}
```
### 解法六:正则表达式
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one
nums.sort() // cannot use mutating member on immutable value: 'nums' is a 'let' constant
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! } // value of type 'NSTextCheckingResult' has no member 'captures'
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
let nums = regex.matches(in: numbers, range: NSRange(numbers.startIndex..., in: numbers)).map { Int(String($0.captures[0]))! } // value of type 'NSTextCheckingResult' has no member 'captures'
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
return nums.sorted { $0 < $1 }.joined()
}
```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 nums = numbers.map { String($0) }
return nums.sorted { $0 < $1 }.joined()
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0.asciiValue! - 48) }
return nums.sorted().joined(separator: " ")
}
```swift
// Input is a space-delimited string of numberals from 'zero' to 'nine'.
// Valid choices are 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight' and 'nine'.
// Return the string with numbers sorted from smallest to largest
// sortNumbers(numbers: "three one five") == "one three five"
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0.asciiValue! - 48) }
return nums.sorted().joined(separator: " ")
}
```
// XCTAssertTrue failed
func sortNumbers(numbers: String) -> String {
let nums = numbers.map { String($0) }
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
func sortNumbers(numbers: String) -> String {
let regex = "\\d+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
func sortNumbers(numbers: String) -> String {
let regex = "\\D+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
```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 nums = numbers.map { String($0) }
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
```
### 解法二:正则表达式
```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 regex = "\\d+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
```
### 解法三:正则表达式
```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 regex = "\\D+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
```
### 解法四:正则表达式
```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 regex = "\\D+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
```
### 解法五:正则表达式
```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 regex = "\\D+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
return sorted.joined()
}
```
### 解法六:正则表达式
```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 regex = "\\D+"
let nums = numbers.split(separator: regex, omittingEmptySubsequences: false)
let sorted = nums.sorted { nums[$0] < nums[$1] }
let sorted = nums.sorted { nums[$0] < nums[$1] } // instance method 'sorted(using:)' requires the types 'String' and '((Int, Int) -> Bool).Compared' be equivalent
let sorted = nums.sorted { nums[$0] < nums[$1] } // type '(Int, Int) -> Bool' cannot conform to 'SortComparator'
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
let sorted = nums.sorted { nums[$0] < nums[$1] } // instance method 'sorted(using:)' requires the types 'String.SubSequence' (aka 'Substring') and '((Int, Int) -> Bool).Compared' be equivalent
let sorted = nums.sorted { nums[$0] < nums[$1] } // type '(Int, Int) -> Bool' cannot conform to 'SortComparator'
func sortNumbers(numbers: String) -> String { // invalid redeclaration of 'sortNumbers(numbers:)'
let sorted = nums.sorted { nums[$0] < nums[$1] } // instance method 'sorted(using:)' requires the types 'String.SubSequence' (aka 'Substring') and '((Int, Int) -> Bool).Compared' be equivalent
let sorted = nums.sorted { nums[$0] < nums[$1] } // type '(Int, Int) -> Bool' cannot conform to 'SortComparator'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else { fatalError("Cannot find closest elements from an array of length 1 or less") }
let sorted = numbers.sorted()
let closest = sorted[0..<2]
let closestDiff = abs(closest[0] - closest[1])
var closestIndex = 0
for i in 1..<numbers.count {
let diff = abs(sorted[i] - sorted[i-1])
if diff < closestDiff {
closestDiff = diff
closestIndex = i
}
}
return (sorted[closestIndex], sorted[closestIndex-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 > 1 else { fatalError("Cannot find closest elements from an array of length 1 or less") }
let sorted = numbers.sorted()
let closest = sorted[0..<2]
let closestDiff = abs(closest[0] - closest[1])
var closestIndex = 0
for i in 1..<numbers.count {
let diff = abs(sorted[i] - sorted[i-1])
if diff < closestDiff {
closestDiff = diff
closestIndex = i
}
}
return (sorted[closestIndex], sorted[closestIndex-1])
}
```
closestDiff = diff // cannot assign to value: 'closestDiff' is a 'let' constant
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else { fatalError("At least two numbers are required") }
let sorted = numbers.sorted()
let closest = sorted.first!
let secondClosest = sorted[1]
let diff = abs(closest - secondClosest)
let result = (closest, secondClosest)
return diff < 0.0000001 ? result : (secondClosest, closest)
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else { fatalError("At least two numbers are required") }
let sorted = numbers.sorted()
let closest = sorted.first!
let secondClosest = sorted[1]
let result = (closest, secondClosest)
return abs(closest - secondClosest) < 0.0000001 ? result : (secondClosest, closest)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else { fatalError("At least two numbers are required") }
let sorted = numbers.sorted()
let closest = sorted.first!
let secondClosest = sorted[1]
let diff = abs(closest - secondClosest)
let result = (closest, secondClosest)
return diff < 0.0000001 ? result : (secondClosest, closest)
}
```
### 解法二
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else { fatalError("At least two numbers are required") }
let sorted = numbers.sorted()
let closest = sorted.first!
let secondClosest = sorted[1]
let result = (closest, secondClosest)
return abs(closest - secondClosest) < 0.0000001 ? result : (secondClosest, closest)
}
```
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
if abs(left - right) < 0.000000000000001 {
return (left, right)
}
if left < right {
return (left, sorted[mid + 1])
} else {
return (sorted[mid - 1], right)
}
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
if abs(left - right) < 0.000000000000001 {
return (left, right)
}
if left < right {
return findClosestElements(numbers: sorted[0..<mid])
} else {
return findClosestElements(numbers: sorted[mid..<sorted.count])
}
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
if abs(left - right) < 0.000000000000001 {
return (left, right)
}
var leftIndex = 0
var rightIndex = numbers.count - 1
while leftIndex < rightIndex {
let midIndex = leftIndex + (rightIndex - leftIndex) / 2
let midValue = numbers[midIndex]
if abs(left - midValue) < abs(right - midValue) {
rightIndex = midIndex
} else {
leftIndex = midIndex + 1
}
}
return (numbers[leftIndex], numbers[leftIndex + 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 > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
if abs(left - right) < 0.000000000000001 {
return (left, right)
}
if left < right {
return (left, sorted[mid + 1])
} else {
return (sorted[mid - 1], 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 > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
if abs(left - right) < 0.000000000000001 {
return (left, right)
}
if left < right {
return findClosestElements(numbers: sorted[0..<mid])
} else {
return findClosestElements(numbers: sorted[mid..<sorted.count])
}
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
if abs(left - right) < 0.000000000000001 {
return (left, right)
}
var leftIndex = 0
var rightIndex = numbers.count - 1
while leftIndex < rightIndex {
let midIndex = leftIndex + (rightIndex - leftIndex) / 2
let midValue = numbers[midIndex]
if abs(left - midValue) < abs(right - midValue) {
rightIndex = midIndex
} else {
leftIndex = midIndex + 1
}
}
return (numbers[leftIndex], numbers[leftIndex + 1])
}
```
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
return findClosestElements(numbers: sorted[0..<mid]) // cannot convert value of type 'ArraySlice<Double>' to expected argument type '[Double]'
return findClosestElements(numbers: sorted[mid..<sorted.count]) // cannot convert value of type 'ArraySlice<Double>' to expected argument type '[Double]'
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let min = sorted.first!
let max = sorted.last!
let minIndex = numbers.firstIndex(of: min)!
let maxIndex = numbers.lastIndex(of: max)!
let minDistance = abs(min - max)
if minIndex == maxIndex {
return (min, max)
}
let left = abs(min - numbers[minIndex + 1])
let right = abs(max - numbers[maxIndex - 1])
if left < right {
return (min, numbers[minIndex + 1])
} else {
return (numbers[maxIndex - 1], max)
}
}
```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 > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let min = sorted.first!
let max = sorted.last!
let minIndex = numbers.firstIndex(of: min)!
let maxIndex = numbers.lastIndex(of: max)!
let minDistance = abs(min - max)
if minIndex == maxIndex {
return (min, max)
}
let left = abs(min - numbers[minIndex + 1])
let right = abs(max - numbers[maxIndex - 1])
if left < right {
return (min, numbers[minIndex + 1])
} else {
return (numbers[maxIndex - 1], max)
}
}
```
let minDistance = abs(min - max) // initialization of immutable value 'minDistance' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else { fatalError("Array must be of length at least 2") }
let sorted = numbers.sorted()
let mid = (numbers.count - 1) / 2
let left = sorted[mid]
let right = sorted[mid + 1]
if abs(left - right) < 1e-10 {
return (left, right)
} else if left < right {
return (left, sorted[mid + 1])
} else {
return (sorted[mid], 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 > 1 else { fatalError("Array must be of length at least 2") }
let sorted = numbers.sorted()
let mid = (numbers.count - 1) / 2
let left = sorted[mid]
let right = sorted[mid + 1]
if abs(left - right) < 1e-10 {
return (left, right)
} else if left < right {
return (left, sorted[mid + 1])
} else {
return (sorted[mid], right)
}
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let minIndex = sorted.firstIndex(of: min)!
let maxIndex = sorted.lastIndex(of: max)!
let minDistance = abs(min - max)
var minIndex = minIndex
var maxIndex = maxIndex
while abs(min - max) > 0.0000001 {
if minIndex == maxIndex {
break
}
if abs(min - sorted[minIndex + 1]) < abs(min - sorted[maxIndex - 1]) {
maxIndex -= 1
} else {
minIndex += 1
}
}
return (sorted[minIndex], sorted[maxIndex])
}
```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 > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let minIndex = sorted.firstIndex(of: min)!
let maxIndex = sorted.lastIndex(of: max)!
let minDistance = abs(min - max)
var minIndex = minIndex
var maxIndex = maxIndex
while abs(min - max) > 0.0000001 {
if minIndex == maxIndex {
break
}
if abs(min - sorted[minIndex + 1]) < abs(min - sorted[maxIndex - 1]) {
maxIndex -= 1
} else {
minIndex += 1
}
}
return (sorted[minIndex], sorted[maxIndex])
}
```
var minIndex = minIndex // invalid redeclaration of 'minIndex'
var maxIndex = maxIndex // invalid redeclaration of 'maxIndex'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let diff = abs(max - min)
let mid = min + diff / 2
let left = sorted.firstIndex(of: mid) ?? 0
let right = left + 1
let leftNum = sorted[left]
let rightNum = sorted[right]
if abs(leftNum - mid) < abs(rightNum - mid) {
return (leftNum, rightNum)
} else {
return (rightNum, leftNum)
}
}
```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 > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let diff = abs(max - min)
let mid = min + diff / 2
let left = sorted.firstIndex(of: mid) ?? 0
let right = left + 1
let leftNum = sorted[left]
let rightNum = sorted[right]
if abs(leftNum - mid) < abs(rightNum - mid) {
return (leftNum, rightNum)
} else {
return (rightNum, leftNum)
}
}
```
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
return (left, right)
}
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
let diff = abs(left - right)
let mid = (left + right) / 2
let left = sorted[sorted.binarySearch(left, options: .backwards) ?? 0]
let right = sorted[sorted.binarySearch(right, options: .backwards) ?? 0]
if abs(left - mid) < diff {
return (left, mid)
} else {
return (mid, 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 > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
return (left, right)
}
```
### 解法二
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = sorted.count / 2
let left = sorted[mid - 1]
let right = sorted[mid]
let diff = abs(left - right)
let mid = (left + right) / 2
let left = sorted[sorted.binarySearch(left, options: .backwards) ?? 0]
let right = sorted[sorted.binarySearch(right, options: .backwards) ?? 0]
if abs(left - mid) < diff {
return (left, mid)
} else {
return (mid, right)
}
}
```
func findClosestElements(numbers: [Double]) -> (Double, Double) { // invalid redeclaration of 'findClosestElements(numbers:)'
let mid = (left + right) / 2 // invalid redeclaration of 'mid'
let left = sorted[sorted.binarySearch(left, options: .backwards) ?? 0] // cannot infer contextual base in reference to member 'backwards'
let left = sorted[sorted.binarySearch(left, options: .backwards) ?? 0] // value of type '[Double]' has no member 'binarySearch'
let right = sorted[sorted.binarySearch(right, options: .backwards) ?? 0] // cannot infer contextual base in reference to member 'backwards'
let right = sorted[sorted.binarySearch(right, options: .backwards) ?? 0] // value of type '[Double]' has no member 'binarySearch'
if abs(left - mid) < diff { // cannot convert value of type 'Double' to expected argument type 'Int32'
if abs(left - mid) < diff { // cannot convert value of type 'Duration' to expected argument type 'Int32'
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = (numbers.count - 1) / 2
let left = sorted[mid]
let right = sorted[mid + 1]
let diff = abs(left - right)
return (left, right)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
guard numbers.count > 1 else {
return (numbers[0], numbers[0])
}
let sorted = numbers.sorted()
let mid = (numbers.count - 1) / 2
let left = sorted[mid]
let right = sorted[mid + 1]
let diff = abs(left - right)
return (left, right)
}
```
let diff = abs(left - right) // initialization of immutable value 'diff' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let min = sorted.first!
let max = sorted.last!
let closest = min + (max - min) / 2
let minIndex = sorted.firstIndex(of: closest)!
let maxIndex = sorted.lastIndex(of: closest)!
let minValue = sorted[minIndex]
let maxValue = sorted[maxIndex]
return (minValue, maxValue)
}
```swift
// From a supplied array of numbers (of length at least two) select and return two that are the closest to each
// other and return them in order (smaller number, larger number).
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.2]) == (2.0, 2.2)
// findClosestElements(numbers: [1.0, 2.0, 3.0, 4.0, 5.0, 2.0]) == (2.0, 2.0)
func findClosestElements(numbers: [Double]) -> (Double, Double) {
let sorted = numbers.sorted()
let min = sorted.first!
let max = sorted.last!
let closest = min + (max - min) / 2
let minIndex = sorted.firstIndex(of: closest)!
let maxIndex = sorted.lastIndex(of: closest)!
let minValue = sorted[minIndex]
let maxValue = sorted[maxIndex]
return (minValue, maxValue)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 - min / range }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 / 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 }
}
```
### 解法二
```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 / range }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 - min / range }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 / 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 }
}
```
### 解法二
```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 }
}
```
### 解法三
```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 / 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 / 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 / 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 / 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
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted.last!
let range = max - min
return sorted.map { (($0 - min) / range) }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
let mid = numbers.count / 2
let left = numbers[0..<mid]
let right = numbers[mid..<numbers.count]
let leftResult = rescaleToUnit(numbers: left)
let rightResult = rescaleToUnit(numbers: right)
return merge(left: leftResult, right: rightResult, min: min, range: range)
}
func merge(left: [Double], right: [Double], min: Double, range: Double) -> [Double] {
var result = [Double]()
var i = 0
var j = 0
while i < left.count && j < right.count {
let leftValue = left[i]
let rightValue = right[j]
if leftValue < rightValue {
result.append(min + (leftValue * range))
i += 1
} else {
result.append(min + (rightValue * range))
j += 1
}
}
while i < left.count {
result.append(min + (left[i] * range))
i += 1
}
while j < right.count {
result.append(min + (right[j] * range))
j += 1
}
return result
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法二:排序
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted.last!
let range = max - min
return sorted.map { (($0 - min) / range) }
}
```
### 解法三:分治
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
let mid = numbers.count / 2
let left = numbers[0..<mid]
let right = numbers[mid..<numbers.count]
let leftResult = rescaleToUnit(numbers: left)
let rightResult = rescaleToUnit(numbers: right)
return merge(left: leftResult, right: rightResult, min: min, range: range)
}
func merge(left: [Double], right: [Double], min: Double, range: Double) -> [Double] {
var result = [Double]()
var i = 0
var j = 0
while i < left.count && j < right.count {
let leftValue = left[i]
let rightValue = right[j]
if leftValue < rightValue {
result.append(min + (leftValue * range))
i += 1
} else {
result.append(min + (rightValue * range))
j += 1
}
}
while i < left.count {
result.append(min + (left[i] * range))
i += 1
}
while j < right.count {
result.append(min + (right[j] * range))
j += 1
}
return result
}
```
### 解法四:二分查找
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
let mid = numbers.count / 2
let left = numbers[0..<mid]
let right = numbers[mid..<numbers.count]
let leftResult = rescaleToUnit(numbers: left)
let rightResult = rescaleToUnit(numbers: right)
return merge(left: leftResult, right: rightResult, min: min, range: range)
}
func merge(left: [Double], right: [Double], min: Double, range: Double) -> [Double] {
var result = [Double]
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
let leftResult = rescaleToUnit(numbers: left) // cannot convert value of type 'ArraySlice<Double>' to expected argument type '[Double]'
let rightResult = rescaleToUnit(numbers: right) // cannot convert value of type 'ArraySlice<Double>' to expected argument type '[Double]'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 - min / range }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 / 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 }
}
```
### 解法二
```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 }
}
```
### 解法三
```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 / 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 / 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 / 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 / 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
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let range = max - min
return sorted.map { (($0 - min) / range) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法二:排序
```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 sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let range = max - min
return sorted.map { (($0 - min) / range) }
}
```
### 解法三:分治
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法四:二分查找
```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) }
}
```
### 解法五:数学
```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) }
}
```
### 解法六:数学
```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) }
}
```
### 解法七:数学
```swift
// Given array of numbers (of at least two
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
return numbers.map { $0 / Double(numbers.count) }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
return numbers.map { $0 / numbers.max()! }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
return numbers.map { $0 / numbers.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()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法二:使用数组方法
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
return numbers.map { $0 / Double(numbers.count) }
}
```
### 解法三:使用数组方法
```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] {
return numbers.map { $0 / numbers.max()! }
}
```
### 解法四:使用数组方法
```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] {
return numbers.map { $0 / numbers.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()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法六:使用数组方法
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法七:使用数组方法
```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.7
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法二
```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) }
}
```
### 解法三
```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) }
}
```
### 解法四
```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) }
}
```
### 解法五
```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) }
}
```
### 解法六
```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) }
}
```
### 解法七
```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
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
### 解法二
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { (($0 - min) / range) }
}
```
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
return numbers.map { $0 - min / range }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let range = max - min
return sorted.map { $0 - min / range }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
let mid = min + range / 2
let midIndex = numbers.firstIndex(of: mid) ?? 0
let left = numbers[0...midIndex]
let right = numbers[midIndex...]
return left.map { $0 - min / range } + right.map { $0 - mid / range }
}
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
let mid = min + range / 2
let left = numbers[0...numbers.firstIndex(of: mid) ?? 0]
let right = numbers[numbers.firstIndex(of: mid) ?? 0...]
return left.map { $0 - min / range } + right.map { $0 - mid / 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 }
}
```
### 解法二:排序
```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 sorted = numbers.sorted()
let min = sorted[0]
let max = sorted[sorted.count - 1]
let range = max - min
return sorted.map { $0 - min / range }
}
```
### 解法三:二分查找
```swift
// Given array of numbers (of at least two elements), apply a linear transform to that array,
// such that the smallest number will become 0 and the largest will become 1
// rescaleToUnit(numbers: [1.0, 2.0, 3.0, 4.0, 5.0]) == [0.0, 0.25, 0.5, 0.75, 1.0]
func rescaleToUnit(numbers: [Double]) -> [Double] {
let min = numbers.min()!
let max = numbers.max()!
let range = max - min
let mid = min + range / 2
let midIndex = numbers.firstIndex(of: mid) ?? 0
let left = numbers[0...midIndex]
let right = numbers[midIndex...]
return left.map { $0 - min / range } + right.map { $0 - mid / 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
let mid = min + range / 2
let left = numbers[0...numbers.firstIndex(of: mid) ?? 0]
let right = numbers[numbers.firstIndex(of: mid) ?? 0...]
return left.map { $0 - min / range } + right.map { $0 - mid / 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
let mid = min + range / 2
let left = numbers[0...numbers.firstIndex(of: mid) ?? 0]
let right = numbers[numbers.firstIndex(of: mid) ?? 0...]
return left.map { $0 - min / range } + right.map { $0 - mid / range }
}
```
### 解法六:分治 + 迭代
```swift
// Given array of numbers
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
func rescaleToUnit(numbers: [Double]) -> [Double] { // invalid redeclaration of 'rescaleToUnit(numbers:)'
let left = numbers[0...numbers.firstIndex(of: mid) ?? 0] // cannot convert value of type 'Int' to expected argument type 'ClosedRange<Array<Double>.Index>' (aka 'ClosedRange<Int>')
let left = numbers[0...numbers.firstIndex(of: mid) ?? 0] // value of optional type 'Array<Double>.Index?' (aka 'Optional<Int>') must be unwrapped to a value of type 'Array<Double>.Index' (aka 'Int')
let right = numbers[numbers.firstIndex(of: mid) ?? 0...] // cannot convert value of type 'PartialRangeFrom<Int>' to expected argument type 'Array<Double>.Index' (aka 'Int')
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
func filterDictionaries(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap { $0 as? [AnyHashable] }
}
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap { $0 as? [AnyHashable] }
}
func filterSets(values: [AnyHashable]) -> [Set<AnyHashable>] {
return values.compactMap { $0 as? Set<AnyHashable> }
}
func filterTuples(values: [AnyHashable]) -> [(Int, Int)] {
return values.compactMap { $0 as? (Int, Int) }
}
func filterEnums(values: [AnyHashable]) -> [MyEnum] {
return values.compactMap { $0 as? MyEnum }
}
func filterStructs(values: [AnyHashable]) -> [MyStruct] {
return values.compactMap { $0 as? MyStruct }
}
func filterClasses(values: [AnyHashable]) -> [MyClass] {
return values.compactMap { $0 as? MyClass }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### Filter out only strings
```swift
// Filter given array of any swiftthon values only for strings
// filterStrings(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
```
### Filter out only dictionaries
```swift
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [[]]
func filterDictionaries(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap { $0 as? [AnyHashable] }
}
```
### Filter out only arrays
```swift
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [[], [:]]
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.compactMap { $0 as? [AnyHashable] }
}
```
### Filter out only sets
```swift
// Filter given array of any swiftthon values only for sets
// filterSets(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Set<AnyHashable>]
func filterSets(values: [AnyHashable]) -> [Set<AnyHashable>] {
return values.compactMap { $0 as? Set<AnyHashable> }
}
```
### Filter out only tuples
```swift
// Filter given array of any swiftthon values only for tuples
// filterTuples(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [(1, 2)]
func filterTuples(values: [AnyHashable]) -> [(Int, Int)] {
return values.compactMap { $0 as? (Int, Int) }
}
```
### Filter out only enums
```swift
// Filter given array of any swiftthon values only for enums
// filterEnums(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [.a]
func filterEnums(values: [AnyHashable]) -> [MyEnum] {
return values.compactMap { $0 as? MyEnum }
}
```
### Filter out only structs
```swift
// Filter given array of any swiftthon values only for structs
// filterStructs(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [MyStruct(a: 1, b: 2)]
func filterStructs(values: [AnyHashable]) -> [MyStruct] {
return values.compactMap { $0 as? MyStruct }
}
```
### Filter out only classes
```swift
// Filter given array of any swiftthon values only for classes
// filterClasses(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [MyClass(a: 1, b: 2)]
func filterClasses(values: [AnyHashable]) -> [MyClass] {
return values.compactMap { $0 as? MyClass }
}
```
### Filter out
func filterEnums(values: [AnyHashable]) -> [MyEnum] { // cannot find type 'MyEnum' in scope
func filterStructs(values: [AnyHashable]) -> [MyStruct] { // cannot find type 'MyStruct' in scope
func filterClasses(values: [AnyHashable]) -> [MyClass] { // cannot find type 'MyClass' in scope
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.filter { $0 is String }.map { $0 as! String }
}
func filterFloats(values: [AnyHashable]) -> [Float] {
return values.filter { $0 is Float }.map { $0 as! Float }
}
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.filter { $0 is Double }.map { $0 as! Double }
}
func filterBools(values: [AnyHashable]) -> [Bool] {
return values.filter { $0 is Bool }.map { $0 as! Bool }
}
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.filter { $0 is Array }.map { $0 as! [[AnyHashable]] }
}
func filterSets(values: [AnyHashable]) -> Set<AnyHashable> {
return values.filter { $0 is Set }.map { $0 as! Set<AnyHashable> }
}
func filterDictionaries(values: [AnyHashable]) -> [Map<AnyHashable, AnyHashable>] {
return values.filter { $0 is Map }.map { $0 as! Map<AnyHashable, AnyHashable> }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.1.2. Filter only strings
```swift
// Filter given array of any swiftthon values only for strings
// filterStrings(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.filter { $0 is String }.map { $0 as! String }
}
```
### 2.1.3. Filter only floats
```swift
// Filter given array of any swiftthon values only for floats
// filterFloats(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [2.14]
func filterFloats(values: [AnyHashable]) -> [Float] {
return values.filter { $0 is Float }.map { $0 as! Float }
}
```
### 2.1.4. Filter only doubles
```swift
// Filter given array of any swiftthon values only for doubles
// filterDoubles(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [2.14]
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.filter { $0 is Double }.map { $0 as! Double }
}
```
### 2.1.5. Filter only booleans
```swift
// Filter given array of any swiftthon values only for booleans
// filterBools(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterBools(values: [AnyHashable]) -> [Bool] {
return values.filter { $0 is Bool }.map { $0 as! Bool }
}
```
### 2.1.6. Filter only arrays
```swift
// Filter given array of any swiftthon values only for arrays
// filterArrays(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.filter { $0 is Array }.map { $0 as! [[AnyHashable]] }
}
```
### 2.1.7. Filter only sets
```swift
// Filter given array of any swiftthon values only for sets
// filterSets(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterSets(values: [AnyHashable]) -> Set<AnyHashable> {
return values.filter { $0 is Set }.map { $0 as! Set<AnyHashable> }
}
```
### 2.1.8. Filter only dictionaries
```swift
// Filter given array of any swiftthon values only for dictionaries
// filterDictionaries(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterDictionaries(values: [AnyHashable]) -> [Map<AnyHashable, AnyHashable>] {
return values.filter { $0 is Map }.map { $0 as! Map<AnyHashable, AnyHashable> }
}
```
### 2.1.9. Filter only tuples
```swift
// Filter given array of any swiftthon values only for tuples
// filterTuples(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterTup
return values.filter { $0 is Array }.map { $0 as! [[AnyHashable]] } // generic parameter 'Element' could not be inferred in cast to 'Array'
return values.filter { $0 is Set }.map { $0 as! Set<AnyHashable> } // cannot convert return expression of type '[Set<AnyHashable>]' to return type 'Set<AnyHashable>'
return values.filter { $0 is Set }.map { $0 as! Set<AnyHashable> } // generic parameter 'Element' could not be inferred in cast to 'Set'
func filterDictionaries(values: [AnyHashable]) -> [Map<AnyHashable, AnyHashable>] { // cannot find type 'Map' in scope
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
func filterFloats(values: [AnyHashable]) -> [Float] {
return values.compactMap { $0 as? Float }
}
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.compactMap { $0 as? Double }
}
func filterBooleans(values: [AnyHashable]) -> [Bool] {
return values.compactMap { $0 as? Bool }
}
func filterDates(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
func filterDatetimes(values: [AnyHashable]) -> [DateTime] {
return values.compactMap { $0 as? DateTime }
}
func filterTimestamps(values: [AnyHashable]) -> [Timestamp] {
return values.compactMap { $0 as? Timestamp }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 3.1.2. Filter out strings
```swift
// Filter given array of any swiftthon values only for strings
// filterStrings(values: [1, 2, 3.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
```
### 3.1.3. Filter out floats
```swift
// Filter given array of any swiftthon values only for floats
// filterFloats(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [3.14]
func filterFloats(values: [AnyHashable]) -> [Float] {
return values.compactMap { $0 as? Float }
}
```
### 3.1.4. Filter out doubles
```swift
// Filter given array of any swiftthon values only for doubles
// filterDoubles(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [3.14]
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.compactMap { $0 as? Double }
}
```
### 3.1.5. Filter out booleans
```swift
// Filter given array of any swiftthon values only for booleans
// filterBooleans(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [true, false]
func filterBooleans(values: [AnyHashable]) -> [Bool] {
return values.compactMap { $0 as? Bool }
}
```
### 3.1.6. Filter out dates
```swift
// Filter given array of any swiftthon values only for dates
// filterDates(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterDates(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
```
### 3.1.7. Filter out datetimes
```swift
// Filter given array of any swiftthon values only for datetimes
// filterDatetimes(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterDatetimes(values: [AnyHashable]) -> [DateTime] {
return values.compactMap { $0 as? DateTime }
}
```
### 3.1.8. Filter out timestamps
```swift
// Filter given array of any swiftthon values only for timestamps
// filterTimestamps(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterTimestamps(values: [AnyHashable]) -> [Timestamp] {
return values.compactMap { $0 as? Timestamp }
}
```
### 3.1.9. Filter out URLs
```swift
// Filter given array of any swiftthon values only for URLs
// filterURLs(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["https://github.com/krzyzanik/swift-nio"]
func filterURLs(values: [AnyHashable]) -> [URL
func filterDatetimes(values: [AnyHashable]) -> [DateTime] { // cannot find type 'DateTime' in scope
func filterTimestamps(values: [AnyHashable]) -> [Timestamp] { // cannot find type 'Timestamp' in scope
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
func filterFloats(values: [AnyHashable]) -> [Float] {
return values.compactMap { $0 as? Float }
}
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.compactMap { $0 as? Double }
}
func filterBools(values: [AnyHashable]) -> [Bool] {
return values.compactMap { $0 as? Bool }
}
func filterDates(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
func filterDatetimes(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
func filterTimes(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.2.1. Filter out strings
```swift
// Filter given array of any swiftthon values only for strings
// filterStrings(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
```
### 2.2.2. Filter out floats
```swift
// Filter given array of any swiftthon values only for floats
// filterFloats(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [2.14]
func filterFloats(values: [AnyHashable]) -> [Float] {
return values.compactMap { $0 as? Float }
}
```
### 2.2.3. Filter out doubles
```swift
// Filter given array of any swiftthon values only for doubles
// filterDoubles(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [2.14]
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.compactMap { $0 as? Double }
}
```
### 2.2.4. Filter out bools
```swift
// Filter given array of any swiftthon values only for bools
// filterBools(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [true]
func filterBools(values: [AnyHashable]) -> [Bool] {
return values.compactMap { $0 as? Bool }
}
```
### 2.2.5. Filter out dates
```swift
// Filter given array of any swiftthon values only for dates
// filterDates(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterDates(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
```
### 2.2.6. Filter out datetimes
```swift
// Filter given array of any swiftthon values only for datetimes
// filterDatetimes(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterDatetimes(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
```
### 2.2.7. Filter out times
```swift
// Filter given array of any swiftthon values only for times
// filterTimes(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterTimes(values: [AnyHashable]) -> [Date] {
return values.compactMap { $0 as? Date }
}
```
### 2.2.8. Filter out timestamps
```swift
// Filter given array of any swiftthon values only for timestamps
// filterTimestamps(values: [1, 2.14, 5, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterTimestamps(values: [AnyHashable
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.filter { $0 is String }.map { $0 as! String }
}
func filterDictionaries(values: [AnyHashable]) -> [[AnyHashable]] {
return values.filter { $0 is [AnyHashable : AnyHashable] }.map { $0 as! [[AnyHashable : AnyHashable]] }
}
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.filter { $0 is [AnyHashable] }.map { $0 as! [[AnyHashable]] }
}
func filterSets(values: [AnyHashable]) -> [Set<AnyHashable>] {
return values.filter { $0 is Set<AnyHashable> }.map { $0 as! Set<AnyHashable> }
}
func filterTuples(values: [AnyHashable]) -> [(AnyHashable)] {
return values.filter { $0 is (AnyHashable) }.map { $0 as! (AnyHashable) }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.1.2. Filter out only strings
```swift
// 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.filter { $0 is String }.map { $0 as! String }
}
```
### 2.1.3. Filter out only dictionaries
```swift
// 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], [] as [AnyHashable]]) == [[:]]
func filterDictionaries(values: [AnyHashable]) -> [[AnyHashable]] {
return values.filter { $0 is [AnyHashable : AnyHashable] }.map { $0 as! [[AnyHashable : AnyHashable]] }
}
```
### 2.1.4. Filter out only arrays
```swift
// 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]]) == [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]
func filterArrays(values: [AnyHashable]) -> [[AnyHashable]] {
return values.filter { $0 is [AnyHashable] }.map { $0 as! [[AnyHashable]] }
}
```
### 2.1.5. Filter out only sets
```swift
// 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]]) == [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]
func filterSets(values: [AnyHashable]) -> [Set<AnyHashable>] {
return values.filter { $0 is Set<AnyHashable> }.map { $0 as! Set<AnyHashable> }
}
```
### 2.1.6. Filter out only tuples
```swift
// 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]]) == [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]
func filterTuples(values: [AnyHashable]) -> [(AnyHashable)] {
return values.filter { $0 is (AnyHashable) }.map { $0 as! (AnyHashable) }
}
```
### 2.1.7. Filter out only enums
```swift
// 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]]) == [1, 2
return values.filter { $0 is (AnyHashable) }.map { $0 as! (AnyHashable) } // forced cast of 'AnyHashable' to same type has no effect
return values.filter { $0 is (AnyHashable) }.map { $0 as! (AnyHashable) } // 'is' test is always true
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.2. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.3. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.4. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.5. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.6. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.7. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 2.1.8. Filter out non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
func filterNonIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
func filterIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : 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 { $0 as? Int }
}
```
### 2. Filter out all non-integers from given array of any swiftthon values
```swift
// Filter out all non-integers from given array of any swiftthon values
// filterNonIntegers(values: ["a", 3.14, 5]) == ["a"]
// filterNonIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterNonIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
```
### 3. Filter out all integers from given array of any swiftthon values
```swift
// Filter out all integers from given array of any swiftthon values
// filterIntegers(values: ["a", 3.14, 5]) == ["a", 3.14]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
```
### 4. Filter out all non-integers from given array of any swiftthon values
```swift
// Filter out all non-integers from given array of any swiftthon values
// filterNonIntegers(values: ["a", 3.14, 5]) == ["a"]
// filterNonIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterNonIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
```
### 5. Filter out all integers from given array of any swiftthon values
```swift
// Filter out all integers from given array of any swiftthon values
// filterIntegers(values: ["a", 3.14, 5]) == ["a", 3.14]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
```
### 6. Filter out all non-integers from given array of any swiftthon values
```swift
// Filter out all non-integers from given array of any swiftthon values
// filterNonIntegers(values: ["a", 3.14, 5]) == ["a"]
// filterNonIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterNonIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
```
### 7. Filter out all integers from given array of any swiftthon values
```swift
// Filter out all integers from given array of any swiftthon values
// filterIntegers(values: ["a", 3.14, 5]) == ["a", 3.14]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == []
func filterIntegers(values: [AnyHashable]) -> [AnyHashable] {
return values.compactMap { $0 as? Int == nil ? $0 : nil }
}
```
### 8. Filter out all non-integers from given array of any swiftthon values
```swift
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.2. Filter out all non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.3. Filter out all integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.4. Filter out all non-integers and integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.5. Filter out all integers and non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.6. Filter out all integers and non-integers and integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.7. Filter out all integers and integers and non-integers
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.2.8. Filter out all integers and integers and non-integers and integers
```swift
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.filter { $0 is String }.map { $0 as! String }
}
func filterFloats(values: [AnyHashable]) -> [Double] {
return values.filter { $0 is Double }.map { $0 as! Double }
}
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.filter { $0 is Double }.map { $0 as! Double }
}
func filterBools(values: [AnyHashable]) -> [Bool] {
return values.filter { $0 is Bool }.map { $0 as! Bool }
}
func filterDates(values: [AnyHashable]) -> [Date] {
return values.filter { $0 is Date }.map { $0 as! Date }
}
func filterDatetimes(values: [AnyHashable]) -> [Date] {
return values.filter { $0 is Date }.map { $0 as! Date }
}
func filterTimestamps(values: [AnyHashable]) -> [Date] {
return values.filter { $0 is Date }.map { $0 as! Date }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.filter { $0 is Int }.map { $0 as! Int }
}
```
### 2.1.2. Filter out strings
```swift
// Filter given array of any swiftthon values only for strings
// filterStrings(values: [1, 2.14, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == ["abc"]
func filterStrings(values: [AnyHashable]) -> [String] {
return values.filter { $0 is String }.map { $0 as! String }
}
```
### 2.1.3. Filter out floats
```swift
// Filter given array of any swiftthon values only for floats
// filterFloats(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [2.14]
func filterFloats(values: [AnyHashable]) -> [Double] {
return values.filter { $0 is Double }.map { $0 as! Double }
}
```
### 2.1.4. Filter out doubles
```swift
// Filter given array of any swiftthon values only for doubles
// filterDoubles(values: [1, 2.14, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [2.14]
func filterDoubles(values: [AnyHashable]) -> [Double] {
return values.filter { $0 is Double }.map { $0 as! Double }
}
```
### 2.1.5. Filter out booleans
```swift
// Filter given array of any swiftthon values only for booleans
// filterBools(values: [1, 2.14, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [true, false]
func filterBools(values: [AnyHashable]) -> [Bool] {
return values.filter { $0 is Bool }.map { $0 as! Bool }
}
```
### 2.1.6. Filter out dates
```swift
// Filter given array of any swiftthon values only for dates
// filterDates(values: [1, 2.14, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterDates(values: [AnyHashable]) -> [Date] {
return values.filter { $0 is Date }.map { $0 as! Date }
}
```
### 2.1.7. Filter out datetimes
```swift
// Filter given array of any swiftthon values only for datetimes
// filterDatetimes(values: [1, 2.14, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterDatetimes(values: [AnyHashable]) -> [Date] {
return values.filter { $0 is Date }.map { $0 as! Date }
}
```
### 2.1.8. Filter out timestamps
```swift
// Filter given array of any swiftthon values only for timestamps
// filterTimestamps(values: [1, 2.14, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [Date(timeIntervalSince1970: 0)]
func filterTimestamps(values: [AnyHashable]) -> [Date] {
return values.filter { $0 is Date }.map { $0 as! Date }
}
```
### 2.1.9. Filter out tuples
```swift
// Filter given array of any swiftthon values only for tuples
// filterTuples(values: [1, 2.14, 3,
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
func filterStrings(values: [AnyHashable]) -> [String] {
return values.compactMap { $0 as? String }
}
func filterStrings(values: [AnyHashable], length: Int) -> [String] {
return values.compactMap { $0 as? String }.filter { $0.count > length }
}
```swift
// Filter given array of any swiftthon values only for integers
// filterIntegers(values: ["a", 3.14, 5]) == [5]
// filterIntegers(values: [1, 2, 3, "abc", [:] as [AnyHashable : AnyHashable], [] as [AnyHashable]]) == [1, 2, 3]
func filterIntegers(values: [AnyHashable]) -> [Int] {
return values.compactMap { $0 as? Int }
}
```
### 1.2.1. Filter by type
```swift
// 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 { $0 as? String }
}
```
### 1.2.2. Filter by type and value
```swift
// Filter given array of any swiftthon values only for strings with length > 3
// filterStrings(values: ["a", 3.14, 5], length: 3) == []
// filterStrings(values: ["abc", "def", "ghi"], length: 3) == ["abc", "def"]
func filterStrings(values: [AnyHashable], length: Int) -> [String] {
return values.compactMap { $0 as? String }.filter { $0.count > length }
}
```
### 1.2.3. Filter by type and value
```swift
// Filter given array of any swiftthon values only for strings with length > 3
// filterStrings(values: ["a", 3.14, 5], length: 3) == []
// filterStrings(values: ["abc", "def", "ghi"], length: 3) == ["abc", "def"]
func filterStrings(values: [AnyHashable], length: Int) -> [String] {
return values.compactMap { $0 as? String }.filter { $0.count > length }
}
```
### 1.2.4. Filter by type and value
```swift
// Filter given array of any swiftthon values only for strings with length > 3
// filterStrings(values: ["a", 3.14, 5], length: 3) == []
// filterStrings(values: ["abc", "def", "ghi"], length: 3) == ["abc", "def"]
func filterStrings(values: [AnyHashable], length: Int) -> [String] {
return values.compactMap { $0 as? String }.filter { $0.count > length }
}
```
### 1.2.5. Filter by type and value
```swift
// Filter given array of any swiftthon values only for strings with length > 3
// filterStrings(values: ["a", 3.14, 5], length: 3) == []
// filterStrings(values: ["abc", "def", "ghi"], length: 3) == ["abc", "def"]
func filterStrings(values: [AnyHashable], length: Int) -> [String] {
return values.compactMap { $0 as? String }.filter { $0.count > length }
}
```
### 1.2.6. Filter by type and value
```swift
// Filter given array of any swiftthon values only for strings with length > 3
// filterStrings(values: ["a", 3.14, 5], length: 3) == []
// filterStrings(values: ["abc", "def", "ghi"], length: 3) == ["abc", "def"]
func filterStrings(values: [AnyHashable], length: Int) -> [String] {
return values.compactMap { $0 as? String }.filter { $0.count > length }
}
```
### 1.2.7. Filter by type and value
```swift
// Filter given array of any swiftthon values only for strings with length > 3
// filterStrings(values: ["a", 3.14, 5], length: 3) == []
// filterStrings(values: ["abc", "def", "ghi"], length: 3) == ["abc", "def"]
func filterStrings(values:
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
func strcat(string1: String, string2: String, string3: String) -> String {
return string1 + string2 + string3
}
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
func strchr(string: String, character: Character) -> String? {
for c in string {
if c == character {
return String(c)
}
}
return nil
}
func strstr(string: String, character: Character) -> String? {
for i in 0..<string.count {
if string[i] == character {
return String(string[i..<string.count])
}
}
return nil
}
func strtok(string: String, character: Character) -> [String] {
var tokens = [String]()
var start = 0
var end = 0
while end < string.count {
if string[end] == character {
tokens.append(string[start..<end])
start = end + 1
}
end += 1
}
if start < end {
tokens.append(string[start..<end])
}
return tokens
}
func strtok(string: String, character: Character) -> String {
var result = ""
for token in strtok(string: string, character: character) {
result += token
result += character
}
return String(result.dropLast())
}
```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
}
```
### 2. 字符串拼接
```swift
// Concatenate two strings
// strcat(string1: "abc", string2: "def") == "abcdef"
// strcat(string1: "abc", string2: "def", string3: "ghi") == "abcdefghi"
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
func strcat(string1: String, string2: String, string3: String) -> String {
return string1 + string2 + string3
}
```
### 3. 字符串比较
```swift
// Compare two strings
// strcmp(string1: "abc", string2: "def") == -1
// strcmp(string1: "abc", string2: "abc") == 0
// strcmp(string1: "abc", string2: "def") == 1
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
```
### 4. 字符串查找
```swift
// Find a character in a string
// strchr(string: "abc", character: "c") == "c"
// strchr(string: "abc", character: "d") == nil
func strchr(string: String, character: Character) -> String? {
for c in string {
if c == character {
return String(c)
}
}
return nil
}
```
### 5. 字符串替换
```swift
// Replace a character in a string
// strstr(string: "abc", character: "c") == "c"
// strstr(string: "abc", character: "d") == nil
func strstr(string: String, character: Character) -> String? {
for i in 0..<string.count {
if string[i] == character {
return String(string[i..<string.count])
}
}
return nil
}
```
### 6. 字符串分割
```swift
// Split a string into an array of substrings separated by a given character
// strtok(string: "abc,def,ghi", character: ",") == ["abc", "def", "ghi"]
// strtok(string: "abc,def,ghi", character: ",") == ["abcdefghi"]
func strtok(string: String, character: Character) -> [String] {
var tokens = [String]()
var start = 0
var end = 0
while end < string.count {
if string[end] == character {
tokens.append(string[start..<end])
start = end + 1
}
end += 1
}
if start < end {
tokens.append(string[start..<end])
}
return tokens
}
```
### 7. 字符串合并
```swift
// Merge an array of substrings into a single string separated by a given character
// strtok(string: "abcdefghi", character: ",") == "abcdefghi"
// strtok(string: "abcdefghi", character: ",") == "abcdefghi"
func strtok(string: String, character: Character) -> String {
var result = ""
for token in strtok(string: string, character: character) {
result += token
result += character
}
return String(result.dropLast())
}
```
### 8. 字符串转数字
```swift
// Convert a string to an integer
// atoi(string: "123") == 123
// atoi(string: "123abc") == 0
if string[i] == character { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
return String(string[i..<string.count]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if string[end] == character { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
tokens.append(string[start..<end]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
tokens.append(string[start..<end]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
result += token // cannot convert value of type 'Character' to expected argument type 'String'
result += character // cannot convert value of type 'Character' to expected argument type 'String'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcat(string: String, string2: String) -> String {
return string + string2
}
func strcmp(string: String, string2: String) -> Int {
if string < string2 {
return -1
} else if string > string2 {
return 1
} else {
return 0
}
}
func strchr(string: String, character: Character) -> Int? {
for (index, char) in string.enumerated() {
if char == character {
return index
}
}
return nil
}
func strstr(string: String, character: Character, replacement: String) -> String {
var result = ""
for (index, char) in string.enumerated() {
if char == character {
result += replacement
} else {
result += String(char)
}
}
return result
}
func strtok(string: String, delimiter: Character) -> [String] {
var result = [String]()
var buffer = ""
for char in string {
if char == delimiter {
result.append(buffer)
buffer = ""
} else {
buffer += String(char)
}
}
result.append(buffer)
return result
}
func strtok(string: String, delimiter: Character, joiner: Character) -> String {
var result = ""
var buffer = ""
for char in string {
if char == delimiter {
result += buffer + joiner
buffer = ""
} else {
buffer += String(char)
}
}
result += buffer
return result
}
func strtolower(string: String) -> String {
return string.lowercased()
}
```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
}
```
### 2. 字符串拼接
```swift
// Return string concatenated with given string
// strcat(string: "", string: "") == ""
// strcat(string: "abc", string: "def") == "abcdef"
func strcat(string: String, string2: String) -> String {
return string + string2
}
```
### 3. 字符串比较
```swift
// Return 0 if strings are equal
// Return 1 if string1 > string2
// Return -1 if string1 < string2
// strcmp(string: "abc", string: "def") == -1
// strcmp(string: "def", string: "abc") == 1
func strcmp(string: String, string2: String) -> Int {
if string < string2 {
return -1
} else if string > string2 {
return 1
} else {
return 0
}
}
```
### 4. 字符串查找
```swift
// Return index of first occurrence of character in string
// strchr(string: "abc", character: "c") == 2
// strchr(string: "abc", character: "d") == nil
func strchr(string: String, character: Character) -> Int? {
for (index, char) in string.enumerated() {
if char == character {
return index
}
}
return nil
}
```
### 5. 字符串替换
```swift
// Return string with character replaced with given string
// strstr(string: "abc", character: "c", replacement: "d") == "abd"
// strstr(string: "abc", character: "d", replacement: "d") == "abc"
func strstr(string: String, character: Character, replacement: String) -> String {
var result = ""
for (index, char) in string.enumerated() {
if char == character {
result += replacement
} else {
result += String(char)
}
}
return result
}
```
### 6. 字符串分割
```swift
// Return array of substrings separated by given character
// strtok(string: "abc,def", delimiter: ",") == ["abc", "def"]
// strtok(string: "abc", delimiter: ",") == ["abc"]
func strtok(string: String, delimiter: Character) -> [String] {
var result = [String]()
var buffer = ""
for char in string {
if char == delimiter {
result.append(buffer)
buffer = ""
} else {
buffer += String(char)
}
}
result.append(buffer)
return result
}
```
### 7. 字符串合并
```swift
// Return string with substrings merged by given character
// strtok(string: "abc,def", delimiter: ",", joiner: "") == "abcdef"
// strtok(string: "abc", delimiter: ",", joiner: "") == "abc"
func strtok(string: String, delimiter: Character, joiner: Character) -> String {
var result = ""
var buffer = ""
for char in string {
if char == delimiter {
result += buffer + joiner
buffer = ""
} else {
buffer += String(char)
}
}
result += buffer
return result
}
```
### 8. 字符串大小写转换
```swift
// Return string with all characters converted to lowercase
// strtolower(string: "ABC") == "abc"
// strtolower(string: "abc") == "abc"
func strtolower(string: String) -> String {
return string.lowercased()
}
```
```swift
for (index, char) in string.enumerated() { // immutable value 'index' was never used; consider replacing with '_' or removing it
result += buffer + joiner // cannot convert value of type 'Character' to expected argument type 'String'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
return count
}
// Return the number of occurrences of the given character in the given string
// count(string: "abc", char: "a") == 1
// count(string: "abc", char: "b") == 1
// count(string: "abc", char: "c") == 1
func count(string: String, char: Character) -> Int {
var count = 0
for c in string {
if c == char {
count += 1
}
}
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
func strchr(string: String, character: Character) -> Int {
for (index, char) in string.enumerated() {
if char == character {
return index
}
}
return -1
}
func strstr(string: String, character: Character, replacement: Character) -> String {
var string = string
for (index, char) in string.enumerated() {
if char == character {
string.remove(at: index)
string.insert(replacement, at: index)
}
}
return string
}
func strtok(string: String, character: Character) -> [String] {
var string = string
var tokens = [String]()
while !string.isEmpty {
let index = strchr(string: string, character: character)
if index == -1 {
tokens.append(string)
break
}
tokens.append(string[..<index])
string.removeSubrange(Range(uncheckedBounds: (lower: index, upper: index + 1)))
}
return tokens
}
func strtok(string: String, character: Character) -> String {
var string = string
var result = ""
while !string.isEmpty {
let index = strchr(string: string, character: character)
if index == -1 {
result += string
break
}
result += string[..<index]
string.removeSubrange(Range(uncheckedBounds: (lower: index, upper: index + 1)))
}
return result
}
```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
}
```
### 2. 字符串拼接
```swift
// Return concatenated string
// strcat(string1: "abc", string2: "def") == "abcdef"
// strcat(string1: "abc", string2: "def") == "abcdef"
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
```
### 3. 字符串比较
```swift
// Return 0 if equal, -1 if string1 < string2, 1 if string1 > string2
// strcmp(string1: "abc", string2: "def") == 1
// strcmp(string1: "abc", string2: "abc") == 0
// strcmp(string1: "abc", string2: "def") == -1
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
```
### 4. 字符串查找
```swift
// Return index of first occurrence of character in string, or -1 if not found
// strchr(string: "abc", character: "c") == 2
// strchr(string: "abc", character: "d") == -1
func strchr(string: String, character: Character) -> Int {
for (index, char) in string.enumerated() {
if char == character {
return index
}
}
return -1
}
```
### 5. 字符串替换
```swift
// Return string with all occurrences of character replaced by replacement
// strstr(string: "abc", character: "c", replacement: "d") == "abd"
// strstr(string: "abc", character: "d", replacement: "d") == "abc"
func strstr(string: String, character: Character, replacement: Character) -> String {
var string = string
for (index, char) in string.enumerated() {
if char == character {
string.remove(at: index)
string.insert(replacement, at: index)
}
}
return string
}
```
### 6. 字符串分割
```swift
// Return array of substrings separated by character
// strtok(string: "abc,def", character: ",") == ["abc", "def"]
// strtok(string: "abc,def", character: ",") == ["abc", "def"]
func strtok(string: String, character: Character) -> [String] {
var string = string
var tokens = [String]()
while !string.isEmpty {
let index = strchr(string: string, character: character)
if index == -1 {
tokens.append(string)
break
}
tokens.append(string[..<index])
string.removeSubrange(Range(uncheckedBounds: (lower: index, upper: index + 1)))
}
return tokens
}
```
### 7. 字符串合并
```swift
// Return string with substrings merged into one
// strtok(string: "abc,def", character: ",") == "abcdef"
// strtok(string: "abc,def", character: ",") == "abcdef"
func strtok(string: String, character: Character) -> String {
var string = string
var result = ""
while !string.isEmpty {
let index = strchr(string: string, character: character)
if index == -1 {
result += string
break
}
result += string[..<index]
string.removeSubrange(Range(uncheckedBounds: (lower: index, upper: index + 1)))
}
return result
}
```
###
string.remove(at: index) // cannot convert value of type 'Int' to expected argument type 'String.Index'
string.insert(replacement, at: index) // cannot convert value of type 'Int' to expected argument type 'String.Index'
tokens.append(string[..<index]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
string.removeSubrange(Range(uncheckedBounds: (lower: index, upper: index + 1))) // instance method 'removeSubrange' requires the types 'String.Index' and 'Int' be equivalent
result += string[..<index] // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
string.removeSubrange(Range(uncheckedBounds: (lower: index, upper: index + 1))) // instance method 'removeSubrange' requires the types 'String.Index' and 'Int' be equivalent
func strlen(string: String) -> Int {
var length = 0
for _ in string {
length += 1
}
return length
}
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
func strchr(string: String, character: Character) -> Character? {
for c in string {
if c == character {
return c
}
}
return nil
}
func strstr(string: String, character: Character) -> Character? {
for (index, c) in string.enumerated() {
if c == character {
return string[index]
}
}
return nil
}
func strtok(string: String, delimiter: Character) -> [String] {
var substrings = [String]()
var currentString = ""
for c in string {
if c == delimiter {
substrings.append(currentString)
currentString = ""
} else {
currentString.append(c)
}
}
substrings.append(currentString)
return substrings
}
func strcat(string: String, substrings: [String]) -> String {
var result = string
for s in substrings {
result += s
}
return result
}
```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
}
```
### 2. 字符串拼接
```swift
// Concatenate two strings
// strcat(string1: "abc", string2: "def") == "abcdef"
// strcat(string1: "abc", string2: "def") == "abcdef"
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
```
### 3. 字符串比较
```swift
// Compare two strings
// strcmp(string1: "abc", string2: "def") == -1
// strcmp(string1: "abc", string2: "abc") == 0
// strcmp(string1: "abc", string2: "abcd") == -1
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
```
### 4. 字符串查找
```swift
// Find a character in a string
// strchr(string: "abc", character: "a") == "a"
// strchr(string: "abc", character: "d") == nil
func strchr(string: String, character: Character) -> Character? {
for c in string {
if c == character {
return c
}
}
return nil
}
```
### 5. 字符串替换
```swift
// Replace a character in a string
// strstr(string: "abc", character: "a") == "a"
// strstr(string: "abc", character: "d") == nil
func strstr(string: String, character: Character) -> Character? {
for (index, c) in string.enumerated() {
if c == character {
return string[index]
}
}
return nil
}
```
### 6. 字符串分割
```swift
// Split a string into substrings
// strtok(string: "abc,def", delimiter: ",") == ["abc", "def"]
// strtok(string: "abc,def", delimiter: ",") == ["abc", "def"]
func strtok(string: String, delimiter: Character) -> [String] {
var substrings = [String]()
var currentString = ""
for c in string {
if c == delimiter {
substrings.append(currentString)
currentString = ""
} else {
currentString.append(c)
}
}
substrings.append(currentString)
return substrings
}
```
### 7. 字符串合并
```swift
// Merge a list of substrings into a string
// strcat(string: "abc", substrings: ["def", "ghi"]) == "abcdefghi"
// strcat(string: "abc", substrings: ["def", "ghi"]) == "abcdefghi"
func strcat(string: String, substrings: [String]) -> String {
var result = string
for s in substrings {
result += s
}
return result
}
```
### 8. 字符串比较
```swift
// Compare two strings
// strcmp(string1: "abc", string2: "def") == -1
// strcmp(string1: "abc", string2: "abc") == 0
// strcmp(string1: "abc", string2: "abcd") == -1
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
```
### 9.
return string[index] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func strlen(string: String) -> Int {
return string.count
}
func strlen(string: String) -> Int {
var count = 0
for c in string {
count += 1
}
return count
}
func strcat(string: String, string2: String) -> String {
return string + string2
}
func strcat(string: String, string2: String) -> String {
var result = ""
result += string
result += string2
return result
}
func strcmp(string: String, string2: String) -> Int {
if string < string2 {
return -1
} else if string > string2 {
return 1
} else {
return 0
}
}
func strcmp(string: String, string2: String) -> Int {
if string.compare(string2) == ComparisonResult.orderedSame {
return 0
} else if string.compare(string2) == ComparisonResult.orderedAscending {
return -1
} else {
return 1
}
}
func strchr(string: String, character: Character) -> Int? {
for (index, c) in string.enumerated() {
if c == character {
return index
}
}
return nil
}
func strstr(string: String, character: Character) -> String {
var result = ""
for c in string {
if c == character {
result += character
} else {
result += c
}
}
return result
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
return string.count
}
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for c in string {
count += 1
}
return count
}
```
### 2. 字符串拼接
```swift
// Return concatenated string
// strcat(string: "") == ""
// strcat(string: "abc") == "abc"
func strcat(string: String, string2: String) -> String {
return string + string2
}
// Return concatenated string
// strcat(string: "") == ""
// strcat(string: "abc") == "abc"
func strcat(string: String, string2: String) -> String {
var result = ""
result += string
result += string2
return result
}
```
### 3. 字符串比较
```swift
// Return 0 if strings are equal
// strcmp(string: "abc", string: "abc") == 0
// strcmp(string: "abc", string: "abcd") == -1
// strcmp(string: "abcd", string: "abc") == 1
func strcmp(string: String, string2: String) -> Int {
if string < string2 {
return -1
} else if string > string2 {
return 1
} else {
return 0
}
}
// Return 0 if strings are equal
// strcmp(string: "abc", string: "abc") == 0
// strcmp(string: "abc", string: "abcd") == -1
// strcmp(string: "abcd", string: "abc") == 1
func strcmp(string: String, string2: String) -> Int {
if string.compare(string2) == ComparisonResult.orderedSame {
return 0
} else if string.compare(string2) == ComparisonResult.orderedAscending {
return -1
} else {
return 1
}
}
```
### 4. 字符串查找
```swift
// Return index of first occurrence of character in string
// strchr(string: "abc", character: "c") == 2
// strchr(string: "abc", character: "d") == nil
func strchr(string: String, character: Character) -> Int? {
for (index, c) in string.enumerated() {
if c == character {
return index
}
}
return nil
}
// Return index of first occurrence of character in string
// strchr(string: "abc", character: "c") == 2
// strchr(string: "abc", character: "d") == nil
func strchr(string: String, character: Character) -> Int? {
for (index, c) in string.enumerated() {
if c == character {
return index
}
}
return nil
}
```
### 5. 字符串替换
```swift
// Return string with character replaced
// strstr(string: "abc", character: "c") == "abc"
// strstr(string: "abc", character: "d") == ""
func strstr(string: String, character: Character) -> String {
var result = ""
for c in string {
if c == character {
result += character
} else {
result += c
}
}
return result
}
// Return string with character replaced
// strstr(string: "abc", character: "c") == "abc"
// strstr(string: "abc", character: "d") == ""
func strstr(string: String, character: Character) -> String {
var result = ""
for (index, c) in string.enumerated() {
if c == character {
result += character
} else {
result += string[index]
}
}
func strlen(string: String) -> Int { // invalid redeclaration of 'strlen(string:)'
func strcat(string: String, string2: String) -> String { // invalid redeclaration of 'strcat(string:string2:)'
func strcmp(string: String, string2: String) -> Int { // invalid redeclaration of 'strcmp(string:string2:)'
result += character // cannot convert value of type 'Character' to expected argument type 'String'
result += c // cannot convert value of type 'Character' to expected argument type 'String'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
func strchr(string: String, character: Character) -> Int {
for (index, char) in string.enumerated() {
if char == character {
return index
}
}
return -1
}
func strstr(string: String, character: Character) -> String {
var result = ""
for (index, char) in string.enumerated() {
if char == character {
result += string[string.index(string.startIndex, offsetBy: index + 1) ..< string.index(string.startIndex, offsetBy: string.count)]
break
}
}
return result
}
func strtok(string: String, character: Character) -> [String] {
var result = [String]()
var startIndex = string.startIndex
var endIndex = string.startIndex
while endIndex < string.endIndex {
endIndex = string.index(endIndex, offsetBy: 1)
if string[endIndex] == character {
result.append(string[startIndex..<endIndex])
startIndex = string.index(endIndex, offsetBy: 1)
}
}
result.append(string[startIndex..<endIndex])
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
}
```
### 2. 字符串拼接
```swift
// Return concatenated string
// strcat(string1: "", string2: "") == ""
// strcat(string1: "abc", string2: "def") == "abcdef"
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
```
### 3. 字符串比较
```swift
// Return 0 if strings are equal
// Return -1 if string1 is less than string2
// Return 1 if string1 is greater than string2
// strcmp(string1: "", string2: "") == 0
// strcmp(string1: "abc", string2: "def") == -1
// strcmp(string1: "def", string2: "abc") == 1
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
```
### 4. 字符串查找
```swift
// Return index of first occurrence of character in string
// Return -1 if character is not found
// strchr(string: "", character: "") == -1
// strchr(string: "abc", character: "a") == 0
// strchr(string: "abc", character: "d") == -1
func strchr(string: String, character: Character) -> Int {
for (index, char) in string.enumerated() {
if char == character {
return index
}
}
return -1
}
```
### 5. 字符串替换
```swift
// Return string with character replaced
// strstr(string: "", character: "") == ""
// strstr(string: "abc", character: "a") == "bc"
// strstr(string: "abc", character: "d") == ""
func strstr(string: String, character: Character) -> String {
var result = ""
for (index, char) in string.enumerated() {
if char == character {
result += string[string.index(string.startIndex, offsetBy: index + 1) ..< string.index(string.startIndex, offsetBy: string.count)]
break
}
}
return result
}
```
### 6. 字符串分割
```swift
// Return array of substrings separated by character
// Return empty array if character is not found
// strtok(string: "", character: "") == []
// strtok(string: "abc", character: "a") == ["bc"]
// strtok(string: "abc", character: "d") == []
func strtok(string: String, character: Character) -> [String] {
var result = [String]()
var startIndex = string.startIndex
var endIndex = string.startIndex
while endIndex < string.endIndex {
endIndex = string.index(endIndex, offsetBy: 1)
if string[endIndex] == character {
result.append(string[startIndex..<endIndex])
startIndex = string.index(endIndex, offsetBy: 1)
}
}
result.append(string[startIndex..<endIndex])
return result
}
```
### 7. 字符串合并
```swift
// Return string with substrings merged
// strtok(string: "", character: "") == ""
// strtok(string: "abc", character: "a") == "bc"
// strtok(string: "abc", character: "d") == "abc"
func strtok(string: String, character: Character) -> String {
var result = ""
var startIndex = string.startIndex
var endIndex = string.startIndex
while endIndex < string.endIndex {
endIndex = string.index(endIndex, offset
result.append(string[startIndex..<endIndex]) // subscript 'subscript(_:)' requires the types 'String.Index' and 'Int' be equivalent
result.append(string[startIndex..<endIndex]) // subscript 'subscript(_:)' requires the types 'String.Index' and 'Int' be equivalent
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
func strchr(string: String, character: Character) -> Character? {
for c in string {
if c == character {
return c
}
}
return nil
}
func strstr(string: String, character: Character, replacement: Character) -> String {
var result = ""
for c in string {
if c == character {
result.append(replacement)
} else {
result.append(c)
}
}
return result
}
func strtok(string: String, delimiter: Character) -> [String] {
var result = [String]()
var start = 0
for (index, c) in string.enumerated() {
if c == delimiter {
result.append(string[start..<index])
start = index + 1
}
}
result.append(string[start..<string.count])
return result
}
func strjoin(strings: [String]) -> String {
var result = ""
for s in strings {
result.append(s)
result.append(", ")
}
result.removeLast()
return result
}
func strcspn(string: String, charactersToIgnore: CharacterSet) -> Int {
var count = 0
for c in string {
if !charactersToIgnore.contains(c) {
count += 1
}
}
return count
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
```
### 2. 字符串拼接
```swift
// Concatenate two strings
// strcat(string1: "Hello", string2: "World") == "HelloWorld"
func strcat(string1: String, string2: String) -> String {
return string1 + string2
}
```
### 3. 字符串比较
```swift
// Compare two strings
// strcmp(string1: "Hello", string2: "World") == -1
// strcmp(string1: "World", string2: "Hello") == 1
func strcmp(string1: String, string2: String) -> Int {
if string1 < string2 {
return -1
} else if string1 > string2 {
return 1
} else {
return 0
}
}
```
### 4. 字符串查找
```swift
// Find a character in a string
// strchr(string: "Hello", character: "l") == "l"
// strchr(string: "Hello", character: "z") == nil
func strchr(string: String, character: Character) -> Character? {
for c in string {
if c == character {
return c
}
}
return nil
}
```
### 5. 字符串替换
```swift
// Replace a character in a string
// strstr(string: "Hello", character: "l", replacement: "o") == "Helloo"
func strstr(string: String, character: Character, replacement: Character) -> String {
var result = ""
for c in string {
if c == character {
result.append(replacement)
} else {
result.append(c)
}
}
return result
}
```
### 6. 字符串分割
```swift
// Split a string into substrings
// strtok(string: "Hello, World", delimiter: ",") == ["Hello", " World"]
func strtok(string: String, delimiter: Character) -> [String] {
var result = [String]()
var start = 0
for (index, c) in string.enumerated() {
if c == delimiter {
result.append(string[start..<index])
start = index + 1
}
}
result.append(string[start..<string.count])
return result
}
```
### 7. 字符串合并
```swift
// Merge a list of strings into a single string
// strjoin(strings: ["Hello", "World"]) == "Hello, World"
func strjoin(strings: [String]) -> String {
var result = ""
for s in strings {
result.append(s)
result.append(", ")
}
result.removeLast()
return result
}
```
### 8. 字符串编码
```swift
// Encode a string into a byte array
// strcspn(string: "Hello", charactersToIgnore: "abc") == 5
func strcspn(string: String, charactersToIgnore: CharacterSet) -> Int {
var count = 0
for c in string {
if !charactersToIgnore.contains(c) {
count += 1
}
}
return count
}
```
### 9. 字符串解码
```swift
// Decode a byte array into a string
// strspn(byteArray: [0x48, 0x65, 0x6c, 0x6c, 0x6f], charactersToIgnore: "abc") == 5
func strspn(byteArray: [UInt8], charactersToIgnore: CharacterSet) -> Int {
var count = 0
for c in byteArray {
if !charactersToIgnore.contains(Character(UnicodeScalar(c))) {
result.append(string[start..<index]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
result.append(string[start..<string.count]) // 'subscript(_:)' is unavailable: cannot subscript String with an integer range, use a String.Index range instead.
if !charactersToIgnore.contains(c) { // cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'
func strlen(string: String) -> Int {
var count = 0
for _ in string {
count += 1
}
return count
}
class Solution {
func reverseWords(_ s: String) -> String {
let arr = s.split(separator: " ").map { String($0) }
var res = ""
for i in (0..<arr.count).reversed() {
if i == arr.count - 1 {
res += arr[i]
} else {
res += arr[i] + " "
}
}
return res
}
}
```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
}
```
### 代码
```swift
class Solution {
func reverseWords(_ s: String) -> String {
let arr = s.split(separator: " ").map { String($0) }
var res = ""
for i in (0..<arr.count).reversed() {
if i == arr.count - 1 {
res += arr[i]
} else {
res += arr[i] + " "
}
}
return res
}
}
```
func strlen(string: String) -> Int {
var count = 0
for c in string {
count += 1
}
return count
}
class Solution {
func reverseWords(_ s: String) -> String {
let strArr = s.split(separator: " ")
var res = ""
for str in strArr {
res += String(str.reversed()) + " "
}
return String(res.reversed())
}
}
```swift
// Return length of given string
// strlen(string: "") == 0
// strlen(string: "abc") == 3
func strlen(string: String) -> Int {
var count = 0
for c in string {
count += 1
}
return count
}
```
### 代码
```swift
class Solution {
func reverseWords(_ s: String) -> String {
let strArr = s.split(separator: " ")
var res = ""
for str in strArr {
res += String(str.reversed()) + " "
}
return String(res.reversed())
}
}
```
for c in string { // immutable value 'c' was never used; consider replacing with '_' or removing it
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法二:二分查找
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left
}
```
### 解法三:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法四:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法五:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法六:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法七:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法八:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法九:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法十:数学
```swift
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
var i = 1
while i * i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
var i = n
while i * i > n {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
```
### 解法二
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法三
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 1
while i * i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
```
### 解法四
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i * i > n {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法五
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法六
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i * i > n {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法七
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法八
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i * i > n {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法九
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 0 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法十
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 2
}
return i / 2
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法二
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法三
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法四
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法五
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法六
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法七
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法八
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法九
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法十
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法十一
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n:
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = 1
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 1
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```
### 解法二:二分查找
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
```
### 解法三:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
if n == 1 {
return 1
}
let i = n / 2
if i * 2 == n {
return i
} else {
return largestDivisor(n: i)
}
}
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 2
}
return i / 2
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 3
}
return i / 3
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 5
}
return i / 5
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 7
}
return i / 7
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 11
}
return i / 11
}
```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 = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return 1
}
```
### 解法二:递归
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
if n == 1 {
return 1
}
let i = n / 2
if i * 2 == n {
return i
} else {
return largestDivisor(n: i)
}
}
```
### 解法三:二分查找
```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 left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
```
### 解法四:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法五:数学
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法六:数学
```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 n % i == 0 {
i *= 3
}
return i / 3
}
```
### 解法七:数学
```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 n % i == 0 {
i *= 5
}
return i / 5
}
```
### 解法八:数学
```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 n % i == 0 {
i *= 7
}
return i / 7
}
```
### 解法九:数学
```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 n % i == 0 {
i *= 11
}
return i / 11
}
```
### 解法十:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
func largestDivisor(n: Int) -> Int {
var i = 1
while i * i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```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 = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```
### 解法二
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 1
while i * i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```
### 解法三
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```
### 解法四
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法五
```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 n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法六
```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 n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法七
```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 n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法八
```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 n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法九
```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 n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法十
```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 n % i == 0 {
i += 1
}
return i == n ? -1 : i
}
```
### 解法十一
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= largestDivisor(n: i)
}
return 1
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法二:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= largestDivisor(n: i)
}
return 1
}
```
### 解法三:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法四:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法五:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法六:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法七:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法八:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法九:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法十:
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
func largestDivisor(n: Int) -> Int {
if n == 1 {
return 1
}
let i = n / 2
if n % i == 0 {
return i
} else {
return largestDivisor(n: i)
}
}
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
func largestDivisor(n: Int) -> Int {
var i = 2
while n % i == 0 {
i *= 2
}
return i / 2
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = n
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return 1
}
```
### 解法二:递归
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
if n == 1 {
return 1
}
let i = n / 2
if n % i == 0 {
return i
} else {
return largestDivisor(n: i)
}
}
```
### 解法三:二分查找
```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 left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left
}
```
### 解法四:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
### 解法五:数学
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法六:数学
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法七:数学
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法八:数学
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法九:数学
```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 n % i == 0 {
i *= 2
}
return i / 2
}
```
### 解法十:数学
```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
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return i
}
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left
}
func largestDivisor(n: Int) -> Int {
var i = 2
while i * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```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 = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return i
}
```
### 解法二:二分查找
```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 left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left
}
```
### 解法三:数学
```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 * i <= n {
if n % i == 0 {
return i
}
i += 1
}
return n
}
```
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var i = 1
while i < n {
if n % i == 0 {
return i
}
i += 1
}
return -1
}
```
### 解法二:二分查找
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
var left = 1
var right = n
while left < right {
let mid = left + (right - left) / 2
if n % mid == 0 {
left = mid + 1
} else {
right = mid
}
}
return left - 1
}
```
### 解法三:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```
### 解法四:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```
### 解法五:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```
### 解法六:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```
### 解法七:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```
### 解法八:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n: 15) == 5
func largestDivisor(n: Int) -> Int {
let sqrt = Int(sqrt(Double(n)))
var i = sqrt
while i > 1 {
if n % i == 0 {
return i
}
i -= 1
}
return -1
}
```
### 解法九:数学
```swift
// For a given number n, find the largest number that divides n evenly, smaller than n
// largestDivisor(n:
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func largestDivisor(n: Int) -> Int { // invalid redeclaration of 'largestDivisor(n:)'
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
var i = 2
while n > 1 {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
var i = 2
while n > 1 {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
var i = 2
while n > 1 {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
var i = 2
while n > 1 {
if n % i == 0 {
factors.append(i)
n /= i
} else {
i += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var num = n
var i = 2
while num > 1 {
if num % i == 0 {
factors.append(i)
num /= i
} else {
i += 1
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors: [Int] = []
var num = n
var i = 2
while num > 1 {
if num % i == 0 {
factors.append(i)
num /= i
} else {
i += 1
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var num = n
for i in 2...n {
while num % i == 0 {
factors.append(i)
num /= i
}
}
return factors
}
class Solution {
func primeFactors(_ n: Int) -> [Int] {
var factors = [Int]()
var num = n
for i in 2...n {
while num % i == 0 {
factors.append(i)
num /= i
}
}
return factors
}
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var num = n
for i in 2...n {
while num % i == 0 {
factors.append(i)
num /= i
}
}
return factors
}
```
### 解题思路
### 代码
```swift
class Solution {
func primeFactors(_ n: Int) -> [Int] {
var factors = [Int]()
var num = n
for i in 2...n {
while num % i == 0 {
factors.append(i)
num /= i
}
}
return factors
}
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```swift
// Return array of prime factors of given integer in the order from smallest to largest.
// Each of the factors should be arrayed number of times corresponding to how many times it appeares in factorization.
// Input number should be equal to the product of all factors
// factorize(n: 8) == [2, 2, 2]
// factorize(n: 25) == [5, 5]
// factorize(n: 70) == [2, 5, 7]
func factorize(n: Int) -> [Int] {
var factors = [Int]()
var n = n
for i in 2...n {
while n % i == 0 {
factors.append(i)
n /= i
}
}
return factors
}
```
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.contains(number) {
continue
}
result.append(number)
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.remove(where: { $0 == number })
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.removeFirst()
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.removeLast()
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.remove(at: 0)
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.contains(number) {
continue
}
result.append(number)
}
return result
}
```
### 解法二
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.remove(where: { $0 == number })
}
return result
}
```
### 解法三
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
result.removeFirst()
}
return result
}
```
### 解法四
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
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]()
for number in numbers {
result.append(number)
result.remove(at: 0)
}
return result
}
```
### 解法六
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
result.append(number)
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]()
for number in numbers {
result.append(number)
result.removeFirst()
}
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]) ->
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
result.remove(where: { $0 == number }) // no exact matches in call to instance method 'remove'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var i = 0
for number in numbers {
if i == 0 || result[i - 1] != number {
result.append(number)
}
i += 1
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int: Int]()
var i = 0
for number in numbers {
if result[number] == nil {
result[number] = 1
result.append(number)
}
i += 1
}
return result.keys.map { $0 }
}
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
return removeDuplicates(numbers: numbers) + [last]
}
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
var result = removeDuplicates(numbers: numbers)
if result.count == 0 || result.last! != last {
result.append(last)
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
```
### 解法二:双指针
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var i = 0
for number in numbers {
if i == 0 || result[i - 1] != number {
result.append(number)
}
i += 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: Int]()
var i = 0
for number in numbers {
if result[number] == nil {
result[number] = 1
result.append(number)
}
i += 1
}
return result.keys.map { $0 }
}
```
### 解法四:递归
```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] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
return removeDuplicates(numbers: numbers) + [last]
}
```
### 解法五:递归 + 哈希表
```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] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
var result = removeDuplicates(numbers: numbers)
if result.count == 0 || result.last! != last {
result.append(last)
}
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] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
var result = removeDuplicates(numbers: numbers)
if result.count == 0 || result.last! != last {
result.append(last)
}
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:
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
result.append(number) // value of type '[Int : Int]' has no member 'append'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
let last = numbers.removeLast() // cannot use mutating member on immutable value: 'numbers' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
let last = numbers.removeLast() // cannot use mutating member on immutable value: 'numbers' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else {
return []
}
var result = [Int]()
result.append(numbers[0])
for i in 1..<numbers.count {
if result.last! != numbers[i] {
result.append(numbers[i])
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else {
return []
}
var result = [Int]()
result.append(numbers[0])
for i in 1..<numbers.count {
if result.last! != numbers[i] {
result.append(numbers[i])
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if !seen.contains(number) {
result.append(number)
seen.insert(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
guard numbers.count > 0 else { return [] }
var result = [Int]()
result.append(numbers[0])
var i = 0
for j in 1..<numbers.count {
if numbers[j] != numbers[i] {
i += 1
result.append(numbers[j])
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var seen = Set<Int>()
for number in numbers {
if !seen.contains(number) {
result.append(number)
seen.insert(number)
}
}
return result
}
```
### 解法二:双指针
```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] {
guard numbers.count > 0 else { return [] }
var result = [Int]()
result.append(numbers[0])
var i = 0
for j in 1..<numbers.count {
if numbers[j] != numbers[i] {
i += 1
result.append(numbers[j])
}
}
return result
}
```
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
```
// XCTAssertTrue failed
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for num in numbers {
if dict[num] == nil {
result.append(num)
dict[num] = 1
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var i = 0
for num in numbers {
if i < 1 || num != result[i - 1] {
result.append(num)
i += 1
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for num in numbers {
if dict[num] == nil {
result.append(num)
dict[num] = 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 i = 0
for num in numbers {
if i < 1 || num != result[i - 1] {
result.append(num)
i += 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 i = 0
for num in numbers {
if i < 1 || num != result[i - 1] {
result.append(num)
i += 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 i = 0
for num in numbers {
if i < 1 || num != result[i - 1] {
result.append(num)
i += 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 i = 0
for num in numbers {
if i < 1 || num != result[i - 1] {
result.append(num)
i += 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 i = 0
for num in numbers {
if i < 1 || num != result[i - 1] {
result.append(num)
i += 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,
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
var result = [Int]()
result.append(numbers[0])
var i = 1
for j in 1..<numbers.count {
if numbers[j] != numbers[i - 1] {
result.append(numbers[j])
i += 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]()
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
```
### 解法二:双指针
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
var result = [Int]()
result.append(numbers[0])
var i = 1
for j in 1..<numbers.count {
if numbers[j] != numbers[i - 1] {
result.append(numbers[j])
i += 1
}
}
return result
}
```
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = numbers
var i = 0
while i < result.count {
var j = i + 1
while j < result.count {
if result[i] == result[j] {
result.remove(at: j)
} else {
j += 1
}
}
i += 1
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
var i = 0
for j in 1..<numbers.count {
if numbers[i] != numbers[j] {
i += 1
numbers[i] = numbers[j]
}
}
return Array(numbers[0..<i + 1])
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = Set<Int>()
for number in numbers {
result.insert(number)
}
return Array(result)
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int: Int]()
var i = 0
for number in numbers {
if result[number] == nil {
result[number] = 1
numbers[i] = number
i += 1
}
}
return Array(numbers[0..<i])
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = [Int]()
var i = 0
for number in numbers {
if result.count == 0 || result[i] != number {
result.append(number)
i += 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 = numbers
var i = 0
while i < result.count {
var j = i + 1
while j < result.count {
if result[i] == result[j] {
result.remove(at: j)
} else {
j += 1
}
}
i += 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] {
if numbers.count == 0 {
return []
}
var i = 0
for j in 1..<numbers.count {
if numbers[i] != numbers[j] {
i += 1
numbers[i] = numbers[j]
}
}
return Array(numbers[0..<i + 1])
}
```
### 解法三:HashSet
```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 = Set<Int>()
for number in numbers {
result.insert(number)
}
return Array(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] {
if numbers.count == 0 {
return []
}
var i = 0
for j in 1..<numbers.count {
if numbers[i] != numbers[j] {
i += 1
numbers[i] = numbers[j]
}
}
return Array(numbers[0..<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: Int]()
var i = 0
for number in numbers {
if result[number] == nil {
result[number] = 1
numbers[i] = number
i += 1
}
}
return Array(numbers[0..<i])
}
```
### 解法六:递归 + 哈希表 + 数组
```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 i = 0
for number in numbers {
if result.count == 0 || result[i] != number {
result.append(number)
i += 1
}
}
return result
}
```
### 解法
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
numbers[i] = numbers[j] // cannot assign through subscript: 'numbers' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
numbers[i] = number // cannot assign through subscript: 'numbers' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result: [Int] = []
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
var slow = 0
var fast = 1
while fast < numbers.count {
if numbers[slow] != numbers[fast] {
slow += 1
numbers[slow] = numbers[fast]
}
fast += 1
}
return Array(numbers[0..<slow + 1])
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var set: Set<Int> = []
for number in numbers {
set.insert(number)
}
return Array(set)
}
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
return removeDuplicates(numbers: numbers) + [last]
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var map: [Int: Int] = [:]
var result: [Int] = []
for number in numbers {
if map[number] == nil {
result.append(number)
map[number] = 1
}
}
return result
}
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var result: [Int] = []
for number in numbers {
if result.count == 0 || result.last! != number {
result.append(number)
}
}
return result
}
```
### 解法二:双指针
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
if numbers.count == 0 {
return []
}
var slow = 0
var fast = 1
while fast < numbers.count {
if numbers[slow] != numbers[fast] {
slow += 1
numbers[slow] = numbers[fast]
}
fast += 1
}
return Array(numbers[0..<slow + 1])
}
```
### 解法三:Set
```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 set: Set<Int> = []
for number in numbers {
set.insert(number)
}
return Array(set)
}
```
### 解法四:递归
```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] {
if numbers.count == 0 {
return []
}
let last = numbers.removeLast()
return removeDuplicates(numbers: numbers) + [last]
}
```
### 解法五:递归 + 哈希表
```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 map: [Int: Int] = [:]
var result: [Int] = []
for number in numbers {
if map[number] == nil {
result.append(number)
map[number] = 1
}
}
return result
}
```
### 解法六:递归 + 哈希表 + 数组
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4]) == [1, 3, 4]
func removeDuplicates(numbers: [Int]) -> [Int] {
var map: [Int: Int] = [:]
var result: [Int] = []
for number in numbers {
if map[number] == nil {
result.append(number)
map[number] = 1
}
}
return result
}
```
### 解法七:递归 + 哈希表 + 数组 + 数组
```swift
// From an array of integers, remove all elements that occur more than once.
// Keep order of elements left the same as in the input.
// removeDuplicates(numbers: [1, 2, 3, 2, 4])
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
numbers[slow] = numbers[fast] // cannot assign through subscript: 'numbers' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
let last = numbers.removeLast() // cannot use mutating member on immutable value: 'numbers' is a 'let' constant
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
func removeDuplicates(numbers: [Int]) -> [Int] {
var result = numbers
var i = 0
while i < result.count {
let j = result.index(result.startIndex, offsetBy: i + 1)
if result[i] == result[j] {
result.remove(at: j)
} else {
i += 1
}
}
return result
}
func removeDuplicates(numbers: [Int]) -> [Int] {
var i = 0
for j in 1 ..< numbers.count {
if numbers[i] != numbers[j] {
i += 1
numbers[i] = numbers[j]
}
}
return Array(numbers[0 ..< 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 = numbers
var i = 0
while i < result.count {
let j = result.index(result.startIndex, offsetBy: i + 1)
if result[i] == result[j] {
result.remove(at: j)
} else {
i += 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 i = 0
for j in 1 ..< numbers.count {
if numbers[i] != numbers[j] {
i += 1
numbers[i] = numbers[j]
}
}
return Array(numbers[0 ..< i + 1])
}
```
func removeDuplicates(numbers: [Int]) -> [Int] { // invalid redeclaration of 'removeDuplicates(numbers:)'
numbers[i] = numbers[j] // cannot assign through subscript: 'numbers' is a 'let' constant
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
func flipCase(string: String) -> String {
return string.replacingOccurrences(of: "[a-z]", with: String(c.uppercase))
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法二:使用正则表达式
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.replacingOccurrences(of: "[a-z]", with: String(c.uppercase))
}
```
### 解法三:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法四:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法五:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法六:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法七:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法八:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法九:使用字符串的遍历
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
### 解法十:使用字符串的
func flipCase(string: String) -> String { // invalid redeclaration of 'flipCase(string:)'
return string.replacingOccurrences(of: "[a-z]", with: String(c.uppercase)) // cannot find 'c' in scope
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(Character(UnicodeScalar(c.asciiValue! - 32)!))
} else {
result.append(Character(UnicodeScalar(c.asciiValue! + 32)!))
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(Character(UnicodeScalar(c.asciiValue! - 32)!))
} else {
result.append(Character(UnicodeScalar(c.asciiValue! + 32)!))
}
}
return result
}
```
result.append(Character(UnicodeScalar(c.asciiValue! - 32)!)) // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
result.append(Character(UnicodeScalar(c.asciiValue! + 32)!)) // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(c.uppercased().first!)
} else {
result.append(c.lowercased().first!)
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(c.uppercased().first!)
} else {
result.append(c.lowercased().first!)
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(Character(UnicodeScalar(c.asciiValue! - 32)!))
} else {
result.append(Character(UnicodeScalar(c.asciiValue! + 32)!))
}
}
return result
}
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c.isLowercase ? Character(UnicodeScalar(c.asciiValue! - 32)!): Character(UnicodeScalar(c.asciiValue! + 32)!))
}
return result
}
func flipCase(string: String) -> String {
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) }
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(Character(UnicodeScalar(c.asciiValue! - 32)!))
} else {
result.append(Character(UnicodeScalar(c.asciiValue! + 32)!))
}
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c.isLowercase ? Character(UnicodeScalar(c.asciiValue! - 32)!): Character(UnicodeScalar(c.asciiValue! + 32)!))
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c.isLowercase ? Character(UnicodeScalar(c.asciiValue! - 32)!): Character(UnicodeScalar(c.asciiValue! + 32)!))
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) }
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) }
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) }
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) }
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) }
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
result.append(Character(UnicodeScalar(c.asciiValue! - 32)!)) // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
result.append(Character(UnicodeScalar(c.asciiValue! + 32)!)) // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
func flipCase(string: String) -> String { // invalid redeclaration of 'flipCase(string:)'
result.append(c.isLowercase ? Character(UnicodeScalar(c.asciiValue! - 32)!): Character(UnicodeScalar(c.asciiValue! + 32)!)) // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
result.append(c.isLowercase ? Character(UnicodeScalar(c.asciiValue! - 32)!): Character(UnicodeScalar(c.asciiValue! + 32)!)) // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
func flipCase(string: String) -> String { // invalid redeclaration of 'flipCase(string:)'
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) } // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) } // cannot convert return expression of type '[Character]' to return type 'String'
return string.map { $0.isLowercase ? Character(UnicodeScalar($0.asciiValue! - 32)!) : Character(UnicodeScalar($0.asciiValue! + 32)!) } // cannot force unwrap value of non-optional type 'UnicodeScalar' (aka 'Unicode.Scalar')
func flipCase(string: String) -> String {
var chars = Array(string)
for i in 0..<chars.count {
if chars[i].isLowercase {
chars[i] = chars[i].uppercased()
} else {
chars[i] = chars[i].lowercased()
}
}
return String(chars)
}
func reverseString(string: String) -> String {
var chars = Array(string)
var left = 0
var right = chars.count - 1
while left < right {
chars.swapAt(left, right)
left += 1
right -= 1
}
return String(chars)
}
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var chars = Array(string)
for i in 0..<chars.count {
if chars[i].isLowercase {
chars[i] = chars[i].uppercased()
} else {
chars[i] = chars[i].lowercased()
}
}
return String(chars)
}
```
```swift
// For a given string, reverse its characters.
// reverseString(string: "hello") == "olleh"
func reverseString(string: String) -> String {
var chars = Array(string)
var left = 0
var right = chars.count - 1
while left < right {
chars.swapAt(left, right)
left += 1
right -= 1
}
return String(chars)
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count += 1
}
}
return count
}
```
```swift
// For a given string, return the number of occurrences of a given target letter.
// countLetters(string: "tree", letter: "e") == 2
func countLetters(string: String, letter: Character) -> Int {
var count = 0
for c in string {
if c == letter {
count
chars[i] = chars[i].uppercased() // cannot assign value of type 'String' to subscript of type 'String.Element' (aka 'Character')
chars[i] = chars[i].lowercased() // cannot assign value of type 'String' to subscript of type 'String.Element' (aka 'Character')
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased().first!)
} else {
result.append(char.lowercased().first!)
}
}
return result
}
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
if char.isLowercase {
result.append(char.uppercased().first!)
} else {
result.append(char.lowercased().first!)
}
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for char in string {
result.append(char.isLowercase ? char.uppercased().first! : char.lowercased().first!)
}
return result
}
```
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
func flipCase(string: String) -> String { // invalid redeclaration of 'flipCase(string:)'
func flipCase(string: String) -> String {
let chars = Array(string)
var result = ""
for char in chars {
if char.isLowercase {
result.append(char.uppercased().first!)
} else {
result.append(char.lowercased().first!)
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
let chars = Array(string)
var result = ""
for char in chars {
if char.isLowercase {
result.append(char.uppercased().first!)
} else {
result.append(char.lowercased().first!)
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
// XCTAssertTrue failed
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(c.uppercased().first!)
} else {
result.append(c.lowercased().first!)
}
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
if c.isLowercase {
result.append(c.uppercased().first!)
} else {
result.append(c.lowercased().first!)
}
}
return result
}
```
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```swift
// For a given string, flip lowercase characters to uppercase and uppercase to lowercase.
// flipCase(string: "Hello") == "hELLO"
func flipCase(string: String) -> String {
var result = ""
for c in string {
result.append(c == "a" || c == "A" ? "A" : "a")
}
return result
}
```
// XCTAssertTrue failed
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func split(string: String) -> [String] {
return Array(string)
}
func join(strings: [String]) -> String {
return strings.joined()
}
func split(string: String) -> [Character] {
return Array(string)
}
func join(characters: [Character]) -> String {
return String(characters)
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined()
}
```
### 2.1.2 字符串转数组
```swift
// Split a string into an array of strings
// split("abc") == ["a", "b", "c"]
func split(string: String) -> [String] {
return Array(string)
}
```
### 2.1.3 数组转字符串
```swift
// Join an array of strings into a single string
// join(strings: ["a", "b", "c"]) == "abc"
func join(strings: [String]) -> String {
return strings.joined()
}
```
### 2.1.4 字符串转数组
```swift
// Split a string into an array of characters
// split(string: "abc") == ["a", "b", "c"]
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.1.5 数组转字符串
```swift
// Join an array of characters into a single string
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.1.6 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "abc") == ["a", "b", "c"]
func split(string: String) -> [String] {
return Array(string)
}
```
### 2.1.7 数组转字符串
```swift
// Join an array of strings into a single string
// join(strings: ["a", "b", "c"]) == "abc"
func join(strings: [String]) -> String {
return strings.joined()
}
```
### 2.1.8 字符串转数组
```swift
// Split a string into an array of characters
// split(string: "abc") == ["a", "b", "c"]
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.1.9 数组转字符串
```swift
// Join an array of characters into a single string
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.1.10 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "abc") == ["a", "b", "c"]
func split(string: String) -> [String] {
return Array(string)
}
```
### 2.1.11 数组转字符串
```swift
// Join an array of strings into a single string
// join(strings: ["a", "b", "c"]) == "abc"
func join(strings: [String]) -> String {
return strings.joined()
}
```
### 2.1.12 字符串转数组
```swift
// Split a string into an array of characters
// split(string: "abc") == ["a", "b", "c"]
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.1.13 数组转字符串
```swift
// Join an array of characters into a single string
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.1.14 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "abc") == ["a", "b", "c"]
func split(string: String) ->
return Array(string) // missing argument label 'arrayLiteral:' in call
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined()
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined(separator: "")
}
```
```swift
// Conc
func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
func concatenate(strings: [String]) -> String { // invalid redeclaration of 'concatenate(strings:)'
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined()
}
```
### 2.3 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "a b c") == ["a", "b", "c"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.4 字符串转字典
```swift
// Split a string into an array of strings
// split(string: "a=b c=d") == ["a=b", "c=d"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.5 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "a b c") == ["a", "b", "c"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.6 字符串转字典
```swift
// Split a string into an array of strings
// split(string: "a=b c=d") == ["a=b", "c=d"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.7 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "a b c") == ["a", "b", "c"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.8 字符串转字典
```swift
// Split a string into an array of strings
// split(string: "a=b c=d") == ["a=b", "c=d"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.9 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "a b c") == ["a", "b", "c"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.10 字符串转字典
```swift
// Split a string into an array of strings
// split(string: "a=b c=d") == ["a=b", "c=d"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.11 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "a b c") == ["a", "b", "c"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.12 字符串转字典
```swift
// Split a string into an array of strings
// split(string: "a=b c=d") == ["a=b", "c=d"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.13 字符串转数组
```swift
// Split a string into an array of strings
// split(string: "a b c") == ["a", "b", "c"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
### 2.14 字符串转字典
```swift
// Split a string into an array of strings
// split(string: "a=b c=d") == ["a=b", "c=d"]
func split(string: String) -> [String] {
return string.split(separator: " ")
}
```
###
return string.split(separator: " ") // no 'split' candidates produce the expected contextual result type '[String]'
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func sort(strings: [String]) -> [String] {
return strings.sorted()
}
func removeDuplicates(strings: [String]) -> [String] {
return Set(strings).sorted()
}
func intersection(strings: [String], otherStrings: [String]) -> [String] {
return strings.filter { otherStrings.contains($0) }
}
func difference(strings: [String], otherStrings: [String]) -> [String] {
return strings.filter { !otherStrings.contains($0) }
}
func symmetricDifference(strings: [String], otherStrings: [String]) -> [String] {
return Set(strings).symmetricDifference(Set(otherStrings)).sorted()
}
func isSubset(strings: [String], otherStrings: [String]) -> Bool {
return strings.allSatisfy { otherStrings.contains($0) }
}
func containsAll(strings: [String], otherStrings: [String]) -> Bool {
return strings.contains(where: { otherStrings.contains($0) })
}
func containsAny(strings: [String], otherStrings: [String]) -> Bool {
return strings.contains(where: { otherStrings.contains($0) })
}
func isEmpty(strings: [String]) -> Bool {
return strings.isEmpty
}
```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()
}
```
### 2.2.3. 数组排序
```swift
// Sort array of strings
// sort(strings: ["c", "a", "b"]) == ["a", "b", "c"]
func sort(strings: [String]) -> [String] {
return strings.sorted()
}
```
### 2.2.4. 数组去重
```swift
// Remove duplicates from an array of strings
// removeDuplicates(strings: ["a", "b", "a", "b", "c"]) == ["a", "b", "c"]
func removeDuplicates(strings: [String]) -> [String] {
return Set(strings).sorted()
}
```
### 2.2.5. 数组交集
```swift
// Find the intersection of two arrays of strings
// intersection(["a", "b", "c"], ["b", "c", "d"]) == ["b", "c"]
func intersection(strings: [String], otherStrings: [String]) -> [String] {
return strings.filter { otherStrings.contains($0) }
}
```
### 2.2.6. 数组差集
```swift
// Find the difference between two arrays of strings
// difference(["a", "b", "c"], ["b", "c", "d"]) == ["a"]
func difference(strings: [String], otherStrings: [String]) -> [String] {
return strings.filter { !otherStrings.contains($0) }
}
```
### 2.2.7. 数组对称差集
```swift
// Find the symmetric difference of two arrays of strings
// symmetricDifference(["a", "b", "c"], ["b", "c", "d"]) == ["a", "d"]
func symmetricDifference(strings: [String], otherStrings: [String]) -> [String] {
return Set(strings).symmetricDifference(Set(otherStrings)).sorted()
}
```
### 2.2.8. 数组是否包含另一个数组
```swift
// Check if one array of strings is a subset of another
// isSubset(["a", "b"], ["a", "b", "c"]) == true
// isSubset(["a", "b"], ["a", "c"]) == false
func isSubset(strings: [String], otherStrings: [String]) -> Bool {
return strings.allSatisfy { otherStrings.contains($0) }
}
```
### 2.2.9. 数组是否包含另一个数组中的所有元素
```swift
// Check if one array of strings contains all elements of another
// containsAll(["a", "b", "c"], ["a", "b"]) == true
// containsAll(["a", "b", "c"], ["a", "c"]) == false
func containsAll(strings: [String], otherStrings: [String]) -> Bool {
return strings.contains(where: { otherStrings.contains($0) })
}
```
### 2.2.10. 数组是否包含另一个数组中的任意元素
```swift
// Check if one array of strings contains any element of another
// containsAny(["a", "b", "c"], ["a", "b"]) == true
// containsAny(["a", "b", "c"], ["a", "c"]) == true
func containsAny(strings: [String], otherStrings: [String]) -> Bool {
return strings.contains(where: { otherStrings.contains($0) })
}
```
### 2.2.11. 数组是否为空
```swift
// Check if an array of strings is empty
// isEmpty(["a", "b", "c"]) == false
// isEmpty([]) == true
func isEmpty(strings: [String]) -> Bool {
return strings.isEmpty
}
```
### 2.2.12. 数组是否为空
```swift
// Check if an array
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func split(string: String) -> [String] {
return Array(string)
}
func split(string: String) -> [Character] {
return Array(string)
}
```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()
}
```
### 2.3.2. 字符串数组转字符串
```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()
}
```
### 2.3.3. 字符串转字符串数组
```swift
// Split string into array of strings
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [String] {
return Array(string)
}
```
### 2.3.4. 字符串数组转字符串数组
```swift
// Split string into array of strings
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [String] {
return Array(string)
}
```
### 2.3.5. 字符串转字符数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.6. 字符串数组转字符数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.7. 字符串转字符数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.8. 字符串数组转字符数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.9. 字符串转数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.10. 字符串数组转数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.11. 字符串转数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.12. 字符串数组转数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
}
```
### 2.3.13. 字符串转数组
```swift
// Split string into array of characters
// split("abc") == ["a", "b", "c"]
// split("") == []
func split(string: String) -> [Character] {
return Array(string)
return Array(string) // missing argument label 'arrayLiteral:' in call
func concatenate(strings: [String]) -> String {
return strings.joined()
}
class Solution {
func reverseWords(_ s: String) -> String {
return s.split(separator: " ").reversed().joined(separator: " ")
}
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined()
}
```
### 代码
```swift
class Solution {
func reverseWords(_ s: String) -> String {
return s.split(separator: " ").reversed().joined(separator: " ")
}
}
```
func concatenate(strings: [String]) -> String {
return strings.joined()
}
```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()
}
```
### 2. 字符串拼接
```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()
}
```
### 3. 字符串拼接
```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()
}
```
### 4. 字符串拼接
```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()
}
```
### 5. 字符串拼接
```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()
}
```
### 6. 字符串拼接
```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()
}
```
### 7. 字符串拼接
```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()
}
```
### 8. 字符串拼接
```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()
}
```
### 9. 字符串拼接
```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()
}
```
### 10. 字符串拼接
```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()
}
```
### 11. 字符串拼接
```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()
}
```
### 12. 字符串拼接
```swift
// Concatenate array of strings into a single string
// concatenate(strings
func concatenate(strings: [String]) -> String {
return strings.joined()
}
func join(strings: [String]) -> String {
return strings.joined(separator: " ")
}
func characters(string: String) -> [Character] {
return Array(string)
}
func join(characters: [Character]) -> String {
return String(characters)
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
return strings.joined()
}
```
### 2.2.2. 字符串数组转字符串
```swift
// Convert array of strings into a single string
// join(strings: [] as [String]) == ""
// join(strings: ["a", "b", "c"]) == "a b c"
func join(strings: [String]) -> String {
return strings.joined(separator: " ")
}
```
### 2.2.3. 字符串转数组
```swift
// Convert string into an array of characters
// characters(string: "") == []
// characters(string: "abc") == ["a", "b", "c"]
func characters(string: String) -> [Character] {
return Array(string)
}
```
### 2.2.4. 字符串转数组
```swift
// Convert string into an array of characters
// characters(string: "") == []
// characters(string: "abc") == ["a", "b", "c"]
func characters(string: String) -> [Character] {
return Array(string)
}
```
### 2.2.5. 数组转字符串
```swift
// Convert array of characters into a string
// join(characters: [] as [Character]) == ""
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.2.6. 数组转字符串
```swift
// Convert array of characters into a string
// join(characters: [] as [Character]) == ""
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.2.7. 字符串转数组
```swift
// Convert string into an array of characters
// characters(string: "") == []
// characters(string: "abc") == ["a", "b", "c"]
func characters(string: String) -> [Character] {
return Array(string)
}
```
### 2.2.8. 字符串转数组
```swift
// Convert string into an array of characters
// characters(string: "") == []
// characters(string: "abc") == ["a", "b", "c"]
func characters(string: String) -> [Character] {
return Array(string)
}
```
### 2.2.9. 数组转字符串
```swift
// Convert array of characters into a string
// join(characters: [] as [Character]) == ""
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.2.10. 数组转字符串
```swift
// Convert array of characters into a string
// join(characters: [] as [Character]) == ""
// join(characters: ["a", "b", "c"]) == "abc"
func join(characters: [Character]) -> String {
return String(characters)
}
```
### 2.2.11. 字符串转数组
```swift
// Convert string into an array of characters
// characters(string: "") == []
// characters(string: "abc") == ["a", "b", "c"]
func characters(string: String) -> [Character] {
return Array(string)
}
```
### 2.2.12. 字符串转数组
```swift
// Convert string into an array of characters
// characters(string: "") == []
// characters(string: "abc") == ["a", "b", "c"]
func characters(string: String) -> [Character] {
return Array(string)
}
func concatenate(strings: [String]) -> String {
return strings.joined()
}
class Solution {
func reverseWords(_ s: String) -> String {
let words = s.split(separator: " ")
var res = ""
for word in words.reversed() {
if word.count > 0 {
res += word + " "
}
}
return String(res.dropLast())
}
}
```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()
}
```
### 代码
```swift
class Solution {
func reverseWords(_ s: String) -> String {
let words = s.split(separator: " ")
var res = ""
for word in words.reversed() {
if word.count > 0 {
res += word + " "
}
}
return String(res.dropLast())
}
}
```
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
class Solution {
func reverseWords(_ s: String) -> String {
let words = s.split(separator: " ")
let reverseWords = words.reversed()
return reverseWords.joined(separator: " ")
}
}
```swift
// Concatenate array of strings into a single string
// concatenate(strings: [] as [String]) == ""
// concatenate(strings: ["a", "b", "c"]) == "abc"
func concatenate(strings: [String]) -> String {
var result = ""
for string in strings {
result += string
}
return result
}
```
### 代码
```swift
class Solution {
func reverseWords(_ s: String) -> String {
let words = s.split(separator: " ")
let reverseWords = words.reversed()
return reverseWords.joined(separator: " ")
}
}
```
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```
### 2.2.2. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bcd", "cde"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```
### 2.2.3. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bcd", "cde"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```
### 2.2.4. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bcd", "cde"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```
### 2.2.5. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bcd", "cde"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```
### 2.2.6. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bcd", "cde"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```
### 2.2.7. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["bcd", "cde"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { !$0.hasPrefix(prefix) }
}
```
### 2.2.8. 过滤器
```swift
// Filter an input array of strings only for ones that don't start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a
func filterByPrefix(strings: [String], prefix: String) -> [String] { // invalid redeclaration of 'filterByPrefix(strings:prefix:)'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```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) }
}
```
### 2. 字符串数组转成字符串
```swift
// Convert an array of strings to a single string, separated by commas.
// joinStrings(strings: [] as [String]) == ""
// joinStrings(strings: ["abc", "bcd", "cde", "array"]) == "abc,bcd,cde,array"
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
```
### 3. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of substrings, split on a given separator.
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bcd", "cde", "array"], separator: ",") == ["abc", "bcd", "cde", "array"]
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```
### 4. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of substrings, split on a given separator.
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bcd", "cde", "array"], separator: ",") == ["abc", "bcd", "cde", "array"]
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```
### 5. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of substrings, split on a given separator.
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bcd", "cde", "array"], separator: ",") == ["abc", "bcd", "cde", "array"]
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```
### 6. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of substrings, split on a given separator.
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bcd", "cde", "array"], separator: ",") == ["abc", "bcd", "cde", "array"]
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```
### 7. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of substrings, split on a given separator.
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bcd", "cde", "array"], separator: ",") == ["abc", "bcd", "cde", "array"]
func splitStrings(strings: [String], separator: String) -> [String] {
return strings.split(separator: separator)
}
```
### 8. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of substrings, split on a given separator.
// splitStrings(strings: [] as [String], separator: "") == [] as [String]
// splitStrings(strings: ["abc", "bcd", "cde", "array"], separator
return strings.split(separator: separator) // cannot convert return expression of type '[ArraySlice<String>]' to return type '[String]'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
func splitStrings(strings: [String]) -> [Character] {
return strings.joined().map { String($0) }
}
func splitAndTrimStrings(strings: [String]) -> [Character] {
return strings.map { String($0.first!) }
}
func splitAndTrimLastStrings(strings: [String]) -> [Character] {
return strings.map { String($0.last!) }
}
func splitAndTrimFirstLastStrings(strings: [String]) -> [Character] {
return strings.map { String($0.dropFirst!.dropLast!) }
}
```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) }
}
```
### 2. 字符串数组转成字符串
```swift
// Convert an array of strings into a single string, with each string separated by a comma.
// joinStrings(strings: [] as [String]) == ""
// joinStrings(strings: ["abc", "bcd", "cde", "array"]) == "abc,bcd,cde,array"
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
```
### 3. 字符串数组转成字符串数组
```swift
// Convert an array of strings into an array of characters.
// splitStrings(strings: [] as [String]) == [] as [Character]
// splitStrings(strings: ["abc", "bcd", "cde", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitStrings(strings: [String]) -> [Character] {
return strings.joined().map { String($0) }
}
```
### 4. 字符串数组转成字符串数组
```swift
// Convert an array of strings into an array of characters, with each character in the array being the first character of each string in the array.
// splitAndTrimStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimStrings(strings: ["abc", "bcd", "cde", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitAndTrimStrings(strings: [String]) -> [Character] {
return strings.map { String($0.first!) }
}
```
### 5. 字符串数组转成字符串数组
```swift
// Convert an array of strings into an array of characters, with each character in the array being the last character of each string in the array.
// splitAndTrimLastStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimLastStrings(strings: ["abc", "bcd", "cde", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitAndTrimLastStrings(strings: [String]) -> [Character] {
return strings.map { String($0.last!) }
}
```
### 6. 字符串数组转成字符串数组
```swift
// Convert an array of strings into an array of characters, with each character in the array being the first character of each string in the array, with the first character of the first string in the array being the last character of the last string in the array.
// splitAndTrimFirstLastStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimFirstLastStrings(strings: ["abc", "bcd", "cde", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitAndTrimFirstLastStrings(strings: [String]) -> [Character] {
return strings.map { String($0.dropFirst!.dropLast!) }
}
```
### 7. 字符串数组转成字符串数组
```swift
// Convert an array of strings into an array of characters, with each character in the array being the last character of each string in the array, with the last character of the first string in the array being the first character of the last string in the array.
// splitAndTrimFirstLastStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimFirstLastStrings(strings: ["abc", "bcd", "cde", "array"]) == ["a", "b", "c", "d
return strings.joined().map { String($0) } // cannot convert value of type 'String' to closure result type 'Character'
return strings.map { String($0.first!) } // cannot convert value of type 'String' to closure result type 'Character'
return strings.map { String($0.last!) } // cannot convert value of type 'String' to closure result type 'Character'
return strings.map { String($0.dropFirst!.dropLast!) } // reference to member 'dropLast' cannot be resolved without a contextual type
return strings.map { String($0.dropFirst!.dropLast!) } // cannot force unwrap value of non-optional type '(Int) -> DropFirstSequence<String>'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
func joinStringsWithPrefix(strings: [String], prefix: String) -> String {
return strings.joined(separator: ",").prefix(prefix.count)
}
func joinStringsWithSuffix(strings: [String], suffix: String) -> String {
return strings.joined(separator: ",").suffix(suffix.count)
}
func joinStringsWithPrefixAndSuffix(strings: [String], prefix: String, suffix: String) -> String {
return strings.joined(separator: ",").prefix(prefix.count).suffix(suffix.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] {
return strings.filter { $0.hasPrefix(prefix) }
}
```
### 2. 字符串数组转成字符串
```swift
// Convert an array of strings to a single string, with each string separated by a comma.
// joinStrings(strings: [] as [String]) == ""
// joinStrings(strings: ["abc", "bcd", "cde", "array"]) == "abc,bcd,cde,array"
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
```
### 3. 字符串数组转成字符串,并加上前缀
```swift
// Convert an array of strings to a single string, with each string separated by a comma and prefixed with a given prefix.
// joinStringsWithPrefix(strings: [] as [String], prefix: "a") == ""
// joinStringsWithPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == "aabc,abcd,acde,aarray"
func joinStringsWithPrefix(strings: [String], prefix: String) -> String {
return strings.joined(separator: ",").prefix(prefix.count)
}
```
### 4. 字符串数组转成字符串,并加上后缀
```swift
// Convert an array of strings to a single string, with each string separated by a comma and suffixed with a given suffix.
// joinStringsWithSuffix(strings: [] as [String], suffix: "a") == ""
// joinStringsWithSuffix(strings: ["abc", "bcd", "cde", "array"], suffix: "a") == "abca,bcda,cdea,arraya"
func joinStringsWithSuffix(strings: [String], suffix: String) -> String {
return strings.joined(separator: ",").suffix(suffix.count)
}
```
### 5. 字符串数组转成字符串,并加上前后缀
```swift
// Convert an array of strings to a single string, with each string separated by a comma and prefixed and suffixed by given prefix and suffix.
// joinStringsWithPrefixAndSuffix(strings: [] as [String], prefix: "a", suffix: "a") == ""
// joinStringsWithPrefixAndSuffix(strings: ["abc", "bcd", "cde", "array"], prefix: "a", suffix: "a") == "aabca,abcda,acdea,aarraya"
func joinStringsWithPrefixAndSuffix(strings: [String], prefix: String, suffix: String) -> String {
return strings.joined(separator: ",").prefix(prefix.count).suffix(suffix.count)
}
```
### 6. 字符串数组转成字符串,并加上前缀和后缀
```swift
// Convert an array of strings to a single string, with each string separated by a comma and prefixed and suffixed by given prefix and suffix.
// joinStringsWithPrefixAndSuffix(strings: [] as [String], prefix: "a", suffix: "a") == ""
// joinStringsWithPrefixAndSuffix(strings: ["abc", "bcd", "cde", "array"], prefix: "a", suffix: "a") == "aabca,abcda,acdea,aarraya"
func joinStringsWithPrefixAndSuffix(strings: [String], prefix: String, suffix: String) -> String {
return strings.joined(separator: ",").prefix(prefix.count).suffix(suffix.count)
}
```
### 7. 字符串数组转成字符串,并加上前缀和后缀,并加上分隔符
```swift
// Convert an array of strings to a single string, with each string separated by a given separator and prefixed and suffixed by given prefix and suffix.
return strings.joined(separator: ",").prefix(prefix.count) // no 'prefix' candidates produce the expected contextual result type 'String'
return strings.joined(separator: ",").suffix(suffix.count) // no 'suffix' candidates produce the expected contextual result type 'String'
return strings.joined(separator: ",").prefix(prefix.count).suffix(suffix.count) // no 'suffix' candidates produce the expected contextual result type 'String'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func characters(of string: String) -> [Character] {
return Array(string)
}
func string(of array: [Character]) -> String {
return String(array)
}
func dictionary(of array: [String], key: String) -> [String: String] {
return array.reduce([String: String]()) {
$0[$1] = key
return $0
}
}
func pairs(of dictionary: [String: String]) -> [(String, String)] {
return dictionary.map { (key, value) in
(key, value)
}
}
func tuple(of array: [String]) -> (String, String, String) {
return (array[0], array[1], array[2])
}
func set(of array: [String]) -> Set<String> {
return Set(array)
}
func array(of array: [String]) -> [String] {
return array
}
```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) }
}
```
### 2. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(of: "abc") == ["a", "b", "c"]
// characters(of: "") == []
func characters(of string: String) -> [Character] {
return Array(string)
}
```
### 3. 数组转字符串
```swift
// Convert an array of characters to a string.
// string(of: ["a", "b", "c"]) == "abc"
// string(of: []) == ""
func string(of array: [Character]) -> String {
return String(array)
}
```
### 4. 数组转字典
```swift
// Convert an array to a dictionary with a given key and value.
// dictionary(of: ["a": 1, "b": 2, "c": 3], key: "a") == [1: "a", 2: "b", 3: "c"]
// dictionary(of: [], key: "a") == []
func dictionary(of array: [String], key: String) -> [String: String] {
return array.reduce([String: String]()) {
$0[$1] = key
return $0
}
}
```
### 5. 字典转数组
```swift
// Convert a dictionary to an array of key-value pairs.
// pairs(of: [1: "a", 2: "b", 3: "c"]) == [(1, "a"), (2, "b"), (3, "c")]
// pairs(of: []) == []
func pairs(of dictionary: [String: String]) -> [(String, String)] {
return dictionary.map { (key, value) in
(key, value)
}
}
```
### 6. 数组转元组
```swift
// Convert an array to a tuple.
// tuple(of: ["a", "b", "c"]) == ("a", "b", "c")
// tuple(of: []) == ()
func tuple(of array: [String]) -> (String, String, String) {
return (array[0], array[1], array[2])
}
```
### 7. 数组转集合
```swift
// Convert an array to a set.
// set(of: ["a", "b", "c"]) == ["a", "b", "c"]
// set(of: []) == []
func set(of array: [String]) -> Set<String> {
return Set(array)
}
```
### 8. 数组转数组
```swift
// Convert an array to another array.
// array(of: [1, 2, 3]) == [1, 2, 3]
// array(of: []) == []
func array(of array: [String]) -> [String] {
return array
}
```
### 9. 数组转数组
```swift
// Convert an array to another array.
// array(of: [1, 2, 3]) == [1, 2, 3]
// array(of: []) == []
func array(of array: [String]) -> [String] {
return array
}
```
### 10. 数组转数组
```swift
// Convert an array to another array.
// array(of: [1, 2, 3]) == [1, 2, 3]
// array(of: []) == []
func array(of array: [String]) -> [String] {
return array
}
```
### 11. 数组转数组
```swift
// Convert an array to another array.
// array(of: [1, 2, 3]) == [1, 2, 3]
// array(of: []) == []
func array(of array: [String]) -> [String] {
return array
$0[$1] = key // cannot assign through subscript: '$0' is immutable
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.element }
}
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.offset }.map { strings[$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) }
}
```
### 2. 利用数组下标
```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.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.element }
}
```
### 3. 利用数组下标
```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.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.offset }.map { strings[$0] }
}
```
### 4. 利用数组下标
```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.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.offset }.map { strings[$0] }
}
```
### 5. 利用数组下标
```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.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.offset }.map { strings[$0] }
}
```
### 6. 利用数组下标
```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.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.offset }.map { strings[$0] }
}
```
### 7. 利用数组下标
```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.enumerated().filter { $0.element.hasPrefix(prefix) }.map { $0.offset }.map { strings[$0] }
}
```
### 8.
func filterByPrefix(strings: [String], prefix: String) -> [String] { // invalid redeclaration of 'filterByPrefix(strings:prefix:)'
func filterByPrefix(strings: [String], prefix: String) -> [String] { // invalid redeclaration of 'filterByPrefix(strings:prefix:)'
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func characters(in string: String) -> [Character] {
return Array(string)
}
func String(of array: [Character]) -> String {
return String(array)
}
```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) }
}
```
### 2. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(in: "abc") == ["a", "b", "c"]
// characters(in: "") == []
func characters(in string: String) -> [Character] {
return Array(string)
}
```
### 3. 数组转字符串
```swift
// Convert an array of characters to a string.
// String(of: [Character]()) == ""
// String(of: ["a", "b", "c"]) == "abc"
func String(of array: [Character]) -> String {
return String(array)
}
```
### 4. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(in: "abc") == ["a", "b", "c"]
// characters(in: "") == []
func characters(in string: String) -> [Character] {
return Array(string)
}
```
### 5. 数组转字符串
```swift
// Convert an array of characters to a string.
// String(of: [Character]()) == ""
// String(of: ["a", "b", "c"]) == "abc"
func String(of array: [Character]) -> String {
return String(array)
}
```
### 6. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(in: "abc") == ["a", "b", "c"]
// characters(in: "") == []
func characters(in string: String) -> [Character] {
return Array(string)
}
```
### 7. 数组转字符串
```swift
// Convert an array of characters to a string.
// String(of: [Character]()) == ""
// String(of: ["a", "b", "c"]) == "abc"
func String(of array: [Character]) -> String {
return String(array)
}
```
### 8. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(in: "abc") == ["a", "b", "c"]
// characters(in: "") == []
func characters(in string: String) -> [Character] {
return Array(string)
}
```
### 9. 数组转字符串
```swift
// Convert an array of characters to a string.
// String(of: [Character]()) == ""
// String(of: ["a", "b", "c"]) == "abc"
func String(of array: [Character]) -> String {
return String(array)
}
```
### 10. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(in: "abc") == ["a", "b", "c"]
// characters(in: "") == []
func characters(in string: String) -> [Character] {
return Array(string)
}
```
### 11. 数组转字符串
```swift
// Convert an array of characters to a string.
// String(of: [Character]()) == ""
// String(of: ["a", "b", "c"]) == "abc"
func String(of array: [Character]) -> String {
return String(array)
}
```
### 12. 字符串转数组
```swift
// Convert a string to an array of characters.
// characters(in: "abc") == ["a", "b", "c"]
// characters(in: "") == []
func characters(in string: String) -> [Character] {
return Array(string)
}
```
### 13. 数组转字符串
```swift
// Convert an array of characters to a string.
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```swift
// Filter an input array of strings only for ones that start with a given prefix.
// filterByPrefix(strings: [] as [String], prefix: "a") == [] as [String]
// filterByPrefix(strings: ["abc", "bcd", "cde", "array"], prefix: "a") == ["abc", "array"]
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
```
### 2. 判断字符串是否以指定字符串开头
```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) }
}
```
### 3. 判断字符串是否以指定字符串开头
```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) }
}
```
### 4. 判断字符串是否以指定字符串开头
```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) }
}
```
### 5. 判断字符串是否以指定字符串开头
```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) }
}
```
### 6. 判断字符串是否以指定字符串开头
```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) }
}
```
### 7. 判断字符串是否以指定字符串开头
```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) }
}
```
### 8. 判断字符串是否以指定字符串开头
```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 filter
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func charactersInString(string: String) -> [Character] {
return Array(string)
}
func stringFromCharacters(characters: [Character]) -> String {
return String(characters)
}
func asInt(string: String) -> Int {
return Int(string) ?? 0
}
func asString(integer: Int) -> String {
return "\(integer)"
}
func asBool(string: String) -> Bool {
return string == "true"
}
func asString(boolean: Bool) -> String {
return "\(boolean)"
}
```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) }
}
```
### 2. 字符串转数组
```swift
// Convert a string to an array of characters.
// charactersInString(string: "abc") == ["a", "b", "c"]
func charactersInString(string: String) -> [Character] {
return Array(string)
}
```
### 3. 数组转字符串
```swift
// Convert an array of characters to a string.
// stringFromCharacters(characters: ["a", "b", "c"]) == "abc"
func stringFromCharacters(characters: [Character]) -> String {
return String(characters)
}
```
### 4. 字符串转数字
```swift
// Convert a string to an integer.
// asInt(string: "123") == 123
func asInt(string: String) -> Int {
return Int(string) ?? 0
}
```
### 5. 数字转字符串
```swift
// Convert an integer to a string.
// asString(integer: 123) == "123"
func asString(integer: Int) -> String {
return "\(integer)"
}
```
### 6. 字符串转布尔值
```swift
// Convert a string to a boolean.
// asBool(string: "true") == true
func asBool(string: String) -> Bool {
return string == "true"
}
```
### 7. 布尔值转字符串
```swift
// Convert a boolean to a string.
// asString(boolean: true) == "true"
func asString(boolean: Bool) -> String {
return "\(boolean)"
}
```
### 8. 字符串转数组
```swift
// Convert a string to an array of characters.
// charactersInString(string: "abc") == ["a", "b", "c"]
func charactersInString(string: String) -> [Character] {
return Array(string)
}
```
### 9. 数组转字符串
```swift
// Convert an array of characters to a string.
// stringFromCharacters(characters: ["a", "b", "c"]) == "abc"
func stringFromCharacters(characters: [Character]) -> String {
return String(characters)
}
```
### 10. 字符串转数字
```swift
// Convert a string to an integer.
// asInt(string: "123") == 123
func asInt(string: String) -> Int {
return Int(string) ?? 0
}
```
### 11. 数字转字符串
```swift
// Convert an integer to a string.
// asString(integer: 123) == "123"
func asString(integer: Int) -> String {
return "\(integer)"
}
```
### 12. 字符串转布尔值
```swift
// Convert a string to a boolean.
// asBool(string: "true") == true
func asBool(string: String) -> Bool {
return string == "true"
}
```
### 13. 布尔值转字符串
```swift
// Convert a boolean to a string.
// asString(boolean: true) == "true"
func asString(boolean: Bool) -> String {
return "\(boolean)"
}
```
### 14. 字符串转数组
```swift
// Convert a string to an array of characters.
// charactersInString(string: "abc") == ["a", "b", "c"]
func charactersInString(string: String) -> [Character] {
return Array(string)
}
```
### 15. 数组转字符串
```swift
// Convert an array of characters to a string.
// stringFrom
func filterByPrefix(strings: [String], prefix: String) -> [String] {
return strings.filter { $0.hasPrefix(prefix) }
}
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
func splitStrings(strings: [String]) -> [Character] {
return strings.joined().map { String($0) }
}
func splitAndTrimStrings(strings: [String]) -> [Character] {
return strings.joined().filter { !$0.isWhitespace }.map { String($0) }
}
func splitAndTrimAndLowercaseStrings(strings: [String]) -> [Character] {
return strings.joined().filter { !$0.isWhitespace }.map { String($0).lowercased() }
}
```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) }
}
```
### 2. 字符串数组转成字符串
```swift
// Convert an array of strings to a single string, with each string separated by a comma.
// joinStrings(strings: [] as [String]) == ""
// joinStrings(strings: ["abc", "bcd", "cde", "array"]) == "abc,bcd,cde,array"
func joinStrings(strings: [String]) -> String {
return strings.joined(separator: ",")
}
```
### 3. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters.
// splitStrings(strings: [] as [String]) == [] as [Character]
// splitStrings(strings: ["abc", "bcd", "cde", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitStrings(strings: [String]) -> [Character] {
return strings.joined().map { String($0) }
}
```
### 4. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters, removing all whitespace characters.
// splitAndTrimStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimStrings(strings: ["abc", " bcd ", "cde ", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitAndTrimStrings(strings: [String]) -> [Character] {
return strings.joined().filter { !$0.isWhitespace }.map { String($0) }
}
```
### 5. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters, removing all whitespace characters and case-insensitive.
// splitAndTrimAndLowercaseStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimAndLowercaseStrings(strings: ["abc", " bcd ", "cde ", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitAndTrimAndLowercaseStrings(strings: [String]) -> [Character] {
return strings.joined().filter { !$0.isWhitespace }.map { String($0).lowercased() }
}
```
### 6. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters, removing all whitespace characters and case-insensitive.
// splitAndTrimAndLowercaseStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimAndLowercaseStrings(strings: ["abc", " bcd ", "cde ", "array"]) == ["a", "b", "c", "d", "e", "a", "r", "r", "a", "r", "y"]
func splitAndTrimAndLowercaseStrings(strings: [String]) -> [Character] {
return strings.joined().filter { !$0.isWhitespace }.map { String($0).lowercased() }
}
```
### 7. 字符串数组转成字符串数组
```swift
// Convert an array of strings to an array of characters, removing all whitespace characters and case-insensitive.
// splitAndTrimAndLowercaseStrings(strings: [] as [String]) == [] as [Character]
// splitAndTrimAndLowercaseStrings(strings: ["abc", " bcd ", "cde ", "array"]) == ["a", "b", "c", "d", "e",
return strings.joined().map { String($0) } // cannot convert value of type 'String' to closure result type 'Character'
return strings.joined().filter { !$0.isWhitespace }.map { String($0) } // cannot convert value of type 'String' to closure result type 'Character'
return strings.joined().filter { !$0.isWhitespace }.map { String($0).lowercased() } // cannot convert value of type 'String' to closure result type 'Character'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法二:
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法三:
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法四:
```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 }
}
```
### 解法五:
```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 }
}
```
### 解法六:
```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 }
}
```
### 解法七:
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法八:
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
func getPositive(l: [Int]) -> [Int] {
return l.reduce([Int]()) { (result, i) in
if i > 0 {
result.append(i)
}
return result
}
}
func getPositive(l: [Int]) -> [Int] {
return l.reduce([Int]()) { (result, i) in
result.append(contentsOf: filter(i))
return result
}
}
func filter(_ i: Int) -> [Int] {
return i > 0 ? [i] : []
}
func getPositive(l: [Int]) -> [Int] {
return l.reduce([Int]()) { (result, i) in
result.append(contentsOf: filter(i).map { $0 })
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
}
```
### 方法二:使用filter
```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 }
}
```
### 方法三:使用reduce
```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.reduce([Int]()) { (result, i) in
if i > 0 {
result.append(i)
}
return result
}
}
```
### 方法四:使用reduce + filter
```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.reduce([Int]()) { (result, i) in
result.append(contentsOf: filter(i))
return result
}
}
func filter(_ i: Int) -> [Int] {
return i > 0 ? [i] : []
}
```
### 方法五:使用reduce + filter + map
```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.reduce([Int]()) { (result, i) in
result.append(contentsOf: filter(i).map { $0 })
return result
}
}
func filter(_ i: Int) -> [Int] {
return i > 0 ? [i] : []
}
```
### 方法六:使用reduce + filter + map + filter
```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.reduce([Int]()) { (result, i) in
result.append
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
result.append(i) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
result.append(contentsOf: filter(i)) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
result.append(contentsOf: filter(i).map { $0 }) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法二
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法三
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法四
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法五
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法六
```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 }
}
```
### 解法七
```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
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
var left = 0
var right = l.count - 1
while left <= right {
if l[left] > 0 {
result.append(l[left])
left += 1
} else {
left += 1
}
if l[right] > 0 {
result.append(l[right])
right -= 1
} else {
right -= 1
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
} else if i == 0 {
continue
} else {
let subResult = getPositive(l: Array(i...))
for j in subResult {
result.append(j)
}
}
}
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
}
```
### 方法二:双指针
```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]()
var left = 0
var right = l.count - 1
while left <= right {
if l[left] > 0 {
result.append(l[left])
left += 1
} else {
left += 1
}
if l[right] > 0 {
result.append(l[right])
right -= 1
} else {
right -= 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)
} else if i == 0 {
continue
} else {
let subResult = getPositive(l: Array(i...))
for j in subResult {
result.append(j)
}
}
}
return result
}
```
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法二:
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法三:
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法四:
```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 }
}
```
### 解法五:
```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 }
}
```
### 解法六:
```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 }
}
```
### 解法七:
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法八:
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解题思路2
使用filter过滤器
### 代码
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法二
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法三
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法四
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法五
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法六
```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 }
}
```
### 解法七
```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
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var digits = digits
var carry = 1
for i in stride(from: digits.count - 1, through: 0, by: -1) {
let sum = digits[i] + carry
digits[i] = sum % 10
carry = sum / 10
}
if carry > 0 {
digits.insert(carry, at: 0)
}
return digits
}
}
```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
}
```
### 解题思路
### 代码
```swift
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var digits = digits
var carry = 1
for i in stride(from: digits.count - 1, through: 0, by: -1) {
let sum = digits[i] + carry
digits[i] = sum % 10
carry = sum / 10
}
if carry > 0 {
digits.insert(carry, at: 0)
}
return digits
}
}
```
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法二
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法三
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
### 解法四
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法五
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
return l.filter { $0 > 0 }
}
```
### 解法六
```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 }
}
```
### 解法七
```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
func getPositive(l: [Int]) -> [Int] { // invalid redeclaration of 'getPositive(l:)'
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```swift
// Return only positive numbers in the array.
// getPositive(l: [-1, 2, -4, 5, 6]) == [2, 5, 6]
// getPositive(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == [5, 3, 2, 3, 9, 123, 1]
func getPositive(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if i > 0 {
result.append(i)
}
}
return result
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
let sqrt = Int(sqrt(Double(n)))
for i in 2..<sqrt {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法二:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法三:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
let sqrt = Int(sqrt(Double(n)))
for i in 2..<sqrt {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法四:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
let sqrt = Int(sqrt(Double(n)))
for i in 2..<sqrt {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法五:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
let sqrt = Int(sqrt(Double(n)))
for i in 2..<sqrt {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法六:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime
func isPrime(n: Int) -> Bool { // invalid redeclaration of 'isPrime(n:)'
func isPrime(n: Int) -> Bool { // invalid redeclaration of 'isPrime(n:)'
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
var arr = Array(repeating: true, count: n)
while i * i <= n {
if arr[i] == true {
var j = i * i
while j <= n {
arr[j] = false
j += i
}
}
i += 2
}
return arr[n]
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
var arr = Array(repeating: true, count: n)
arr[0] = false
arr[1] = false
while i * i <= n {
if arr[i] == true {
var j = i * i
while j <= n {
arr[j] = false
j += i
}
}
i += 2
}
return arr[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 < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法二:埃拉托斯特尼筛法
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
var arr = Array(repeating: true, count: n)
while i * i <= n {
if arr[i] == true {
var j = i * i
while j <= n {
arr[j] = false
j += i
}
}
i += 2
}
return arr[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 < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
var arr = Array(repeating: true, count: n)
arr[0] = false
arr[1] = false
while i * i <= n {
if arr[i] == true {
var j = i * i
while j <= n {
arr[j] = false
j += i
}
}
i += 2
}
return arr[n]
}
```
func isPrime(n: Int) -> Bool { // invalid redeclaration of 'isPrime(n:)'
func isPrime(n: Int) -> Bool { // invalid redeclaration of 'isPrime(n:)'
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 || n == 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 || n == 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法二:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法三:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法四:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法五:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i
func isPrime(n: Int) -> Bool { // invalid redeclaration of 'isPrime(n:)'
func isPrime(n: Int) -> Bool { // invalid redeclaration of 'isPrime(n:)'
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法二
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
for i in 3..<Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法二:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法三:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法四:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n == 2 {
return true
}
if n % 2 == 0 {
return false
}
var i = 3
while i * i <= n {
if n % i == 0 {
return false
}
i += 2
}
return true
}
```
### 解法五:
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n <= 1 {
return false
}
if n == 2
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 || n == 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```swift
// Return true if a given number is prime, and false otherwise.
// isPrime(n: 6) == false
// isPrime(n: 101) == true
// isPrime(n: 11) == true
// isPrime(n: 13441) == true
// isPrime(n: 61) == true
// isPrime(n: 4) == false
// isPrime(n: 1) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
if n == 2 || n == 3 {
return true
}
if n % 2 == 0 || n % 3 == 0 {
return false
}
var i = 5
while i * i <= n {
if n % i == 0 || n % (i + 2) == 0 {
return false
}
i += 6
}
return true
}
```
func sortThird(l: [Int]) -> [Int] {
var l = l
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 })
l.insert(contentsOf: l.indices.filter { $0 % 3 == 0 }.map { $0 }, at: 0)
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
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 })
l.insert(contentsOf: l.indices.filter { $0 % 3 == 0 }.map { $0 }, at: 0)
return l
}
```
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 }) // cannot convert value of type '[Range<Array<Int>.Index>.Element]' (aka 'Array<Int>') to expected argument type 'Range<Array<Int>.Index>' (aka 'Range<Int>')
func sortThird(l: [Int]) -> [Int] {
var l = l
let third = l.count / 3
let first = l.filter { $0 % 3 == 0 }
let second = l.filter { $0 % 3 == 1 }
let third = l.filter { $0 % 3 == 2 }
l = first + second + third
return l
}
func sortThird(l: [Int]) -> [Int] {
var l = l
let third = l.count / 3
let first = l.filter { $0 % 3 == 0 }
let second = l.filter { $0 % 3 == 1 }
let third = l.filter { $0 % 3 == 2 }
l = first + second + third
l.sort()
return l
}
func sortThird(l: [Int]) -> [Int] {
var l = l
let third = l.count / 3
let first = l.filter { $0 % 3 == 0 }
let second = l.filter { $0 % 3 == 1 }
let third = l.filter { $0 % 3 == 2 }
l = first + second + third
l.sort { $0 < $1 }
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
let third = l.count / 3
let first = l.filter { $0 % 3 == 0 }
let second = l.filter { $0 % 3 == 1 }
let third = l.filter { $0 % 3 == 2 }
l = first + second + third
return l
}
```
### 解法二
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
let third = l.count / 3
let first = l.filter { $0 % 3 == 0 }
let second = l.filter { $0 % 3 == 1 }
let third = l.filter { $0 % 3 == 2 }
l = first + second + third
l.sort()
return l
}
```
### 解法三
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
let third = l.count / 3
let first = l.filter { $0 % 3 == 0 }
let second = l.filter { $0 % 3 == 1 }
let third = l.filter { $0 % 3 == 2 }
l = first + second + third
l.sort { $0 < $1 }
return l
}
```
let third = l.filter { $0 % 3 == 2 } // invalid redeclaration of 'third'
func sortThird(l: [Int]) -> [Int] { // invalid redeclaration of 'sortThird(l:)'
let third = l.filter { $0 % 3 == 2 } // invalid redeclaration of 'third'
func sortThird(l: [Int]) -> [Int] { // invalid redeclaration of 'sortThird(l:)'
let third = l.filter { $0 % 3 == 2 } // invalid redeclaration of 'third'
func sortThird(l: [Int]) -> [Int] {
var l = l
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 })
l.insert(contentsOf: l.indices.filter { $0 % 3 == 0 }.map { $0 }, at: 0)
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
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 })
l.insert(contentsOf: l.indices.filter { $0 % 3 == 0 }.map { $0 }, at: 0)
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
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 })
l.insert(contentsOf: l.indices.filter { $0 % 3 == 0 }.map { $0 }, at: 0)
return l
}
```
l.removeSubrange(l.indices.filter { $0 % 3 == 0 }.map { $0 }) // cannot convert value of type '[Range<Array<Int>.Index>.Element]' (aka 'Array<Int>') to expected argument type 'Range<Array<Int>.Index>' (aka 'Range<Int>')
func sortThird(l: [Int]) -> [Int] {
var l = l
l.removeSubrange(0...2)
l.insert(l.remove(at: 0), at: 2)
return l
}
func sortThird(l: [Int]) -> [Int] {
let l = l.sorted { (a, b) -> Bool in
return a % 3 == b % 3
}
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
l.removeSubrange(0...2)
l.insert(l.remove(at: 0), at: 2)
return l
}
```
### 解法二
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
let l = l.sorted { (a, b) -> Bool in
return a % 3 == b % 3
}
return l
}
```
func sortThird(l: [Int]) -> [Int] { // invalid redeclaration of 'sortThird(l:)'
func sortThird(l: [Int]) -> [Int] {
let l = l.sorted()
var l1 = [Int]()
var l2 = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
l1.append(l[i])
} else {
l2.append(l[i])
}
}
return l1 + l2
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
let l = l.sorted()
var l1 = [Int]()
var l2 = [Int]()
for i in 0..<l.count {
if i % 3 == 0 {
l1.append(l[i])
} else {
l2.append(l[i])
}
}
return l1 + l2
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
let mid = l.count / 3
l.removeSubrange(0..<mid)
l.removeSubrange(l.count - mid..<l.count)
l.append(contentsOf: l)
l.removeSubrange(l.count - mid..<l.count)
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
var l = l
let mid = l.count / 3
l.removeSubrange(0..<mid)
l.removeSubrange(l.count - mid..<l.count)
l.append(contentsOf: l)
l.removeSubrange(l.count - mid..<l.count)
return l
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var l1 = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l1.remove(at: i)
l1.insert(l[i], at: i)
}
}
for i in 0..<l.count {
if i % 3 == 0 {
l2.remove(at: i)
l2.insert(l[i], at: i)
}
}
return l1
}
```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 l1 = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l1.remove(at: i)
l1.insert(l[i], at: i)
}
}
for i in 0..<l.count {
if i % 3 == 0 {
l2.remove(at: i)
l2.insert(l[i], at: i)
}
}
return l1
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var l1 = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l1.remove(at: i)
l1.insert(l[i], at: i)
}
}
for i in 0..<l.count {
if i % 3 == 0 {
l2.remove(at: i)
l2.insert(l[i], at: i)
}
}
return l1
}
```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 l1 = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l1.remove(at: i)
l1.insert(l[i], at: i)
}
}
for i in 0..<l.count {
if i % 3 == 0 {
l2.remove(at: i)
l2.insert(l[i], at: i)
}
}
return l1
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
let sorted = l.sorted { $0 % 3 == $1 % 3 }
var result = [Int]()
for i in 0..<l.count {
if sorted[i] % 3 == 0 {
result.append(l[i])
}
}
for i in 0..<l.count {
if sorted[i] % 3 != 0 {
result.append(l[i])
}
}
return result
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the indicies that are not divisible by three, while its values at the indicies that are divisible by three are equal
// to the values of the corresponding indicies of l, but sorted.
// sortThird(l: [1, 2, 3]) == [1, 2, 3]
// sortThird(l: [5, 6, 3, 4, 8, 9, 2]) == [2, 6, 3, 4, 8, 9, 5]
func sortThird(l: [Int]) -> [Int] {
let sorted = l.sorted { $0 % 3 == $1 % 3 }
var result = [Int]()
for i in 0..<l.count {
if sorted[i] % 3 == 0 {
result.append(l[i])
}
}
for i in 0..<l.count {
if sorted[i] % 3 != 0 {
result.append(l[i])
}
}
return result
}
```
// XCTAssertTrue failed
func sortThird(l: [Int]) -> [Int] {
var l = l
var l1 = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l1.remove(at: i)
l1.insert(l[i], at: i)
}
}
for i in 0..<l.count {
if i % 3 == 0 {
l2.remove(at: i)
l2.insert(l[i], at: i)
}
}
return l1
}
```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 l1 = l
var l2 = l
for i in 0..<l.count {
if i % 3 == 0 {
l1.remove(at: i)
l1.insert(l[i], at: i)
}
}
for i in 0..<l.count {
if i % 3 == 0 {
l2.remove(at: i)
l2.insert(l[i], at: i)
}
}
return l1
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
return l.sorted { (a, b) -> Bool in
return a < b
}.reduce([], { (result, i) -> [Int] in
if result.contains(i) {
return result
} else {
result.append(i)
return result
}
})
}
func unique(l: [Int]) -> [Int] {
return Set(l).sorted()
}
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { (result, i) -> Void in
if !result.contains(i) {
result.append(i)
}
}.sorted()
}
func unique(l: [Int]) -> [Int] {
return l.reduce(into: Set<Int>()) { (result, i) -> Void in
result.insert(i)
}.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 dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
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] {
return l.sorted { (a, b) -> Bool in
return a < b
}.reduce([], { (result, i) -> [Int] in
if result.contains(i) {
return result
} else {
result.append(i)
return result
}
})
}
```
### 解法三:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return Set(l).sorted()
}
```
### 解法四:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { (result, i) -> Void in
if !result.contains(i) {
result.append(i)
}
}.sorted()
}
```
### 解法五:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: Set<Int>()) { (result, i) -> Void in
result.insert(i)
}.sorted()
}
```
### 解法六:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: Set<Int>()) { (result, i) -> Void in
result.insert(i)
}.sorted()
}
```
### 解法七:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: Set<Int>()) { (result, i) -> Void in
result.insert(i)
}.sorted()
}
```
### 解法八:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
result.append(i) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = Set<Int>()
for i in l {
result.insert(i)
}
return Array(result)
}
func unique(l: [Int]) -> [Int] {
var result = [Int: Int]()
for i in l {
result[i] = 1
}
return Array(result.keys)
}
func unique(l: [Int]) -> [Int] {
return l.sorted { (i, j) -> Bool in
return i < j
}.reduce([Int]()) { (result, i) -> [Int] in
if !result.contains(i) {
result.append(i)
}
return result
}
}
func unique(l: [Int]) -> [Int] {
return l.sorted().reduce(into: Set<Int>()) { (result, i) in
result.insert(i)
}
}
func unique(l: [Int]) -> [Int] {
return l.sorted().reduce(into: [Int: Int]()) { (result, i) in
result[i] = 1
}
}
func unique(l: [Int]) -> [Int] {
return l.sorted().reduce([Int]()) { (result, i) in
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
}
```
### 解法二:Set
```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 = Set<Int>()
for i in l {
result.insert(i)
}
return Array(result)
}
```
### 解法三:Hash Table
```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: Int]()
for i in l {
result[i] = 1
}
return Array(result.keys)
}
```
### 解法四:Sort
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted { (i, j) -> Bool in
return i < j
}.reduce([Int]()) { (result, i) -> [Int] in
if !result.contains(i) {
result.append(i)
}
return result
}
}
```
### 解法五:Sort + Set
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted().reduce(into: Set<Int>()) { (result, i) in
result.insert(i)
}
}
```
### 解法六:Sort + Hash Table
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted().reduce(into: [Int: Int]()) { (result, i) in
result[i] = 1
}
}
```
### 解法七:Sort + Array
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted().reduce([Int]()) { (result, i) in
if !result.contains(i) {
result.append(i)
}
return result
}
}
```
### 解法八:Sort + Array + Set
```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:
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
result.append(i) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.sorted().reduce(into: Set<Int>()) { (result, i) in // cannot convert return expression of type 'Set<Int>' to return type '[Int]'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.sorted().reduce(into: [Int: Int]()) { (result, i) in // cannot convert return expression of type '[Int : Int]' to return type '[Int]'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
result.append(i) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
return Array(Set(l))
}
func unique(l: [Int]) -> [Int] {
return l.sorted { $0 < $1 }.reduce([], +)
}
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.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
}
```
### 解法二
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return Array(Set(l))
}
```
### 解法三
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted { $0 < $1 }.reduce([], +)
}
```
### 解法四
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.sorted()
}
```
### 解法五
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.sorted()
}
```
### 解法六
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.sorted()
}
```
### 解法七
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.sorted()
}
```
### 解法八
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.sorted()
}
```
### 解法九
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0.append($1) }.sorted()
}
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.sorted { $0 < $1 }.reduce([], +) // cannot convert return expression of type 'Int' to return type '[Int]'
return l.sorted { $0 < $1 }.reduce([], +) // cannot convert value of type '[Any]' to expected argument type 'Int'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
if !set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var l = l
l.sort()
for i in l {
if result.count == 0 || i != result.last! {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var count = [Int: Int]()
for i in l {
if count[i] == nil {
count[i] = 1
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 dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
```
### 解法二:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
if !set.contains(i) {
set.insert(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]()
var l = l
l.sort()
for i in l {
if result.count == 0 || i != result.last! {
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]()
var count = [Int: Int]()
for i in l {
if count[i] == nil {
count[i] = 1
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]()
var count = [Int: Int]()
for i in l {
if count[i] == nil {
count[i] = 1
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]()
var count = [Int: Int]()
for i in l {
if count[i] == nil {
count[i] = 1
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]()
var count = [Int: Int]()
for i in l {
if count[i] == nil {
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
for i in l {
dict[i] = 1
}
var result = [Int]()
for i in l {
result.append(i)
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
if !set.contains(i) {
result.append(i)
set.insert(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
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 dict = [Int: Int]()
for i in l {
dict[i] = 1
}
var result = [Int]()
for i in l {
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 set = Set<Int>()
var result = [Int]()
for i in l {
if !set.contains(i) {
result.append(i)
set.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 dict = [Int: Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
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 dict = [Int: Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
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 dict = [Int: Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
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 dict = [Int: Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
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 dict = [Int: Int]()
for i in l {
if dict[i
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
for i in l {
dict[i] = 1
}
return dict.keys.sorted()
}
func unique(l: [Int]) -> [Int] {
let sorted = l.sorted()
var result = [Int]()
for i in 0..<sorted.count {
if i == 0 || sorted[i] != sorted[i - 1] {
result.append(sorted[i])
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
for i in l {
set.insert(i)
}
return set.sorted()
}
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
for i in l {
dict[i] = (dict[i] ?? 0) + 1
}
var result = [Int]()
for i in l {
if dict[i] == 1 {
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 dict = [Int: Int]()
for i in l {
dict[i] = 1
}
return dict.keys.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] {
let sorted = l.sorted()
var result = [Int]()
for i in 0..<sorted.count {
if i == 0 || sorted[i] != sorted[i - 1] {
result.append(sorted[i])
}
}
return result
}
```
### 解法三:Set
```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 set = Set<Int>()
for i in l {
set.insert(i)
}
return set.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 dict = [Int: Int]()
for i in l {
dict[i] = (dict[i] ?? 0) + 1
}
var result = [Int]()
for i in l {
if dict[i] == 1 {
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 dict = [Int: Int]()
for i in l {
dict[i] = (dict[i] ?? 0) + 1
}
var result = [Int]()
for i in l {
if dict[i] == 1 {
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 dict = [Int: Int]()
for i in l {
dict[i] = (dict[i] ?? 0) + 1
}
var result = [Int]()
for i in l {
if dict[i] == 1 {
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 dict = [Int: Int]()
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
if !set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
if set.insert(i).success {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
if set.insert(i).0 {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
result.append(i)
set.insert(i)
}
return result
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
var result = [Int]()
for i in l {
result.append(i)
set.insert(i).0
}
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 dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
```
### 解法二:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
if !set.contains(i) {
set.insert(i)
result.append(i)
}
}
return result
}
```
### 解法三:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
if set.insert(i).success {
result.append(i)
}
}
return result
}
```
### 解法四:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
if set.insert(i).0 {
result.append(i)
}
}
return result
}
```
### 解法五:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
result.append(i)
set.insert(i)
}
return result
}
```
### 解法六:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
result.append(i)
set.insert(i).0
}
return result
}
```
### 解法七:Set
```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 set = Set<Int>()
var result = [Int]()
for i in l {
result.append(i)
set.insert(i)
}
return result
}
```
### 解法八:Set
```swift
// Return sorted unique elements in an array
// unique(l: [5,
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
if set.insert(i).success { // value of tuple type '(inserted: Bool, memberAfterInsert: Int)' has no member 'success'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
set.insert(i).0 // expression of type 'Bool' is unused
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i)
result.sort()
result.removeDuplicates()
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i)
result.sort()
result.removeDuplicates(in: result)
}
return result
}
func unique(l: [Int]) -> [Int] {
var result = [Int]()
for i in l {
result.append(i)
result.sort()
result.removeDuplicates(using: {$0 == $1})
}
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 dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
result.append(i)
dict[i] = 1
}
}
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
}
```
### 解法三
```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 {
result.append(i)
result.sort()
result.removeDuplicates()
}
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 {
result.append(i)
result.sort()
result.removeDuplicates(in: result)
}
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 {
result.append(i)
result.sort()
result.removeDuplicates(using: {$0 == $1})
}
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 {
result.append(i)
result.sort()
result.removeDuplicates(using: {$0 == $1})
}
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 {
result.append(i)
result.sort()
result.removeDuplicates(using: {$0 == $1})
}
return result
}
```
### 解法八
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 12
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
result.removeDuplicates() // value of type '[Int]' has no member 'removeDuplicates'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
result.removeDuplicates(in: result) // value of type '[Int]' has no member 'removeDuplicates'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
result.removeDuplicates(using: {$0 == $1}) // value of type '[Int]' has no member 'removeDuplicates'
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
return l.sorted { $0 < $1 }.reduce(into: [Int]()) {
if !$1.contains($2) {
$1.append($2)
}
}
}
func unique(l: [Int]) -> [Int] {
var set = Set<Int>()
return l.reduce(into: [Int]()) {
if !set.contains($2) {
set.insert($2)
$1.append($2)
}
}
}
func unique(l: [Int]) -> [Int] {
var dict = [Int: Int]()
return l.sorted { $0 < $1 }.reduce(into: [Int]()) {
if !dict[$2]!.contains($1) {
dict[$2]!.append($1)
$1.append($2)
}
}
}
```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 dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
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] {
return l.sorted { $0 < $1 }.reduce(into: [Int]()) {
if !$1.contains($2) {
$1.append($2)
}
}
}
```
### 解法三:集合
```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 set = Set<Int>()
return l.reduce(into: [Int]()) {
if !set.contains($2) {
set.insert($2)
$1.append($2)
}
}
}
```
### 解法四:哈希表
```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 dict = [Int: Int]()
var result = [Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
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 dict = [Int: Int]()
return l.sorted { $0 < $1 }.reduce(into: [Int]()) {
if !dict[$2]!.contains($1) {
dict[$2]!.append($1)
$1.append($2)
}
}
}
```
### 解法六:集合 + 哈希表
```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 set = Set<Int>()
return l.reduce(into: [Int]()) {
if !set.contains($2) {
set.insert($2)
$1.append($2)
}
}
}
```
### 解法七:排序 + 集合
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted { $0 < $1 }.reduce(into: Set<Int>()) {
if !$1
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.sorted { $0 < $1 }.reduce(into: [Int]()) { // contextual closure type '(inout [Int], Int) throws -> ()' expects 2 arguments, but 3 were used in closure body
if !$1.contains($2) { // value of type 'Int' has no member 'contains'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.reduce(into: [Int]()) { // contextual closure type '(inout [Int], Int) throws -> ()' expects 2 arguments, but 3 were used in closure body
$1.append($2) // value of type 'Int' has no member 'append'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.sorted { $0 < $1 }.reduce(into: [Int]()) { // contextual closure type '(inout [Int], Int) throws -> ()' expects 2 arguments, but 3 were used in closure body
if !dict[$2]!.contains($1) { // value of type 'Int' has no member 'contains'
func unique(l: [Int]) -> [Int] {
var dict: [Int: Int] = [:]
var result: [Int] = []
for i in l {
if dict[i] == nil {
dict[i] = 1
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
var result: [Int] = []
for i in l {
if !result.contains(i) {
result.append(i)
}
}
return result
}
func unique(l: [Int]) -> [Int] {
return l.sorted { $0 < $1 }.reduce(into: []) { $0[$1] = $1 }.map { $0 }
}
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 }
}
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
var dict: [Int: Int] = [:]
var result: [Int] = []
for i in l {
if dict[i] == nil {
dict[i] = 1
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
}
```
### 解法三
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.sorted { $0 < $1 }.reduce(into: []) { $0[$1] = $1 }.map { $0 }
}
```
### 解法四
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 }
}
```
### 解法五
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 }
}
```
### 解法六
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 }
}
```
### 解法七
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 }
}
```
### 解法八
```swift
// Return sorted unique elements in an array
// unique(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [0, 2, 3, 5, 9, 123]
func unique(l: [Int]) -> [Int] {
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 }
}
```
### 解
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
func unique(l: [Int]) -> [Int] { // invalid redeclaration of 'unique(l:)'
return l.reduce(into: [Int]()) { $0[$1] = $1 }.filter { $0.count == 1 } // trailing closure passed to parameter of type 'Predicate<Int>' that does not accept a closure
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
func maxElement(l: [Int]) -> Int {
return quickSelect(l: l, k: l.count - 1)
}
func quickSelect(l: [Int], k: Int) -> Int {
let pivot = l[0]
var left = [Int]()
var right = [Int]()
for i in l {
if i < pivot {
left.append(i)
} else if i > pivot {
right.append(i)
}
}
if k < left.count {
return quickSelect(l: left, k: k)
} else if k > left.count {
return quickSelect(l: right, k: k - left.count - 1)
} else {
return pivot
}
}
```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
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:动态规划
```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 dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法四:分治
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法五:快速选择
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return quickSelect(l: l, k: l.count - 1)
}
func quickSelect(l: [Int], k: Int) -> Int {
let pivot = l[0]
var left = [Int]()
var right = [Int]()
for i in l {
if i < pivot {
left.append(i)
} else if i > pivot {
right.append(i)
}
}
if k < left.count {
return quickSelect(l: left, k: k)
} else if k > left.count {
return quickSelect(l: right, k: k - left.count - 1)
} else {
return pivot
}
}
```
### 解法六:堆
```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 heap = Heap<Int>(
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(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 maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
return maxElement(l: l, start: 0, end: l.count - 1)
}
func maxElement(l: [Int], start: Int, end: Int) -> Int {
if start == end {
return l[start]
}
let mid = (start + end) / 2
let left = maxElement(l: Array(l[start..<mid]), start: start, end: mid)
let right = maxElement(l: Array(l[mid + 1..<end]), start: mid + 1, end: end)
return max(left, right)
}
```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
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return maxElement(l: l, start: 0, end: l.count - 1)
}
func maxElement(l: [Int], start: Int, end: Int) -> Int {
if start == end {
return l[start]
}
let mid = (start + end) / 2
let left = maxElement(l: Array(l[start..<mid]), start: start, end: mid)
let right = maxElement(l: Array(l[mid + 1..<end]), start: mid + 1, end: end)
return max(left, right)
}
```
### 解法四:分治 + 递归
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return maxElement(l: l, start: 0, end: l.count - 1)
}
func maxElement(l: [Int], start: Int, end: Int) -> Int {
if start == end {
return l[start]
}
let mid = (start + end) / 2
let left = maxElement(l: Array(l[start..<mid]), start: start, end: mid)
let right = maxElement(l: Array(l[mid + 1..<end]), start: mid + 1, end: end)
return max(left, right)
}
func maxElement(l: [Int], start: Int, end: Int) -> Int {
if start == end {
return l[start]
}
let mid = (start + end) / 2
let left = maxElement(l: Array(l[start..<mid]), start: start, end: mid)
let right = maxElement(l: Array(l[mid + 1..<end]), start: mid + 1, end: end)
return max(left, right)
}
```
### 解法五:分治 + 迭代
```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 start = 0
var end = l.count - 1
return maxElement(l:
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
func maxElement(l: [Int]) -> Int {
var stack = [Int]()
stack.append(l[0])
for i in 1..<l.count {
if l[i] > stack.last! {
stack.append(l[i])
} else {
stack.popLast()
stack.append(l[i])
}
}
return stack.last!
}
```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
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法四:动态规划
```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 dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:单调栈
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var stack = [Int]()
stack.append(l[0])
for i in 1..<l.count {
if l[i] > stack.last! {
stack.append(l[i])
} else {
stack.popLast()
stack.append(l[i])
}
}
return stack.last!
}
```
### 解法六:BFPRT
```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 {
let n = l.count
if n == 1 {
return l[0]
}
let k = n / 5
let ls = Array(l[0..<k])
let rs = Array(l[k..<n])
let lmax = maxElement(l: ls)
let rmax = maxElement(l: rs)
if lmax >
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
stack.popLast() // result of call to 'popLast()' is unused
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = Array(l[0..<l.count])
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法四:动态规划
```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 dp = Array(l[0..<l.count])
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var dp = Array(l[0..<l.count])
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法六:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var dp = Array(l[0..<l.count])
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法七:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(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 maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
func maxElement(l: [Int]) -> Int {
var left = 0
var right = l.count - 1
while left < right {
let mid = left + (right - left) / 2
if l[mid] < l[right] {
left = mid + 1
} else {
right = mid
}
}
return l[left]
}
```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
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法四:动态规划
```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 dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:二分查找
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var left = 0
var right = l.count - 1
while left < right {
let mid = left + (right - left) / 2
if l[mid] < l[right] {
left = mid + 1
} else {
right = mid
}
}
return l[left]
}
```
### 解法六:分治 + 动态规划
```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 dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
var left = 0
var right = l.count - 1
while
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(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 maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
func maxElement(l: [Int]) -> Int {
var stack = [Int]()
for i in 0..<l.count {
while let top = stack.last, l[top] < l[i] {
stack.removeLast()
}
stack.append(i)
}
return l[stack[0]]
}
func maxElement(l: [Int]) -> Int {
var queue = PriorityQueue<Int> { (a, b) in a > b }
for i in l {
queue.push(i)
}
return queue.peek()!
}
```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
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法四:动态规划
```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 dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:单调栈
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var stack = [Int]()
for i in 0..<l.count {
while let top = stack.last, l[top] < l[i] {
stack.removeLast()
}
stack.append(i)
}
return l[stack[0]]
}
```
### 解法六:优先队列
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var queue = PriorityQueue<Int> { (a, b) in a > b }
for i in l {
queue.push(i)
}
return queue.peek()!
}
```
### 解法七:快速选择
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l:
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
var queue = PriorityQueue<Int> { (a, b) in a > b } // cannot find 'PriorityQueue' in scope
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElement(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = l[0..<mid]
let right = l[mid..<l.count]
return max(maxElement(l: left), maxElement(l: right))
}
func maxElement(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
if l.count == 1 {
return l[0]
}
var dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
dp[1] = max(l[0], l[1])
for i in 2..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
### 解法二:递归
```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
}
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = l[0..<mid]
let right = l[mid..<l.count]
return max(maxElement(l: left), maxElement(l: right))
}
```
### 解法三:分治
```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
}
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = l[0..<mid]
let right = l[mid..<l.count]
return max(maxElement(l: left), maxElement(l: right))
}
```
### 解法四:动态规划
```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
}
if l.count == 1 {
return l[0]
}
var dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
dp[1] = max(l[0], l[1])
for i in 2..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
if l.count == 0 {
return 0
}
if l.count == 1 {
return l[0]
}
var dp = [Int](repeating: 0, count: l.count)
dp[0] = l[0]
dp[1] = max(l[0], l[1])
for i in 2..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法六:分治优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
return max(maxElement(l: left), maxElement(l: right)) // cannot convert value of type 'ArraySlice<Int>' to expected argument type '[Int]'
return max(maxElement(l: left), maxElement(l: right)) // cannot convert value of type 'ArraySlice<Int>' to expected argument type '[Int]'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(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 maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
### 解法二:递归
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法四:动态规划
```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 dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法六:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法七:动态规划优化
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
func maxElement(l: [Int]) -> Int {
if l.count == 1 {
return l[0]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
return maxElement(l: l, start: 0, end: l.count - 1)
}
func maxElement(l: [Int], start: Int, end: Int) -> Int {
if start == end {
return l[start]
}
let mid = (start + end) / 2
let left = maxElement(l: Array(l[start..<mid]), start: start, end: mid)
let right = maxElement(l: Array(l[mid + 1..<end]), start: mid + 1, end: end)
return max(left, right)
}
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
var max = dp[l.count - 1]
for i in 0..<l.count {
if dp[i] > max {
max = dp[i]
}
}
return max
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in l {
if i > max {
max = i
}
}
return max
}
```
### 解法二:递归
```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]
}
let mid = l.count / 2
let left = maxElement(l: Array(l[0..<mid]))
let right = maxElement(l: Array(l[mid..<l.count]))
return max(left, right)
}
```
### 解法三:分治
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
return maxElement(l: l, start: 0, end: l.count - 1)
}
func maxElement(l: [Int], start: Int, end: Int) -> Int {
if start == end {
return l[start]
}
let mid = (start + end) / 2
let left = maxElement(l: Array(l[start..<mid]), start: start, end: mid)
let right = maxElement(l: Array(l[mid + 1..<end]), start: mid + 1, end: end)
return max(left, right)
}
```
### 解法四:动态规划
```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 dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
return dp[l.count - 1]
}
```
### 解法五:动态规划优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var dp = Array(repeating: 0, count: l.count)
dp[0] = l[0]
for i in 1..<l.count {
dp[i] = max(dp[i - 1], l[i])
}
var max = dp[l.count - 1]
for i in 0..<l.count {
if dp[i] > max {
max = dp[i]
}
}
return max
}
```
### 解法六:分治优化
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int])
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(l:)'
func maxElement(l: [Int]) -> Int { // invalid redeclaration of 'maxElement(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
}
class Solution {
func maxSubArray(_ nums: [Int]) -> Int {
var max = nums[0]
var sum = 0
for i in 0..<nums.count {
if sum > 0 {
sum += nums[i]
} else {
sum = nums[i]
}
max = max > sum ? max : sum
}
return max
}
}
```swift
// Return maximum element in the array.
// maxElement(l: [1, 2, 3]) == 3
// maxElement(l: [5, 3, -5, 2, -3, 3, 9, 0, 123, 1, -10]) == 123
func maxElement(l: [Int]) -> Int {
var max = l[0]
for i in 1..<l.count {
if l[i] > max {
max = l[i]
}
}
return max
}
```
### 解题思路
### 代码
```swift
class Solution {
func maxSubArray(_ nums: [Int]) -> Int {
var max = nums[0]
var sum = 0
for i in 0..<nums.count {
if sum > 0 {
sum += nums[i]
} else {
sum = nums[i]
}
max = max > sum ? max : sum
}
return max
}
}
```
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func fizzBuzz(n: Int) -> Int {
if n < 1 {
return 0
}
if n == 1 {
return 0
}
if n % 11 == 0 || n % 13 == 0 {
return 1 + fizzBuzz(n: n - 1)
} else {
return fizzBuzz(n: n - 1)
}
}
func fizzBuzz(n: Int) -> Int {
var memo = [Int: Int]()
func helper(n: Int) -> Int {
if n < 1 {
return 0
}
if n == 1 {
return 0
}
if let count = memo[n] {
return count
}
if n % 11 == 0 || n % 13 == 0 {
return 1 + helper(n: n - 1)
} else {
return helper(n: n - 1)
}
}
return helper(n: n)
}
func fizzBuzz(n: Int) -> Int {
var memo = [Int: Int]()
for i in 1...n {
if let count = memo[i] {
continue
}
if i % 11 == 0 || i % 13 == 0 {
memo[i] = 1
} else {
memo[i] = 0
}
}
var count = 0
for i in 1...n {
if memo[i] == 1 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法二:递归
```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 {
if n < 1 {
return 0
}
if n == 1 {
return 0
}
if n % 11 == 0 || n % 13 == 0 {
return 1 + fizzBuzz(n: n - 1)
} else {
return fizzBuzz(n: n - 1)
}
}
```
### 解法三:递归 + 记忆化
```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 memo = [Int: Int]()
func helper(n: Int) -> Int {
if n < 1 {
return 0
}
if n == 1 {
return 0
}
if let count = memo[n] {
return count
}
if n % 11 == 0 || n % 13 == 0 {
return 1 + helper(n: n - 1)
} else {
return helper(n: n - 1)
}
}
return helper(n: n)
}
```
### 解法四:循环
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法五:循环 + 记忆化
```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 memo = [Int: Int]()
for i in 1...n {
if let count = memo[i] {
continue
}
if i % 11 == 0 || i % 13 == 0 {
memo[i] = 1
} else {
memo[i] = 0
}
}
var count = 0
for i in 1...n {
if memo[i] == 1 {
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
// fizzBu
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
if i % 11 == 0 && i % 13 == 0 {
count += 1
} else if i % 11 == 0 {
count += 1
} else if i % 13 == 0 {
count += 1
}
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法二:数学
```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 % 11 == 0 && i % 13 == 0 {
count += 1
} else if i % 11 == 0 {
count += 1
} else if i % 13 == 0 {
count += 1
}
}
}
return count
}
```
### 解法三:数学
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法四:数学
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法五:数学
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法六:数学
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法七:数学
```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) ==
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
### 解法二:数学
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
### 解法三:数学
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
### 解法四:数学
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
### 解法五:数学
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
### 解法六:数学
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
### 解法七:数学
```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 result = 0
for i in 1...n
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
if i % 10 == 7 {
count += 1
}
}
return count
}
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 || i % 7 == 0 {
count += 1
}
}
return count
}
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 || i % 7 == 0 {
count += 1
}
if i % 10 == 7 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
### 解法二
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
if i % 10 == 7 {
count += 1
}
}
return count
}
```
### 解法三
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 || 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 || i % 7 == 0 {
count += 1
}
if i % 10 == 7 {
count += 1
}
}
return count
}
```
### 解法五
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 || i % 7 == 0 {
count += 1
}
if i % 10 == 7 {
count += 1
}
}
return count
}
```
### 解法六
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 || i % 7 == 0 {
count += 1
}
if i % 10 == 7 {
count += 1
}
}
return count
}
```
### 解法七
```swift
// Return the number
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int { // invalid redeclaration of 'fizzBuzz(n:)'
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```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 result = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
result += 1
}
}
return result
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```swift
// Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13.
// fizzBuzz(n: 50) == 0
// fizzBuzz(n: 78) == 2
// fizzBuzz(n: 79) == 3
func fizzBuzz(n: Int) -> Int {
var count = 0
for i in 1...n {
if i % 11 == 0 || i % 13 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
let even = l.filter { $0 % 2 == 0 }
let odd = l.filter { $0 % 2 == 1 }
return even + odd.sorted()
}
func sortEven(l: [Int]) -> [Int] {
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
var i = 0
var j = 0
var result = [Int]()
while i < even.count && j < odd.count {
result.append(even[i])
result.append(odd[j])
i += 1
j += 1
}
if i < even.count {
result.append(contentsOf: even[i..<even.count])
}
if j < odd.count {
result.append(contentsOf: odd[j..<odd.count])
}
return result
}
```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] {
let even = l.filter { $0 % 2 == 0 }
let odd = l.filter { $0 % 2 == 1 }
return even + odd.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 = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
var i = 0
var j = 0
var result = [Int]()
while i < even.count && j < odd.count {
result.append(even[i])
result.append(odd[j])
i += 1
j += 1
}
if i < even.count {
result.append(contentsOf: even[i..<even.count])
}
if j < odd.count {
result.append(contentsOf: odd[j..<odd.count])
}
return result
}
```
### 方法三:递归
```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] {
let even = l.filter { $0 % 2 == 0 }
let odd = l.filter { $0 % 2 == 1 }
return even + odd.sorted()
}
```
func sortEven(l: [Int]) -> [Int] { // invalid redeclaration of 'sortEven(l:)'
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even)
return odd
}
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even.sorted())
return odd
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even)
return odd
}
```
### 解法二
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even.sorted())
return odd
}
```
### 解法三
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even.sorted())
return odd
}
```
### 解法四
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even.sorted())
return odd
}
```
### 解法五
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 != 0 }
odd.append(contentsOf: even.sorted())
return odd
}
```
### 解法六
```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])
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
var even = l.filter { $0 % 2 == 0 } // variable 'even' was never mutated; consider changing to 'let' constant
func sortEven(l: [Int]) -> [Int] { // invalid redeclaration of 'sortEven(l:)'
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
func sortEven(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 2 == 0 {
i += 1
} else if l[j] % 2 == 1 {
j -= 1
} else {
l.swapAt(i, j)
i += 1
j -= 1
}
}
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
### 解法二:双指针
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var i = 0
var j = l.count - 1
while i < j {
if l[i] % 2 == 0 {
i += 1
} else if l[j] % 2 == 1 {
j -= 1
} else {
l.swapAt(i, j)
i += 1
j -= 1
}
}
return l
}
```
func sortEven(l: [Int]) -> [Int] { // invalid redeclaration of 'sortEven(l:)'
func sortEven(l: [Int]) -> [Int] {
var l = l
var odd = l[0...(l.count - 1)].filter { $0 % 2 != 0 }
var even = l[0...(l.count - 1)].filter { $0 % 2 == 0 }
odd.sort()
even.sort()
var result = [Int]()
for i in 0...(l.count - 1) {
if i % 2 == 0 {
result.append(even[i / 2])
} else {
result.append(odd[i / 2])
}
}
return result
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var odd = l[0...(l.count - 1)].filter { $0 % 2 != 0 }
var even = l[0...(l.count - 1)].filter { $0 % 2 == 0 }
odd.sort()
even.sort()
var result = [Int]()
for i in 0...(l.count - 1) {
if i % 2 == 0 {
result.append(even[i / 2])
} else {
result.append(odd[i / 2])
}
}
return result
}
```
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
odd.reverse()
return even + odd
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
odd.reverse()
return even + odd
}
```
### 解法二
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
odd.reverse()
return even + odd
}
```
### 解法三
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
odd.reverse()
return even + odd
}
```
### 解法四
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
odd.reverse()
return even + odd
}
```
### 解法五
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var even = l.filter { $0 % 2 == 0 }
var odd = l.filter { $0 % 2 == 1 }
odd.reverse()
return even + odd
}
```
### 解法六
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
var
var l = l // variable 'l' was never mutated; consider changing to 'let' constant
var even = l.filter { $0 % 2 == 0 } // variable 'even' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i + 1]
l.remove(at: i + 1)
}
}
l.sort()
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i + 1]
l.remove(at: i + 1)
}
}
l.sort()
return l
}
```
### 解法二
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i + 1]
l.remove(at: i + 1)
}
}
l.sort()
return l
}
```
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
// Fatal error: Index out of range
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the odd indicies, while its values at the even indicies are equal
// to the values of the even indicies of l, but sorted.
// sortEven(l: [1, 2, 3]) == [1, 2, 3]
// sortEven(l: [5, 6, 3, 4]) == [3, 6, 5, 4]
func sortEven(l: [Int]) -> [Int] {
var l = l
for i in 0..<l.count {
if i % 2 == 0 {
l[i] = l[i] + l[i+1]
l.remove(at: i+1)
}
}
l.sort()
return l
}
```
```swift
// This function takes an array l and returns an array l' such that
// l' is identical to l in the 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]) ==
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = 1
var fibPrev = 1
var fibPrevPrev = 1
var n = 1
while n < n {
fibPrevPrev = fibPrev
fibPrev = fib
fib = fibPrev + fibPrevPrev
if isPrime(fib) {
n += 1
}
}
return fib
}
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 fib = 1
var fibPrev = 1
var fibPrevPrev = 1
var n = 1
while n < n {
fibPrevPrev = fibPrev
fibPrev = fib
fib = fibPrev + fibPrevPrev
if isPrime(fib) {
n += 1
}
}
return fib
}
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
}
```
if isPrime(fib) { // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var a = 1, b = 2, c = 0
for _ in 1...n {
c = a + b
a = b
b = c
if isPrime(c) {
return c
}
}
return -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
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 1, b = 2, c = 0
for _ in 1...n {
c = a + b
a = b
b = c
if isPrime(c) {
return c
}
}
return -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
}
```
if isPrime(c) { // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(1)
fib.append(2)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
var j = 0
while fib[j] < n {
j += 1
}
return fib[j]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(1)
fib.append(2)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
var j = 0
while fib[j] < n {
j += 1
}
return fib[j]
}
```
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(2)
fib.append(3)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
return fib[i - 1]
}
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(2)
fib.append(3)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
var j = 1
while fib[i - 1] % j != 0 {
j += 1
}
return fib[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 fib = [Int]()
fib.append(2)
fib.append(3)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
return fib[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 fib = [Int]()
fib.append(2)
fib.append(3)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
var j = 1
while fib[i - 1] % j != 0 {
j += 1
}
return fib[i - 1]
}
```
func primeFib(n: Int) -> Int { // invalid redeclaration of 'primeFib(n:)'
func primeFib(n: Int) -> Int {
var fibonacci = [Int]()
fibonacci.append(1)
fibonacci.append(2)
var i = 2
while fibonacci[i] < n {
fibonacci.append(fibonacci[i] + fibonacci[i - 1])
i += 1
}
return fibonacci[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 fibonacci = [Int]()
fibonacci.append(1)
fibonacci.append(2)
var i = 2
while fibonacci[i] < n {
fibonacci.append(fibonacci[i] + fibonacci[i - 1])
i += 1
}
return fibonacci[i - 1]
}
```
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var a = 1
var b = 2
var c = 0
var i = 0
while i < n {
c = a + b
if isPrime(c) {
i += 1
a = b
b = c
}
}
return c
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var a = 1
var b = 2
var c = 0
var i = 0
while i < n {
c = a + b
if isPrime(c) {
i += 1
a = b
b = c
}
}
return c
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
if isPrime(c) { // missing argument label 'n:' in call
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(2)
fib.append(3)
var i = 2
while fib[i] < n {
let fib_i = fib[i]
let fib_i_1 = fib[i - 1]
let fib_i_2 = fib[i - 2]
if fib_i % 2 == 0 {
fib.append(fib_i)
} else if fib_i % 3 == 0 {
fib.append(fib_i)
} else if fib_i_1 % 2 == 0 {
fib.append(fib_i_1)
} else if fib_i_1 % 3 == 0 {
fib.append(fib_i_1)
} else if fib_i_2 % 2 == 0 {
fib.append(fib_i_2)
} else if fib_i_2 % 3 == 0 {
fib.append(fib_i_2)
} else {
fib.append(fib_i)
}
i += 1
}
return fib[n - 1]
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(2)
fib.append(3)
var i = 2
while fib[i] < n {
let fib_i = fib[i]
let fib_i_1 = fib[i - 1]
let fib_i_2 = fib[i - 2]
if fib_i % 2 == 0 {
fib.append(fib_i)
} else if fib_i % 3 == 0 {
fib.append(fib_i)
} else if fib_i_1 % 2 == 0 {
fib.append(fib_i_1)
} else if fib_i_1 % 3 == 0 {
fib.append(fib_i_1)
} else if fib_i_2 % 2 == 0 {
fib.append(fib_i_2)
} else if fib_i_2 % 3 == 0 {
fib.append(fib_i_2)
} else {
fib.append(fib_i)
}
i += 1
}
return fib[n - 1]
}
```
// Fatal error: Index out of range
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fib = 2
var fibPrev = 1
var fibPrevPrev = 1
var i = 2
while i < n {
fib = fibPrev + fibPrevPrev
fibPrevPrev = fibPrev
fibPrev = fib
if fib % 2 == 0 {
fibPrev = fibPrev / 2
}
if fib % 3 == 0 {
fibPrev = fibPrev / 3
}
if fib % 5 == 0 {
fibPrev = fibPrev / 5
}
if fib % 7 == 0 {
fibPrev = fibPrev / 7
}
if fib % 11 == 0 {
fibPrev = fibPrev / 11
}
if fib % 13 == 0 {
fibPrev = fibPrev / 13
}
if fib % 17 == 0 {
fibPrev = fibPrev / 17
}
if fib % 19 == 0 {
fibPrev = fibPrev / 19
}
if fib % 23 == 0 {
fibPrev = fibPrev / 23
}
if fib % 29 == 0 {
fibPrev = fibPrev / 29
}
if fib % 31 == 0 {
fibPrev = fibPrev / 31
}
if fib % 37 == 0 {
fibPrev = fibPrev / 37
}
if fib % 41 == 0 {
fibPrev = fibPrev / 41
}
if fib % 43 == 0 {
fibPrev = fibPrev / 43
}
if fib % 47 == 0 {
fibPrev = fibPrev / 47
}
if fib % 53 == 0 {
fibPrev = fibPrev / 53
}
if fib % 59 == 0 {
fibPrev = fibPrev / 59
}
if fib % 61 == 0 {
fibPrev = fibPrev / 61
}
if fib % 67 == 0 {
fibPrev = fibPrev / 67
}
if fib % 71 == 0 {
fibPrev = fibPrev / 71
}
if fib % 73 == 0 {
fibPrev = fibPrev / 73
}
if fib % 79 == 0 {
fibPrev = fibPrev / 79
}
if fib % 83 == 0 {
fibPrev = fibPrev / 83
}
if fib % 89 == 0 {
fibPrev = fibPrev / 89
}
if fib % 97 == 0 {
fibPrev = fibPrev / 97
}
if fib % 101 == 0 {
fibPrev = fibPrev / 101
}
if fib % 103 == 0 {
fibPrev = fibPrev / 103
}
if fib % 107 == 0 {
fibPrev = fibPrev / 107
}
if fib % 109 == 0 {
fibPrev = fibPrev / 109
}
if fib % 113 == 0 {
fibPrev = fibPrev / 113
}
if fib % 127 == 0 {
fibPrev = fibPrev / 127
}
if fib % 131 == 0 {
fibPrev = fibPrev / 131
}
if fib % 137 == 0 {
XCTAssertTrue(primeFib(n: 1) == 2) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 2) == 3) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 3) == 5) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 4) == 13) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 5) == 89) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 6) == 233) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 7) == 1597) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 8) == 28657) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 9) == 514229) // cannot find 'primeFib' in scope
XCTAssertTrue(primeFib(n: 10) == 433494437) // cannot find 'primeFib' in scope
func primeFib(n: Int) -> Int {
var fib = [Int]()
fib.append(1)
fib.append(2)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
return fib[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 fib = [Int]()
fib.append(1)
fib.append(2)
var i = 2
while fib[i] < n {
fib.append(fib[i] + fib[i - 1])
i += 1
}
return fib[i - 1]
}
```
// Fatal error: Index out of range
func primeFib(n: Int) -> Int {
var fibs = [2, 3]
var i = 2
while fibs.count < n {
let last = fibs[fibs.count - 1]
let next = last + fibs[fibs.count - 2]
if isPrime(num: next) {
fibs.append(next)
}
i += 1
}
return fibs[n - 1]
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```swift
// prime_fib returns n-th number that is a Fibonacci number and it's also prime.
// primeFib(n: 1) == 2
// primeFib(n: 2) == 3
// primeFib(n: 3) == 5
// primeFib(n: 4) == 13
// primeFib(n: 5) == 89
func primeFib(n: Int) -> Int {
var fibs = [2, 3]
var i = 2
while fibs.count < n {
let last = fibs[fibs.count - 1]
let next = last + fibs[fibs.count - 2]
if isPrime(num: next) {
fibs.append(next)
}
i += 1
}
return fibs[n - 1]
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set<Int>(l)
for i in set {
let complement = -i
if set.contains(complement) {
return true
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in l {
if map[i] == nil {
map[i] = 1
} else {
map[i]! += 1
}
}
for i in l {
let complement = -i
if map[complement] != nil {
if map[complement]! == 1 {
map[complement] = nil
} else {
map[complement]! -= 1
}
if map[complement] == nil {
return true
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set<Int>(l)
for i in set {
let complement = -i
if set.contains(complement) {
return true
}
}
return false
}
```
### 解法二
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in l {
if map[i] == nil {
map[i] = 1
} else {
map[i]! += 1
}
}
for i in l {
let complement = -i
if map[complement] != nil {
if map[complement]! == 1 {
map[complement] = nil
} else {
map[complement]! -= 1
}
if map[complement] == nil {
return true
}
}
}
return false
}
```
### 解法三
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in l {
if map[i] == nil {
map[i] = 1
} else {
map[i]! += 1
}
}
for i in l {
let complement = -i
if map[complement] != nil {
if map[complement]! == 1 {
map[complement] = nil
} else {
map[complement]! -= 1
}
if map[complement] == nil {
return true
}
}
}
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[0 - l[i]] = i
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
var i = 0
var j = sorted.count - 1
while i < j {
let sum = sorted[i] + sorted[j]
if sum == 0 {
return true
} else if sum > 0 {
j -= 1
} else {
i += 1
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
for i in 0..<sorted.count {
let target = 0 - sorted[i]
var left = i + 1
var right = sorted.count - 1
while left < right {
let mid = left + (right - left) / 2
if sorted[mid] > target {
right = mid
} else {
left = mid + 1
}
}
if sorted[left] == target {
return true
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
var dict = [Int: Int]()
for i in 0..<sorted.count {
if dict[sorted[i]] != nil {
return true
}
dict[0 - sorted[i]] = i
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[0 - l[i]] = i
}
return false
}
```
### 解法二:排序 + 双指针
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
var i = 0
var j = sorted.count - 1
while i < j {
let sum = sorted[i] + sorted[j]
if sum == 0 {
return true
} else if sum > 0 {
j -= 1
} else {
i += 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 {
let sorted = l.sorted()
for i in 0..<sorted.count {
let target = 0 - sorted[i]
var left = i + 1
var right = sorted.count - 1
while left < right {
let mid = left + (right - left) / 2
if sorted[mid] > target {
right = mid
} else {
left = mid + 1
}
}
if sorted[left] == target {
return true
}
}
return false
}
```
### 解法四:排序 + 哈希表
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
var dict = [Int: Int]()
for i in 0..<sorted.count {
if dict[sorted[i]] != nil {
return true
}
dict[0 - sorted[i]] = i
}
return false
}
```
### 解法五:排序 + 哈希表 + 计
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
for j in i + 1..<l.count {
for k in j + 1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
let complement = -l[i]
if set.contains(complement) {
return true
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
let complement = -l[i]
if set.contains(complement) && set.count == l.count {
return true
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
let complement = -l[i]
if set.contains(complement) && set.count == l.count - 1 {
return true
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
for j in i + 1..<l.count {
for k in j + 1..<l.count {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```
### 解法二
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
let complement = -l[i]
if set.contains(complement) {
return true
}
}
return false
}
```
### 解法三
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
let complement = -l[i]
if set.contains(complement) && set.count == l.count {
return true
}
}
return false
}
```
### 解法四
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in 0..<l.count {
let complement = -l[i]
if set.contains(complement) && set.count == l.count - 1 {
return true
}
}
return false
}
```
### 解法五
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1,
let set = Set(l) // initialization of immutable value 'set' was never used; consider replacing with assignment to '_' or removing it
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in set {
for j in set {
let k = i + j
if k == 0 && set.contains(k) {
return true
}
}
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set(l)
for i in set {
for j in set {
let k = i + j
if k == 0 && set.contains(k) {
return true
}
}
}
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
let n = l.count
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let n = l.count
let l = l.sorted()
for i in 0..<n {
var j = i + 1
var k = n - 1
while j < k {
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
}
func triplesSumToZero(l: [Int]) -> Bool {
let n = l.count
var dict = [Int: Int]()
for i in 0..<n {
if dict[l[i]] != nil {
return true
}
dict[l[i]] = i
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let n = l.count
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if l[i] + l[j] + l[k] == 0 {
return true
}
}
}
}
return false
}
```
### 解法二:排序 + 双指针
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let n = l.count
let l = l.sorted()
for i in 0..<n {
var j = i + 1
var k = n - 1
while j < k {
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 {
let n = l.count
var dict = [Int: Int]()
for i in 0..<n {
if dict[l[i]] != nil {
return true
}
dict[l[i]] = i
}
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[0 - l[i]] = i
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[0 - l[i]] = i
}
return false
}
```
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set<Int>(l)
for i in set {
let complement = -i
if set.contains(complement) {
return true
}
}
return false
}
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
let n = sorted.count
for i in 0..<n {
let j = n - 1
let k = i + 1
while j > k {
let sum = sorted[i] + sorted[j] + sorted[k]
if sum == 0 {
return true
} else if sum > 0 {
j -= 1
} else {
k += 1
}
}
}
return 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
}
func triplesSumToZero(l: [Int]) -> Bool {
let sum = l.reduce(0, +)
if sum % 3 != 0 {
return false
}
let target = sum / 3
var set = Set<Int>()
for i in l {
if set.contains(target - i) {
return true
}
set.insert(i)
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let set = Set<Int>(l)
for i in set {
let complement = -i
if set.contains(complement) {
return true
}
}
return false
}
```
### 解法二:排序+双指针
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let sorted = l.sorted()
let n = sorted.count
for i in 0..<n {
let j = n - 1
let k = i + 1
while j > k {
let sum = sorted[i] + sorted[j] + sorted[k]
if sum == 0 {
return true
} else if sum > 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 {
var set = Set<Int>()
for i in l {
if set.contains(-i) {
return true
}
set.insert(i)
}
return false
}
```
### 解法四:数学
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
let sum = l.reduce(0, +)
if sum % 3 != 0 {
return false
}
let target = sum / 3
var set = Set<Int>()
for i in l {
if set.contains(target - i) {
return true
}
set.insert(i)
}
return false
}
```
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
j -= 1 // left side of mutating operator isn't mutable: 'j' is a 'let' constant
k += 1 // left side of mutating operator isn't mutable: 'k' is a 'let' constant
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'triplesSumToZero(l:)'
func triplesSumToZero(l: [Int]) -> Bool {
let n = l.count
var dp = Array(repeating: Array(repeating: Array(repeating: false, count: n), count: n), count: n)
for i in 0..<n {
for j in 0..<n {
dp[i][j][0] = true
}
}
for i in 1..<n {
for j in 1..<n {
for k in 1..<n {
dp[i][j][k] = l[i] + l[j] + l[k] == 0 && dp[i - 1][j - 1][k - 1]
}
}
}
return dp[n - 1][n - 1][n - 1]
}
```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 n = l.count
var dp = Array(repeating: Array(repeating: Array(repeating: false, count: n), count: n), count: n)
for i in 0..<n {
for j in 0..<n {
dp[i][j][0] = true
}
}
for i in 1..<n {
for j in 1..<n {
for k in 1..<n {
dp[i][j][k] = l[i] + l[j] + l[k] == 0 && dp[i - 1][j - 1][k - 1]
}
}
}
return dp[n - 1][n - 1][n - 1]
}
```
### 解法二:动态规划
```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 n = l.count
var dp = Array(repeating: Array(repeating: Array(repeating: false, count: n), count: n), count: n)
for i in 0..<n {
for j in 0..<n {
dp[i][j][0] = true
}
}
for i in 1..<n {
for j in 1..<n {
for k in 1..<n {
dp[i][j][k] = l[i] + l[j] + l[k] == 0 && dp[i - 1][j - 1][k - 1]
}
}
}
return dp[n - 1][n - 1][n - 1]
}
```
### 解法三:动态规划
```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 n = l.count
var dp = Array(repeating: Array(repeating: Array(repeating: false, count: n), count: n), count: n)
for i in 0..<n {
for j in 0..<n {
dp[i][j][0] = true
}
}
for i in 1..<n {
for j in 1..<n {
for k in 1..<n {
dp[i][j][k] = l[i] + l[j] + l[k] == 0 && dp[i - 1][j - 1][k - 1]
}
}
}
return dp[n - 1][n - 1][n - 1]
}
```
### 解法四:动态规划
```swift
// triples_sum_to_
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if map[num] != nil {
return true
}
map[num] = i
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if map[num] != nil {
return true
}
map[num] = i
}
return false
}
```
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if map[num] != nil {
return true
}
map[num] = i
}
return false
}
```
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if map[num] != nil {
return true
}
map[num] = i
}
return false
}
```
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var map = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if map[num] != nil {
return true
}
map[num] = i
}
return false
}
```
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1])
// XCTAssertTrue failed
func triplesSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in 0..<l.count {
if seen.contains(-l[i]) {
return true
}
seen.insert(l[i])
}
return false
}
```swift
// triples_sum_to_zero takes an array of integers as an input.
// it returns true if there are three distinct elements in the array that
// sum to zero, and false otherwise.
// triplesSumToZero(l: [1, 3, 5, 0]) == false
// triplesSumToZero(l: [1, 3, -2, 1]) == true
// triplesSumToZero(l: [1, 2, 3, 7]) == false
// triplesSumToZero(l: [2, 4, -5, 3, 9, 7]) == true
// triplesSumToZero(l: [1]) == false
func triplesSumToZero(l: [Int]) -> Bool {
var seen = Set<Int>()
for i in 0..<l.count {
if seen.contains(-l[i]) {
return true
}
seen.insert(l[i])
}
return false
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var cars = [Int]()
for i in 0..<n {
cars.append(i)
}
var ans = 0
for i in 0..<n {
var j = i
while j < n {
if cars[j] < cars[i] {
ans += 1
}
j += n
}
}
return ans
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var cars = [Int]()
for i in 0..<n {
cars.append(i)
}
var ans = 0
for i in 0..<n {
var j = i
while j < n {
if cars[j] < cars[i] {
ans += 1
}
j += n
}
}
return ans
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
cars[i] = i
}
while true {
var temp = Array(repeating: 0, count: n)
for i in 0..<n {
if cars[i] == 0 {
continue
}
let j = (cars[i] + 1) % n
temp[j] = temp[j] + 1
}
if temp.contains(0) {
break
}
for i in 0..<n {
if cars[i] == 0 {
continue
}
let j = (cars[i] + 1) % n
if temp[j] > 0 {
result += 1
cars[i] = 0
temp[j] -= 1
}
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
cars[i] = i
}
while true {
var temp = Array(repeating: 0, count: n)
for i in 0..<n {
if cars[i] == 0 {
continue
}
let j = (cars[i] + 1) % n
temp[j] = temp[j] + 1
}
if temp.contains(0) {
break
}
for i in 0..<n {
if cars[i] == 0 {
continue
}
let j = (cars[i] + 1) % n
if temp[j] > 0 {
result += 1
cars[i] = 0
temp[j] -= 1
}
}
}
return result
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
if cars[i] == 0 {
cars[i] = 1
for j in i + 1..<n {
if cars[j] == 1 {
cars[j] = 0
result += 1
}
}
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
if cars[i] == 0 {
cars[i] = 1
for j in i + 1..<n {
if cars[j] == 1 {
cars[j] = 0
result += 1
}
}
}
}
return result
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
let n = n
var count = 0
for i in 0..<n {
if i % 2 == 0 {
count += 1
}
}
return count
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
let n = n
var count = 0
for i in 0..<n {
if i % 2 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
let mod = 1000000007
var ans = 0
var left = 0
var right = 1
for _ in 0..<n {
let temp = left
left = (left + right) % mod
right = (temp + right) % mod
ans = (ans + left) % mod
}
return ans
}
```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 {
let mod = 1000000007
var ans = 0
var left = 0
var right = 1
for _ in 0..<n {
let temp = left
left = (left + right) % mod
right = (temp + right) % mod
ans = (ans + left) % mod
}
return ans
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
let n = n
var cars = Array(repeating: 0, count: n)
var result = 0
while true {
let left = cars.reversed()
let right = cars
var i = 0
while i < n {
if left[i] > right[i] {
result += 1
cars[i] = 0
} else {
cars[i] += 1
}
i += 1
}
if cars == left {
break
}
}
return result
}
```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 {
let n = n
var cars = Array(repeating: 0, count: n)
var result = 0
while true {
let left = cars.reversed()
let right = cars
var i = 0
while i < n {
if left[i] > right[i] {
result += 1
cars[i] = 0
} else {
cars[i] += 1
}
i += 1
}
if cars == left {
break
}
}
return result
}
```
if left[i] > right[i] { // cannot convert value of type 'Int' to expected argument type 'ReversedCollection<[Int]>.Index'
if cars == left { // cannot convert value of type 'ReversedCollection<[Int]>' to expected argument type '[Int]'
func carRaceCollision(n: Int) -> Int {
var cars = [Int]()
for i in 0..<n {
cars.append(i)
}
var result = 0
var left = 0
var right = n - 1
while left < right {
if cars[left] < cars[right] {
result += 1
left += 1
} else {
result += 1
right -= 1
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var cars = [Int]()
for i in 0..<n {
cars.append(i)
}
var result = 0
var left = 0
var right = n - 1
while left < right {
if cars[left] < cars[right] {
result += 1
left += 1
} else {
result += 1
right -= 1
}
}
return result
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
let n = n
var cars = [Int]()
for i in 0..<n {
cars.append(i)
}
var result = 0
while !cars.isEmpty {
let car1 = cars.removeFirst()
let car2 = cars.removeFirst()
if car1 < car2 {
result += 1
}
}
return result
}
```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 {
let n = n
var cars = [Int]()
for i in 0..<n {
cars.append(i)
}
var result = 0
while !cars.isEmpty {
let car1 = cars.removeFirst()
let car2 = cars.removeFirst()
if car1 < car2 {
result += 1
}
}
return result
}
```
// XCTAssertTrue failed
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
cars[i] = i
}
while true {
var temp = Array(repeating: 0, count: n)
for i in 0..<n {
if cars[i] == 0 {
temp[i] = 1
} else {
temp[i] = cars[i]
}
}
for i in 0..<n {
if temp[i] == 0 {
continue
}
for j in 0..<n {
if temp[j] == 0 {
continue
}
if temp[i] < temp[j] {
result += 1
break
}
}
}
cars = temp
if cars.contains(0) {
break
}
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
cars[i] = i
}
while true {
var temp = Array(repeating: 0, count: n)
for i in 0..<n {
if cars[i] == 0 {
temp[i] = 1
} else {
temp[i] = cars[i]
}
}
for i in 0..<n {
if temp[i] == 0 {
continue
}
for j in 0..<n {
if temp[j] == 0 {
continue
}
if temp[i] < temp[j] {
result += 1
break
}
}
}
cars = temp
if cars.contains(0) {
break
}
}
return result
}
```
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
cars[i] = i
}
while true {
let next = cars.map { (i) -> Int in
if i == 0 {
return n - 1
} else {
return i - 1
}
}
if next.elementsEqual(cars) {
break
}
cars = next
result += 1
}
return result
}
```swift
// Imagine a road that's a perfectly straight infinitely long line.
// n cars are driving left to right; simultaneously, a different set of n cars
// are driving right to left. The two sets of cars start out being very far from
// each other. All cars move in the same speed. Two cars are said to collide
// when a car that's moving left to right hits a car that's moving right to left.
// However, the cars are infinitely sturdy and strong; as a result, they continue moving
// in their trajectory as if they did not collide.
// This function outputs the number of such collisions.
func carRaceCollision(n: Int) -> Int {
var cars = Array(repeating: 0, count: n)
var result = 0
for i in 0..<n {
cars[i] = i
}
while true {
let next = cars.map { (i) -> Int in
if i == 0 {
return n - 1
} else {
return i - 1
}
}
if next.elementsEqual(cars) {
break
}
cars = next
result += 1
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 2. 数组遍历
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 3. 数组遍历 + 数组下标
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 4. 数组遍历 + 数组下标 + 数组元素
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 5. 数组遍历 + 数组下标 + 数组元素 + 数组下标
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 6. 数组遍历 + 数组下标 + 数组元素 + 数组下标 + 数组元素
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
func incrList(l: [Int]) -> [Int] {
if l.count == 0 {
return [Int]()
}
var result = [Int]()
result.append(l[0] + 1)
result += incrList(l: Array(l[1...]))
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 方法二:使用递归
```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] {
if l.count == 0 {
return [Int]()
}
var result = [Int]()
result.append(l[0] + 1)
result += incrList(l: Array(l[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] {
if l.count == 0 {
return [Int]()
}
var result = [Int]()
result.append(l[0] + 1)
result += incrList(l: Array(l[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] {
if l.count == 0 {
return [Int]()
}
var result = [Int]()
result.append(l[0] + 1)
result += incrList(l: Array(l[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] {
if l.count == 0 {
return [Int]()
}
var result = [Int]()
result.append(l[0] + 1)
result += incrList(l: Array(l[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] {
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(incr(l[i]))
}
return result
}
func incr(i: Int) -> Int {
return i + 1
}
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(incr(i: i))
}
return result
}
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l: l, i: 0)
}
func incrListHelper(l: [Int], i: Int) -> [Int] {
if i == l.count {
return []
}
return [incr(i: i)] + incrListHelper(l: l, i: i + 1)
}
func incrListHelper(l: [Int], i: Int) -> [Int] {
return i == l.count ? [] : [incr(i: i)] + incrListHelper(l: l, i: i + 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 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 解法二:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(incr(l[i]))
}
return result
}
func incr(i: Int) -> Int {
return i + 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 0..<l.count {
result.append(incr(i: i))
}
return result
}
func incr(i: Int) -> Int {
return i + 1
}
```
### 解法四:递归 + 闭包 + 尾递归优化
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l: l, i: 0)
}
func incrListHelper(l: [Int], i: Int) -> [Int] {
if i == l.count {
return []
}
return [incr(i: i)] + incrListHelper(l: l, i: i + 1)
}
func incr(i: Int) -> Int {
return i + 1
}
```
### 解法五:递归 + 尾递归优化
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l: l, i: 0)
}
func incrListHelper(l: [Int], i: Int) -> [Int] {
return i == l.count ? [] : [incr(i: i)] + incrListHelper(l: l, i: i + 1)
}
func incr(i: Int) -> Int {
return i + 1
}
```
### 解法六:递归 + 尾递归优化 + 闭包
```swift
// Return array with elements incremented by 1.
// inc
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
result.append(incr(l[i])) // missing argument label 'i:' in call
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
func incrListHelper(l: [Int], i: Int) -> [Int] { // invalid redeclaration of 'incrListHelper(l:i:)'
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 2. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 3. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 4. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 5. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 6. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 7. 递归
```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, 1
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(incr(l[i]))
}
return result
}
func incr(i: Int) -> Int {
return i + 1
}
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l, 0, l.count)
}
func incrListHelper(l: [Int], _ i: Int, _ n: Int) -> [Int] {
if i == n {
return []
}
return [l[i]] + incrListHelper(l, i + 1, n)
}
func incrListHelper(l: [Int], _ i: Int, _ n: Int) -> [Int] {
return i == n ? [] : [l[i]] + incrListHelper(l, i + 1, n)
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(l[i] + 1)
}
return result
}
```
### 解法二:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<l.count {
result.append(incr(l[i]))
}
return result
}
func incr(i: Int) -> Int {
return i + 1
}
```
### 解法三:递归 + 尾递归优化
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l, 0, l.count)
}
func incrListHelper(l: [Int], _ i: Int, _ n: Int) -> [Int] {
if i == n {
return []
}
return [l[i]] + incrListHelper(l, i + 1, n)
}
```
### 解法四:递归 + 尾递归优化 + 闭包
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l, 0, l.count)
}
func incrListHelper(l: [Int], _ i: Int, _ n: Int) -> [Int] {
return i == n ? [] : [l[i]] + incrListHelper(l, i + 1, n)
}
```
### 解法五:递归 + 尾递归优化 + 闭包 + 尾递归优化
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
return incrListHelper(l, 0, l.count)
}
func incrListHelper(l: [Int], _ i: Int, _ n: Int) -> [Int] {
return i == n ? [] : [l[i]] + incrListHelper(l, i + 1, n)
}
```
### 解法六:尾递归优化 + 闭包 + 尾递归优化
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
result.append(incr(l[i])) // missing argument label 'i:' in call
func incrList(l: [Int]) -> [Int] { // invalid redeclaration of 'incrList(l:)'
return incrListHelper(l, 0, l.count) // missing argument label 'l:' in call
return incrListHelper(l, 0, l.count) // cannot convert value of type '[Int]' to expected argument type 'Int'
return incrListHelper(l, 0, l.count) // cannot convert value of type 'Int' to expected argument type '[Int]'
return [l[i]] + incrListHelper(l, i + 1, n) // cannot convert value of type '[Int]' to expected argument type 'Int'
return [l[i]] + incrListHelper(l, i + 1, n) // cannot convert value of type 'Int' to expected argument type '[Int]'
return [l[i]] + incrListHelper(l, i + 1, n) // missing argument label 'l:' in call
func incrListHelper(l: [Int], _ i: Int, _ n: Int) -> [Int] { // invalid redeclaration of 'incrListHelper(l:_:_:)'
return i == n ? [] : [l[i]] + incrListHelper(l, i + 1, n) // cannot convert value of type 'Int' to expected argument type '[Int]'
return i == n ? [] : [l[i]] + incrListHelper(l, i + 1, n) // cannot convert value of type '[Int]' to expected argument type 'Int'
return i == n ? [] : [l[i]] + incrListHelper(l, i + 1, n) // missing argument label 'l:' in call
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法二:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法三:递归 + 数组
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法四:递归 + 数组 + 数组
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法五:递归 + 数组 + 数组 + 数组
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法六:递归 + 数组 + 数组 + 数组 + 数组
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法七:递归 + 数组 + 数组 + 数组 + 数组 + 数组
```swift
// Return array with elements incre
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 2. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 3. 迭代
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 4. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 5. 迭代
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 6. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 7. 迭代
```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])
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法二:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法三:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法四:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法五:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 解法六:递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 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
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 2. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 3. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 4. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 5. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 6. 递归
```swift
// Return array with elements incremented by 1.
// incrList(l: [1, 2, 3]) == [2, 3, 4]
// incrList(l: [5, 3, 5, 2, 3, 3, 9, 0, 123]) == [6, 4, 6, 3, 4, 4, 10, 1, 124]
func incrList(l: [Int]) -> [Int] {
var result = l
for i in 0..<l.count {
result[i] += 1
}
return result
}
```
### 7. 递归
```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, 1
func pairsSumToZero(l: [Int]) -> Bool {
// 1. create a dictionary to store the elements and their indexes
var dict: [Int: Int] = [:]
for (index, element) in l.enumerated() {
dict[element] = index
}
// 2. iterate through the array
for (index, element) in l.enumerated() {
// 3. check if the element is in the dictionary
let complement = -element
if dict[complement] != nil && dict[complement] != index {
return true
}
}
return false
}
func pairsSumToZero(l: [Int]) -> Bool {
// 1. sort the array
let sorted = l.sorted()
// 2. create two pointers
var left = 0
var right = sorted.count - 1
// 3. iterate through the array
while left < right {
// 4. check if the sum is zero
let sum = sorted[left] + sorted[right]
if sum == 0 {
return true
} else if sum > 0 {
// 5. if the sum is greater than zero, move the right pointer to the left
right -= 1
} else {
// 6. if the sum is less than zero, move the left pointer to the right
left += 1
}
}
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 {
// 1. create a dictionary to store the elements and their indexes
var dict: [Int: Int] = [:]
for (index, element) in l.enumerated() {
dict[element] = index
}
// 2. iterate through the array
for (index, element) in l.enumerated() {
// 3. check if the element is in the dictionary
let complement = -element
if dict[complement] != nil && dict[complement] != index {
return true
}
}
return false
}
```
### 解法二:双指针
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
// 1. sort the array
let sorted = l.sorted()
// 2. create two pointers
var left = 0
var right = sorted.count - 1
// 3. iterate through the array
while left < right {
// 4. check if the sum is zero
let sum = sorted[left] + sorted[right]
if sum == 0 {
return true
} else if sum > 0 {
// 5. if the sum is greater than zero, move the right pointer to the left
right -= 1
} else {
// 6. if the sum is less than zero, move the left pointer to the right
left += 1
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'pairsSumToZero(l:)'
func pairsSumToZero(l: [Int]) -> Bool {
// 1. create a dictionary to store the elements and their indexes
var dict = [Int: Int]()
for (index, element) in l.enumerated() {
if dict.keys.contains(element) {
return true
}
dict[element] = index
}
return false
}
func pairsSumToZero(l: [Int]) -> Bool {
// 1. sort the array
let sorted = l.sorted()
// 2. create two pointers
var left = 0
var right = sorted.count - 1
// 3. while the pointers are not equal, check if the sum is zero
while left < right {
let sum = sorted[left] + sorted[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
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 {
// 1. create a dictionary to store the elements and their indexes
var dict = [Int: Int]()
for (index, element) in l.enumerated() {
if dict.keys.contains(element) {
return true
}
dict[element] = index
}
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 {
// 1. sort the array
let sorted = l.sorted()
// 2. create two pointers
var left = 0
var right = sorted.count - 1
// 3. while the pointers are not equal, check if the sum is zero
while left < right {
let sum = sorted[left] + sorted[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
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 {
// 1. sort the array
let sorted = l.sorted()
// 2. create two pointers
var left = 0
var right = sorted.count - 1
// 3. while the pointers are not equal, check if the sum is zero
while left < right {
let sum = sorted[left] + sorted[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'pairsSumToZero(l:)'
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if dict[i] != nil {
return true
}
dict[i * -1] = 1
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if dict[i] != nil {
return true
}
dict[i * -1] = 1
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[(-1 * num)] = i
}
return false
}
func pairsSumToZero(l: [Int]) -> Bool {
let l = l.sorted()
var left = 0
var right = l.count - 1
while left < right {
let sum = l[left] + l[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
return false
}
func pairsSumToZero(l: [Int]) -> Bool {
var bitmap = 0
for num in l {
if num < 0 {
num = -1 * num
}
if bitmap & (1 << num) != 0 {
return true
}
bitmap |= 1 << num
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[(-1 * num)] = 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 {
let l = l.sorted()
var left = 0
var right = l.count - 1
while left < right {
let sum = l[left] + l[right]
if sum == 0 {
return true
} else if sum > 0 {
right -= 1
} else {
left += 1
}
}
return false
}
```
### 解法三:哈希表
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[(-1 * num)] = 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 bitmap = 0
for num in l {
if num < 0 {
num = -1 * num
}
if bitmap & (1 << num) != 0 {
return true
}
bitmap |= 1 << num
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'pairsSumToZero(l:)'
func pairsSumToZero(l: [Int]) -> Bool { // invalid redeclaration of 'pairsSumToZero(l:)'
num = -1 * num // cannot assign to value: 'num' is a 'let' constant
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[l[i] * -1] = i
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[l[i] * -1] = i
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
// 1. create a dictionary with key-value pairs
// where the key is the number and the value is the number's index
var dict = [Int: Int]()
for (index, value) in l.enumerated() {
dict[value] = index
}
// 2. iterate through the array
for (index, value) in l.enumerated() {
let complement = -value
if dict.keys.contains(complement) && dict[complement] != index {
return true
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
// 1. create a dictionary with key-value pairs
// where the key is the number and the value is the number's index
var dict = [Int: Int]()
for (index, value) in l.enumerated() {
dict[value] = index
}
// 2. iterate through the array
for (index, value) in l.enumerated() {
let complement = -value
if dict.keys.contains(complement) && dict[complement] != index {
return true
}
}
return false
}
```
### 解法二
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
// 1. create a dictionary with key-value pairs
// where the key is the number and the value is the number's index
var dict = [Int: Int]()
for (index, value) in l.enumerated() {
dict[value] = index
}
// 2. iterate through the array
for (index, value) in l.enumerated() {
let complement = -value
if dict.keys.contains(complement) && dict[complement] != index {
return true
}
}
return false
}
```
### 解法三
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
// 1. create a dictionary with key-value pairs
// where the key is the number and the value is the number's index
var dict = [Int: Int]()
for (index, value) in l.enumerated() {
dict[value] = index
}
// 2. iterate through the array
for (index, value) in l.enumerated() {
let complement = -value
if dict.keys.contains(complement) && dict[complement] != index {
return true
}
}
return false
}
```
### 解法四
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[(-1 * num)] = i
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[(-1 * num)] = i
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[0 - l[i]] = i
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
if dict[l[i]] != nil {
return true
}
dict[0 - l[i]] = i
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[num * -1] = i
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in 0..<l.count {
let num = l[i]
if dict[num] != nil {
return true
}
dict[num * -1] = i
}
return false
}
```
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
} else {
return true
}
}
return false
}
```swift
// pairs_sum_to_zero takes an array of integers as an input.
// it returns true if there are two distinct elements in the array that
// sum to zero, and false otherwise.
// pairsSumToZero(l: [1, 3, 5, 0]) == false
// pairsSumToZero(l: [1, 3, -2, 1]) == false
// pairsSumToZero(l: [1, 2, 3, 7]) == false
// pairsSumToZero(l: [2, 4, -5, 3, 5, 7]) == true
// pairsSumToZero(l: [1]) == false
func pairsSumToZero(l: [Int]) -> Bool {
var dict = [Int: Int]()
for i in l {
if dict[i] == nil {
dict[i] = 1
} else {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func changeBase(x: Int, base: Int) -> String {
var num = x
var res = ""
var baseNum = 0
while num > 0 {
baseNum = num % base
num /= base
res = "\(baseNum)" + res
}
return res
}
```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 num = x
var res = ""
var baseNum = 0
while num > 0 {
baseNum = num % base
num /= base
res = "\(baseNum)" + res
}
return res
}
```
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
var base = base
while number > 0 {
result = String(Character(UnicodeScalar(Int(number % base) + 48)!)) + result
number /= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
var base = base
while number > 0 {
result = String(Character(UnicodeScalar(Int(number % base) + 48)!)) + result
number /= base
}
return result
}
```
var base = base // variable 'base' was never mutated; consider changing to 'let' constant
func changeBase(x: Int, base: Int) -> String {
var num = x
var res = ""
var baseStr = ""
for i in 0..<base {
baseStr.append("\(i)")
}
while num > 0 {
let temp = num % base
res.insert(baseStr[temp], at: res.startIndex)
num /= base
}
return res
}
```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 num = x
var res = ""
var baseStr = ""
for i in 0..<base {
baseStr.append("\(i)")
}
while num > 0 {
let temp = num % base
res.insert(baseStr[temp], at: res.startIndex)
num /= base
}
return res
}
```
res.insert(baseStr[temp], at: res.startIndex) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
var baseNumber = 1
while number > 0 {
let digit = number % base
number /= base
result = String(digit) + result
baseNumber *= base
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var number = x
var baseNumber = 1
while number > 0 {
let digit = number % base
number /= base
result = String(digit) + result
baseNumber *= base
}
return result
}
```
func changeBase(x: Int, base: Int) -> String {
var num = x
var res = ""
var baseStr = ""
for _ in 0..<base {
baseStr.append("0")
}
while num > 0 {
let digit = num % base
num /= base
res = String(digit) + res
}
return res.prefix(base) == baseStr ? res : (baseStr + res)
}
```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 num = x
var res = ""
var baseStr = ""
for _ in 0..<base {
baseStr.append("0")
}
while num > 0 {
let digit = num % base
num /= base
res = String(digit) + res
}
return res.prefix(base) == baseStr ? res : (baseStr + res)
}
```
// XCTAssertTrue failed
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
var base = base
while num > 0 {
let mod = num % base
result = String(mod) + 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
var base = base
while num > 0 {
let mod = num % base
result = String(mod) + result
num /= base
}
return result
}
```
var base = base // variable 'base' was never mutated; consider changing to 'let' constant
```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 num = x
var res = ""
var baseStr = String(base)
var baseStr2 = String(base)
var baseStr3 = String(base)
var baseStr4 = String(base)
var baseStr5 = String(base)
var baseStr6 = String(base)
var baseStr7 = String(base)
var baseStr8 = String(base)
var baseStr9 = String(base)
var baseStr10 = String(base)
var baseStr11 = String(base)
var baseStr12 = String(base)
var baseStr13 = String(base)
var baseStr14 = String(base)
var baseStr15 = String(base)
var baseStr16 = String(base)
var baseStr17 = String(base)
var baseStr18 = String(base)
var baseStr19 = String(base)
var baseStr20 = String(base)
var baseStr21 = String(base)
var baseStr22 = String(base)
var baseStr23 = String(base)
var baseStr24 = String(base)
var baseStr25 = String(base)
var baseStr26 = String(base)
var baseStr27 = String(base)
var baseStr28 = String(base)
var baseStr29 = String(base)
var baseStr30 = String(base)
var baseStr31 = String(base)
var baseStr32 = String(base)
var baseStr33 = String(base)
var baseStr34 = String(base)
var baseStr35 = String(base)
var baseStr36 = String(base)
var baseStr37 = String(base)
var baseStr38 = String(base)
var baseStr39 = String(base)
var baseStr40 = String(base)
var baseStr41 = String(base)
var baseStr42 = String(base)
var baseStr43 = String(base)
var baseStr44 = String(base)
var baseStr45 = String(base)
var baseStr46 = String(base)
var baseStr47 = String(base)
var baseStr48 = String(base)
var baseStr49 = String(base)
var baseStr50 = String(base)
var baseStr51 = String(base)
var baseStr52 = String(base)
var baseStr53 = String(base)
var baseStr54 = String(base)
var baseStr55 = String(base)
var baseStr56 = String(base)
var baseStr57 = String(base)
var baseStr58 = String(base)
var baseStr59 = String(base)
var baseStr60 = String(base)
var baseStr61 = String(base)
var baseStr62 = String(base)
var baseStr63 = String(base)
var baseStr64 = String(base)
var baseStr65 = String(base)
var baseStr66 = String(base)
var baseStr67 = String(base)
var baseStr68 = String(base)
var baseStr69 = String(base)
var baseStr70 = String(base)
var baseStr71 = String(base)
var baseStr72 = String(base)
var baseStr73 = String(base)
var baseStr74 = String(base)
var baseStr75 = String(base)
var baseStr76 = String(base)
var baseStr77 = String(base)
var baseStr78 = String(base)
var baseStr79 = String(base)
var baseStr80 = String(base)
var baseStr81 = String(base)
var baseStr82 = String(base)
var baseStr83 = String(base)
var baseStr84 = String(base)
var baseStr85 = String(base)
XCTAssertTrue(changeBase(x: 8, base: 3) == "22") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 9, base: 3) == "100") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 234, base: 2) == "11101010") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 16, base: 2) == "10000") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 8, base: 2) == "1000") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 7, base: 2) == "111") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 2, base: 3) == "2") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 3, base: 4) == "3") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 4, base: 5) == "4") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 5, base: 6) == "5") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 6, base: 7) == "6") // cannot find 'changeBase' in scope
XCTAssertTrue(changeBase(x: 7, base: 8) == "7") // cannot find 'changeBase' in scope
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
var base = base
while num > 0 {
let digit = num % base
num /= base
result = String(digit) + result
}
return result
}
```swift
// Change numerical base of input number x to base.
// return string representation after the conversion.
// base numbers are less than 10.
// changeBase(x: 8, base: 3) == "22"
// changeBase(x: 8, base: 2) == "1000"
// changeBase(x: 7, base: 2) == "111"
func changeBase(x: Int, base: Int) -> String {
var result = ""
var num = x
var base = base
while num > 0 {
let digit = num % base
num /= base
result = String(digit) + result
}
return result
}
```
var base = base // variable 'base' was never mutated; consider changing to 'let' constant
func changeBase(x: Int, base: Int) -> String {
var res = ""
var n = x
if n == 0 {
return "0"
}
while n > 0 {
let mod = n % base
let char = String(mod)
res = char + res
n /= base
}
return res
}
```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 res = ""
var n = x
if n == 0 {
return "0"
}
while n > 0 {
let mod = n % base
let char = String(mod)
res = char + res
n /= base
}
return res
}
```
func changeBase(x: Int, base: Int) -> String {
var num = x
var res = ""
var baseNum = 1
while num > 0 {
let digit = num % base
num /= base
res = String(digit) + res
baseNum *= base
}
return res
}
class Solution {
func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
if numerator == 0 {
return "0"
}
var res = ""
if (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0) {
res += "-"
}
var numerator = abs(numerator)
var denominator = abs(denominator)
var integer = numerator / denominator
res += String(integer)
numerator = numerator % denominator
if numerator == 0 {
return res
}
res += "."
var map = [Int: Int]()
var index = 0
while numerator > 0 {
if map[numerator] != nil {
let i = map[numerator]!
res = res.replacingSubrange(i...i+1, with: "(" + String(res[i...i+1]) + ")")
return res
}
map[numerator] = index
numerator *= 10
let digit = numerator / denominator
res += String(digit)
numerator = numerator % denominator
index += 1
}
return res
}
}
```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 num = x
var res = ""
var baseNum = 1
while num > 0 {
let digit = num % base
num /= base
res = String(digit) + res
baseNum *= base
}
return res
}
```
### 解题思路
### 代码
```swift
class Solution {
func fractionToDecimal(_ numerator: Int, _ denominator: Int) -> String {
if numerator == 0 {
return "0"
}
var res = ""
if (numerator < 0 && denominator > 0) || (numerator > 0 && denominator < 0) {
res += "-"
}
var numerator = abs(numerator)
var denominator = abs(denominator)
var integer = numerator / denominator
res += String(integer)
numerator = numerator % denominator
if numerator == 0 {
return res
}
res += "."
var map = [Int: Int]()
var index = 0
while numerator > 0 {
if map[numerator] != nil {
let i = map[numerator]!
res = res.replacingSubrange(i...i+1, with: "(" + String(res[i...i+1]) + ")")
return res
}
map[numerator] = index
numerator *= 10
let digit = numerator / denominator
res += String(digit)
numerator = numerator % denominator
index += 1
}
return res
}
}
```
res = res.replacingSubrange(i...i+1, with: "(" + String(res[i...i+1]) + ")") // value of type 'String' has no member 'replacingSubrange'
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func containsCloseNums(nums: [Int], k: Int) -> Bool {
var map = [Int: Int]()
for num in nums {
let diff = k - num
if map[diff] != nil {
return true
}
map[num] = num
}
return false
}
func wordCounts(words: [String]) -> [String: Int] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) + 1
}
return map
}
func uniqWords(words: [String]) -> (Int, Int) {
var map = [String: Int]()
var unique = 0
var total = 0
for word in words {
if map[word] == nil {
unique += 1
}
map[word] = word
total += 1
}
return (unique, total)
}
func commonWords(words: [String]) -> [String] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) + 1
}
var result = [String]()
for (word, count) in map {
if count == words.count {
result.append(word)
}
}
return result
}
func uncommonWords(words: [String], commonWords: [String]) -> [String] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) + 1
}
var result = [String]()
for (word, count) in map {
if !commonWords.contains(word) {
result.append(word)
}
}
return result
}
```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
}
```
### 2. 返回一个数组
```swift
// Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
// containsCloseNums([1, 2, 3, 4, 5], 7) == true
func containsCloseNums(nums: [Int], k: Int) -> Bool {
var map = [Int: Int]()
for num in nums {
let diff = k - num
if map[diff] != nil {
return true
}
map[num] = num
}
return false
}
```
### 3. 返回一个字典
```swift
// Given a list of words, return a dictionary that counts the occurrences of each word.
// wordCounts(["apple", "apple", "banana", "banana", "banana", "banana"]) == ["banana": 4, "apple": 2]
func wordCounts(words: [String]) -> [String: Int] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) + 1
}
return map
}
```
### 4. 返回一个元组
```swift
// Given a list of words, return a tuple of (number of unique words, number of words in the list).
// uniqWords(["apple", "apple", "banana", "banana", "banana", "banana"]) == (3, 6)
func uniqWords(words: [String]) -> (Int, Int) {
var map = [String: Int]()
var unique = 0
var total = 0
for word in words {
if map[word] == nil {
unique += 1
}
map[word] = word
total += 1
}
return (unique, total)
}
```
### 5. 返回一个数组
```swift
// Given a list of words, return a list of words that contains all of the given words and no other words.
// commonWords(["apple", "apple", "banana", "banana", "banana", "banana"]) == ["banana", "banana", "banana"]
func commonWords(words: [String]) -> [String] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) + 1
}
var result = [String]()
for (word, count) in map {
if count == words.count {
result.append(word)
}
}
return result
}
```
### 6. 返回一个数组
```swift
// Given a list of words, return a list of words that does not appear in the provided list of words.
// uncommonWords(["apple", "apple", "banana", "banana", "banana", "banana"], ["banana", "apple"]) == ["banana", "banana", "banana"]
func uncommonWords(words: [String], commonWords: [String]) -> [String] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) + 1
}
var result = [String]()
for (word, count) in map {
if !commonWords.contains(word) {
result.append(word)
}
}
return result
}
```
### 7. 返回一个数组
```swift
// Given a list of words, return a list of words that appear exactly once in the list.
// singleWords(["apple", "apple", "banana", "banana", "banana", "banana"]) == ["banana"]
func singleWords(words: [String]) -> [String] {
var map = [String: Int]()
for word in words {
map[word] = (map[word] ?? 0) +
map[word] = word // cannot assign value of type 'String' to type 'Int?'
for (word, count) in map { // immutable value 'count' was never used; consider replacing with '_' or removing it
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func sum(_ nums: [Int]) -> Int {
return nums.reduce(0, +)
}
func max(_ nums: [Int]) -> Int {
return nums.max()!
}
func min(_ nums: [Int]) -> Int {
return nums.min()!
}
func product(_ nums: [Int]) -> Int {
return nums.reduce(1, *)
}
func sum(_ nums: [Int]) -> Int {
return nums.reduce(0, *)
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
### 2. 求和
```swift
// Given an array of integers, return the sum of its elements.
// sum([1, 2, 3]) == 6
func sum(_ nums: [Int]) -> Int {
return nums.reduce(0, +)
}
```
### 3. 求最大值
```swift
// Given an array of integers, return the largest element.
// max([1, 2, 3]) == 3
func max(_ nums: [Int]) -> Int {
return nums.max()!
}
```
### 4. 求最小值
```swift
// Given an array of integers, return the smallest element.
// min([1, 2, 3]) == 1
func min(_ nums: [Int]) -> Int {
return nums.min()!
}
```
### 5. 求和
```swift
// Given an array of integers, return the product of its elements.
// product([1, 2, 3]) == 6
func product(_ nums: [Int]) -> Int {
return nums.reduce(1, *)
}
```
### 6. 求积
```swift
// Given an array of integers, return the sum of its elements.
// sum([1, 2, 3]) == 6
func sum(_ nums: [Int]) -> Int {
return nums.reduce(0, +)
}
```
### 7. 求最大值
```swift
// Given an array of integers, return the largest element.
// max([1, 2, 3]) == 3
func max(_ nums: [Int]) -> Int {
return nums.max()!
}
```
### 8. 求最小值
```swift
// Given an array of integers, return the smallest element.
// min([1, 2, 3]) == 1
func min(_ nums: [Int]) -> Int {
return nums.min()!
}
```
### 9. 求和
```swift
// Given an array of integers, return the product of its elements.
// product([1, 2, 3]) == 6
func product(_ nums: [Int]) -> Int {
return nums.reduce(1, *)
}
```
### 10. 求积
```swift
// Given an array of integers, return the sum of its elements.
// sum([1, 2, 3]) == 6
func sum(_ nums: [Int]) -> Int {
return nums.reduce(0, *)
}
```
### 11. 求最大值
```swift
// Given an array of integers, return the largest element.
// max([1, 2, 3]) == 3
func max(_ nums: [Int]) -> Int {
return nums.max()!
}
```
### 12. 求最小值
```swift
// Given an array of integers, return the smallest element.
// min([1, 2, 3]) == 1
func min(_ nums: [Int]) -> Int {
return nums.min()!
}
```
### 13. 求和
```swift
// Given an array of integers, return the product of its elements.
// product([1, 2, 3]) == 6
func product(_ nums: [Int]) -> Int {
return nums.reduce(1, *)
}
```
### 14. 求积
```swift
// Given an array of integers, return the sum of its elements.
// sum([1, 2, 3]) == 6
func sum(_ nums: [Int]) -> Int {
return nums.reduce(0, *)
}
```
### 15. 求最大值
```swift
func sum(_ nums: [Int]) -> Int { // invalid redeclaration of 'sum'
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func stringConcatenation(str: String, n: Int) -> String {
return String(repeating: str, count: n)
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for (index, num) in nums.enumerated() {
if let other = dict[target - num] {
return [other, index]
}
dict[num] = index
}
return []
}
func removeKthLast(node: ListNode?, k: Int) -> ListNode? {
var fast = node
var slow = node
for _ in 1...k {
fast = fast?.next
}
if fast == nil {
return node?.next
}
while fast?.next != nil {
fast = fast?.next
slow = slow?.next
}
slow?.next = slow?.next?.next
return node
}
func numberOfPairs(nums: [Int], target: Int) -> Int {
var dict = [Int: Int]()
var count = 0
for num in nums {
if let other = dict[target - num] {
count += 1
}
dict[num] = (dict[num] ?? 0) + 1
}
return count
}
```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
}
```
### 2. 字符串
```swift
// Given a string and a non-negative int n, return a larger string that is n
// copies of the original string
// stringConcatenation(str: "Chocolate", n: 2) == "ChoChoChoChoChoCho"
func stringConcatenation(str: String, n: Int) -> String {
return String(repeating: str, count: n)
}
```
### 3. 数组
```swift
// Given an array of integers, return indices of the two numbers such that they
// add up to a specific sum. You may assume that each input would have exactly one
// solution, and you may not use the same element twice.
// twoSum([2, 7, 11, 15], 9) == [1, 2]
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for (index, num) in nums.enumerated() {
if let other = dict[target - num] {
return [other, index]
}
dict[num] = index
}
return []
}
```
### 4. 链表
```swift
// Given a singly linked list and an integer k, remove the kth last element from
// the list. k is guaranteed to be smaller than the length of the list.
// The list is very long, so making more than one pass is prohibitively expensive.
// You may only use constant extra space.
// removeKthLast(node: 1, k: 1) == 1
func removeKthLast(node: ListNode?, k: Int) -> ListNode? {
var fast = node
var slow = node
for _ in 1...k {
fast = fast?.next
}
if fast == nil {
return node?.next
}
while fast?.next != nil {
fast = fast?.next
slow = slow?.next
}
slow?.next = slow?.next?.next
return node
}
```
### 5. 栈
```swift
// Given an array of integers and a target value, determine the number of
// pairs of array elements that have a difference equal to the target.
// You may assume that each input would have exactly one solution.
// numberOfPairs([1, 2, 3, 4, 5], target: 3) == 2
func numberOfPairs(nums: [Int], target: Int) -> Int {
var dict = [Int: Int]()
var count = 0
for num in nums {
if let other = dict[target - num] {
count += 1
}
dict[num] = (dict[num] ?? 0) + 1
}
return count
}
```
### 6. 队列
```swift
// Given an array of integers and a target value, determine the number of
// pairs of array elements that have a difference equal to the target.
// You may assume that each input would have exactly one solution.
// numberOfPairs([1, 2, 3, 4, 5], target: 3) == 2
func numberOfPairs(nums: [Int], target: Int) -> Int {
var dict = [Int: Int]()
var count = 0
for num in nums {
if let other = dict[target - num] {
count += 1
}
dict[num] = (dict[num] ?? 0) + 1
}
return count
}
```
### 7. 字符串
```swift
// Given a string and a non-negative int n, return a larger string that is n
// copies of the original string
// stringConcatenation(str: "Chocolate", n: 2) == "ChoChoChoChoChoCho"
func stringConcatenation(str: String, n: Int) -> String {
return String(repeating:
func removeKthLast(node: ListNode?, k: Int) -> ListNode? { // cannot find type 'ListNode' in scope
func removeKthLast(node: ListNode?, k: Int) -> ListNode? { // cannot find type 'ListNode' in scope
fast = fast?.next // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
fast = fast?.next // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
slow = slow?.next // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
slow?.next = slow?.next?.next // type of expression is ambiguous without a type annotation
if let other = dict[target - num] { // value 'other' was defined but never used; consider replacing with boolean test
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
```swift
// Given length of a side and high return area for a triangle.
// triangleArea(a: 5, h: 3) == 7.5
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
```
``
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```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
}
```
### 2. 判断一个数是否为素数
```swift
// Given a number return if it is a prime number.
// isPrime(10) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 3. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 4. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 5. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 6. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 7. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 8. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 9. 判断一个数是否为回文数
```swift
// Given a number return if it is a palindrome number.
// palindromeNumber(12321) == true
func palindromeNumber(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
### 10.
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func twoSum(list: [Int], k: Int) -> Bool {
for i in 0..<list.count {
for j in i+1..<list.count {
if list[i] + list[j] == k {
return true
}
}
}
return false
}
func findWord(words: [String], s: String) -> [Int] {
var result: [Int] = []
for i in 0..<words.count {
if words[i].contains(s) {
result.append(i)
}
}
return result
}
```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
}
```
### 2. 返回一个数组
```swift
// Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
// twoSum(list: [1, 2, 3, 4], k: 6) == true
func twoSum(list: [Int], k: Int) -> Bool {
for i in 0..<list.count {
for j in i+1..<list.count {
if list[i] + list[j] == k {
return true
}
}
}
return false
}
```
### 3. 返回一个字典
```swift
// Given a list of words and a string s, return the indices of all the words that contain the given string as a substring.
// findWord(words: ["leet", "code"], s: "t") == [0, 1]
func findWord(words: [String], s: String) -> [Int] {
var result: [Int] = []
for i in 0..<words.count {
if words[i].contains(s) {
result.append(i)
}
}
return result
}
```
### 4. 返回一个元组
```swift
// Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
// twoSum(list: [1, 2, 3, 4], k: 6) == true
func twoSum(list: [Int], k: Int) -> Bool {
for i in 0..<list.count {
for j in i+1..<list.count {
if list[i] + list[j] == k {
return true
}
}
}
return false
}
```
### 5. 返回一个数组
```swift
// Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
// twoSum(list: [1, 2, 3, 4], k: 6) == true
func twoSum(list: [Int], k: Int) -> Bool {
for i in 0..<list.count {
for j in i+1..<list.count {
if list[i] + list[j] == k {
return true
}
}
}
return false
}
```
### 6. 返回一个字典
```swift
// Given a list of words and a string s, return the indices of all the words that contain the given string as a substring.
// findWord(words: ["leet", "code"], s: "t") == [0, 1]
func findWord(words: [String], s: String) -> [Int] {
var result: [Int] = []
for i in 0..<words.count {
if words[i].contains(s) {
result.append(i)
}
}
return result
}
```
### 7. 返回一个元组
```swift
// Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
// twoSum(list: [1, 2, 3, 4], k: 6) == true
func twoSum(list: [Int], k: Int) -> Bool {
for i in 0..<list.count {
for j in i+1..<list.count {
if list[i] + list[j] == k {
return true
}
}
}
return false
}
```
### 8. 返回一个数组
```swift
// Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
// twoSum(list: [1, 2, 3, 4], k: 6) == true
func twoSum(list: [Int], k: Int) -> Bool {
for i in 0..<list.count {
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func notString(s: String) -> String {
return "not " + s
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for (index, num) in nums.enumerated() {
let complement = target - num
if let complementIndex = dict[complement] {
return [complementIndex, index]
}
dict[num] = index
}
return []
}
func kthLast(head: ListNode?, _ k: Int) -> ListNode? {
guard head != nil else {
return nil
}
var fast = head
var slow = head
for _ in 0 ..< k {
fast = fast?.next
}
while fast?.next != nil {
fast = fast?.next
slow = slow?.next
}
slow?.next = slow?.next?.next
return head
}
func longestSubarray(nums: [Int], _ k: Int) -> Int {
var dict = [Int: Int]()
var left = 0
var right = 0
var maxLength = 0
while right < nums.count {
dict[nums[right]] = (dict[nums[right]] ?? 0) + 1
while dict[nums[right]]! > k {
dict[nums[left]]! -= 1
left += 1
}
maxLength = max(maxLength, right - left + 1)
right += 1
}
return maxLength
}
func longestSubstring(s: String) -> Int {
var dict = [Character: Int]()
var left = 0
var right = 0
var maxLength = 0
while right < s.count {
let c = s[s.index(s.startIndex, offsetBy: right)]
if let index = dict[c] {
left = max(left, index + 1)
}
dict[c] = right
maxLength = max(maxLength, right - left + 1)
right += 1
}
return maxLength
}
```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
}
```
### 2. 字符串
```swift
// Given a string, return a new string where "not " has been added to the front.
// notString("contains") == "not contains"
func notString(s: String) -> String {
return "not " + s
}
```
### 3. 数组
```swift
// Given an array of integers, return indices of the two numbers such that they add up to a specific sum.
// You may assume that each input would have exactly one solution, and you may not use the same element twice.
// twoSum([2, 7, 11, 15], 9) == [0, 1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for (index, num) in nums.enumerated() {
let complement = target - num
if let complementIndex = dict[complement] {
return [complementIndex, index]
}
dict[num] = index
}
return []
}
```
### 4. 链表
```swift
// Given a singly linked list and an integer k, remove the kth last element from the list.
// kthLast([1, 2, 3, 4, 5], 2) == 3
func kthLast(head: ListNode?, _ k: Int) -> ListNode? {
guard head != nil else {
return nil
}
var fast = head
var slow = head
for _ in 0 ..< k {
fast = fast?.next
}
while fast?.next != nil {
fast = fast?.next
slow = slow?.next
}
slow?.next = slow?.next?.next
return head
}
```
### 5. 栈
```swift
// Given an array of integers, return the length of the longest subarray such that all its elements are distinct.
// longestSubarray([1, 2, 3, 2, 1], 3) == 2
func longestSubarray(nums: [Int], _ k: Int) -> Int {
var dict = [Int: Int]()
var left = 0
var right = 0
var maxLength = 0
while right < nums.count {
dict[nums[right]] = (dict[nums[right]] ?? 0) + 1
while dict[nums[right]]! > k {
dict[nums[left]]! -= 1
left += 1
}
maxLength = max(maxLength, right - left + 1)
right += 1
}
return maxLength
}
```
### 6. 字符串
```swift
// Given a string, find the length of the longest substring without repeating characters.
// longestSubstring("abcabcbb") == 3
func longestSubstring(s: String) -> Int {
var dict = [Character: Int]()
var left = 0
var right = 0
var maxLength = 0
while right < s.count {
let c = s[s.index(s.startIndex, offsetBy: right)]
if let index = dict[c] {
left = max(left, index + 1)
}
dict[c] = right
maxLength = max(maxLength, right - left + 1)
right += 1
}
return maxLength
}
```
### 7. 数组
```swift
// 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.
// productExceptSelf([1, 2, 3, 4]) == [24, 12, 8, 6]
func productExceptSelf(nums: [Int]) -> [Int] {
var leftProduct = 1
var rightProduct = 1
var result
func kthLast(head: ListNode?, _ k: Int) -> ListNode? { // cannot find type 'ListNode' in scope
func kthLast(head: ListNode?, _ k: Int) -> ListNode? { // cannot find type 'ListNode' in scope
fast = fast?.next // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
fast = fast?.next // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
slow = slow?.next // value of optional type 'Optional<_>' must be unwrapped to a value of type '_'
slow?.next = slow?.next?.next // type of expression is ambiguous without a type annotation
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for i in 0..<nums.count {
let num = nums[i]
if let index = dict[target - num] {
return [index, i]
}
dict[num] = i
}
return []
}
func findClosest(words: [String], target: String) -> Int {
var dict = [String: Int]()
for i in 0..<words.count {
let word = words[i]
dict[word] = i
}
var minDistance = Int.max
var minIndex = -1
for i in 0..<words.count {
let word = words[i]
let distance = distance(word: target, target: word)
if distance < minDistance {
minDistance = distance
minIndex = i
}
}
return minIndex
}
func distance(word: String, target: String) -> Int {
var distance = 0
var i = 0
var j = target.count - 1
while i < target.count && j >= 0 {
if target[j] == word[i] {
i += 1
j -= 1
} else {
distance += 1
i += 1
j -= 1
}
}
return distance
}
```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
}
```
### 2. 返回一个数组
```swift
// Given a list of numbers and a target number, return the indices of the two numbers that sum to the target.
// twoSum(nums: [2, 7, 11, 15], target: 9) == [0, 1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for i in 0..<nums.count {
let num = nums[i]
if let index = dict[target - num] {
return [index, i]
}
dict[num] = i
}
return []
}
```
### 3. 返回一个字典
```swift
// Given a list of words and a string, return the index of the word that is the closest to the end of the list.
// findClosest(words: ["a", "b", "c"], target: "b") == 1
func findClosest(words: [String], target: String) -> Int {
var dict = [String: Int]()
for i in 0..<words.count {
let word = words[i]
dict[word] = i
}
var minDistance = Int.max
var minIndex = -1
for i in 0..<words.count {
let word = words[i]
let distance = distance(word: target, target: word)
if distance < minDistance {
minDistance = distance
minIndex = i
}
}
return minIndex
}
func distance(word: String, target: String) -> Int {
var distance = 0
var i = 0
var j = target.count - 1
while i < target.count && j >= 0 {
if target[j] == word[i] {
i += 1
j -= 1
} else {
distance += 1
i += 1
j -= 1
}
}
return distance
}
```
### 4. 返回一个元组
```swift
// Given a list of numbers and a target number, return the indices of the two numbers that sum to the target.
// twoSum(nums: [2, 7, 11, 15], target: 9) == [0, 1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for i in 0..<nums.count {
let num = nums[i]
if let index = dict[target - num] {
return [index, i]
}
dict[num] = i
}
return []
}
```
### 5. 返回一个数组
```swift
// Given a list of numbers and a target number, return the indices of the two numbers that sum to the target.
// twoSum(nums: [2, 7, 11, 15], target: 9) == [0, 1]
func twoSum(nums: [Int], target: Int) -> [Int] {
var dict = [Int: Int]()
for i in 0..<nums.count {
let num = nums[i]
if let index = dict[target - num] {
return [index, i]
}
dict[num] = i
}
return []
}
```
### 6. 返回一个字典
```swift
// Given a list of words and a string, return the index of the word that is the closest to the end of the list.
// findClosest(words: ["a", "b", "c"], target: "b") == 1
func findClosest(words: [String], target: String) -> Int {
var dict = [String: Int]()
for i in 0..<words.count {
let word = words[i]
dict[word] = i
}
if target[j] == word[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if target[j] == word[i] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func sum(array: [Int]) -> Int {
return array.reduce(0, +)
}
func max(array: [Int]) -> Int {
return array.max()!
}
func min(array: [Int]) -> Int {
return array.min()!
}
func average(array: [Int]) -> Double {
return Double(array.reduce(0, +)) / Double(array.count)
}
func product(array: [Int]) -> Int {
return array.reduce(1, *)
}
```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
}
```
### 2. 求和
```swift
// Given an array of integers, return the sum of its elements.
// sum(array: [1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, +)
}
```
### 3. 求最大值
```swift
// Given an array of integers, return the largest element.
// max(array: [1, 2, 3]) == 3
func max(array: [Int]) -> Int {
return array.max()!
}
```
### 4. 求最小值
```swift
// Given an array of integers, return the smallest element.
// min(array: [1, 2, 3]) == 1
func min(array: [Int]) -> Int {
return array.min()!
}
```
### 5. 求平均值
```swift
// Given an array of integers, return the average of its elements.
// average(array: [1, 2, 3]) == 2
func average(array: [Int]) -> Double {
return Double(array.reduce(0, +)) / Double(array.count)
}
```
### 6. 求乘积
```swift
// Given an array of integers, return the product of its elements.
// product(array: [1, 2, 3]) == 6
func product(array: [Int]) -> Int {
return array.reduce(1, *)
}
```
### 7. 求和
```swift
// Given an array of integers, return the sum of its elements.
// sum(array: [1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, +)
}
```
### 8. 求最大值
```swift
// Given an array of integers, return the largest element.
// max(array: [1, 2, 3]) == 3
func max(array: [Int]) -> Int {
return array.max()!
}
```
### 9. 求最小值
```swift
// Given an array of integers, return the smallest element.
// min(array: [1, 2, 3]) == 1
func min(array: [Int]) -> Int {
return array.min()!
}
```
### 10. 求平均值
```swift
// Given an array of integers, return the average of its elements.
// average(array: [1, 2, 3]) == 2
func average(array: [Int]) -> Double {
return Double(array.reduce(0, +)) / Double(array.count)
}
```
### 11. 求乘积
```swift
// Given an array of integers, return the product of its elements.
// product(array: [1, 2, 3]) == 6
func product(array: [Int]) -> Int {
return array.reduce(1, *)
}
```
### 12. 求和
```swift
// Given an array of integers, return the sum of its elements.
// sum(array: [1, 2, 3]) == 6
func sum(array: [Int]) -> Int {
return array.reduce(0, +)
}
```
### 13. 求最大值
```swift
// Given an array of integers, return the largest element.
// max(array: [1, 2, 3]) == 3
func max(array: [Int]) -> Int {
return array.max()!
}
```
### 14. 求最小值
```swift
// Given an array of integers, return the smallest element.
// min(array: [1, 2, 3]) == 1
func min(array: [
func triangleArea(a: Int, h: Int) -> Double {
return Double(a) * Double(h) / 2
}
func firstIndexOfNumber(numbers: String, target: Int) -> Int {
var index = 0
for c in numbers {
if Int(String(c)) == target {
return index
}
index += 1
}
return -1
}
func lastIndexOfNumber(numbers: String, target: Int) -> Int {
var index = numbers.count - 1
for c in numbers.reversed() {
if Int(String(c)) == target {
return index
}
index -= 1
}
return -1
}
```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
}
```
### 2. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the first index of this number.
// firstIndexOfNumber(numbers: "1234567890", target: 4) == 4
func firstIndexOfNumber(numbers: String, target: Int) -> Int {
var index = 0
for c in numbers {
if Int(String(c)) == target {
return index
}
index += 1
}
return -1
}
```
### 3. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the last index of this number.
// lastIndexOfNumber(numbers: "1234567890", target: 4) == 8
func lastIndexOfNumber(numbers: String, target: Int) -> Int {
var index = numbers.count - 1
for c in numbers.reversed() {
if Int(String(c)) == target {
return index
}
index -= 1
}
return -1
}
```
### 4. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the first index of this number.
// firstIndexOfNumber(numbers: "1234567890", target: 4) == 4
func firstIndexOfNumber(numbers: String, target: Int) -> Int {
var index = 0
for c in numbers {
if Int(String(c)) == target {
return index
}
index += 1
}
return -1
}
```
### 5. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the last index of this number.
// lastIndexOfNumber(numbers: "1234567890", target: 4) == 8
func lastIndexOfNumber(numbers: String, target: Int) -> Int {
var index = numbers.count - 1
for c in numbers.reversed() {
if Int(String(c)) == target {
return index
}
index -= 1
}
return -1
}
```
### 6. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the first index of this number.
// firstIndexOfNumber(numbers: "1234567890", target: 4) == 4
func firstIndexOfNumber(numbers: String, target: Int) -> Int {
var index = 0
for c in numbers {
if Int(String(c)) == target {
return index
}
index += 1
}
return -1
}
```
### 7. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the last index of this number.
// lastIndexOfNumber(numbers: "1234567890", target: 4) == 8
func lastIndexOfNumber(numbers: String, target: Int) -> Int {
var index = numbers.count - 1
for c in numbers.reversed() {
if Int(String(c)) == target {
return index
}
index -= 1
}
return -1
}
```
### 8. 字符串转换为数字
```swift
// Given a string of numbers and a target number, return the first index of this number.
// firstIndexOfNumber(numbers: "1234567890", target: 4) == 4
func firstIndexOfNumber(numbers: String, target: Int) -> Int {
var index = 0
for c in numbers {
if Int(String(c)) == target {
return index
}
index += 1
}
return -1
}
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 5...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 5...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
return fib4(n: n - 1) + fib4(n: n - 2) + fib4(n: n - 3) + fib4(n: n - 4)
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
return fib4(n: n - 1) + fib4(n: n - 2) + fib4(n: n - 3) + fib4(n: n - 4)
}
```
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var fibArray = [Int](repeating: 0, count: 4)
fibArray[0] = 0
fibArray[1] = 0
fibArray[2] = 2
fibArray[3] = 0
for i in 4...n {
fibArray[0] = fibArray[1]
fibArray[1] = fibArray[2]
fibArray[2] = fibArray[3]
fibArray[3] = fibArray[0] + fibArray[1] + fibArray[2] + fibArray[3]
}
return fibArray[3]
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var fibArray = [Int](repeating: 0, count: 4)
fibArray[0] = 0
fibArray[1] = 0
fibArray[2] = 2
fibArray[3] = 0
for i in 4...n {
fibArray[0] = fibArray[1]
fibArray[1] = fibArray[2]
fibArray[2] = fibArray[3]
fibArray[3] = fibArray[0] + fibArray[1] + fibArray[2] + fibArray[3]
}
return fibArray[3]
}
```
for i in 4...n { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 5...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 5...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 5...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 5...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 2
}
if n == 3 {
return 0
}
if n == 4 {
return 2
}
var a = 0
var b = 2
var c = 0
var d = 2
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```swift
// The Fib4 number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fib4(0) -> 0
// fib4(1) -> 0
// fib4(2) -> 2
// fib4(3) -> 0
// fib4(n) -> fib4(n-1) + fib4(n-2) + fib4(n-3) + fib4(n-4).
// Please write a function to efficiently compute the n-th element of the fib4 number sequence. Do not use recursion.
// fib4(n: 5) == 4
// fib4(n: 6) == 8
// fib4(n: 7) == 14
func fib4(n: Int) -> Int {
if n < 4 {
return 0
}
var a = 0
var b = 0
var c = 2
var d = 0
for _ in 4...n {
a = b
b = c
c = d
d = a + b + c
}
return d
}
```
// XCTAssertTrue failed
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:快速排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法四:堆排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法五:计数排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法六:基数排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法七:桶排序
```swift
// Return median of elements in the
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:快速排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法四:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法五:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法六:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法七:二分查找
```swift
// Return median of
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:快速排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法四:堆排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法五:计数排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法六:基数排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法七:桶排序
```swift
// Return median of elements in the
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:快速排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法四:插入排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法五:冒泡排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法六:选择排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法七:希尔排序
```swift
// Return median of elements in the
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:快速选择
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:快速排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法四:插入排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法五:冒泡排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法六:选择排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法七:堆排序
```swift
// Return median of elements in the array
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:快速选择
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m - 1] + l[m]) / 2.0
} else {
return Double(l[m])
}
}
```
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 方法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
func median(l: [Int]) -> Double {
let n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法二:二分查找
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
### 解法三:快速排序
```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 n = l.count
let m = n / 2
let l = l.sorted()
if n % 2 == 0 {
return Double(l[m] + l[m - 1]) / 2.0
} else {
return Double(l[m])
}
}
```
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
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 isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = regexForPalindrome(text: lowerText)
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText))
return matches.count > 0
}
func regexForPalindrome(text: String) -> NSRegularExpression {
let pattern = "^[a-zA-Z0-9]*$"
let regex = try! NSRegularExpression(pattern: pattern)
return regex
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
var left = 0
var right = array.count - 1
while left < right {
if array[left] != array[right] {
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 {
let lowerText = text.lowercased()
let array = Array(lowerText)
var left = 0
var right = array.count - 1
while left < right {
if array[left] != array[right] {
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 {
let lowerText = text.lowercased()
let regex = regexForPalindrome(text: lowerText)
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText))
return matches.count > 0
}
func regexForPalindrome(text: String) -> NSRegularExpression {
let pattern = "^[a-zA-Z0-9]*$"
let regex = try! NSRegularExpression(pattern: pattern)
return regex
}
```
### 解法四:正则表达式
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = regexForPalindrome(text: lowerText)
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText))
return matches.count > 0
}
func regexForPalindrome(text: String) -> NSRegularExpression {
let pattern = "^[a-zA-Z0-9]*$"
let regex = try! NSRegularExpression(pattern: pattern)
return regex
}
```
### 解法五:正则表达式
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = regexForPalindrome(text: lowerText)
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText))
return matches.count > 0
}
func regexForPalindrome(text: String) -> NSRegularExpression {
let pattern = "^[a-zA-Z0-9]*$"
let regex = try! NSRegularExpression(pattern: pattern)
return regex
}
```
### 解法六
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText)) // initializer 'init(_:in:)' requires the types 'String.Index' and 'AttributedString.Index' be equivalent
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText)) // cannot convert value of type 'Range<String.Index>?' to expected argument type 'NSRange' (aka '_NSRange')
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let pattern = "^[a-zA-Z0-9]*$"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: lowerText, range: NSRange(lowerText.startIndex..., in: lowerText))
return matches.count == 1 && matches[0].location == 0 && matches[0].length == lowerText.count
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法二:双指针
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
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 {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let pattern = "^[a-zA-Z0-9]*$"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: lowerText, range: NSRange(lowerText.startIndex..., in: lowerText))
return matches.count == 1 && matches[0].location == 0 && matches[0].length == lowerText.count
}
```
### 解法四:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
return matches.count == 1 && matches[0].location == 0 && matches[0].length == lowerText.count // value of type 'NSTextCheckingResult' has no member 'location'
return matches.count == 1 && matches[0].location == 0 && matches[0].length == lowerText.count // value of type 'NSTextCheckingResult' has no member 'length'
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let lowerTextArray = Array(lowerText)
let reversedTextArray = Array(reversedText)
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerTextArray[left] != reversedTextArray[right] {
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 {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法二
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
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 {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let lowerTextArray = Array(lowerText)
let reversedTextArray = Array(reversedText)
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerTextArray[left] != reversedTextArray[right] {
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 {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let lowerTextArray = Array(lowerText)
let reversedTextArray = Array(reversedText)
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerTextArray[left] != reversedTextArray[right] {
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 {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let lowerTextArray = Array(lowerText)
let reversedTextArray = Array(reversedText)
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerTextArray[left] != reversedTextArray[right] {
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 {
let lowerText = text.lowercased()
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
func isPalindrome(text: String) -> Bool {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
var left = 0
var right = count - 1
while left < right {
if chars[left] != chars[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
var left = 0
var right = count - 1
while left < right {
if !chars[left].isLetterOrNumber {
left += 1
continue
}
if !chars[right].isLetterOrNumber {
right -= 1
continue
}
if chars[left].lowercased() != chars[right].lowercased() {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
let pattern = "^[a-zA-Z0-9]+$"
let regex = try! NSRegularExpression(pattern: pattern)
let match = regex.firstMatch(in: text, options: [], range: NSRange(location: 0, length: count))
return match != nil
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
var left = 0
var right = count - 1
while left < right {
if chars[left] != chars[right] {
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 {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
var left = 0
var right = count - 1
while left < right {
if !chars[left].isLetterOrNumber {
left += 1
continue
}
if !chars[right].isLetterOrNumber {
right -= 1
continue
}
if chars[left].lowercased() != chars[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 {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
let pattern = "^[a-zA-Z0-9]+$"
let regex = try! NSRegularExpression(pattern: pattern)
let match = regex.firstMatch(in: text, options: [], range: NSRange(location: 0, length: count))
return match != nil
}
```
### 解法四:Swift 自带 API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
var left = 0
var right = count - 1
while left < right {
if !chars[left].isLetterOrNumber {
left += 1
continue
}
if !chars[right].isLetterOrNumber {
right -= 1
continue
}
if chars[left].lowercased() != chars[right].lowercased() {
return false
}
left += 1
right -= 1
}
return true
}
```
### 解法五:Swift 自带 API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let chars = Array(text)
let count = chars.count
if count == 0 {
return true
}
var left = 0
var right = count - 1
while left < right {
if !chars[
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if !chars[left].isLetterOrNumber { // value of type 'String.Element' (aka 'Character') has no member 'isLetterOrNumber'
if !chars[right].isLetterOrNumber { // value of type 'String.Element' (aka 'Character') has no member 'isLetterOrNumber'
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(lowerText)
if matches.count == 0 {
return false
}
let firstMatch = matches[0]
let firstIndex = firstMatch.range.location
let lastIndex = firstMatch.range.location + firstMatch.range.length - 1
let reversedText = String(lowerText[firstIndex...lastIndex])
return lowerText[firstIndex...lastIndex] == reversedText
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法二:双指针
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
var left = 0
var right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
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 {
let lowerText = text.lowercased()
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(lowerText)
if matches.count == 0 {
return false
}
let firstMatch = matches[0]
let firstIndex = firstMatch.range.location
let lastIndex = firstMatch.range.location + firstMatch.range.length - 1
let reversedText = String(lowerText[firstIndex...lastIndex])
return lowerText[firstIndex...lastIndex] == reversedText
}
```
### 解法四:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法五:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法六:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法七:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversed
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
let matches = regex.matches(lowerText) // missing argument label 'in:' in call
let matches = regex.matches(lowerText) // missing argument for parameter 'range' in call
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 2. 反转字符串
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 3. 反转字符串,然后比较
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 4. 反转字符串,然后比较,使用数组
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 5. 反转字符串,然后比较,使用数组,使用数组比使用字符串快
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 6. 反转字符串,然后比较,使用数组,使用数组比使用字符串快,使用数组比使用字符串快
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 7. 反转字符串,然后比较,使用数组,使用数组比使用字符串快,使用数组比使用字符串快,使用数组比使用字符串快
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 8. 反转字符串,然后比较,使用数组,使用数组比使用字符串快,使用数组比使用字符串快,使用数组比使用字符串快,使用数组比使用字符串
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let textLength = lowerText.count
var left = 0
var right = textLength - 1
while left < right {
if lowerText[left] != lowerText[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(in: lowerText, range: NSRange(lowerText.startIndex..., in: lowerText))
if matches.count == 0 {
return true
}
let match = matches[0]
let matchRange = match.range
let matchText = lowerText[matchRange]
let reversedMatchText = reversedText[matchRange]
return matchText == reversedMatchText
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法二:双指针
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let textLength = lowerText.count
var left = 0
var right = textLength - 1
while left < right {
if lowerText[left] != lowerText[right] {
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 {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(in: lowerText, range: NSRange(lowerText.startIndex..., in: lowerText))
if matches.count == 0 {
return true
}
let match = matches[0]
let matchRange = match.range
let matchText = lowerText[matchRange]
let reversedMatchText = reversedText[matchRange]
return matchText == reversedMatchText
}
```
### 解法四:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法五:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法六:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法七:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd")
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
let matchText = lowerText[matchRange] // subscript 'subscript(_:)' requires that 'NSRange' (aka '_NSRange') conform to 'RangeExpression'
let reversedMatchText = reversedText[matchRange] // subscript 'subscript(_:)' requires that 'NSRange' (aka '_NSRange') conform to 'RangeExpression'
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
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 isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = regex(pattern: "^[a-zA-Z0-9]*$")
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText))
let count = matches.count
if count == 0 {
return true
}
let first = lowerText[matches[0].range.lowerBound]
let last = lowerText[matches[count - 1].range.upperBound - 1]
return first == last
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
return array.isEqual(to: array.reversed())
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
return lowerText == String(array.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
var left = 0
var right = array.count - 1
while left < right {
if array[left] != array[right] {
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 {
let lowerText = text.lowercased()
let array = Array(lowerText)
var left = 0
var right = array.count - 1
while left < right {
if array[left] != array[right] {
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 {
let lowerText = text.lowercased()
let regex = regex(pattern: "^[a-zA-Z0-9]*$")
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText))
let count = matches.count
if count == 0 {
return true
}
let first = lowerText[matches[0].range.lowerBound]
let last = lowerText[matches[count - 1].range.upperBound - 1]
return first == last
}
```
### 解法四:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
return array.isEqual(to: array.reversed())
}
```
### 解法五:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
return lowerText == String(array.reversed())
}
```
### 解法六:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let array = Array(lowerText)
return lowerText == String(array.reversed())
}
```
### 解法七:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
let regex = regex(pattern: "^[a-zA-Z0-9]*$") // use of local variable 'regex' before its declaration
let matches = regex.matches(in: lowerText, range: Range(lowerText.startIndex..., in: lowerText)) // initializer 'init(_:in:)' requires the types 'String.Index' and 'AttributedString.Index' be equivalent
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
return array.isEqual(to: array.reversed()) // value of type '[String.Element]' (aka 'Array<Character>') has no member 'isEqual'
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
var left = 0, right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(lowerText)
let count = matches.count
if count == 0 {
return true
}
let match = matches[count - 1]
let start = match.range.location
let end = match.range.location + match.range.length
let substring = lowerText[start..<end]
return substring == String(substring.reversed())
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法二:双指针
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
var left = 0, right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
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 {
let lowerText = text.lowercased()
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(lowerText)
let count = matches.count
if count == 0 {
return true
}
let match = matches[count - 1]
let start = match.range.location
let end = match.range.location + match.range.length
let substring = lowerText[start..<end]
return substring == String(substring.reversed())
}
```
### 解法四:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法五:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法六:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法七:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lower
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
let matches = regex.matches(lowerText) // missing argument for parameter 'range' in call
let matches = regex.matches(lowerText) // missing argument label 'in:' in call
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
var left = 0, right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
return false
}
left += 1
right -= 1
}
return true
}
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(lowerText)
if matches.count == 0 {
return false
}
let firstMatch = matches[0]
let first = lowerText.index(lowerText.startIndex, offsetBy: firstMatch.range.lowerBound)
let last = lowerText.index(lowerText.startIndex, offsetBy: firstMatch.range.upperBound - 1)
let reversedText = String(lowerText[first...last])
return lowerText == reversedText
}
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法二:双指针
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
var left = 0, right = lowerText.count - 1
while left < right {
if lowerText[left] != lowerText[right] {
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 {
let lowerText = text.lowercased()
let regex = try! NSRegularExpression(pattern: "^[a-zA-Z0-9]*$", options: [])
let matches = regex.matches(lowerText)
if matches.count == 0 {
return false
}
let firstMatch = matches[0]
let first = lowerText.index(lowerText.startIndex, offsetBy: firstMatch.range.lowerBound)
let last = lowerText.index(lowerText.startIndex, offsetBy: firstMatch.range.upperBound - 1)
let reversedText = String(lowerText[first...last])
return lowerText == reversedText
}
```
### 解法四:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法五:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法六:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lowerText = text.lowercased()
let reversedText = String(lowerText.reversed())
return lowerText == reversedText
}
```
### 解法七:API
```swift
// Checks if given string is a palindrome
// isPalindrome(text: "") == true
// isPalindrome(text: "aba") == true
// isPalindrome(text: "aaaaa") == true
// isPalindrome(text: "zbcd") == false
func isPalindrome(text: String) -> Bool {
let lower
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if lowerText[left] != lowerText[right] { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func isPalindrome(text: String) -> Bool { // invalid redeclaration of 'isPalindrome(text:)'
let matches = regex.matches(lowerText) // missing argument for parameter 'range' in call
let matches = regex.matches(lowerText) // missing argument label 'in:' in call
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0,
func modp(n: Int, p: Int) -> Int { // invalid redeclaration of 'modp(n:p:)'
p = (p * p) % p // cannot assign to value: 'p' is a 'let' constant
func modp(n: Int, p: Int) -> Int {
return (n % p + p) % p
}
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
}
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum = a + b
a = b
b = sum
}
return sum % 1000000007
}
}
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
let base = [[1,1],[1,0]]
let m = [[1,1],[1,0]]
var res = [[1,0],[0,1]]
var n = n - 1
while n > 0 {
if n & 1 == 1 {
res = multiply(res, m)
}
m = multiply(m, m)
n >>= 1
}
return res[0][0]
}
func multiply(_ a: [[Int]], _ b: [[Int]]) -> [[Int]] {
var c = [[Int]](repeating: [Int](repeating: 0, count: 2), count: 2)
for i in 0..<2 {
for j in 0..<2 {
for k in 0..<2 {
c[i][j] += a[i][k] * b[k][j]
}
}
}
return c
}
}
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
var dp = [Int](repeating: 0, count: 2)
dp[1] = 1
for _ in 2...n {
let sum = dp[0] + dp[1]
dp[0] = dp[1]
dp[1] = sum % 1000000007
}
return dp[1]
}
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return (n % p + p) % p
}
```
### 解题思路
#### 方法一:递归
```swift
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
}
```
#### 方法二:迭代
```swift
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
var a = 0, b = 1, sum = 0
for _ in 2...n {
sum = a + b
a = b
b = sum
}
return sum % 1000000007
}
}
```
#### 方法三:矩阵快速幂
```swift
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
let base = [[1,1],[1,0]]
let m = [[1,1],[1,0]]
var res = [[1,0],[0,1]]
var n = n - 1
while n > 0 {
if n & 1 == 1 {
res = multiply(res, m)
}
m = multiply(m, m)
n >>= 1
}
return res[0][0]
}
func multiply(_ a: [[Int]], _ b: [[Int]]) -> [[Int]] {
var c = [[Int]](repeating: [Int](repeating: 0, count: 2), count: 2)
for i in 0..<2 {
for j in 0..<2 {
for k in 0..<2 {
c[i][j] += a[i][k] * b[k][j]
}
}
}
return c
}
}
```
### 解题思路
#### 方法四:动态规划
```swift
class Solution {
func fib(_ n: Int) -> Int {
if n < 2 {
return n
}
var dp = [Int](repeating: 0, count: 2)
dp[1] = 1
for _ in 2...n {
let sum = dp[0] + dp[1]
dp[0] = dp[1]
dp[1] = sum % 1000000007
}
return dp[1]
}
}
```
class Solution { // invalid redeclaration of 'Solution'
class Solution { // invalid redeclaration of 'Solution'
m = multiply(m, m) // cannot assign to value: 'm' is a 'let' constant
class Solution { // invalid redeclaration of 'Solution'
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * 2) % p
}
n >>= 1
}
return res
}
func modp(n: Int, p: Int) -> Int {
var n = n
var res = [[1, 0], [0, 1]]
while n > 0 {
if n & 1 == 1 {
res = multiply(res, [[2, 0], [0, 2]])
}
n >>= 1
}
return res[0][0]
}
func multiply(_ a: [[Int]], _ b: [[Int]]) -> [[Int]] {
var res = [[0, 0], [0, 0]]
for i in 0..<2 {
for j in 0..<2 {
res[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % 101
}
}
return res
}
func modp(n: Int, p: Int) -> Int {
if n == 0 {
return 1
}
let half = modp(n >> 1, p: p)
let res = (half * half) % p
if n & 1 == 1 {
return (res * 2) % p
}
return res
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
### 解法二:快速幂
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * 2) % p
}
n >>= 1
}
return res
}
```
### 解法三:矩阵快速幂
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var res = [[1, 0], [0, 1]]
while n > 0 {
if n & 1 == 1 {
res = multiply(res, [[2, 0], [0, 2]])
}
n >>= 1
}
return res[0][0]
}
func multiply(_ a: [[Int]], _ b: [[Int]]) -> [[Int]] {
var res = [[0, 0], [0, 0]]
for i in 0..<2 {
for j in 0..<2 {
res[i][j] = (a[i][0] * b[0][j] + a[i][1] * b[1][j]) % 101
}
}
return res
}
```
### 解法四:递归
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
if n == 0 {
return 1
}
let half = modp(n >> 1, p: p)
let res = (half * half) % p
if n & 1 == 1 {
return (res * 2) % p
}
return res
}
```
### 解法五:迭代
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101)
func modp(n: Int, p: Int) -> Int { // invalid redeclaration of 'modp(n:p:)'
func modp(n: Int, p: Int) -> Int { // invalid redeclaration of 'modp(n:p:)'
func modp(n: Int, p: Int) -> Int { // invalid redeclaration of 'modp(n:p:)'
let half = modp(n >> 1, p: p) // missing argument label 'n:' in call
let res = (half * half) % p // cannot convert value of type 'Duration' to expected argument type 'Int'
func modp(n: Int, p: Int) -> Int {
return n % p
}
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
let a = a.map({Int(String($0))!})
let b = b.map({Int(String($0))!})
var result = [Int]()
var carry = 0
for i in 0..<max(a.count, b.count) {
let sum = carry
if i < a.count {
sum += a[a.count - 1 - i]
}
if i < b.count {
sum += b[b.count - 1 - i]
}
carry = sum / 2
result.insert(sum % 2, at: 0)
}
if carry > 0 {
result.insert(carry, at: 0)
}
return result.map({String($0)}).joined(separator: "")
}
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n % p
}
```
### 代码
```swift
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
let a = a.map({Int(String($0))!})
let b = b.map({Int(String($0))!})
var result = [Int]()
var carry = 0
for i in 0..<max(a.count, b.count) {
let sum = carry
if i < a.count {
sum += a[a.count - 1 - i]
}
if i < b.count {
sum += b[b.count - 1 - i]
}
carry = sum / 2
result.insert(sum % 2, at: 0)
}
if carry > 0 {
result.insert(carry, at: 0)
}
return result.map({String($0)}).joined(separator: "")
}
}
```
sum += a[a.count - 1 - i] // left side of mutating operator isn't mutable: 'sum' is a 'let' constant
sum += b[b.count - 1 - i] // left side of mutating operator isn't mutable: 'sum' is a 'let' constant
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
class Solution:
def superPow(self, a: int, b: List[int]) -> int:
mod = 1337
def modp(n):
res = 1
while n:
if n & 1:
res = res * a % mod
a = a * a % mod
n >>= 1
return res
return modp(int(''.join(map(str, b[::-1])), 2))
```
```Java []
class Solution {
private static final int MOD = 1337;
public int superPow(int a, List<Integer> b) {
int n = 0;
for(int i: b) n = (n << 1) + i;
return modp(a, n);
}
private int modp(int a, int n) {
if(n == 0) return 1;
int res = modp(a, n >> 1);
res = (int) ((long) res * res % MOD);
if((n & 1) == 1) {
res = (int) ((long) res * a % MOD);
}
return res;
}
}
class Solution {
public:
const int MOD = 1337;
int superPow(int a, vector<int>& b) {
int n = 0;
for(int i: b) n = (n << 1) + i;
return modp(a, n);
}
int modp(int a, int n) {
if(n == 0) return 1;
int res = modp(a, n >> 1);
res = (int) ((long) res * res % MOD);
if((n & 1) == 1) {
res = (int) ((long) res * a % MOD);
}
return res;
}
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
var res = 1
while n > 0 {
if n & 1 == 1 {
res = (res * p) % p
}
p = (p * p) % p
n >>= 1
}
return res
}
```
### 解题思路
#### 方法一:快速幂
##### 算法流程
1. 初始化: 幂指数 $n$ ,模数 $p$ ,结果 $res = 1$ ;
2. 递归计算 $n$ 的二进制表示;
1. 若 $n$ 为 $0$ ,则直接返回 $res$ ;
2. 否则,计算 $res = res * res$ ;
3. 递归计算 $res = res * res \% p$ ;
3. 返回值: 最终返回幂指数 $n$ 的结果 $res$ 。
##### 复杂度分析
- **时间复杂度 $O(\log n)$ :** 递归计算 $n$ 的二进制表示需要 $O(\log n)$ 的时间。
- **空间复杂度 $O(\log n)$ :** 系统递归需要 $O(\log n)$ 的栈空间。
##### 代码
```Python []
class Solution:
def superPow(self, a: int, b: List[int]) -> int:
mod = 1337
def modp(n):
res = 1
while n:
if n & 1:
res = res * a % mod
a = a * a % mod
n >>= 1
return res
return modp(int(''.join(map(str, b[::-1])), 2))
```
```Java []
class Solution {
private static final int MOD = 1337;
public int superPow(int a, List<Integer> b) {
int n = 0;
for(int i: b) n = (n << 1) + i;
return modp(a, n);
}
private int modp(int a, int n) {
if(n == 0) return 1;
int res = modp(a, n >> 1);
res = (int) ((long) res * res % MOD);
if((n & 1) == 1) {
res = (int) ((long) res * a % MOD);
}
return res;
}
}
```
```C++ []
class Solution {
public:
const int MOD = 1337;
int superPow(int a, vector<int>& b) {
int n = 0;
for(int i: b) n = (n << 1) + i;
return modp(a, n);
}
int modp(int a, int n) {
if(n == 0) return 1;
int res = modp(a, n >> 1);
res = (int) ((long) res * res % MOD);
if((n & 1) == 1) {
res = (int) ((long) res * a % MOD);
}
return res;
}
};
```
#### 方法二:快速幂 + 迭代
##### 算法流程
1. 初始化: 幂指数 $n$ ,模数 $p$ ,结果 $res = 1$ ;
2. 迭代计算 $n$ 的二进制表示;
1. 计算 $res = res * res \% p$ ;
2. 递归计算 $res = res * res \% p$ ;
3. 返回值: 最终返回幂指数 $n$ 的结果 $res$ 。
##### 复杂度分析
- **时间复杂度 $O(\log n)$ :** 递归计算 $n$ 的二进制表示需要 $O(\log n)$ 的时间。
- **空间复杂度 $O(\log n)$ :** 系统递归需要 $O(\log n)$ 的栈空间。
##### 代码
```Python []
class Solution:
def superP
def superPow(self, a: int, b: List[int]) -> int: // expected '{' in class
def superPow(self, a: int, b: List[int]) -> int: // cannot find type 'def' in scope
while n: // expected '{' after 'while' condition
while n: // cannot find 'n' in scope
if n & 1: // expected '{' after 'if' condition
if n & 1: // type 'Int' cannot be used as a boolean; test for '!= 0' instead
if n & 1: // cannot find 'n' in scope
return res // return invalid outside of a func
return modp(int(''.join(map(str, b[::-1])), 2)) // expected expression in list of expressions
return modp(int(''.join(map(str, b[::-1])), 2)) // return invalid outside of a func
return modp(int(''.join(map(str, b[::-1])), 2)) // single-quoted string literal found, use '"'
``` // expected expression
class Solution { // invalid redeclaration of 'Solution'
private static final int MOD = 1337; // expected declaration
private static final int MOD = 1337; // consecutive declarations on a line must be separated by ';'
private static final int MOD = 1337; // static declarations are already final
private static final int MOD = 1337; // found an unexpected second identifier in function declaration; is there an accidental break?
private static final int MOD = 1337; // expected 'func' keyword in static method declaration
private static final int MOD = 1337; // expected '{' in body of function declaration
private static final int MOD = 1337; // expected '(' in argument list of function declaration
public int superPow(int a, List<Integer> b) { // found an unexpected second identifier in function declaration; is there an accidental break?
public int superPow(int a, List<Integer> b) { // expected 'func' keyword in instance method declaration
public int superPow(int a, List<Integer> b) { // expected parameter name followed by ':'
public int superPow(int a, List<Integer> b) { // expected ':' following argument label and parameter name
int n = 0; // consecutive statements on a line must be separated by ';'
int n = 0; // cannot find 'n' in scope
int n = 0; // static member 'int' cannot be used on instance of type 'Solution'
for(int i: b) n = (n << 1) + i; // expected 'in' after for-each pattern
for(int i: b) n = (n << 1) + i; // expected pattern
for(int i: b) n = (n << 1) + i; // cannot assign value of type 'UInt8' to type 'UInt8'
for(int i: b) n = (n << 1) + i; // expected ',' separator
for(int i: b) n = (n << 1) + i; // cannot find 'n' in scope
for(int i: b) n = (n << 1) + i; // cannot find 'n' in scope
for(int i: b) n = (n << 1) + i; // found an unexpected second identifier in constant declaration; is there an accidental break?
for(int i: b) n = (n << 1) + i; // expected '{' to start the body of for-each loop
for(int i: b) n = (n << 1) + i; // cannot find 'i' in scope
return modp(a, n); // cannot find 'n' in scope
return modp(a, n); // missing argument labels 'n:p:' in call
return modp(a, n); // unexpected non-void return value in void function
private int modp(int a, int n) { // expected 'func' keyword in instance method declaration
private int modp(int a, int n) { // found an unexpected second identifier in function declaration; is there an accidental break?
private int modp(int a, int n) { // expected ':' following argument label and parameter name
private int modp(int a, int n) { // expected ':' following argument label and parameter name
if(n == 0) return 1; // expected '{' after 'if' condition
res = (int) ((long) res * a % MOD); // cannot find 'res' in scope
res = (int) ((long) res * a % MOD); // cannot find 'long' in scope
res = (int) ((long) res * a % MOD); // cannot find 'MOD' in scope
res = (int) ((long) res * a % MOD); // expected ',' separator
res = (int) ((long) res * a % MOD); // argument passed to call that takes no arguments
res = (int) ((long) res * a % MOD); // static member 'int' cannot be used on instance of type 'Solution'
res = (int) ((long) res * a % MOD); // cannot find 'res' in scope
return res; // cannot find 'res' in scope
class Solution { // invalid redeclaration of 'Solution'
public: // expected declaration
int superPow(int a, vector<int>& b) { // found an unexpected second identifier in function declaration; is there an accidental break?
int superPow(int a, vector<int>& b) { // expected 'func' keyword in instance method declaration
int superPow(int a, vector<int>& b) { // expected ':' following argument label and parameter name
int superPow(int a, vector<int>& b) { // unnamed parameters must be written with the empty name '_'
int superPow(int a, vector<int>& b) { // cannot find type 'vector' in scope
int n = 0; // cannot find 'n' in scope
int n = 0; // consecutive statements on a line must be separated by ';'
for(int i: b) n = (n << 1) + i; // expected '{' to start the body of for-each loop
for(int i: b) n = (n << 1) + i; // found an unexpected second identifier in constant declaration; is there an accidental break?
for(int i: b) n = (n << 1) + i; // expected ',' separator
for(int i: b) n = (n << 1) + i; // cannot find 'i' in scope
for(int i: b) n = (n << 1) + i; // expected 'in' after for-each pattern
for(int i: b) n = (n << 1) + i; // cannot find 'n' in scope
for(int i: b) n = (n << 1) + i; // expected pattern
for(int i: b) n = (n << 1) + i; // cannot assign value of type 'UInt8' to type 'UInt8'
for(int i: b) n = (n << 1) + i; // cannot find 'n' in scope
return modp(a, n); // unexpected non-void return value in void function
return modp(a, n); // missing argument labels 'n:p:' in call
return modp(a, n); // cannot find 'n' in scope
int modp(int a, int n) { // expected 'func' keyword in instance method declaration
int modp(int a, int n) { // expected ':' following argument label and parameter name
int modp(int a, int n) { // found an unexpected second identifier in function declaration; is there an accidental break?
int modp(int a, int n) { // expected ':' following argument label and parameter name
if(n == 0) return 1; // expected '{' after 'if' condition
res = (int) ((long) res * a % MOD); // cannot find 'long' in scope
res = (int) ((long) res * a % MOD); // cannot find 'res' in scope
res = (int) ((long) res * a % MOD); // cannot find 'res' in scope
res = (int) ((long) res * a % MOD); // expected ',' separator
res = (int) ((long) res * a % MOD); // cannot find 'MOD' in scope
return res; // cannot find 'res' in scope
func modp(n: Int, p: Int) -> Int {
return n % p
}
func modp(n: Int, p: Int) -> Int {
var result = 1
var x = n
var power = 1
while power < p {
power *= 2
}
while power > 0 {
if power & 1 == 1 {
result = (result * x) % p
}
x = (x * x) % p
power >>= 1
}
return result
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n % 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 {
var result = 1
var x = n
var power = 1
while power < p {
power *= 2
}
while power > 0 {
if power & 1 == 1 {
result = (result * x) % p
}
x = (x * x) % p
power >>= 1
}
return result
}
```
func modp(n: Int, p: Int) -> Int { // invalid redeclaration of 'modp(n:p:)'
func modp(n: Int, p: Int) -> Int {
return n % p
}
class Solution {
func superPow(_ a: Int, _ b: [Int]) -> Int {
var ans = 1
var a = a
for i in b.reversed() {
ans = modp(n: ans, p: a) * modp(n: a, p: a) % 1337
a = modp(n: a, p: a)
}
return ans
}
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
return n % p
}
```
### 代码
```swift
class Solution {
func superPow(_ a: Int, _ b: [Int]) -> Int {
var ans = 1
var a = a
for i in b.reversed() {
ans = modp(n: ans, p: a) * modp(n: a, p: a) % 1337
a = modp(n: a, p: a)
}
return ans
}
}
```
for i in b.reversed() { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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 {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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 {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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 {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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 {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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 {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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 {
var n = n
var p = p
while n < 0 {
n += p
}
return n % 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
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
// 2^n modulo p
var res = 1
var x = 2
while n > 0 {
if n & 1 == 1 {
res = (res * x) % p
}
x = (x * x) % p
n >>= 1
}
return res
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
// 2^n modulo p
var res = 1
var x = 2
while n > 0 {
if n & 1 == 1 {
res = (res * x) % p
}
x = (x * x) % p
n >>= 1
}
return res
}
```
### 解法二
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
// 2^n modulo p
var res = 1
var x = 2
while n > 0 {
if n & 1 == 1 {
res = (res * x) % p
}
x = (x * x) % p
n >>= 1
}
return res
}
```
var p = p // variable 'p' was never mutated; consider changing to 'let' constant
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
if n < 0 {
n += p
}
if p < 0 {
p += p
}
var res = 0
while n > 0 {
if n & 1 == 1 {
res = (res + p) % p
}
n >>= 1
p = (p * p) % p
}
return res
}
```swift
// Return 2^n modulo p (be aware of numerics).
// modp(n: 3, p: 5) == 3
// modp(n: 1101, p: 101) == 2
// modp(n: 0, p: 101) == 1
// modp(n: 3, p: 11) == 8
// modp(n: 100, p: 101) == 1
func modp(n: Int, p: Int) -> Int {
var n = n
var p = p
if n < 0 {
n += p
}
if p < 0 {
p += p
}
var res = 0
while n > 0 {
if n & 1 == 1 {
res = (res + p) % p
}
n >>= 1
p = (p * p) % p
}
return res
}
```
// Fatal error: Division by zero in remainder operation
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
var result = ""
for char in text {
if !vowels.contains(char) {
result.append(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
var result = ""
for char in text {
if !vowels.contains(char) {
result.append(char)
}
}
return result
}
```
if !vowels.contains(char) { // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
var result = ""
for char in text {
if !vowels.contains(char) {
result.append(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
var result = ""
for char in text {
if !vowels.contains(char) {
result.append(char)
}
}
return result
}
```
if !vowels.contains(char) { // cannot convert value of type 'Character' to expected argument type 'String'
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
let regex = try! NSRegularExpression(pattern: vowels, options: [])
return regex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.count), withTemplate: "")
}
```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 result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
### 解法二:使用正则表达式
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
let regex = try! NSRegularExpression(pattern: vowels, options: [])
return regex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.count), withTemplate: "")
}
```
### 解法三:使用 Swift 字符串 API
```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 result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
### 解法四:使用 Swift 字符串 API
```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 result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
### 解法五:使用 Swift 字符串 API
```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 result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
### 解法六:使用 Swift 字符串 API
```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:
func removeVowels(text: String) -> String { // invalid redeclaration of 'removeVowels(text:)'
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in text {
if !vowels.contains(char) {
result.append(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for char in text {
if !vowels.contains(char) {
result.append(char)
}
}
return result
}
```
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if !["a", "e", "i", "o", "u"].contains(char) {
result.append(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if !["a", "e", "i", "o", "u"].contains(char) {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if !["a", "e", "i", "o", "u"].contains(char) {
result.append(char)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var result = ""
for char in text {
if !["a", "e", "i", "o", "u"].contains(char) {
result.append(char)
}
}
return result
}
```
// XCTAssertTrue failed
func removeVowels(text: String) -> String {
var vowels = Set<Character>("aeiouAEIOU")
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var vowels = Set<Character>("aeiouAEIOU")
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
var vowels = Set<Character>("aeiouAEIOU") // variable 'vowels' was never mutated; consider changing to 'let' constant
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let vowels = "aeiouAEIOU"
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
func removeVowels(text: String) -> String {
var vowels = Set<Character>("aeiouAEIOU")
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
func removeVowels(text: String) -> String {
let regex = try! NSRegularExpression(pattern: "\\b[aeiouAEIOU]\\b", options: [])
return regex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.count), withTemplate: "")
}
func removeVowels(text: String) -> String {
var vowels = Set<Character>("aeiouAEIOU")
var result = ""
var i = 0
for c in text {
if !vowels.contains(c) {
result.append(c)
i += 1
} else {
result.append(text[i])
i += 1
}
}
return result
}
func removeVowels(text: String) -> String {
var vowels = Set<Character>("aeiouAEIOU")
var result = ""
var i = 0
for c in text {
if !vowels.contains(c) {
result.append(c)
i += 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 vowels = Set<Character>("aeiouAEIOU")
var result = ""
for c in text {
if !vowels.contains(c) {
result.append(c)
}
}
return result
}
```
### 解法二:正则表达式
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
let regex = try! NSRegularExpression(pattern: "\\b[aeiouAEIOU]\\b", options: [])
return regex.stringByReplacingMatches(in: text, options: [], range: NSRange(location: 0, length: text.count), withTemplate: "")
}
```
### 解法三:双指针
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "bcdf"
// removeVowels(text: "aaaaa") == ""
// removeVowels(text: "aaBAA") == "B"
// removeVowels(text: "zbcd") == "zbcd"
func removeVowels(text: String) -> String {
var vowels = Set<Character>("aeiouAEIOU")
var result = ""
var i = 0
for c in text {
if !vowels.contains(c) {
result.append(c)
i += 1
} else {
result.append(text[i])
i += 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 vowels = Set<Character>("aeiouAEIOU")
var result = ""
var i = 0
for c in text {
if !vowels.contains(c) {
result.append(c)
i += 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 vowels = Set<Character>("aeiouAEIOU")
var result = ""
var i = 0
for c in text {
if !vowels.contains(c) {
result.append(c)
i += 1
}
}
return result
}
```
### 解法六:双指针
```swift
// remove_vowels is a function that takes string and returns string without vowels.
// removeVowels(text: "") == ""
// removeVowels(text: "abcdef") == "
var vowels = Set<Character>("aeiouAEIOU") // variable 'vowels' was never mutated; consider changing to 'let' constant
func removeVowels(text: String) -> String { // invalid redeclaration of 'removeVowels(text:)'
func removeVowels(text: String) -> String { // invalid redeclaration of 'removeVowels(text:)'
result.append(text[i]) // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func removeVowels(text: String) -> String { // invalid redeclaration of 'removeVowels(text:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count += 1
}
}
return count == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var i = 0
var j = l.count - 1
while i < j {
if l[i] < t {
i += 1
}
if l[j] >= t {
j -= 1
}
}
return i == j
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count |= 1 << num
}
}
return count == (1 << l.count) - 1
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
count |= 1 << num
}
return count & (count + 1) == 0
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count += 1
}
}
return 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 {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == 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 {
var i = 0
var j = l.count - 1
while i < j {
if l[i] < t {
i += 1
}
if l[j] >= t {
j -= 1
}
}
return i == j
}
```
### 解法四:计数
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count += 1
}
}
return 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 {
var count = 0
for num in l {
if num < t {
count |= 1 << num
}
}
return count == (1 << l.count) - 1
}
```
### 解法六:位运算优化
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
count |= 1 << num
}
return count & (count + 1) == 0
}
```
### 解法七:位运算优化
```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:
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var i = 0
var j = l.count - 1
while i < j {
if l[i] >= t {
i += 1
}
if l[j] < t {
j -= 1
}
}
return i == j
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return 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 {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == 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 {
var i = 0
var j = l.count - 1
while i < j {
if l[i] >= t {
i += 1
}
if l[j] < t {
j -= 1
}
}
return i == j
}
```
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.reduce(0, { $0 + ($1 < t ? 1 : 0) }) == 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 {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return 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.reduce(0, { $0 + ($1 < t ? 1 : 0) }) == l.count
}
```
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.reduce(true) { $0 && $1 < t }
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] >= t {
right = mid - 1
} else {
left = mid + 1
}
}
return left == l.count || l[left] >= t
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
return l.reduce(true) { $0 && $1 < t }
}
```
### 解法二:二分查找
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] >= t {
right = mid - 1
} else {
left = mid + 1
}
}
return left == l.count || l[left] >= t
}
```
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count += 1
}
}
return count == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
let sorted = l.sorted()
for i in 0..<sorted.count {
if sorted[i] >= t {
return false
}
}
return true
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left < right {
if l[left] >= t {
break
}
left += 1
}
while left < right {
if l[right] >= t {
right -= 1
} else {
break
}
}
return left == right
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var sum = 0
for num in l {
sum |= num
}
return sum <= t
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count += 1
}
}
return 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 {
let sorted = l.sorted()
for i in 0..<sorted.count {
if sorted[i] >= t {
return false
}
}
return true
}
```
### 解法三:二分查找
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == 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 {
var left = 0
var right = l.count - 1
while left < right {
if l[left] >= t {
break
}
left += 1
}
while left < right {
if l[right] >= t {
right -= 1
} else {
break
}
}
return left == right
}
```
### 解法五:计数
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for num in l {
if num < t {
count += 1
}
}
return 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 {
var sum = 0
for num in l {
sum |= num
}
return sum <= t
}
```
### 解法七:位运算
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var sum = 0
for i in l {
sum += i
if sum > t {
return false
}
}
return true
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[i] += 1
if dp[i] > t {
return false
}
}
return true
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[min(i, t)] += 1
if dp[t] > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var sum = 0
for i in l {
sum += i
if sum > t {
return false
}
}
return true
}
```
### 解法二:动态规划
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[i] += 1
if dp[i] > t {
return false
}
}
return true
}
```
### 解法三:动态规划
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[min(i, t)] += 1
if dp[t] > t {
return false
}
}
return true
}
```
### 解法四:动态规划
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[min(i, t)] += 1
if dp[t] > t {
return false
}
}
return true
}
```
### 解法五:动态规划
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[min(i, t)] += 1
if dp[t] > t {
return false
}
}
return true
}
```
### 解法六:动态规划
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var dp = [Int](repeating: 0, count: t + 1)
for i in l {
dp[min(i, t)] += 1
if dp[t] > t {
return false
}
}
return true
}
```
### 解法七:动态规划
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == l.count
}
func belowThreshold(l: [Int], t: Int) -> Bool {
var left = 0
var right = l.count - 1
while left < right {
if l[left] >= t {
break
}
left += 1
}
while left < right {
if l[right] >= t {
right -= 1
} else {
break
}
}
return left == right
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return 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 {
var left = 0
var right = l.count - 1
while left <= right {
let mid = left + (right - left) / 2
if l[mid] < t {
left = mid + 1
} else {
right = mid - 1
}
}
return left == 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 {
var left = 0
var right = l.count - 1
while left < right {
if l[left] >= t {
break
}
left += 1
}
while left < right {
if l[right] >= t {
right -= 1
} else {
break
}
}
return left == right
}
```
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool { // invalid redeclaration of 'belowThreshold(l:t:)'
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return 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 {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count == l.count
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return 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 {
var count = 0
for i in l {
if i < t {
count += 1
}
}
return count == l.count
}
```
func belowThreshold(l: [Int], t: Int) -> Bool {
var sum = 0
for num in l {
sum += num
if sum > t {
return false
}
}
return true
}
```swift
// Return true if all numbers in the array l are below threshold t.
// belowThreshold(l: [1, 2, 4, 10], t: 100) == true
// belowThreshold(l: [1, 20, 4, 10], t: 5) == false
func belowThreshold(l: [Int], t: Int) -> Bool {
var sum = 0
for num in l {
sum += num
if sum > t {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func add(x: Int, y: Int) -> Int {
return x + y
}
struct Point {
var x: Int
var y: Int
}
func add(point: Point) -> Int {
return point.x + point.y
}
func add(point: Point) -> Point {
return Point(x: point.x, y: point.y)
}
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 2. 函数参数类型
函数参数类型,可以是基本类型,也可以是自定义类型。
```swift
// 基本类型
func add(x: Int, y: Int) -> Int {
return x + y
}
// 自定义类型
struct Point {
var x: Int
var y: Int
}
func add(point: Point) -> Int {
return point.x + point.y
}
```
### 3. 函数返回值类型
函数返回值类型,可以是基本类型,也可以是自定义类型。
```swift
// 基本类型
func add(x: Int, y: Int) -> Int {
return x + y
}
// 自定义类型
struct Point {
var x: Int
var y: Int
}
func add(point: Point) -> Point {
return Point(x: point.x, y: point.y)
}
```
### 4. 函数参数默认值
函数参数默认值,可以简化调用函数时的参数传递。
```swift
// 函数参数默认值
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
add(x: 2) // 21
add(x: 2, y: 3) // 5
```
### 5. 函数参数命名
函数参数命名,可以简化调用函数时的参数传递。
```swift
// 函数参数命名
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
add(2) // 12
add(2, 3) // 5
```
### 6. 函数参数类型限制
函数参数类型限制,可以限制函数参数的类型。
```swift
// 函数参数类型限制
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
add(2) // 12
add(2, 3) // 5
add(x: 2, y: "hello") // 无法通过编译
```
### 7. 函数参数可变性
函数参数可变性,可以限制函数参数是否可变。
```swift
// 函数参数可变性
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
add(2) // 12
add(2, 3) // 5
add(x: 2, y: [1, 2, 3]) // 无法通过编译
```
### 8. 函数参数命名冲突
函数参数命名冲突,可以解决函数参数命名冲突的问题。
```swift
// 函数参数命名冲突
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
add(2) // 12
add(2, 3) // 5
```
### 9. 函数参数类型限制冲突
函数参数类型限制冲突,可以解决函数参数类型限制冲突的问题。
```swift
// 函数参数类型限制冲突
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
add(2) // 12
add(2, 3) // 5
add(x: 2, y: "hello") // 无法通过编译
```
### 10. 函数参数可变性冲突
函数参数可变性冲突,可以解决函数参数可变性冲突的问题。
```swift
// 函数参数可变性冲突
func add(x: Int, y: Int = 10) -> Int {
return x + y
}
func add(x: Int, y: Int = 10) -> Int {
return x + y
func add(x: Int, y: Int = 10) -> Int { // invalid redeclaration of 'add(x:y:)'
func add(x: Int, y: Int) -> Int {
return x + y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func sum(x: [Int]) -> Int {
var total = 0
for number in x {
total += number
}
return total
}
func sum(x: [Int]) -> Int {
return x.reduce(0, +)
}
func sumAndMultiply(x: Int, y: Int) -> (Int, Int) {
return (x + y, x * y)
}
func add(x: Int, y: Int) -> Int {
let result = x + y
return result
}
func multiply(x: Int, y: Int) -> Int {
let result = x * y
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
}
```
### 2.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
}
// 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
}
// Sum of an array of numbers
// sum(x: [1, 2, 3, 4]) == 10
func sum(x: [Int]) -> Int {
var total = 0
for number in x {
total += number
}
return total
}
// Sum of an array of numbers
// sum(x: [1, 2, 3, 4]) == 10
func sum(x: [Int]) -> Int {
return x.reduce(0, +)
}
```
### 2.3 函数的返回类型
函数的返回类型也可以是任意类型,包括函数类型。
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Sum of an array of numbers
// sum(x: [1, 2, 3, 4]) == 10
func sum(x: [Int]) -> Int {
var total = 0
for number in x {
total += number
}
return total
}
// Sum of an array of numbers
// sum(x: [1, 2, 3, 4]) == 10
func sum(x: [Int]) -> Int {
return x.reduce(0, +)
}
// Return the sum of two numbers
// sumAndMultiply(x: 2, y: 3) == 10
// sumAndMultiply(x: 5, y: 7) == 102
func sumAndMultiply(x: Int, y: Int) -> (Int, Int) {
return (x + y, x * y)
}
```
### 2.4 函数的参数名称
函数的参数名称可以与函数体中的变量名称相同。
```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 {
let result = x + y
return result
}
// 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 {
let result = x * y
return result
}
// Sum of an array of numbers
// sum(x: [1, 2, 3, 4]) == 10
func sum(x: [Int]) -> Int {
var total = 0
for number in x {
total += number
}
return total
}
// Sum of an array of numbers
// sum(x: [1, 2, 3, 4]) == 10
func sum(x: [Int]) -> Int {
return x.reduce(0, +)
}
// Return the
func sum(x: [Int]) -> Int { // invalid redeclaration of 'sum(x:)'
func add(x: Int, y: Int) -> Int { // invalid redeclaration of 'add(x:y:)'
func multiply(x: Int, y: Int) -> Int { // invalid redeclaration of 'multiply(x:y:)'
func add(x: Int, y: Int) -> Int {
return x + y
}
func getPerson() -> (name: String, age: Int) {
return ("John", 34)
}
func getPerson() -> Optional<(name: String, age: Int)> {
return ("John", 34)
}
func getPerson() -> [(name: String, age: Int)] {
return [("John", 34)]
}
func getPerson() -> [(name: String, age: Int): String] {
return [(name: "John", age: 34): "John"]
}
func getPerson() -> Set<(name: String, age: Int)> {
return [("John", 34)]
}
struct Person {
var name: String
var age: Int
}
func getPerson() -> Person {
return Person(name: "John", age: 34)
}
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
protocol Person {
var name: String { get }
var age: Int { get }
}
struct Person<T> {
var name: String
var age: Int
}
func getPerson<T>() -> Person<T> {
return Person(name: "John", age: 34)
}
func getPerson<T>() -> (name: String, age: Int) {
return ("John", 34)
}
```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
}
```
### 2.3 函数返回值类型为元组
```swift
// 返回一个元组
// getPerson() == ("John", 34)
func getPerson() -> (name: String, age: Int) {
return ("John", 34)
}
```
### 2.4 函数返回值类型为可选类型
```swift
// 返回一个可选类型
// getPerson() == Optional(("John", 34))
func getPerson() -> Optional<(name: String, age: Int)> {
return ("John", 34)
}
```
### 2.5 函数返回值类型为数组
```swift
// 返回一个数组
// getPerson() == [("John", 34)]
func getPerson() -> [(name: String, age: Int)] {
return [("John", 34)]
}
```
### 2.6 函数返回值类型为字典
```swift
// 返回一个字典
// getPerson() == [("John", 34): "John"]
func getPerson() -> [(name: String, age: Int): String] {
return [(name: "John", age: 34): "John"]
}
```
### 2.7 函数返回值类型为集合
```swift
// 返回一个集合
// getPerson() == Set<("John", 34)>
func getPerson() -> Set<(name: String, age: Int)> {
return [("John", 34)]
}
```
### 2.8 函数返回值类型为结构体
```swift
// 返回一个结构体
// getPerson() == Person(name: "John", age: 34)
struct Person {
var name: String
var age: Int
}
func getPerson() -> Person {
return Person(name: "John", age: 34)
}
```
### 2.9 函数返回值类型为类
```swift
// 返回一个类
// getPerson() == Person(name: "John", age: 34)
class Person {
var name: String
var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
func getPerson() -> Person {
return Person(name: "John", age: 34)
}
```
### 2.10 函数返回值类型为协议
```swift
// 返回一个协议
// getPerson() == Person(name: "John", age: 34)
protocol Person {
var name: String { get }
var age: Int { get }
}
struct Person {
var name: String
var age: Int
}
func getPerson() -> Person {
return Person(name: "John", age: 34)
}
```
### 2.11 函数返回值类型为泛型
```swift
// 返回一个泛型
// getPerson() == Person(name: "John", age: 34)
struct Person<T> {
var name: String
var age: Int
}
func getPerson<T>() -> Person<T> {
return Person(name: "John", age: 34)
}
```
### 2.12 函数返回值类型为泛型嵌套元组
```swift
// 返回一个泛型嵌套元组
// getPerson() == ("John", 34)
struct Person<T> {
var name: String
var age: Int
}
func getPerson<T>() -> (name: String, age: Int) {
return ("John", 34)
}
```
### 2.13 函数返回值类型为泛型可选类型
```swift
// 返回一个泛型可选类型
// getPerson() == Optional(("John", 34))
struct Person<T> {
var name: String
var
func getPerson() -> [(name: String, age: Int): String] { // type '(name: String, age: Int)' does not conform to protocol 'Hashable'
func getPerson() -> Set<(name: String, age: Int)> { // type '(name: String, age: Int)' does not conform to protocol 'Hashable'
func getPerson() -> Person { // 'Person' is ambiguous for type lookup in this context
class Person { // invalid redeclaration of 'Person'
protocol Person { // invalid redeclaration of 'Person'
struct Person<T> { // invalid redeclaration of 'Person'
func getPerson<T>() -> Person<T> { // cannot specialize non-generic type 'Person'
func getPerson<T>() -> (name: String, age: Int) { // generic parameter 'T' is not used in function signature
func add(x: Int, y: Int) -> Int {
return x + y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func subtract(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 remainder(x: Int, y: Int) -> Int {
return x % y
}
func abs(x: Int) -> Int {
return abs(x)
}
func sign(x: Int) -> Int {
return x > 0 ? 1 : -1
}
func min(x: Int, y: Int) -> Int {
return min(x, y)
}
func max(x: Int, y: Int) -> Int {
return max(x, y)
}
func difference(x: Int, y: Int) -> Int {
return abs(x - y)
}
func sum(x: Int, y: Int) -> Int {
return x + y
}
func product(x: Int, y: Int) -> Int {
return x * y
}
func quotient(x: Int, y: Int) -> Int {
return x / y
}
func absolute(x: Int) -> Int {
return abs(x)
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Subtract two numbers x and y
// subtract(x: 2, y: 3) == -1
// subtract(x: 5, y: 7) == -2
func subtract(x: Int, y: Int) -> Int {
return x - y
}
// Divide two numbers x and y
// divide(x: 2, y: 3) == 0
// divide(x: 5, y: 7) == 0
func divide(x: Int, y: Int) -> Int {
return x / y
}
// Raise x to the power y
// power(x: 2, y: 3) == 8
// power(x: 5, y: 7) == 16807
func power(x: Int, y: Int) -> Int {
return x ** y
}
// Returns the remainder of x / y
// remainder(x: 2, y: 3) == 2
// remainder(x: 5, y: 7) == 1
func remainder(x: Int, y: Int) -> Int {
return x % y
}
// Returns the absolute value of x
// abs(x: -2) == 2
// abs(x: 2) == 2
func abs(x: Int) -> Int {
return abs(x)
}
// Returns the sign of x
// sign(x: -2) == -1
// sign(x: 2) == 1
func sign(x: Int) -> Int {
return x > 0 ? 1 : -1
}
// Returns the minimum of x and y
// min(x: 2, y: 3) == 2
// min(x: 5, y: 7) == 5
func min(x: Int, y: Int) -> Int {
return min(x, y)
}
// Returns the maximum of x and y
// max(x: 2, y: 3) == 3
// max(x: 5, y: 7) == 7
func max(x: Int, y: Int) -> Int {
return max(x, y)
}
// Returns the absolute value of x - y
// difference(x: 2, y: 3) == 1
// difference(x: 5, y: 7) == 2
func difference(x: Int, y: Int) -> Int {
return abs(x - y)
}
// Returns the absolute value of x + y
// sum(x: 2, y: 3) == 5
// sum(x: 5, y: 7) == 12
func sum(x: Int, y: Int) -> Int {
return x + y
}
// Returns the absolute value of x * y
// product(x: 2, y: 3) == 6
// product(x: 5, y: 7) == 35
func product(x: Int, y: Int) -> Int {
return x * y
}
// Returns the absolute value of x / y
// quotient(x: 2, y: 3) == 0
// quotient(x: 5, y: 7) == 0
func quotient(x: Int, y: Int) -> Int {
return x / y
}
// Returns the remainder of x / y
// remainder(x: 2, y: 3) == 2
// remainder(x: 5, y: 7) == 1
func remainder(x: Int, y: Int) -> Int {
return x % y
}
// Returns the absolute value of x - y
// absolute(x: -2) == 2
// absolute(x: 2) == 2
func absolute(x: Int) -> Int {
return abs(x)
}
// Returns the sign of x
// sign(x: -2
return x ** y // no operator '**' is defined; did you mean 'pow(_:_:)'?
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: Int, y: Int, f: (Int, Int) -> Int) -> Int {
return f(x, y)
}
func add(x: Int = 0, y: Int = 0) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 2.2 函数的参数类型
函数的参数类型可以是任意类型,包括函数类型。
```swift
// 函数的参数类型可以是任意类型,包括函数类型
func add(x: Int, y: Int, f: (Int, Int) -> Int) -> Int {
return f(x, y)
}
// 调用 add 函数
add(x: 2, y: 3, f: add) // 5
```
### 2.3 函数的返回值类型
函数的返回值类型可以是任意类型,包括函数类型。
```swift
// 函数的返回值类型可以是任意类型,包括函数类型
func add(x: Int, y: Int) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
```
### 2.4 函数的参数名称
函数的参数名称可以自定义,但是参数名称不能重复。
```swift
// 函数的参数名称可以自定义,但是参数名称不能重复
func add(x: Int, y: Int) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
```
### 2.5 函数的参数默认值
函数的参数默认值可以给函数调用时提供便利。
```swift
// 函数的参数默认值可以给函数调用时提供便利
func add(x: Int = 0, y: Int = 0) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
add(x: 2) // 2
```
### 2.6 函数的参数标签
函数的参数标签可以给函数调用时提供便利。
```swift
// 函数的参数标签可以给函数调用时提供便利
func add(
x: Int = 0,
y: Int = 0
) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
add(x: 2) // 2
```
### 2.7 函数的嵌套定义
函数的嵌套定义可以给函数调用时提供便利。
```swift
// 函数的嵌套定义可以给函数调用时提供便利
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: Int, y: Int) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
```
### 2.8 函数的嵌套调用
函数的嵌套调用可以给函数调用时提供便利。
```swift
// 函数的嵌套调用可以给函数调用时提供便利
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: Int, y: Int) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
```
### 2.9 函数的嵌套定义和嵌套调用
函数的嵌套定义和嵌套调用可以给函数调用时提供便利。
```swift
// 函数的嵌套定义和嵌套调用可以给函数调用时提供便利
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: Int, y: Int) -> Int {
return x + y
}
// 调用 add 函数
add(x: 2, y: 3) // 5
```
### 2.10 函数的嵌套定义和嵌套调用
函数的嵌套定义和嵌套调用可以给函数调用时提供便利。
```swift
// 函数的嵌套定义和嵌套调用可以给函数调用时提供便利
func add(x: Int, y: Int) -> Int {
func add(x: Int = 0, y: Int = 0) -> Int { // invalid redeclaration of 'add(x:y:)'
func add(x: Int, y: Int) -> Int {
return x + y
}
func apply<T>(_ function: (T) -> Void) {
// 函数体略
}
func apply<T>(_ function: (T) -> Void) {
function(10)
}
func makeIncrementer() -> (Int) -> Int {
var x = 0
return { x += 1; x }
}
func apply<T>(_ function: (T) -> Void, _ default: T = 0) {
// 函数体略
}
func apply<T>(_ function: (T) -> Void, _ default: T = 0) {
function(default)
}
```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
}
```
### 2.2 函数的参数类型
函数的参数类型可以是任意类型,包括函数类型。
```swift
// 定义一个函数,接受一个函数作为参数
func apply<T>(_ function: (T) -> Void) {
// 函数体略
}
// 调用函数,传入一个函数
apply { print("Hello") }
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 调用函数,传入一个函数
apply { print("Hello") }
```
### 2.3 函数的返回值类型
函数的返回值类型也可以是任意类型,包括函数类型。
```swift
// 定义一个函数,返回一个函数
func makeIncrementer() -> (Int) -> Int {
var x = 0
return { x += 1; x }
}
// 调用函数,传入一个函数
let incrementer = makeIncrementer()
incrementer(10) // 11
incrementer(10) // 12
// 定义一个函数,返回一个函数,并调用返回的函数
func makeIncrementer() -> (Int) -> Int {
var x = 0
return { x += 1; x }
}
// 调用函数,传入一个函数
let incrementer = makeIncrementer()
incrementer(10) // 11
incrementer(10) // 12
```
### 2.4 函数的参数默认值
函数的参数默认值可以简化函数调用。
```swift
// 定义一个函数,传入一个函数作为参数,并设置参数默认值
func apply<T>(_ function: (T) -> Void, _ default: T = 0) {
// 函数体略
}
// 调用函数,传入一个函数
apply { print("Hello") }
// 调用函数,传入一个函数,并设置参数默认值
apply { print("Hello") }
// 定义一个函数,传入一个函数作为参数,并设置参数默认值
func apply<T>(_ function: (T) -> Void, _ default: T = 0) {
function(default)
}
// 调用函数,传入一个函数,并设置参数默认值
apply { print("Hello") }
```
### 2.5 函数的参数类型是函数
函数的参数类型是函数,可以接受一个函数作为参数。
```swift
// 定义一个函数,接受一个函数作为参数
func apply<T>(_ function: (T) -> Void) {
// 函数体略
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
function(10)
}
// 定义一个函数,接受一个函数作为参数,并调用传入的函数
func apply<T>(_ function: (T) -> Void) {
func apply<T>(_ function: (T) -> Void) { // invalid redeclaration of 'apply'
function(10) // cannot convert value of type 'Int' to expected argument type 'T'
return { x += 1; x } // contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored
func apply<T>(_ function: (T) -> Void, _ default: T = 0) { // cannot use default expression for inference of 'T' because it is inferrable from parameters #0, #1
func apply<T>(_ function: (T) -> Void, _ default: T = 0) { // cannot use default expression for inference of 'T' because it is inferrable from parameters #0, #1
func apply<T>(_ function: (T) -> Void, _ default: T = 0) { // invalid redeclaration of 'apply'
function(default) // missing argument for parameter #1 in call
function(default) // expected expression in list of expressions
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: Array<Int>, y: Array<Int>) -> Array<Int> {
return x + y
}
func add(x: Int, y: Int, z: Int -> Int) {
z = x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 2.3 函数参数
函数参数有如下类型:
- 值类型参数
- 类型参数
- 函数参数
#### 2.3.1 值类型参数
值类型参数,例如 `Int`、`String`、`Array` 等,在调用函数时,需要显式传递参数值。
```swift
// 值类型参数
func add(x: Int, y: Int) -> Int {
return x + y
}
let result = add(x: 2, y: 3)
print(result) // 5
```
#### 2.3.2 类型参数
类型参数,例如 `Array`、`Dictionary` 等,在调用函数时,不需要显式传递参数值。
```swift
// 类型参数
func add(x: Array<Int>, y: Array<Int>) -> Array<Int> {
return x + y
}
let result = add(x: [1, 2], y: [3, 4])
print(result) // [1, 2, 3, 4]
```
#### 2.3.3 函数参数
函数参数,在调用函数时,不需要显式传递参数值。
```swift
// 函数参数
func add(x: Int, y: Int, z: Int -> Int) {
z = x + y
}
let result = add(x: 2, y: 3, z: { x + y })
print(result) // 5
```
### 2.4 函数返回值
函数返回值,有如下类型:
- 值类型
- 类型
- 函数
#### 2.4.1 值类型
值类型,例如 `Int`、`String`、`Array` 等,函数返回值类型必须与函数参数类型一致。
```swift
// 值类型
func add(x: Int, y: Int) -> Int {
return x + y
}
let result = add(x: 2, y: 3)
print(result) // 5
```
#### 2.4.2 类型
类型,例如 `Array`、`Dictionary` 等,函数返回值类型必须与函数参数类型一致。
```swift
// 类型
func add(x: Array<Int>, y: Array<Int>) -> Array<Int> {
return x + y
}
let result = add(x: [1, 2], y: [3, 4])
print(result) // [1, 2, 3, 4]
```
#### 2.4.3 函数
函数,函数返回值类型必须与函数参数类型一致。
```swift
// 函数
func add(x: Int, y: Int, z: Int -> Int) {
z = x + y
}
let result = add(x: 2, y: 3, z: { x + y })
print(result) // 5
```
### 2.5 函数参数类型
函数参数类型,有如下类型:
- 值类型
- 类型
- 函数
#### 2.5.1 值类型
值类型,例如 `Int`、`String`、`Array` 等,函数参数类型必须与函数返回值类型一致。
```swift
// 值类型
func add(x: Int, y: Int) -> Int {
return x + y
}
let result = add(x: 2, y: 3)
print(result) // 5
```
#### 2.5.2 类型
类型,例如 `Array`、`Dictionary` 等,函数参数类型必须与函数返回值类型一致。
```swift
// 类型
func add(x: Array<Int>, y: Array<Int>) -> Array<Int> {
return x + y
}
let result = add(x: [1, 2], y: [3, 4])
print(result) // [1, 2, 3, 4]
```
#### 2.5.3 函数
函数,函数参数
func add(x: Int, y: Int, z: Int -> Int) { // single argument function types require parentheses
z = x + y // cannot assign to value: 'z' is a 'let' constant
func add(x: Int, y: Int) -> Int {
return x + y
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 2. 函数参数
```swift
// 函数参数
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 3. 函数返回值
```swift
// 函数返回值
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 4. 函数参数类型
```swift
// 函数参数类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 5. 函数返回值类型
```swift
// 函数返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 6. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 7. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 8. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 9. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 10. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 11. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 12. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 13. 函数参数和返回值类型
```swift
// 函数参数和返回值类型
// add(x: 2, y: 3)
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: inout Int, y: Int) {
x += y
}
func add(x: inout Int, y: Int) -> Int {
x += y
return 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
}
```
### 2. 函数参数
函数参数分为两种:
1. 值类型参数
2. 引用类型参数
#### 值类型参数
值类型参数在函数调用时,会复制一份参数的值,因此函数内部对参数值的修改不会影响到函数外部的变量。
```swift
// 值类型参数
func add(x: Int, y: Int) -> Int {
return x + y
}
var a = 1
var b = 2
add(x: a, y: b) // 3
a = 100
b = 200
add(x: a, y: b) // 3
```
#### 引用类型参数
引用类型参数在函数调用时,不会复制参数的值,而是直接传递引用。因此函数内部对参数值的修改会影响到函数外部的变量。
```swift
// 引用类型参数
func add(x: inout Int, y: Int) {
x += y
}
var a = 1
var b = 2
add(x: &a, y: 2)
add(x: &b, y: 3)
print(a) // 3
print(b) // 5
```
### 3. 函数返回值
函数返回值分为两种:
1. 值类型返回值
2. 引用类型返回值
#### 值类型返回值
值类型返回值在函数调用时,会复制返回值的值,因此函数外部的变量不会受到函数内部返回值修改的影响。
```swift
// 值类型返回值
func add(x: Int, y: Int) -> Int {
return x + y
}
var a = 1
var b = 2
let result = add(x: a, y: b)
a = 100
b = 200
print(result) // 3
```
#### 引用类型返回值
引用类型返回值在函数调用时,不会复制返回值的值,而是直接传递引用。因此函数外部的变量会受到函数内部返回值修改的影响。
```swift
// 引用类型返回值
func add(x: inout Int, y: Int) -> Int {
x += y
return x
}
var a = 1
var b = 2
let result = add(x: &a, y: 2)
add(x: &b, y: 3)
print(a) // 3
print(b) // 5
```
### 4. 函数参数和返回值类型
函数参数和返回值类型可以一起指定,也可以分开指定。
```swift
// 函数参数和返回值类型一起指定
func add(x: Int, y: Int) -> Int {
return x + y
}
// 函数参数和返回值类型分开指定
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 5. 函数参数和返回值类型
函数参数和返回值类型可以一起指定,也可以分开指定。
```swift
// 函数参数和返回值类型一起指定
func add(x: Int, y: Int) -> Int {
return x + y
}
// 函数参数和返回值类型分开指定
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 6. 函数参数和返回值类型
函数参数和返回值类型可以一起指定,也可以分开指定。
```swift
// 函数参数和返回值类型一起指定
func add(x: Int, y: Int) -> Int {
return x + y
}
// 函数参数和返回值类型分开指定
func add(x: Int, y: Int) -> Int {
return x + y
}
```
### 7. 函数参数和返回值类型
函数参数和返回值类型可以一起指定,也可以分开指定。
```swift
// 函数参数和返回值类型一起指定
func add(x: Int, y: Int) -> Int {
return x + y
}
func add(x: Int, y: Int) -> Int {
return x + y
}
func multiply(x: Int, y: Int) -> Int {
return x * y
}
func abs(x: Int) -> Int {
return x >= 0 ? x : -x
}
func max(x: Int, y: Int) -> Int {
return x > y ? x : y
}
func min(x: Int, y: Int) -> Int {
return x < y ? x : y
}
func floor(x: Double) -> Double {
return Double(Int(x))
}
func ceil(x: Double) -> Double {
return Double(Int(x) + 1)
}
func round(x: Double) -> Double {
return Double(Int(x + 0.5))
}
func sin(x: Double) -> Double {
return Double.pi * Double(sin(x))
}
func cos(x: Double) -> Double {
return Double.pi * Double(cos(x))
}
func tan(x: Double) -> Double {
return Double.pi * Double(tan(x))
}
func log(x: Double) -> Double {
return Double(log(x))
}
func log10(x: Double) -> Double {
return Double(log10(x))
}
func sqrt(x: Double) -> Double {
return Double(sqrt(x))
}
func cbrt(x: Double) -> Double {
return Double(cbrt(x))
}
```swift
// Add two numbers x and y
// add(x: 2, y: 3) == 5
// add(x: 5, y: 7) == 12
func add(x: Int, y: Int) -> Int {
return x + y
}
// Multiply two numbers x and y
// multiply(x: 2, y: 3) == 6
// multiply(x: 5, y: 7) == 35
func multiply(x: Int, y: Int) -> Int {
return x * y
}
// Return the absolute value of x
// abs(x: -2) == 2
// abs(x: 2) == 2
func abs(x: Int) -> Int {
return x >= 0 ? x : -x
}
// Return the maximum of two numbers x and y
// max(x: 2, y: 3) == 3
// max(x: 5, y: 7) == 7
func max(x: Int, y: Int) -> Int {
return x > y ? x : y
}
// Return the minimum of two numbers x and y
// min(x: 2, y: 3) == 2
// min(x: 5, y: 7) == 5
func min(x: Int, y: Int) -> Int {
return x < y ? x : y
}
// Return the absolute value of x
// floor(x: -2.5) == -3
// floor(x: 2.5) == 2
func floor(x: Double) -> Double {
return Double(Int(x))
}
// Return the absolute value of x
// ceil(x: -2.5) == -2
// ceil(x: 2.5) == 3
func ceil(x: Double) -> Double {
return Double(Int(x) + 1)
}
// Return the absolute value of x
// round(x: -2.5) == -2
// round(x: 2.5) == 3
func round(x: Double) -> Double {
return Double(Int(x + 0.5))
}
```
### 2.2 数学函数
```swift
// Return the sine of x
// sin(x: 0) == 0
// sin(x: 1) == 0.8414709848078965
func sin(x: Double) -> Double {
return Double.pi * Double(sin(x))
}
// Return the cosine of x
// cos(x: 0) == 1
// cos(x: 1) == 0.5403023058681398
func cos(x: Double) -> Double {
return Double.pi * Double(cos(x))
}
// Return the tangent of x
// tan(x: 0) == 0
// tan(x: 1) == 1.5574077246549023
func tan(x: Double) -> Double {
return Double.pi * Double(tan(x))
}
// Return the natural logarithm of x
// log(x: 1) == 0
// log(x: 10) == 2.302585092994046
func log(x: Double) -> Double {
return Double(log(x))
}
// Return the natural logarithm of x
// log10(x: 1) == 0
// log10(x: 10) == 1
func log10(x: Double) -> Double {
return Double(log10(x))
}
// Return the square root of x
// sqrt(x: 4) == 2
// sqrt(x: 100) == 10
func sqrt(x: Double) -> Double {
return Double(sqrt(x))
}
// Return the cube root of x
// cbrt(x: 4) == 2
// cbrt(x: 100) == 10
func cbrt(x: Double) -> Double {
return Double(cbrt(x))
}
// Return the exponential of x
// exp(x: 0) == 1
// exp(x: 1) == 2.7182
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for c in s0 {
for i in 0..<s1.count {
if s1[i] == c {
count += 1
s1[i] = "a"
break
}
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for c in s0 {
for i in 0..<s1.count {
if s1[i] == c {
count += 1
s1[i] = "a"
break
}
}
}
return count == s0.count
}
```
s1[i] = "a" // cannot assign through subscript: 's1' is a 'let' constant
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
guard s0.count == s1.count else { return false }
var count = 0
for c in s0 {
if s1.contains(c) {
count += 1
}
}
return count == s0.count
}
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
guard s0.count == s1.count else { return false }
var count = 0
for c in s0 {
for i in 0..<s1.count {
if s1[i] == c {
count += 1
break
}
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
guard s0.count == s1.count else { return false }
var count = 0
for c in s0 {
if s1.contains(c) {
count += 1
}
}
return count == s0.count
}
```
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
guard s0.count == s1.count else { return false }
var count = 0
for c in s0 {
for i in 0..<s1.count {
if s1[i] == c {
count += 1
break
}
}
}
return count == s0.count
}
```
func sameChars(s0: String, s1: String) -> Bool { // invalid redeclaration of 'sameChars(s0:s1:)'
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var map = [Character: Int]()
for c in s0 {
map[c, default: 0] += 1
}
for c in s1 {
if map[c] == nil {
return false
}
if map[c]! == 1 {
map[c] = nil
} else {
map[c]! -= 1
}
}
for value in map.values {
if value != 0 {
return false
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var map = [Character: Int]()
for c in s0 {
map[c, default: 0] += 1
}
for c in s1 {
if map[c] == nil {
return false
}
if map[c]! == 1 {
map[c] = nil
} else {
map[c]! -= 1
}
}
for value in map.values {
if value != 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for i in 0..<s0.count {
if s0[i] == s1[i] {
count += 1
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for i in 0..<s0.count {
if s0[i] == s1[i] {
count += 1
}
}
return count == s0.count
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
if s0.count != s1.count { return false }
var count = 0
for i in 0..<s0.count {
if s0[i] == s1[i] {
count += 1
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
if s0.count != s1.count { return false }
var count = 0
for i in 0..<s0.count {
if s0[i] == s1[i] {
count += 1
}
}
return count == s0.count
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for c in s0 {
if s1.contains(c) {
count += 1
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for c in s0 {
if s1.contains(c) {
count += 1
}
}
return count == s0.count
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for c in s0 {
if s1.contains(c) {
count += 1
}
}
return count == s0.count
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0)
let s1 = Array(s1)
if s0.count != s1.count {
return false
}
var count = 0
for c in s0 {
if s1.contains(c) {
count += 1
}
}
return count == s0.count
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count { return false }
var chars0 = Array(s0)
var chars1 = Array(s1)
for i in 0..<chars0.count {
if chars0[i] != chars1[i] { return false }
}
return true
}
class Solution {
func isScramble(_ s0: String, _ s1: String) -> Bool {
if s0.count != s1.count { return false }
if s0 == s1 { return true }
let chars0 = Array(s0)
let chars1 = Array(s1)
let count = chars0.count
let chars0Count = Array(repeating: 0, count: 26)
let chars1Count = Array(repeating: 0, count: 26)
for i in 0..<count {
chars0Count[Int(chars0[i].asciiValue! - Character("a").asciiValue!)] += 1
chars1Count[Int(chars1[i].asciiValue! - Character("a").asciiValue!)] += 1
}
for i in 0..<26 {
if chars0Count[i] != chars1Count[i] { return false }
}
for i in 1..<count {
if isScramble(String(chars0[0..<i]), String(chars1[0..<i])) && isScramble(String(chars0[i..<count]), String(chars1[i..<count])) {
return true
}
if isScramble(String(chars0[0..<i]), String(chars1[count-i..<count])) && isScramble(String(chars0[i..<count]), String(chars1[0..<count-i])) {
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 {
if s0.count != s1.count { return false }
var chars0 = Array(s0)
var chars1 = Array(s1)
for i in 0..<chars0.count {
if chars0[i] != chars1[i] { return false }
}
return true
}
```
### 解题思路
### 代码
```swift
class Solution {
func isScramble(_ s0: String, _ s1: String) -> Bool {
if s0.count != s1.count { return false }
if s0 == s1 { return true }
let chars0 = Array(s0)
let chars1 = Array(s1)
let count = chars0.count
let chars0Count = Array(repeating: 0, count: 26)
let chars1Count = Array(repeating: 0, count: 26)
for i in 0..<count {
chars0Count[Int(chars0[i].asciiValue! - Character("a").asciiValue!)] += 1
chars1Count[Int(chars1[i].asciiValue! - Character("a").asciiValue!)] += 1
}
for i in 0..<26 {
if chars0Count[i] != chars1Count[i] { return false }
}
for i in 1..<count {
if isScramble(String(chars0[0..<i]), String(chars1[0..<i])) && isScramble(String(chars0[i..<count]), String(chars1[i..<count])) {
return true
}
if isScramble(String(chars0[0..<i]), String(chars1[count-i..<count])) && isScramble(String(chars0[i..<count]), String(chars1[0..<count-i])) {
return true
}
}
return false
}
}
```
var chars0 = Array(s0) // variable 'chars0' was never mutated; consider changing to 'let' constant
var chars1 = Array(s1) // variable 'chars1' was never mutated; consider changing to 'let' constant
chars0Count[Int(chars0[i].asciiValue! - Character("a").asciiValue!)] += 1 // left side of mutating operator isn't mutable: 'chars0Count' is a 'let' constant
chars1Count[Int(chars1[i].asciiValue! - Character("a").asciiValue!)] += 1 // left side of mutating operator isn't mutable: 'chars1Count' is a 'let' constant
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
var dict = [Character: Int]()
for c in s0 {
dict[c, default: 0] += 1
}
for c in s1 {
if dict[c] == nil {
return false
} else {
dict[c]! -= 1
if dict[c]! < 0 {
return false
}
}
}
return true
}
```swift
// Check if two words have the same characters.
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddeddabc") == true
// sameChars(s0: "abcd", s1: "dddddddabc") == true
// sameChars(s0: "dddddddabc", s1: "abcd") == true
// sameChars(s0: "eabcd", s1: "dddddddabc") == false
// sameChars(s0: "abcd", s1: "dddddddabce") == false
// sameChars(s0: "eabcdzzzz", s1: "dddzzzzzzzddddabc") == false
func sameChars(s0: String, s1: String) -> Bool {
if s0.count != s1.count {
return false
}
var dict = [Character: Int]()
for c in s0 {
dict[c, default: 0] += 1
}
for c in s1 {
if dict[c] == nil {
return false
} else {
dict[c]! -= 1
if dict[c]! < 0 {
return false
}
}
}
return true
}
```
// XCTAssertTrue failed
func sameChars(s0: String, s1: String) -> Bool {
let s0 = Array(s0), s1 = Array(s1)
guard s0.count == s1.count else { return false }
var map = [Character: Int]()
for c in s0 {
map[c, default: 0] += 1
}
for c in s1 {
guard let count = map[c] else { return false }
map[c] = count - 1
}
for value in map.values {
guard value == 0 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 s0 = Array(s0), s1 = Array(s1)
guard s0.count == s1.count else { return false }
var map = [Character: Int]()
for c in s0 {
map[c, default: 0] += 1
}
for c in s1 {
guard let count = map[c] else { return false }
map[c] = count - 1
}
for value in map.values {
guard value == 0 else { return false }
}
return true
}
```
// XCTAssertTrue failed
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 1
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = a
for _ in 3...n {
res = multiply(a, res)
}
return res[0][0]
}
func multiply(a: [[Int]], b: [[Int]]) -> [[Int]] {
var c = [[Int]](repeating: [Int](repeating: 0, count: b[0].count), count: a.count)
for i in 0..<a.count {
for j in 0..<b[0].count {
for k in 0..<a[0].count {
c[i][j] += a[i][k] * b[k][j]
}
}
}
return c
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
func fib(n: Int) -> Int {
fib_helper(n, 1, 1)
}
func fib_helper(n: Int, a: Int, b: Int) -> Int {
if n == 1 {
return a
}
if n == 2 {
return b
}
return fib_helper(n - 1, b, 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 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```
### 解法二:动态规划
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 1
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[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 1
}
if n == 2 {
return 1
}
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = a
for _ in 3...n {
res = multiply(a, res)
}
return res[0][0]
}
func multiply(a: [[Int]], b: [[Int]]) -> [[Int]] {
var c = [[Int]](repeating: [Int](repeating: 0, count: b[0].count), count: a.count)
for i in 0..<a.count {
for j in 0..<b[0].count {
for k in 0..<a[0].count {
c[i][j] += a[i][k] * b[k][j]
}
}
}
return c
}
```
### 解法四:递归
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(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 {
fib_helper(n, 1, 1)
}
func fib_helper(n: Int, a: Int, b: Int) -> Int {
if n == 1 {
return a
}
if n == 2 {
return b
}
return fib_helper(n - 1, b, 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 {
fib_helper(n, 1, 1)
}
func fib_
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
res = multiply(a, res) // missing argument labels 'a:b:' in call
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
fib_helper(n, 1, 1) // missing argument labels 'n:a:b:' in call
return fib_helper(n - 1, b, a + b) // missing argument labels 'n:a:b:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
} else if n == 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
func fib(n: Int) -> Int {
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
for i in 2...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
func fib(n: Int) -> Int {
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = [[1], [0]]
for _ in 2...n {
res = multiply(a, res)
}
return res[0][0]
}
func multiply(_ a: [[Int]], _ b: [[Int]]) -> [[Int]] {
let c = [[0, 0], [0, 0]]
for i in 0..<2 {
for j in 0..<2 {
for k in 0..<2 {
c[i][j] += a[i][k] * b[k][j]
}
}
}
return c
}
func fib(n: Int) -> Int {
var memo = [Int: Int]()
func helper(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if let res = memo[n] {
return res
}
let res = helper(n - 1) + helper(n - 2)
memo[n] = res
return res
}
return helper(n)
}
func fib(n: Int) -> Int {
func helper(_ n: Int, _ a: Int, _ b: Int) -> Int {
if n == 1 {
return a
} else if n == 2 {
return b
}
return helper(n - 1, b, a + b)
}
return helper(n, 1, 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 == 1 {
return 1
} else if n == 2 {
return 1
} else {
return fib(n: n - 1) + fib(n: n - 2)
}
}
```
### 解法二:动态规划
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
for i in 2...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
```
### 解法三:矩阵快速幂
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = [[1], [0]]
for _ in 2...n {
res = multiply(a, res)
}
return res[0][0]
}
func multiply(_ a: [[Int]], _ b: [[Int]]) -> [[Int]] {
let c = [[0, 0], [0, 0]]
for i in 0..<2 {
for j in 0..<2 {
for k in 0..<2 {
c[i][j] += a[i][k] * b[k][j]
}
}
}
return c
}
```
### 解法四:递归 + 记忆化搜索
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
var memo = [Int: Int]()
func helper(_ n: Int) -> Int {
if n == 1 || n == 2 {
return 1
}
if let res = memo[n] {
return res
}
let res = helper(n - 1) + helper(n - 2)
memo[n] = res
return res
}
return helper(n)
}
```
### 解法五:递归 + 尾递归
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
func helper(_ n: Int, _ a: Int, _ b: Int) -> Int {
if n == 1 {
return a
} else if n == 2 {
return b
}
return helper(n - 1, b, a + b)
}
return helper(n, 1, 1)
}
```
### 解法六:尾递归 + 尾调用优化
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
@inline(__always)
func fib(n: Int) -> Int {
func helper(_ n: Int, _ a: Int, _ b: Int) -> Int {
if n == 1 {
return a
} else if n == 2 {
return b
}
return helper(n - 1, b, a + b
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
c[i][j] += a[i][k] * b[k][j] // left side of mutating operator isn't mutable: 'c' is a 'let' constant
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 1
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = [[Int]](repeating: [Int](repeating: 0, count: 1), count: 1)
for _ in 3...n {
res = multiply(a, b)
}
return res[0][0]
}
func multiply(a: [[Int]], b: [[Int]]) -> [[Int]] {
var res = [[Int]](repeating: [Int](repeating: 0, count: b[0].count), count: a.count)
for i in 0..<a.count {
for j in 0..<b[0].count {
for k in 0..<a[0].count {
res[i][j] += a[i][k] * b[k][j]
}
}
}
return res
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var memo = [Int: Int]()
func helper(_ n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
if let value = memo[n] {
return value
}
let res = helper(n - 1) + helper(n - 2)
memo[n] = res
return res
}
return helper(n)
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib_tail(n, 1, 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 == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n: n - 1) + fib(n: n - 2)
}
```
### 解法二:动态规划
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 1
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[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 1
}
if n == 2 {
return 1
}
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = [[Int]](repeating: [Int](repeating: 0, count: 1), count: 1)
for _ in 3...n {
res = multiply(a, b)
}
return res[0][0]
}
func multiply(a: [[Int]], b: [[Int]]) -> [[Int]] {
var res = [[Int]](repeating: [Int](repeating: 0, count: b[0].count), count: a.count)
for i in 0..<a.count {
for j in 0..<b[0].count {
for k in 0..<a[0].count {
res[i][j] += a[i][k] * b[k][j]
}
}
}
return res
}
```
### 解法四:递归 + 记忆化
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var memo = [Int: Int]()
func helper(_ n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
if let value = memo[n] {
return value
}
let res = helper(n - 1) + helper(n - 2)
memo[n] = res
return res
}
return helper(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 1
}
if n == 2 {
return 1
}
return fib_tail(n, 1, 1)
}
func fib_tail(_ n: Int, _ a: Int, _ b: Int) -> Int {
if n == 1 {
return a
}
if n ==
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
res = multiply(a, b) // missing argument labels 'a:b:' in call
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
return fib_tail(n, 1, 1) // cannot find 'fib_tail' in scope
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var n1 = 1
var n2 = 1
var n3 = 0
for _ in 3...n {
n3 = n1 + n2
n1 = n2
n2 = n3
}
return n3
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1, 1, 1)
}
func fib(n: Int, _ n1: Int, _ n2: Int) -> Int {
if n == 1 {
return n1
}
if n == 2 {
return n2
}
return fib(n - 1, n2, n1 + n2)
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var n1 = 1
var n2 = 1
var n3 = 0
for _ in 3...n {
n3 = n1 + n2
n1 = n2
n2 = n3
}
return n3
}
```
### 解法二:动态规划
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var n1 = 1
var n2 = 1
var n3 = 0
for _ in 3...n {
n3 = n1 + n2
n1 = n2
n2 = n3
}
return n3
}
```
### 解法三:尾递归
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```
### 解法四:尾递归优化
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1, 1, 1)
}
func fib(n: Int, _ n1: Int, _ n2: Int) -> Int {
if n == 1 {
return n1
}
if n == 2 {
return n2
}
return fib(n - 1, n2, n1 + n2)
}
```
### 解法五:尾递归优化
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1, 1, 1)
}
func fib(n: Int, _ n1: Int, _ n2: Int) -> Int {
if n == 1 {
return n1
}
if n == 2 {
return n2
}
return fib(n - 1, n2, n1 + n2)
}
```
### 解法六:尾递归优化
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1, 1, 1)
}
func fib(n: Int, _ n1: Int, _ n2: Int) -> Int {
if n == 1 {
return n1
}
if n == 2 {
return
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
return fib(n - 1, 1, 1) // missing argument label 'n:' in call
return fib(n - 1, n2, n1 + n2) // missing argument label 'n:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var fib1 = 1
var fib2 = 1
var fib = 0
for _ in 3...n {
fib = fib1 + fib2
fib1 = fib2
fib2 = fib
}
return fib
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var fib1 = 1
var fib2 = 1
var fib = 0
for _ in 3...n {
fib = fib1 + fib2
fib1 = fib2
fib2 = fib
}
return fib
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var result = 0
var a = 1
var b = 1
for _ in 3...n {
result = a + b
a = b
b = result
}
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 == 1 {
return 1
}
if n == 2 {
return 1
}
var result = 0
var a = 1
var b = 1
for _ in 3...n {
result = a + b
a = b
b = result
}
return result
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 1
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[n]
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = [[1], [0]]
for _ in 3...n {
res = multiply(a, b)
a = res
b = res
}
return res[0][0]
}
func multiply(a: [[Int]], b: [[Int]]) -> [[Int]] {
let m = a.count
let n = b[0].count
let p = a[0].count
var res = [[Int]](repeating: [Int](repeating: 0, count: n), count: m)
for i in 0..<m {
for j in 0..<n {
for k in 0..<p {
res[i][j] += a[i][k] * b[k][j]
}
}
}
return res
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib_tail(n - 1, 1, 1)
}
func fib_tail(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
}
return fib_tail(n - 1, b, 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 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```
### 解法二:动态规划
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
dp[2] = 1
for i in 3...n {
dp[i] = dp[i - 1] + dp[i - 2]
}
return dp[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 1
}
if n == 2 {
return 1
}
let a = [[1, 1], [1, 0]]
let b = [[1], [0]]
var res = [[1], [0]]
for _ in 3...n {
res = multiply(a, b)
a = res
b = res
}
return res[0][0]
}
func multiply(a: [[Int]], b: [[Int]]) -> [[Int]] {
let m = a.count
let n = b[0].count
let p = a[0].count
var res = [[Int]](repeating: [Int](repeating: 0, count: n), count: m)
for i in 0..<m {
for j in 0..<n {
for k in 0..<p {
res[i][j] += a[i][k] * b[k][j]
}
}
}
return res
}
```
### 解法四:递归
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib(n - 1) + fib(n - 2)
}
```
### 解法五:尾递归
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
return fib_tail(n - 1, 1, 1)
}
func fib_tail(n: Int, a: Int, b: Int) -> Int {
if n == 0 {
return a
}
return fib_tail(n - 1, b, a + b)
}
```
### 解法六:尾递归优化
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) ==
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
res = multiply(a, b) // missing argument labels 'a:b:' in call
a = res // cannot assign to value: 'a' is a 'let' constant
b = res // cannot assign to value: 'b' is a 'let' constant
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
return fib(n - 1) + fib(n - 2) // missing argument label 'n:' in call
func fib(n: Int) -> Int { // invalid redeclaration of 'fib(n:)'
return fib_tail(n - 1, 1, 1) // missing argument labels 'n:a:b:' in call
return fib_tail(n - 1, b, a + b) // missing argument labels 'n:a:b:' in call
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```swift
// Return n-th Fibonacci number.
// fib(n: 10) == 55
// fib(n: 1) == 1
// fib(n: 8) == 21
func fib(n: Int) -> Int {
if n == 1 {
return 1
}
if n == 2 {
return 1
}
var a = 1
var b = 1
var c = 0
for _ in 3...n {
c = a + b
a = b
b = c
}
return c
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} 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 c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.count == 0 {
return false
}
stack.removeLast()
}
}
return stack.count == 0
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "<" and ">".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "<") == false
// correctBracketing(brackets: "<>") == true
// correctBracketing(brackets: "<<><>>") == true
// correctBracketing(brackets: "><<>") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "<" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
return l.sorted() == l
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 {
return l.sorted() == l
}
```
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
if l.count <= 1 {
return true
}
let first = l[0]
let last = l[l.count - 1]
if first < last {
return monotonic(l: l[1..<l.count])
} else if first > last {
return monotonic(l: l[0..<l.count - 1])
} else {
return false
}
}
func monotonic(l: [Int]) -> Bool {
var stack = [Int]()
for i in l {
if stack.isEmpty {
stack.append(i)
} else if stack.last! < i {
stack.append(i)
} else if stack.last! > i {
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 {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 <= 1 {
return true
}
let first = l[0]
let last = l[l.count - 1]
if first < last {
return monotonic(l: l[1..<l.count])
} else if first > last {
return monotonic(l: l[0..<l.count - 1])
} else {
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 stack = [Int]()
for i in l {
if stack.isEmpty {
stack.append(i)
} else if stack.last! < i {
stack.append(i)
} else if stack.last! > i {
return false
}
}
return true
}
```
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
return monotonic(l: l[1..<l.count]) // cannot convert value of type 'ArraySlice<Int>' to expected argument type '[Int]'
return monotonic(l: l[0..<l.count - 1]) // cannot convert value of type 'ArraySlice<Int>' to expected argument type '[Int]'
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
if l.count <= 1 {
return true
}
if l[0] > l[1] {
return monotonic(l: Array(l[1...]))
} else if l[0] < l[1] {
return monotonic(l: Array(l[1...]))
} else {
return monotonic(l: Array(l[1...]))
}
}
func monotonic(l: [Int]) -> Bool {
var stack = [Int]()
for i in l {
if stack.isEmpty {
stack.append(i)
} else {
if stack.last! > i {
stack.append(i)
} else if stack.last! < i {
stack.append(i)
} else {
stack.append(i)
}
}
}
return stack.count == l.count
}
func monotonic(l: [Int]) -> Bool {
var i = 0
var j = 1
while j < l.count {
if l[i] > l[j] {
return false
} else if l[i] < l[j] {
return true
}
i += 1
j += 1
}
return true
}
func monotonic(l: [Int]) -> Bool {
let sorted = l.sorted()
for i in 0..<sorted.count-1 {
if sorted[i] > sorted[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 {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 <= 1 {
return true
}
if l[0] > l[1] {
return monotonic(l: Array(l[1...]))
} else if l[0] < l[1] {
return monotonic(l: Array(l[1...]))
} else {
return monotonic(l: Array(l[1...]))
}
}
```
### 解法三:栈
```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 stack = [Int]()
for i in l {
if stack.isEmpty {
stack.append(i)
} else {
if stack.last! > i {
stack.append(i)
} else if stack.last! < i {
stack.append(i)
} else {
stack.append(i)
}
}
}
return stack.count == 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 {
var i = 0
var j = 1
while j < l.count {
if l[i] > l[j] {
return false
} else if l[i] < l[j] {
return true
}
i += 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 {
let sorted = l.sorted()
for i in 0..<sorted.count-1 {
if sorted[i] > sorted[i+1] {
return false
}
}
return true
}
```
### 解法六:数学
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
let sum = l
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
var last = l[0]
var lastDirection = 0
for i in 1..<l.count {
let current = l[i]
if current > last {
last = current
lastDirection = 1
} else if current < last {
last = current
lastDirection = -1
}
if lastDirection == 0 {
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 {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 {
var last = l[0]
var lastDirection = 0
for i in 1..<l.count {
let current = l[i]
if current > last {
last = current
lastDirection = 1
} else if current < last {
last = current
lastDirection = -1
}
if lastDirection == 0 {
return false
}
}
return true
}
```
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 0..<l.count - 1 {
if l[i] > l[i + 1] {
isIncreasing = false
}
if l[i] < l[i + 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in 1..<l.count {
if l[i] > prev {
prev = l[i]
} else if l[i] < prev {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
if l.count <= 1 {
return true
}
if l[0] < l[1] {
return monotonic(l: Array(l[1...]))
} else if l[0] > l[1] {
return monotonic(l: Array(l[1...]))
} else {
return false
}
}
func monotonic(l: [Int]) -> Bool {
var stack = [Int]()
for i in l {
if stack.isEmpty || stack.last! < i {
stack.append(i)
} else {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
var count = 0
for i in l {
if count == 0 || count > 0 && i > stack.last! {
count = 1
} else if count < 0 && i < stack.last! {
count = -1
} else {
return false
}
}
return true
}
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in l[1...] {
if prev > i {
return false
}
prev = i
}
return true
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in 1..<l.count {
if l[i] > prev {
prev = l[i]
} else if l[i] < prev {
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 <= 1 {
return true
}
if l[0] < l[1] {
return monotonic(l: Array(l[1...]))
} else if l[0] > l[1] {
return monotonic(l: Array(l[1...]))
} else {
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 stack = [Int]()
for i in l {
if stack.isEmpty || stack.last! < i {
stack.append(i)
} else {
return false
}
}
return true
}
```
### 解法四:计数
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var count = 0
for i in l {
if count == 0 || count > 0 && i > stack.last! {
count = 1
} else if count < 0 && i < stack.last! {
count = -1
} else {
return false
}
}
return true
}
```
### 解法五:数学
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in l[1...] {
if prev > i {
return false
}
prev = i
}
return true
}
```
### 解法六:数学
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var prev = l[0]
for i in l[1...] {
if prev > i {
return false
}
prev = i
}
return true
}
```
### 解法七:数学
```swift
// Return true is array elements are monotonically
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
if count == 0 || count > 0 && i > stack.last! { // cannot find 'stack' in scope
} else if count < 0 && i < stack.last! { // cannot find 'stack' in scope
func monotonic(l: [Int]) -> Bool { // invalid redeclaration of 'monotonic(l:)'
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isIncreasing = false
}
if l[i] < l[i - 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isIncreasing = false
}
if l[i] < l[i - 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
### 解法二:
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isIncreasing = false
}
if l[i] < l[i - 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
### 解法三:
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isIncreasing = false
}
if l[i] < l[i - 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
### 解法四:
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isIncreasing = false
}
if l[i] < l[i - 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
### 解法五:
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [1, 2, 4, 20]) == true
// monotonic(l: [1, 20, 4, 10]) == false
// monotonic(l: [4, 1, 0, -10]) == true
func monotonic(l: [Int]) -> Bool {
var isIncreasing = true
var isDecreasing = true
for i in 1..<l.count {
if l[i] > l[i - 1] {
isIncreasing = false
}
if l[i] < l[i - 1] {
isDecreasing = false
}
}
return isIncreasing || isDecreasing
}
```
### 解法六:
```swift
// Return true is array elements are monotonically increasing or decreasing.
// monotonic(l: [
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func monotonic(l: [Int]) -> Bool {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
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 {
var last = l[0]
for i in 1..<l.count {
if l[i] > last {
last = l[i]
} else if l[i] < last {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l1 {
dict[i] = 1
}
for i in l2 {
if dict[i] != nil {
result.append(i)
}
}
return result.sorted()
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
### 方法二:哈希表
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var dict = [Int: Int]()
for i in l1 {
dict[i] = 1
}
for i in l2 {
if dict[i] != nil {
result.append(i)
}
}
return result.sorted()
}
```
func common(l1: [Int], l2: [Int]) -> [Int] { // invalid redeclaration of 'common(l1:l2:)'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var map = [Int: Int]()
for i in 0..<l1.count {
if let count = map[l1[i]] {
map[l1[i]] = count + 1
} else {
map[l1[i]] = 1
}
}
for i in 0..<l2.count {
if let count = map[l2[i]] {
if count > 0 {
result.append(l2[i])
map[l2[i]] = count - 1
}
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
### 解法二:哈希表
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var map = [Int: Int]()
for i in 0..<l1.count {
if let count = map[l1[i]] {
map[l1[i]] = count + 1
} else {
map[l1[i]] = 1
}
}
for i in 0..<l2.count {
if let count = map[l2[i]] {
if count > 0 {
result.append(l2[i])
map[l2[i]] = count - 1
}
}
}
return result
}
```
### 解法三:双指针
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
### 解法四:二分查找
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
func common(l1: [Int], l2: [Int]) -> [Int] { // invalid redeclaration of 'common(l1:l2:)'
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result: [Int] = []
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
for i in l1 {
for j in l2 {
if i == j {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
class Solution {
func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>(nums1)
var set2 = Set<Int>(nums2)
for num in set1 {
if set2.contains(num) {
result.append(num)
}
}
return result
}
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
var result = [Int]()
var set1 = Set<Int>(nums1)
var set2 = Set<Int>(nums2)
for num in set1 {
if set2.contains(num) {
result.append(num)
}
}
return result
}
}
```
var set1 = Set<Int>(nums1) // variable 'set1' was never mutated; consider changing to 'let' constant
var set2 = Set<Int>(nums2) // variable 'set2' was never mutated; consider changing to 'let' constant
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```swift
// Return sorted unique common elements for two arrays.
// common(l1: [1, 4, 3, 34, 653, 2, 5], l2: [5, 7, 1, 5, 9, 653, 121]) == [1, 5, 653]
// common(l1: [5, 3, 2, 8], l2: [3, 2]) == [2, 3]
func common(l1: [Int], l2: [Int]) -> [Int] {
var result = [Int]()
var l1 = l1
var l2 = l2
l1.sort()
l2.sort()
var i = 0
var j = 0
while i < l1.count && j < l2.count {
if l1[i] == l2[j] {
result.append(l1[i])
i += 1
j += 1
} else if l1[i] < l2[j] {
i += 1
} else {
j += 1
}
}
return result
}
```
func largestPrimeFactor(n: Int) -> Int {
var i = 2
var n = n
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
while n % 2 == 0 {
n = n / 2
}
for i in 3...Int(sqrt(Double(n))) {
if n % i == 0 {
n = n / i
while n % i == 0 {
n = n / i
}
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
isPrime[0] = false
isPrime[1] = false
for i in 2...Int(sqrt(Double(n))) {
if isPrime[i] {
primes.append(i)
}
for j in 0..<primes.count {
if i * primes[j] > n {
break
}
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
}
}
for i in 0..<primes.count {
if n % primes[i] == 0 {
n = n / primes[i]
while n % primes[i] == 0 {
n = n / primes[i]
}
}
}
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
var n = n
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法二:暴力破解
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
while n % 2 == 0 {
n = n / 2
}
for i in 3...Int(sqrt(Double(n))) {
if n % i == 0 {
n = n / i
while n % i == 0 {
n = n / i
}
}
}
return n
}
```
### 解法三:欧拉筛
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
isPrime[0] = false
isPrime[1] = false
for i in 2...Int(sqrt(Double(n))) {
if isPrime[i] {
primes.append(i)
}
for j in 0..<primes.count {
if i * primes[j] > n {
break
}
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
}
}
for i in 0..<primes.count {
if n % primes[i] == 0 {
n = n / primes[i]
while n % primes[i] == 0 {
n = n / primes[i]
}
}
}
return n
}
```
### 解法四:线性筛
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
isPrime[0] = false
isPrime[1] = false
for i in 2...Int(sqrt(Double(n))) {
if isPrime[i] {
primes.append(i)
}
for j in 0..<primes.count {
if i * primes[j] > n {
break
}
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
}
}
for i in 0..<primes.count {
if n % primes[i] == 0 {
n = n / primes[i]
while n % primes[i] == 0 {
n = n / primes[i]
}
}
}
return n
}
```
### 解法五:线性筛 + 哈希表
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeF
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
} else {
i += 1
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count, i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<primes.count {
if primes[i] > largest && n % primes[i] == 0 {
largest = primes[i]
}
}
return largest
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= 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 n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法三:暴力解法优化
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
while n % i == 0 {
n /= i
}
} else {
i += 1
}
}
return n
}
```
### 解法四:欧拉筛法
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count, i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<primes.count {
if primes[i] > largest && n % primes[i] == 0 {
largest = primes[i]
}
}
return largest
}
```
### 解法五:欧拉筛法优化
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count, i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<primes.count {
if primes[i] > largest && n % primes[i] == 0 {
largest = primes[i]
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 1
for prime in primes {
if n % prime == 0 {
largest = prime
}
}
return largest
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法二:暴力法
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法三:欧拉筛法
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 1
for prime in primes {
if n % prime == 0 {
largest = prime
}
}
return largest
}
```
### 解法四:线性筛法
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 1
for prime in primes {
if n % prime == 0 {
largest = prime
}
}
return largest
}
```
### 解法五:线性筛法优化
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
is
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count, i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<primes.count {
if n % primes[i] == 0 {
largest = max(largest, primes[i])
}
}
return largest
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= 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 n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count, i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<primes.count {
if n % primes[i] == 0 {
largest = max(largest, primes[i])
}
}
return largest
}
```
### 解法三:欧拉筛
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count, i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<primes.count {
if n % primes[i] == 0 {
largest = max(largest, primes[i])
}
}
return largest
}
```
### 解法四:线性筛 + 哈希表
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
var primeFactors = [Int: Int]()
while i * i <= n {
if isPrime[i] {
primes.append(i)
primeFactors[i] = 1
}
var j = 0
while j < primes.count, i * primes[j] <= n {
if isPrime[i * primes[j]] {
primeFactors[i * primes[j]] = primeFactors[i] + 1
}
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largest = 0
for i in 0..<pr
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法二:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法三:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法四:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法五:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法六:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法七:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法八:
```swift
// Return the largest prime factor of n
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法二:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法三:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法四:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法五:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法六:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法七:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法八:
```swift
// Return the largest prime factor of n
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largestPrime = 1
for prime in primes {
if n % prime == 0 {
largestPrime = max(largestPrime, prime)
}
}
return largestPrime
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法二:暴力解法
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法三:欧拉筛
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largestPrime = 1
for prime in primes {
if n % prime == 0 {
largestPrime = max(largestPrime, prime)
}
}
return largestPrime
}
```
### 解法四:线性筛
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
while j < primes.count && i * primes[j] <= n {
isPrime[i * primes[j]] = false
if i % primes[j] == 0 {
break
}
j += 1
}
i += 1
}
var largestPrime = 1
for prime in primes {
if n % prime == 0 {
largestPrime = max(largestPrime, prime)
}
}
return largestPrime
}
```
### 解法五:线性筛
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
var primes = [Int]()
var isPrime = [Bool](repeating: true, count: n + 1)
while i * i <= n {
if isPrime[i] {
primes.append(i)
}
var j = 0
func largestPrimeFactor(n: Int) -> Int { // invalid redeclaration of 'largestPrimeFactor(n:)'
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法二:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法三:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法四:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法五:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法六:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法七:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n = n / i
} else {
i += 1
}
}
return n
}
```
### 解法八:
```swift
//
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法二
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法三
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法四
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法五
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法六
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法七
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法八
```swift
// Return the largest prime factor of n. Assume n > 1
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法二:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法三:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法四:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法五:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法六:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法七:
```swift
// Return the largest prime factor of n. Assume n > 1 and is not a prime.
// largestPrimeFactor(n: 13195) == 29
// largestPrimeFactor(n: 2048) == 2
func largestPrimeFactor(n: Int) -> Int {
var n = n
var i = 2
while i * i <= n {
if n % i == 0 {
n /= i
} else {
i += 1
}
}
return n
}
```
### 解法八:
```swift
// Return the largest prime factor of n
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n - 1)
}
func sumToN(n: Int) -> Int {
return sumToN(n, 1)
}
func sumToN(n: Int, sum: Int) -> Int {
if n == 1 {
return sum
}
return sumToN(n - 1, sum + n)
}
```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
}
```
### 方法二:递归
```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
}
return n + sumToN(n - 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 sumToN(n, 1)
}
func sumToN(n: Int, sum: Int) -> Int {
if n == 1 {
return sum
}
return sumToN(n - 1, sum + n)
}
```
### 方法四:尾递归优化
```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 sumToN(n, 1)
}
func sumToN(n: Int, sum: Int) -> Int {
if n == 1 {
return sum
}
return sumToN(n - 1, sum + n)
}
// MARK: - 尾递归优化
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
// 尾递归优化,将递归转换为循环
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
return n + sumToN(n - 1) // missing argument label 'n:' in call
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
return sumToN(n, 1) // missing argument labels 'n:sum:' in call
return sumToN(n - 1, sum + n) // missing argument labels 'n:sum:' in call
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return sumToN(n: n - 1) + n
}
func sumToN(n: Int) -> Int {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 n * (n + 1) / 2
}
```
### 解法二:递归
```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
}
return sumToN(n: n - 1) + n
}
```
### 解法三:尾递归
```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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n -
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return sumToN(n: n - 1) + n
}
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
```
### 解法二
```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
}
return sumToN(n: n - 1) + n
}
```
### 解法三
```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
}
```
### 解法四
```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
}
```
### 解法五
```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
}
```
### 解法六
```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
}
```
### 解法七
```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
}
```
### 解法八
```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)
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return sumToN(n: n - 1) + n
}
func sumToN(n: Int) -> Int {
var result = 0
func sumToN(n: Int, result: inout Int) {
if n == 1 {
result = 1
return
}
sumToN(n: n - 1, result: &result)
result += n
}
sumToN(n: n, result: &result)
return result
}
```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
}
```
### 解法二:递归
```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
}
return sumToN(n: n - 1) + n
}
```
### 解法三:尾递归
```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 result = 0
func sumToN(n: Int, result: inout Int) {
if n == 1 {
result = 1
return
}
sumToN(n: n - 1, result: &result)
result += n
}
sumToN(n: n, result: &result)
return result
}
```
### 解法四:尾递归优化
```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 result = 0
func sumToN(n: Int, result: inout Int) {
if n == 1 {
result = 1
return
}
sumToN(n: n - 1, result: &result)
result += n
}
sumToN(n: n, result: &result)
return result
}
```
### 解法五:尾递归优化
```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 result = 0
func sumToN(n: Int, result: inout Int) {
if n == 1 {
result = 1
return
}
sumToN(n: n - 1, result: &result)
result += n
}
sumToN(n: n, result: &result)
return result
}
```
### 解法六:尾递归优化
```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 result = 0
func sumToN(n: Int, result: inout Int) {
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumOfSquaresToN(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
func sumOfSquaresToNMinusOne(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6 - n
}
func sumOfSquaresToNMinusOneDividedByTwo(n: Int) -> Int {
return sumOfSquaresToNMinusOne(n) / 2
}
func sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: Int) -> Int {
return sumOfSquaresToNMinusOneDividedByTwo(n) - 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
}
```
```swift
// sum_of_squares_to_n is a function that sums the squares of numbers from 1 to n.
// sumOfSquaresToN(n: 30) == 3630
// sumOfSquaresToN(n: 100) == 338350
// sumOfSquaresToN(n: 5) == 125
// sumOfSquaresToN(n: 10) == 260
// sumOfSquaresToN(n: 1) == 1
func sumOfSquaresToN(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
```
```swift
// sum_of_squares_to_n_minus_one is a function that sums the squares of numbers from 1 to n-1.
// sumOfSquaresToNMinusOne(n: 30) == 2850
// sumOfSquaresToNMinusOne(n: 100) == 25164150
// sumOfSquaresToNMinusOne(n: 5) == 121
// sumOfSquaresToNMinusOne(n: 10) == 240
// sumOfSquaresToNMinusOne(n: 1) == 1
func sumOfSquaresToNMinusOne(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6 - n
}
```
```swift
// sum_of_squares_to_n_minus_one_divided_by_two is a function that sums the squares of numbers from 1 to n-1, then divides the result by 2.
// sumOfSquaresToNMinusOneDividedByTwo(n: 30) == 1450
// sumOfSquaresToNMinusOneDividedByTwo(n: 100) == 12525
// sumOfSquaresToNMinusOneDividedByTwo(n: 5) == 15
// sumOfSquaresToNMinusOneDividedByTwo(n: 10) == 25
// sumOfSquaresToNMinusOneDividedByTwo(n: 1) == 1
func sumOfSquaresToNMinusOneDividedByTwo(n: Int) -> Int {
return sumOfSquaresToNMinusOne(n) / 2
}
```
```swift
// sum_of_squares_to_n_minus_one_divided_by_two_minus_one is a function that sums the squares of numbers from 1 to n-1, then divides the result by 2, then subtracts 1.
// sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: 30) == 1449
// sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: 100) == 12524
// sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: 5) == 14
// sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: 10) == 24
// sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: 1) == 0
func sumOfSquaresToNMinusOneDividedByTwoMinusOne(n: Int) -> Int {
return sumOfSquaresToNMinusOneDividedByTwo(n) - 1
}
```
```swift
// sum_of_squares_to_n_minus_one_divided_by_two_minus_one_minus_n is a function that sums the squares of numbers from 1 to n-1, then divides the result by 2, then subtracts 1, then subtracts n.
//
return sumOfSquaresToNMinusOne(n) / 2 // missing argument label 'n:' in call
return sumOfSquaresToNMinusOneDividedByTwo(n) - 1 // missing argument label 'n:' in call
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n - 1)
}
func sumToN(n: Int) -> Int {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 n * (n + 1) / 2
}
```
### 方法二:递归
```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
}
return n + sumToN(n - 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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
sum += n
}
var sum = 0
sumToN(n, &sum)
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 {
func sumToN(_ n: Int, _ sum: inout Int) {
if n == 1 {
sum = 1
return
}
sumToN(n - 1, &sum)
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
return n + sumToN(n - 1) // missing argument label 'n:' in call
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n: n - 1)
}
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
if n == 1 {
return 1
}
return n + sumToN(n: n - 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 {
if n == 1 {
return 1
}
return n + sumToN(n: n - 1)
}
```
### 迭代解法
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
### 递归解法
```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
}
return n + sumToN(n: n - 1)
}
```
### 迭代解法
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
### 递归解法
```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
}
return n + sumToN(n: n - 1)
}
```
### 迭代解法
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
### 递归解法
func sumToN(n: Int) -> Int { // invalid redeclaration of 'sumToN(n:)'
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumOfSquaresToN(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
func sumOfSquaresToNDifference(n: Int) -> Int {
return sumToN(n: n) * sumToN(n: n) - sumOfSquaresToN(n: n)
}
func sumOfSquaresToNDifferenceSquared(n: Int) -> Int {
return sumOfSquaresToNDifference(n: n) * sumOfSquaresToNDifference(n: n)
}
func sumOfSquaresToNDifferenceCubed(n: Int) -> Int {
return sumOfSquaresToNDifference(n: n) * sumOfSquaresToNDifference(n: n) * sumOfSquaresToNDifference(n: n)
}
```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
}
```
```swift
// sum_of_squares_to_n is a function that sums the squares of numbers from 1 to n.
// sumOfSquaresToN(n: 30) == 3630
// sumOfSquaresToN(n: 100) == 25164150
// sumOfSquaresToN(n: 5) == 125
// sumOfSquaresToN(n: 10) == 260
// sumOfSquaresToN(n: 1) == 1
func sumOfSquaresToN(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
```
```swift
// sum_of_squares_to_n_difference is a function that sums the difference between squares of numbers from 1 to n.
// sumOfSquaresToNDifference(n: 30) == 2510
// sumOfSquaresToNDifference(n: 100) == 15122
// sumOfSquaresToNDifference(n: 5) == 10
// sumOfSquaresToNDifference(n: 10) == 20
// sumOfSquaresToNDifference(n: 1) == 0
func sumOfSquaresToNDifference(n: Int) -> Int {
return sumToN(n: n) * sumToN(n: n) - sumOfSquaresToN(n: n)
}
```
```swift
// sum_of_squares_to_n_difference_squared is a function that sums the square of the difference between squares of numbers from 1 to n.
// sumOfSquaresToNDifferenceSquared(n: 30) == 15122
// sumOfSquaresToNDifferenceSquared(n: 100) == 100200
// sumOfSquaresToNDifferenceSquared(n: 5) == 1
// sumOfSquaresToNDifferenceSquared(n: 10) == 1
// sumOfSquaresToNDifferenceSquared(n: 1) == 0
func sumOfSquaresToNDifferenceSquared(n: Int) -> Int {
return sumOfSquaresToNDifference(n: n) * sumOfSquaresToNDifference(n: n)
}
```
```swift
// sum_of_squares_to_n_difference_cubed is a function that sums the cube of the difference between squares of numbers from 1 to n.
// sumOfSquaresToNDifferenceCubed(n: 30) == 100200
// sumOfSquaresToNDifferenceCubed(n: 100) == 10000000000
// sumOfSquaresToNDifferenceCubed(n: 5) == 1
// sumOfSquaresToNDifferenceCubed(n: 10) == 1
// sumOfSquaresToNDifferenceCubed(n: 1) == 0
func sumOfSquaresToNDifferenceCubed(n: Int) -> Int {
return sumOfSquaresToNDifference(n: n) * sumOfSquaresToNDifference(n: n) * sumOfSquaresToNDifference(n: n)
}
```
```swift
// sum_of_squares_to_n_difference_cubed_squared is a function that sums the square of the cube of the difference between squares of numbers from 1 to n.
// sumOfSquaresToNDifferenceCubedSquared(n: 30) == 10000000000
// sumOfSquaresToNDifferenceCubedSquared(n: 100) == 10000000000000000000
// sumOfSquaresToNDifferenceCubedSqu
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
func sumOfSquares(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
func differenceOfSquares(n: Int) -> Int {
return sumOfSquares(n: n) - sumToN(n: n) * sumToN(n: n)
}
func squareOfSums(n: Int) -> Int {
return n * (n + 1) / 2 * (n + 1) * (n + 2) / 4
}
```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
}
```
### 解法二
```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) == 328350
// sumOfSquares(n: 100) == 25164150
// sumOfSquares(n: 5) == 125
// sumOfSquares(n: 10) == 225
// sumOfSquares(n: 1) == 1
func sumOfSquares(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
// difference_of_squares is a function that returns the difference between the sum of squares of numbers from 1 to n and the square of the sum of numbers from 1 to n.
// differenceOfSquares(n: 30) == 2417
// differenceOfSquares(n: 100) == 251642
// differenceOfSquares(n: 5) == 1
// differenceOfSquares(n: 10) == 2
// differenceOfSquares(n: 1) == 0
func differenceOfSquares(n: Int) -> Int {
return sumOfSquares(n: n) - sumToN(n: n) * sumToN(n: n)
}
```
### 解法三
```swift
// sum_of_squares is a function that sums the squares of numbers from 1 to n.
// sumOfSquares(n: 30) == 328350
// sumOfSquares(n: 100) == 25164150
// sumOfSquares(n: 5) == 125
// sumOfSquares(n: 10) == 225
// sumOfSquares(n: 1) == 1
func sumOfSquares(n: Int) -> Int {
return n * (n + 1) * (2 * n + 1) / 6
}
// square_of_sums is a function that squares the sum of numbers from 1 to n.
// squareOfSums(n: 30) == 3025
// squareOfSums(n: 100) == 255025
// squareOfSums(n: 5) == 1225
// squareOfSums(n: 10) == 2450
// squareOfSums(n: 1) == 1
func squareOfSums(n: Int) -> Int {
return n * (n + 1) / 2 * (n + 1) * (n + 2) / 4
}
// difference_of_squares is a function that returns the difference between the sum of squares of numbers from 1 to n and the square of the sum of numbers from 1 to n.
// differenceOfSquares(n: 30) == 2417
// differenceOfSquares(n: 100) == 251642
// differenceOfSquares(n: 5) == 1
// differenceOfSquares(n: 10) == 2
// differenceOfSquares(n: 1) == 0
func differenceOfSquares(n: Int) -> Int {
return sumOfSquares(n: n) - squareOfSums(n: n)
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
class Solution {
func sumOddLengthSubarrays(_ arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
let left = i + 1
let right = arr.count - i
let leftOdd = (left + 1) >> 1
let rightOdd = (right + 1) >> 1
let leftEven = left >> 1
let rightEven = right >> 1
sum += (leftOdd * rightOdd + leftEven * rightEven) * arr[i]
}
return sum
}
}
```swift
// sum_to_n is a function that sums numbers from 1 to n.
// sumToN(n: 30) == 465
// sumToN(n: 100) == 5050
// sumToN(n: 5) == 15
// sumToN(n: 10) == 55
// sumToN(n: 1) == 1
func sumToN(n: Int) -> Int {
return n * (n + 1) / 2
}
```
### 代码
```swift
class Solution {
func sumOddLengthSubarrays(_ arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
let left = i + 1
let right = arr.count - i
let leftOdd = (left + 1) >> 1
let rightOdd = (right + 1) >> 1
let leftEven = left >> 1
let rightEven = right >> 1
sum += (leftOdd * rightOdd + leftEven * rightEven) * arr[i]
}
return sum
}
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for char in brackets {
if char == "(" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```swift
// brackets is a string of "(" and ")".
// return true if every opening bracket has a corresponding closing bracket.
// correctBracketing(brackets: "(") == false
// correctBracketing(brackets: "()") == true
// correctBracketing(brackets: "(()())") == true
// correctBracketing(brackets: ")(()") == false
func correctBracketing(brackets: String) -> Bool {
var stack = [Character]()
for c in brackets {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
stack.removeLast()
}
}
return stack.isEmpty
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func derivative(_ xs: [Int]) -> [Int] {
if xs.count == 1 {
return []
}
let xs = xs.map { $0 }
let result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路2
递归
### 代码
```swift
class Solution {
func derivative(_ xs: [Int]) -> [Int] {
if xs.count == 1 {
return []
}
let xs = xs.map { $0 }
let result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
}
```
result.append(xs[i] * i) // cannot use mutating member on immutable value: 'result' is a 'let' constant
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int](repeating: 0, count: xs.count - 1)
for i in 1..<xs.count {
result[i - 1] = xs[i] * i
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
let n = nums.count
var left = [Int](repeating: 1, count: n)
var right = [Int](repeating: 1, count: n)
var result = [Int](repeating: 1, count: n)
for i in 1..<n {
left[i] = nums[i - 1] * left[i - 1]
}
for i in stride(from: n - 2, through: 0, by: -1) {
right[i] = nums[i + 1] * right[i + 1]
}
for i in 0..<n {
result[i] = left[i] * right[i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int](repeating: 0, count: xs.count - 1)
for i in 1..<xs.count {
result[i - 1] = xs[i] * i
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
let n = nums.count
var left = [Int](repeating: 1, count: n)
var right = [Int](repeating: 1, count: n)
var result = [Int](repeating: 1, count: n)
for i in 1..<n {
left[i] = nums[i - 1] * left[i - 1]
}
for i in stride(from: n - 2, through: 0, by: -1) {
right[i] = nums[i + 1] * right[i + 1]
}
for i in 0..<n {
result[i] = left[i] * right[i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func derivative(_ xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路2
使用递归,每次递归计算当前项的导数,然后将结果加到结果集中。
### 代码2
```swift
class Solution {
func derivative(_ xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
}
var right = 1
for i in (0..<nums.count).reversed() {
result[i] *= right
right *= nums[i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
var right = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
result[nums.count - 1 - i] *= right
right *= nums[nums.count - 1 - i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
var right = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
result[nums.count - 1 - i] *= right
right *= nums[nums.count - 1 - i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
var right = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
result[nums.count - 1 - i] *= right
right *= nums[nums.count - 1 - i]
}
return result
}
}
```swift
// xs represent coefficients of a polynomial.
// xs[0] + xs[1] * x + xs[2] * x^2 + ....
// Return derivative of this polynomial in the same form.
// derivative(xs: [3, 1, 2, 4, 5]) == [1, 4, 12, 20]
// derivative(xs: [1, 2, 3]) == [2, 6]
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func productExceptSelf(_ nums: [Int]) -> [Int] {
var result = [Int]()
var left = 1
var right = 1
for i in 0..<nums.count {
result.append(left)
left *= nums[i]
result[nums.count - 1 - i] *= right
right *= nums[nums.count - 1 - i]
}
return result
}
}
```
func derivative(xs: [Int]) -> [Int] {
var result = [Int]()
for i in 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
class Solution {
func derivative(_ xs: [Int]) -> [Int] {
return Array(Array(xs[1..<xs.count]).lazy.map { $0 * Int($0) }.reduce(0, +) - Array(Array(xs[0..<xs.count-1]).lazy.map { $0 * Int($0) }.reduce(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 1..<xs.count {
result.append(xs[i] * i)
}
return result
}
```
### 解题思路
#### 1. 暴力解法
直接模拟求导过程,时间复杂度为 $O(n^2)$,空间复杂度为 $O(n)$。
#### 2. 优化解法
求导公式:
$$
f'(x) = \frac{f(x+h) - f(x)}{h}
$$
其中 $h$ 为微小量,可以取 $h = 1$。
$$
f'(x) = \frac{f(x+1) - f(x)}{1}
$$
$$
f'(x) = f(x+1) - f(x)
$$
时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。
### 代码
```swift
class Solution {
func derivative(_ xs: [Int]) -> [Int] {
return Array(Array(xs[1..<xs.count]).lazy.map { $0 * Int($0) }.reduce(0, +) - Array(Array(xs[0..<xs.count-1]).lazy.map { $0 * Int($0) }.reduce(0, +)))
}
}
```
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
c = a + b + c
a = b
b = c - a - b
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
c = a + b + c
a = b
b = c - a - b
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + c
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + b
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + b
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var fibfibArray = [Int](repeating: 0, count: n)
fibfibArray[0] = 0
fibfibArray[1] = 0
fibfibArray[2] = 1
for i in 3...n {
fibfibArray[i] = fibfibArray[i-1] + fibfibArray[i-2] + fibfibArray[i-3]
}
return fibfibArray[n-1]
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var fibfibArray = [Int](repeating: 0, count: n)
fibfibArray[0] = 0
fibfibArray[1] = 0
fibfibArray[2] = 1
for i in 3...n {
fibfibArray[i] = fibfibArray[i-1] + fibfibArray[i-2] + fibfibArray[i-3]
}
return fibfibArray[n-1]
}
```
// Fatal error: Index out of range
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + b
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 0
var c = 1
for _ in 3...n {
a = b
b = c
c = a + b + b
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var pre = 0
var cur = 0
var next = 1
for _ in 3...n {
pre = cur
cur = next
next = pre + cur + next
}
return next
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var pre = 0
var cur = 0
var next = 1
for _ in 3...n {
pre = cur
cur = next
next = pre + cur + next
}
return next
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n < 2 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
c = a + b + c
a = b
b = c - a - b
}
return c
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n < 2 {
return 0
}
if n == 2 {
return 1
}
var a = 0
var b = 1
var c = 1
for _ in 3...n {
c = a + b + c
a = b
b = c - a - b
}
return c
}
```
// XCTAssertTrue failed
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var result = 1
var prev1 = 0
var prev2 = 0
for _ in 3...n {
result = prev1 + prev2 + result
prev1 = prev2
prev2 = result
}
return result
}
```swift
// The FibFib number sequence is a sequence similar to the Fibbonacci sequnece that's defined as follows:
// fibfib(0) == 0
// fibfib(1) == 0
// fibfib(2) == 1
// fibfib(n) == fibfib(n-1) + fibfib(n-2) + fibfib(n-3).
// Please write a function to efficiently compute the n-th element of the fibfib number sequence.
// fibfib(n: 1) == 0
// fibfib(n: 5) == 4
// fibfib(n: 8) == 24
func fibfib(n: Int) -> Int {
if n == 0 {
return 0
}
if n == 1 {
return 0
}
if n == 2 {
return 1
}
var result = 1
var prev1 = 0
var prev2 = 0
for _ in 3...n {
result = prev1 + prev2 + result
prev1 = prev2
prev2 = result
}
return result
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
let vowels = ["a", "e", "i", "o", "u", "y"]
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
let vowels = ["a", "e", "i", "o", "u", "y"]
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
```
### 解法二
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
let vowels = ["a", "e", "i", "o", "u", "y"]
var count = 0
for char in s {
if vowels.contains(char) {
count += 1
}
}
return count
}
```
if vowels.contains(char) { // cannot convert value of type 'Character' to expected argument type 'String'
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```
// 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.index(s.startIndex, offsetBy: s.count - 1) == "y" {
vowels += 1
}
}
return vowels
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var vowels = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" {
vowels += 1
} else if char == "y" && s.index(s.startIndex, offsetBy: s.count - 1) == "y" {
vowels += 1
}
}
return vowels
}
```
} else if char == "y" && s.index(s.startIndex, offsetBy: s.count - 1) == "y" { // referencing operator function '==' on 'StringProtocol' requires that 'String.Index' conform to 'StringProtocol'
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" || c == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" || c == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" || c == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" || c == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for char in s {
if char == "a" || char == "e" || char == "i" || char == "o" || char == "u" || char == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" || c == "y" {
count += 1
}
}
return count
}
```swift
// Write a function vowels_count which takes a string representing
// a word as input and returns the number of vowels in the string.
// Vowels in this case are 'a', 'e', 'i', 'o', 'u'. Here, 'y' is also a
// vowel, but only when it is at the end of the given word.
// Example:
// vowelsCount(s: "abcde") == 2
// vowelsCount(s: "ACEDY") == 3
func vowelsCount(s: String) -> Int {
var count = 0
for c in s {
if c == "a" || c == "e" || c == "i" || c == "o" || c == "u" || c == "y" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
let result = digits.reversed().prefix(digits.count - shift).appending(digits.suffix(shift))
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
let result = digits.reversed().prefix(digits.count - shift).appending(digits.suffix(shift))
return String(result)
}
```
### 解法二:模拟
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
let result = digits.reversed().prefix(digits.count - shift).appending(digits.suffix(shift))
return String(result)
}
```
let result = digits.reversed().prefix(digits.count - shift).appending(digits.suffix(shift)) // reference to member 'appending' cannot be resolved without a contextual type
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
if shift > 0 {
digits.reverse()
digits.removeLast(shift)
digits.append(contentsOf: digits)
}
return String(digits)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
if shift > 0 {
digits.reverse()
digits.removeLast(shift)
digits.append(contentsOf: digits)
}
return String(digits)
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
if shift == 0 {
return String(digits)
}
let result = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift]
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
if shift == 0 {
return String(digits)
}
let result = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift]
return String(result)
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
var shift = shift % digits.count
if shift > 0 {
digits.reverse()
digits.removeLast(shift)
digits.reverse()
}
return String(digits)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
var shift = shift % digits.count
if shift > 0 {
digits.reverse()
digits.removeLast(shift)
digits.reverse()
}
return String(digits)
}
```
var shift = shift % digits.count // variable 'shift' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
var result = digits
if shift > 0 {
result.append(contentsOf: digits.dropLast(digits.count - shift))
result.removeFirst(shift)
} else {
result.removeFirst(digits.count - shift)
result.append(contentsOf: digits)
}
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
var result = digits
if shift > 0 {
result.append(contentsOf: digits.dropLast(digits.count - shift))
result.removeFirst(shift)
} else {
result.removeFirst(digits.count - shift)
result.append(contentsOf: digits)
}
return String(result)
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
var result = digits
result.reverse()
result.append(contentsOf: digits[0..<shift])
result.removeFirst(shift)
result.reverse()
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
let digits = Array(String(x))
let shift = shift % digits.count
var result = digits
result.reverse()
result.append(contentsOf: digits[0..<shift])
result.removeFirst(shift)
result.reverse()
return String(result)
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
digits.reverse()
digits.removeLast(digits.count - shift)
digits.append(contentsOf: digits)
return String(digits)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
digits.reverse()
digits.removeLast(digits.count - shift)
digits.append(contentsOf: digits)
return String(digits)
}
```
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
var shift = shift % digits.count
if shift > 0 {
digits.append(contentsOf: Array(digits[0...shift-1]))
digits.removeFirst(shift)
}
return String(digits)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
var shift = shift % digits.count
if shift > 0 {
digits.append(contentsOf: Array(digits[0...shift-1]))
digits.removeFirst(shift)
}
return String(digits)
}
```
var shift = shift % digits.count // variable 'shift' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
if shift == 0 {
return String(digits)
}
var result = digits[digits.count - shift..<digits.count]
result.append(contentsOf: digits[0..<digits.count - shift])
return String(result)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
if shift == 0 {
return String(digits)
}
var result = digits[digits.count - shift..<digits.count]
result.append(contentsOf: digits[0..<digits.count - shift])
return String(result)
}
```
var digits = Array(String(x)) // variable 'digits' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
digits = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift]
return String(digits)
}
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
digits.reverse()
digits = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift]
digits.reverse()
return String(digits)
}
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
digits = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift]
return String(digits)
}
```
### 方法二:模拟
```swift
// Circular shift the digits of the integer x, shift the digits right by shift
// and return the result as a string.
// If shift > number of digits, return digits reversed.
// circularShift(x: 12, shift: 1) == "21"
// circularShift(x: 12, shift: 2) == "12"
func circularShift(x: Int, shift: Int) -> String {
var digits = Array(String(x))
let shift = shift % digits.count
digits.reverse()
digits = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift]
digits.reverse()
return String(digits)
}
```
digits = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift] // cannot assign value of type 'ArraySlice<String.Element>' (aka 'ArraySlice<Character>') to type '[String.Element]' (aka 'Array<Character>')
func circularShift(x: Int, shift: Int) -> String { // invalid redeclaration of 'circularShift(x:shift:)'
digits = digits[digits.count - shift..<digits.count] + digits[0..<digits.count - shift] // cannot assign value of type 'ArraySlice<String.Element>' (aka 'ArraySlice<Character>') to type '[String.Element]' (aka 'Array<Character>')
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
let chars = Array(s)
var sum = 0
for char in chars {
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 {
let chars = Array(s)
var sum = 0
for char in chars {
if char.isUppercase {
sum += Int(char.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var result = 0
for char in s {
if char.isUppercase {
result += Int(char.asciiValue!) - 64
}
}
return result
}
```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 result = 0
for char in s {
if char.isUppercase {
result += Int(char.asciiValue!) - 64
}
}
return result
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func digitSum(s: String) -> Int {
var sum = 0
for c in s {
if c.isUppercase {
sum += Int(c.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 c in s {
if c.isUppercase {
sum += Int(c.asciiValue!) - 64
}
}
return sum
}
```
// XCTAssertTrue failed
func fruitDistribution(s: String, n: Int) -> Int {
let oranges = Int(s.components(separatedBy: " ")[0])!
let apples = Int(s.components(separatedBy: " ")[1])!
let total = oranges + apples
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let oranges = Int(s.components(separatedBy: " ")[0])!
let apples = Int(s.components(separatedBy: " ")[1])!
let total = oranges + apples
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
### 解法二
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
let mango = n - total
return mango
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
let total = apples + oranges
return n - total
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.split(separator: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[2])!
let total = apples + oranges
return n - total
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
return n - total
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let arr = s.components(separatedBy: " ")
let apples = Int(arr[0])!
let oranges = Int(arr[1])!
let total = apples + oranges
return n - total
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func fruitDistribution(s: String, n: Int) -> Int {
let oranges = Int(s.split(separator: " and ")[0].split(separator: " ")[0])!
let apples = Int(s.split(separator: " and ")[1].split(separator: " ")[0])!
let total = oranges + apples
let mango = n - total
return mango
}
```swift
// In this task, you will be given a string that represents a number of apples and oranges
// that are distributed in a basket of fruit this basket contains
// apples, oranges, and mango fruits. Given the string that represents the total number of
// the oranges and apples and an integer that represent the total number of the fruits
// in the basket return the number of the mango fruits in the basket.
// for examble:
// fruitDistribution(s: "5 apples and 6 oranges", n: 19) == 8
// fruitDistribution(s: "0 apples and 1 oranges", n: 3) == 2
// fruitDistribution(s: "2 apples and 3 oranges", n: 100) == 95
// fruitDistribution(s: "100 apples and 1 oranges", n: 120) == 19
func fruitDistribution(s: String, n: Int) -> Int {
let oranges = Int(s.split(separator: " and ")[0].split(separator: " ")[0])!
let apples = Int(s.split(separator: " and ")[1].split(separator: " ")[0])!
let total = oranges + apples
let mango = n - total
return mango
}
```
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < minValue {
minValue = value
minIndex = index
}
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < minValue {
minValue = value
minIndex = index
}
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var result: [Int] = []
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < minValue {
minValue = value
minIndex = index
}
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result: [Int] = []
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
if value < minValue {
minValue = value
minIndex = index
}
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var evenNodes = [Int]()
for (index, node) in arr.enumerated() {
if node % 2 == 0 {
evenNodes.append(node)
evenNodes.append(index)
}
}
if evenNodes.isEmpty {
return []
}
return [evenNodes.min()!, evenNodes.firstIndex(of: evenNodes.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 evenNodes = [Int]()
for (index, node) in arr.enumerated() {
if node % 2 == 0 {
evenNodes.append(node)
evenNodes.append(index)
}
}
if evenNodes.isEmpty {
return []
}
return [evenNodes.min()!, evenNodes.firstIndex(of: evenNodes.min()!)!]
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minIndex != -1 {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = -1
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minIndex != -1 {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var result: [Int] = []
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result: [Int] = []
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func pluck(arr: [Int]) -> [Int] {
var evenArr = [Int]()
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
evenArr.append(value)
evenArr.append(index)
}
}
if evenArr.count == 0 {
return []
}
return [evenArr.min()!, evenArr.firstIndex(of: evenArr.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 evenArr = [Int]()
for (index, value) in arr.enumerated() {
if value % 2 == 0 {
evenArr.append(value)
evenArr.append(index)
}
}
if evenArr.count == 0 {
return []
}
return [evenArr.min()!, evenArr.firstIndex(of: evenArr.min()!)!]
}
```
// XCTAssertTrue failed
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```swift
// "Given an array representing a branch of a tree that has non-negative integer nodes
// your task is to pluck one of the nodes and return it.
// The plucked node should be the node with the smallest even value.
// If multiple nodes with the same smallest even value are found return the node that has smallest index.
// The plucked node should be returned in an array, [ smalest_value, its index ],
// If there are no even values or the given array is empty, return [].
// Example 1:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 2:
// Explanation: 2 has the smallest even value, and 2 has the smallest index.
// Example 3:
// Example 4:
// Explanation: 0 is the smallest value, but there are two zeros,
// so we will choose the first zero, which has the smallest index.
// Constraints:
// * 1 <= nodes.length <= 10000
// * 0 <= node.value
// pluck(arr: [4, 2, 3]) == [2, 1]
// pluck(arr: [1, 2, 3]) == [2, 1]
// pluck(arr: [] as [Int]) == [] as [Int]
// pluck(arr: [5, 0, 3, 0, 4, 2]) == [0, 1]
func pluck(arr: [Int]) -> [Int] {
var result = [Int]()
var minValue = Int.max
var minIndex = 0
for (index, value) in arr.enumerated() {
if value % 2 == 0 && value < minValue {
minValue = value
minIndex = index
}
}
if minValue != Int.max {
result.append(minValue)
result.append(minIndex)
}
return result
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 && dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 && dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] >= res {
if dict[lst[i]]! >= lst[i] {
res = lst[i]
}
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] >= res {
if dict[lst[i]]! >= lst[i] {
res = lst[i]
}
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i], default: 0] += 1
}
var result = -1
for (key, value) in dict {
if value >= key {
result = max(result, key)
}
}
return result
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i], default: 0] += 1
}
var result = -1
for (key, value) in dict {
if value >= key {
result = max(result, key)
}
}
return result
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 {
if dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 {
if dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 && dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 && dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
var max = -1
for i in lst {
if dict[i]! >= i {
max = max > i ? max : i
}
}
return max
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in lst {
dict[i] = (dict[i] ?? 0) + 1
}
var max = -1
for i in lst {
if dict[i]! >= i {
max = max > i ? max : i
}
}
return max
}
```
func search(lst: [Int]) -> Int {
var map = [Int: Int]()
for i in lst {
map[i] = (map[i] ?? 0) + 1
}
var res = -1
for i in lst {
if map[i]! >= i {
res = max(res, i)
}
}
return res
}
```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 map = [Int: Int]()
for i in lst {
map[i] = (map[i] ?? 0) + 1
}
var res = -1
for i in lst {
if map[i]! >= i {
res = max(res, i)
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > res {
if dict[lst[i]]! >= lst[i] {
res = lst[i]
}
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > res {
if dict[lst[i]]! >= lst[i] {
res = lst[i]
}
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > res && dict[lst[i]]! >= lst[i] {
res = lst[i]
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > res && dict[lst[i]]! >= lst[i] {
res = lst[i]
}
}
return res
}
```
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 && dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
return res
}
```swift
// You are given a non-empty array of positive integers. Return the greatest integer that is greater than
// zero, and has a frequency greater than or equal to the value of the integer itself.
// The frequency of an integer is the number of times it appears in the array.
// If no such a value exist, return -1.
// Examples:
// search(lst: [4, 1, 2, 2, 3, 1]) == 2
// search(lst: [1, 2, 2, 3, 3, 3, 4, 4, 4]) == 3
// search(lst: [5, 5, 4, 4, 4]) == -1
func search(lst: [Int]) -> Int {
var dict = [Int: Int]()
for i in 0..<lst.count {
dict[lst[i]] = (dict[lst[i]] ?? 0) + 1
}
var res = -1
for i in 0..<lst.count {
if lst[i] > 0 && dict[lst[i]]! >= lst[i] {
res = max(res, lst[i])
}
}
return res
}
```
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while lst.count > 0 {
let min = lst.min()!
let max = lst.max()!
res.append(min)
res.append(max)
lst.removeFirst()
lst.removeLast()
}
return res
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while lst.count > 0 {
let min = lst.min()!
let max = lst.max()!
res.append(min)
res.append(max)
lst.removeFirst()
lst.removeLast()
}
return res
}
```
// Fatal error: Can't remove last element from an empty collection
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
lst.sort()
var result = [Int]()
var i = 0
while i < lst.count {
result.append(lst[lst.count - i - 1])
i += 2
}
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 > 0 else {
return []
}
var lst = lst
lst.sort()
var result = [Int]()
var i = 0
while i < lst.count {
result.append(lst[lst.count - i - 1])
i += 2
}
return result
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var result: [Int] = []
var lst = lst
while lst.count > 0 {
result.append(lst.max()!)
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1))
}
return result
}
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var result: [Int] = []
result.append(lst.max()!)
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1))
return result + strangeSortList(lst: lst)
}
```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 > 0 else {
return []
}
var result: [Int] = []
var lst = lst
while lst.count > 0 {
result.append(lst.max()!)
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1))
}
return result
}
```
### 解法二:递归
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var result: [Int] = []
result.append(lst.max()!)
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1))
return result + strangeSortList(lst: lst)
}
```
### 解法三:递归 + 交换
```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 > 0 else {
return []
}
var result: [Int] = []
result.append(lst.max()!)
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1))
return result + strangeSortList(lst: lst)
}
```
### 解法四:递归 + 交换 + 数组
```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 > 0 else {
return []
}
var result: [Int] = []
result.append(lst.max()!)
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1))
return result + strangeSortList(lst: lst)
}
```
### 解法五:递归 + 交换 + 数组 + 数组
```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
func strangeSortList(lst: [Int]) -> [Int] { // invalid redeclaration of 'strangeSortList(lst:)'
lst.remove(at: lst.index(lst.startIndex, offsetBy: lst.count - 1)) // cannot use mutating member on immutable value: 'lst' is a 'let' constant
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
result.append(max(lst))
lst.removeLast()
result.append(min(lst))
lst.removeLast()
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
result.append(max(lst))
lst.removeLast()
result.append(min(lst))
lst.removeLast()
}
return result
}
```
result.append(max(lst)) // cannot convert value of type '[Int]' to expected argument type 'Int'
result.append(max(lst)) // missing argument for parameter #2 in call
result.append(min(lst)) // missing argument for parameter #2 in call
result.append(min(lst)) // cannot convert value of type '[Int]' to expected argument type 'Int'
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
result.append(lst.removeMin()!)
result.append(lst.removeMax()!)
}
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 > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
result.append(lst.removeMin()!)
result.append(lst.removeMax()!)
}
return result
}
```
result.append(lst.removeMin()!) // value of type '[Int]' has no member 'removeMin'
result.append(lst.removeMax()!) // value of type '[Int]' has no member 'removeMax'
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while !lst.isEmpty {
let min = lst.min()!
res.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
res.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return res
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while !lst.isEmpty {
let min = lst.min()!
res.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
res.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return res
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
result.append(lst.removeLast())
result.append(lst.removeFirst())
}
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 > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
result.append(lst.removeLast())
result.append(lst.removeFirst())
}
return result
}
```
// XCTAssertTrue failed
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
let min = lst.min()!
result.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
result.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return result
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var result = [Int]()
while lst.count > 0 {
let min = lst.min()!
result.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
result.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return result
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while lst.count > 0 {
let min = lst.min()!
res.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
res.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return res
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while lst.count > 0 {
let min = lst.min()!
res.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
res.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return res
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while lst.count > 0 {
let min = lst.min()!
res.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
res.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return res
}
```swift
// Given array of integers, return array in strange order.
// Strange sorting, is when you start with the minimum value,
// then maximum of the remaining integers, then minimum and so on.
// Examples:
// strangeSortList(lst: [1, 2, 3, 4]) == [1, 4, 2, 3]
// strangeSortList(lst: [5, 5, 5, 5]) == [5, 5, 5, 5]
// strangeSortList(lst: [] as [Int]) == [] as [Int]
func strangeSortList(lst: [Int]) -> [Int] {
guard lst.count > 0 else {
return []
}
var lst = lst
var res = [Int]()
while lst.count > 0 {
let min = lst.min()!
res.append(min)
lst.remove(at: lst.firstIndex(of: min)!)
let max = lst.max()!
res.append(max)
lst.remove(at: lst.firstIndex(of: max)!)
}
return res
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 10000000000000
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 10000000000000
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - 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 || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c))
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - 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 || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c))
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / 16
}
```
// XCTAssertTrue failed
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let s = (a + b + c) / 2
let area = sqrt(s * (s - a) * (s - b) * (s - c))
return area
}
```
let area = sqrt(s * (s - a) * (s - b) * (s - c)) // cannot convert value of type 'Int' to expected argument type 'Double'
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sum = a + b + c
if sum < 2 * min(a, b, c) {
return -1
}
if a == b && b == c {
return Double(a * a)
}
if a == b || b == c || a == c {
return Double(sum * sum) / 4
}
let p = Double(sum) / 2
let area = Double(p * (p - a) * (p - b) * (p - c))
return sqrt(area)
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
let sum = a + b + c
if sum < 2 * min(a, b, c) {
return -1
}
if a == b && b == c {
return Double(a * a)
}
if a == b || b == c || a == c {
return Double(sum * sum) / 4
}
let p = Double(sum) / 2
let area = Double(p * (p - a) * (p - b) * (p - c))
return sqrt(area)
}
```
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / (p * p * p)
}
```swift
// Given the lengths of the three sides of a triangle. Return the area of
// the triangle rounded to 2 decimal points if the three sides form a valid triangle.
// Otherwise return -1
// Three sides make a valid triangle when the sum of any two sides is greater
// than the third side.
// Example:
// triangleArea(a: 3, b: 4, c: 5) == 6.0
// triangleArea(a: 1, b: 2, c: 10) == -1
func triangleArea(a: Int, b: Int, c: Int) -> Double {
if a + b <= c || a + c <= b || b + c <= a {
return -1
}
let p = (a + b + c) / 2
return Double(p * (p - a) * (p - b) * (p - c)) / (p * p * p)
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = w / q.count
return sum <= max && isBalanced(q)
}
func isBalanced(q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = w / q.count
return sum <= max && isBalanced(q)
}
func isBalanced(q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
return sum <= max && isBalanced(q) // missing argument label 'q:' in call
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let mid = q.count / 2
let leftSum = q[0..<mid].reduce(0, +)
let rightSum = q[mid..<q.count].reduce(0, +)
return sum <= w && leftSum == rightSum
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let mid = q.count / 2
let leftSum = q[0..<mid].reduce(0, +)
let rightSum = q[mid..<q.count].reduce(0, +)
return sum <= w && leftSum == rightSum
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
if sum < w {
return q.contains { $0 <= max }
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
if sum < w {
return q.contains { $0 <= max }
}
return false
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
return isPalindromic(q) && sum <= max
}
func isPalindromic(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
return isPalindromic(q) && sum <= max
}
func isPalindromic(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] + q[right] > max {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
var left = 0
var right = q.count - 1
while left < right {
if q[left] + q[right] > max {
return false
}
left += 1
right -= 1
}
return true
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
var left = 0
var right = q.count - 1
var leftSum = 0
var rightSum = 0
while left < right {
leftSum += q[left]
rightSum += q[right]
if leftSum > max {
break
}
if rightSum > max {
break
}
if leftSum == rightSum {
return true
}
left += 1
right -= 1
}
return false
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = sum / 2
if sum > w {
return false
}
if sum == w {
return true
}
var left = 0
var right = q.count - 1
var leftSum = 0
var rightSum = 0
while left < right {
leftSum += q[left]
rightSum += q[right]
if leftSum > max {
break
}
if rightSum > max {
break
}
if leftSum == rightSum {
return true
}
left += 1
right -= 1
}
return false
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let n = q.count
if n == 1 {
return true
}
var sum = 0
for i in 0..<n {
sum += q[i]
}
if sum > w {
return false
}
var left = 0
var right = n - 1
while left < right {
if q[left] + q[right] > w {
return false
}
left += 1
right -= 1
}
return isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
let n = q.count
var left = 0
var right = n - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let n = q.count
if n == 1 {
return true
}
var sum = 0
for i in 0..<n {
sum += q[i]
}
if sum > w {
return false
}
var left = 0
var right = n - 1
while left < right {
if q[left] + q[right] > w {
return false
}
left += 1
right -= 1
}
return isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
let n = q.count
var left = 0
var right = n - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = w / q.count
return sum <= max && isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
let max = w / q.count
return sum <= max && isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
// XCTAssertTrue failed
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w {
return false
}
let n = q.count
if n == 1 {
return true
}
var left = 0
var right = n - 1
while left < right {
if q[left] + q[right] > w {
return false
}
left += 1
right -= 1
}
return isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w {
return false
}
let n = q.count
if n == 1 {
return true
}
var left = 0
var right = n - 1
while left < right {
if q[left] + q[right] > w {
return false
}
left += 1
right -= 1
}
return isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w { return false }
let n = q.count
var left = 0
var right = n - 1
while left < right {
if q[left] + q[right] > w { return false }
left += 1
right -= 1
}
return isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] { return false }
left += 1
right -= 1
}
return true
}
```swift
// Write a function that returns true if the object q will fly, and false otherwise.
// The object q will fly if it's balanced (it is a palindromic array) and the sum of its elements is less than or equal the maximum possible weight w.
// Example:
// # 1+2 is less than the maximum possible weight, but it's unbalanced.
// # it's balanced, but 3+2+3 is more than the maximum possible weight.
// # 3+2+3 is less than the maximum possible weight, and it's balanced.
// # 3 is less than the maximum possible weight, and it's balanced.
// willItFly(q: [1, 2], w: 5) == false
// willItFly(q: [3, 2, 3], w: 1) == false
// willItFly(q: [3, 2, 3], w: 9) == true
// willItFly(q: [3], w: 5) == true
func willItFly(q: [Int], w: Int) -> Bool {
let sum = q.reduce(0, +)
if sum > w { return false }
let n = q.count
var left = 0
var right = n - 1
while left < right {
if q[left] + q[right] > w { return false }
left += 1
right -= 1
}
return isPalindrome(q)
}
func isPalindrome(_ q: [Int]) -> Bool {
var left = 0
var right = q.count - 1
while left < right {
if q[left] != q[right] { return false }
left += 1
right -= 1
}
return true
}
```
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
if arr[left] == arr[right - 1] {
arr[right] = arr[left]
count += 1
} else if arr[left + 1] == arr[right] {
arr[left] = arr[right]
count += 1
} else {
return -1
}
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
if arr[left] == arr[right - 1] {
arr[right] = arr[left]
count += 1
} else if arr[left + 1] == arr[right] {
arr[left] = arr[right]
count += 1
} else {
return -1
}
left += 1
right -= 1
}
}
return count
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
if arr[left] == arr[right - 1] {
right -= 1
} else if arr[left + 1] == arr[right] {
left += 1
} else {
count += 1
}
left += 1
right -= 1
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] == arr[right] {
left += 1
right -= 1
} else {
if arr[left] == arr[right - 1] {
right -= 1
} else if arr[left + 1] == arr[right] {
left += 1
} else {
count += 1
}
left += 1
right -= 1
}
}
return count
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] == arr[right] {
count += 1
}
}
left += 1
right -= 1
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
var left = 0
var right = arr.count - 1
while left < right {
if arr[left] != arr[right] {
count += 1
if arr[left] == arr[right] {
count += 1
}
}
left += 1
right -= 1
}
return count
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
func smallestChange(arr: [Int]) -> Int {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
dp[i][i] = 1
}
for i in 0..<n-1 {
dp[i][i+1] = abs(arr[i] - arr[i+1])
}
for i in 3..<n {
for j in 0..<n-i {
dp[j][j+i] = min(dp[j+1][j+i-1] + abs(arr[j] - arr[j+i]), dp[j][j+i-1] + abs(arr[j] - arr[j+i]))
}
}
return dp[0][n-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 {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
dp[i][i] = 1
}
for i in 0..<n-1 {
dp[i][i+1] = abs(arr[i] - arr[i+1])
}
for i in 3..<n {
for j in 0..<n-i {
dp[j][j+i] = min(dp[j+1][j+i-1] + abs(arr[j] - arr[j+i]), dp[j][j+i-1] + abs(arr[j] - arr[j+i]))
}
}
return dp[0][n-1]
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n - 1 {
dp[i][i + 1] = arr[i] == arr[i + 1] ? 0 : 1
}
for l in 3...n {
for i in 0..<n - l + 1 {
let j = i + l - 1
dp[i][j] = min(dp[i + 1][j] + 1, dp[i][j - 1] + 1)
if arr[i] == arr[j] {
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1])
}
}
}
return dp[0][n - 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 {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n - 1 {
dp[i][i + 1] = arr[i] == arr[i + 1] ? 0 : 1
}
for l in 3...n {
for i in 0..<n - l + 1 {
let j = i + l - 1
dp[i][j] = min(dp[i + 1][j] + 1, dp[i][j - 1] + 1)
if arr[i] == arr[j] {
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1])
}
}
}
return dp[0][n - 1]
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
if arr[i] == arr[arr.count - 1 - i] {
count -= 1
}
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count - 1 - i] {
count += 1
if arr[i] == arr[arr.count - 1 - i] {
count -= 1
}
}
}
return count
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
func smallestChange(arr: [Int]) -> Int {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dp[i][j] = 0
} else {
dp[i][j] = Int.max
}
}
}
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n {
for j in 0..<n {
if i + 1 <= j - 1 {
if arr[i] == arr[j] {
dp[i][j] = dp[i + 1][j - 1]
} else {
dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1
}
}
}
}
return dp[0][n - 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 {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dp[i][j] = 0
} else {
dp[i][j] = Int.max
}
}
}
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n {
for j in 0..<n {
if i + 1 <= j - 1 {
if arr[i] == arr[j] {
dp[i][j] = dp[i + 1][j - 1]
} else {
dp[i][j] = min(dp[i + 1][j], dp[i][j - 1]) + 1
}
}
}
}
return dp[0][n - 1]
}
```
func smallestChange(arr: [Int]) -> Int {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n - 1 {
dp[i][i + 1] = arr[i] == arr[i + 1] ? 0 : 1
}
for l in 3...n {
for i in 0..<n - l + 1 {
let j = i + l - 1
dp[i][j] = min(dp[i + 1][j] + 1, dp[i][j - 1] + 1)
if arr[i] == arr[j] {
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1])
}
}
}
return dp[0][n - 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 {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n - 1 {
dp[i][i + 1] = arr[i] == arr[i + 1] ? 0 : 1
}
for l in 3...n {
for i in 0..<n - l + 1 {
let j = i + l - 1
dp[i][j] = min(dp[i + 1][j] + 1, dp[i][j - 1] + 1)
if arr[i] == arr[j] {
dp[i][j] = min(dp[i][j], dp[i + 1][j - 1])
}
}
}
return dp[0][n - 1]
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dp[i][j] = 0
} else {
dp[i][j] = Int.max
}
}
}
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n - 1 {
dp[i][i + 1] = (arr[i] == arr[i + 1]) ? 0 : 1
}
for k in 2..<n {
for i in 0..<n - k {
let j = i + k
dp[i][j] = min(dp[i][j], dp[i + 1][j] + (arr[i] == arr[j] ? 0 : 1))
dp[i][j] = min(dp[i][j], dp[i][j - 1] + (arr[i] == arr[j] ? 0 : 1))
}
}
return dp[0][n - 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 {
let n = arr.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dp[i][j] = 0
} else {
dp[i][j] = Int.max
}
}
}
for i in 0..<n {
dp[i][i] = 0
}
for i in 0..<n - 1 {
dp[i][i + 1] = (arr[i] == arr[i + 1]) ? 0 : 1
}
for k in 2..<n {
for i in 0..<n - k {
let j = i + k
dp[i][j] = min(dp[i][j], dp[i + 1][j] + (arr[i] == arr[j] ? 0 : 1))
dp[i][j] = min(dp[i][j], dp[i][j - 1] + (arr[i] == arr[j] ? 0 : 1))
}
}
return dp[0][n - 1]
}
```
// XCTAssertTrue failed
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count-i-1] {
count += 1
if arr[i] == arr[arr.count-i-1] {
count -= 1
}
}
}
return count
}
```swift
// Given an array arr of integers, find the minimum number of elements that
// need to be changed to make the array palindromic. A palindromic array is an array that
// is read the same backwards and forwards. In one change, you can change one element to any other element.
// For example:
// smallestChange(arr: [1, 2, 3, 5, 4, 7, 9, 6]) == 4
// smallestChange(arr: [1, 2, 3, 4, 3, 2, 2]) == 1
// smallestChange(arr: [1, 2, 3, 2, 1]) == 0
func smallestChange(arr: [Int]) -> Int {
var count = 0
var arr = arr
for i in 0..<arr.count/2 {
if arr[i] != arr[arr.count-i-1] {
count += 1
if arr[i] == arr[arr.count-i-1] {
count -= 1
}
}
}
return count
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == lst2.count {
return lst1
}
var result = lst1
for i in 0..<lst2.count {
let count1 = lst1.count
let count2 = lst2.count
if count1 > count2 {
result.removeLast()
count1 -= 1
} else {
result.removeFirst()
count2 -= 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] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == lst2.count {
return lst1
}
var result = lst1
for i in 0..<lst2.count {
let count1 = lst1.count
let count2 = lst2.count
if count1 > count2 {
result.removeLast()
count1 -= 1
} else {
result.removeFirst()
count2 -= 1
}
}
return result
}
```
count1 -= 1 // left side of mutating operator isn't mutable: 'count1' is a 'let' constant
count2 -= 1 // left side of mutating operator isn't mutable: 'count2' is a 'let' constant
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let l1 = lst1.joined(separator: "")
let l2 = lst2.joined(separator: "")
if l1.count < l2.count {
return lst1
} else if l1.count > l2.count {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let l1 = lst1.joined(separator: "")
let l2 = lst2.joined(separator: "")
if l1.count < l2.count {
return lst1
} else if l1.count > l2.count {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
var result: [String] = []
var count1 = 0
var count2 = 0
for i in 0..<lst1.count {
count1 += lst1[i].count
}
for i in 0..<lst2.count {
count2 += lst2[i].count
}
if count1 > count2 {
result = lst2
} else if count1 < count2 {
result = lst1
} else {
result = lst1
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
var result: [String] = []
var count1 = 0
var count2 = 0
for i in 0..<lst1.count {
count1 += lst1[i].count
}
for i in 0..<lst2.count {
count2 += lst2[i].count
}
if count1 > count2 {
result = lst2
} else if count1 < count2 {
result = lst1
} else {
result = lst1
}
return result
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == lst2.count {
return lst1
}
var result = lst1
for i in 0..<lst2.count {
if lst1[i].count > lst2[i].count {
result[i] = 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] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == lst2.count {
return lst1
}
var result = lst1
for i in 0..<lst2.count {
if lst1[i].count > lst2[i].count {
result[i] = lst2[i]
}
}
return result
}
```
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let lst1 = lst1.sorted(by: {$0.count < $1.count})
let lst2 = lst2.sorted(by: {$0.count < $1.count})
var result = [String]()
for i in 0..<min(lst1.count, lst2.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] {
let lst1 = lst1.sorted(by: {$0.count < $1.count})
let lst2 = lst2.sorted(by: {$0.count < $1.count})
var result = [String]()
for i in 0..<min(lst1.count, lst2.count) {
if lst1[i].count < lst2[i].count {
result.append(lst1[i])
} else {
result.append(lst2[i])
}
}
return result
}
```
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == lst2.count {
return lst1
}
let first = lst1.count < lst2.count ? lst1 : lst2
let second = lst1.count < lst2.count ? lst2 : lst1
var result = [String]()
for i in 0..<second.count {
let firstChar = first[i]
let secondChar = second[i]
if firstChar.count > secondChar.count {
result.append(secondChar)
} else if firstChar.count < secondChar.count {
result.append(firstChar)
}
}
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] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == lst2.count {
return lst1
}
let first = lst1.count < lst2.count ? lst1 : lst2
let second = lst1.count < lst2.count ? lst2 : lst1
var result = [String]()
for i in 0..<second.count {
let firstChar = first[i]
let secondChar = second[i]
if firstChar.count > secondChar.count {
result.append(secondChar)
} else if firstChar.count < secondChar.count {
result.append(firstChar)
}
}
return result
}
```
// XCTAssertTrue failed
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
let lst1Count = lst1.reduce(0) { $0 + $1.count }
let lst2Count = lst2.reduce(0) { $0 + $1.count }
if lst1Count > lst2Count {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
let lst1Count = lst1.reduce(0) { $0 + $1.count }
let lst2Count = lst2.reduce(0) { $0 + $1.count }
if lst1Count > lst2Count {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let l1 = lst1.reduce(0) { $0 + $1.count }
let l2 = lst2.reduce(0) { $0 + $1.count }
if l1 < l2 {
return lst1
} else if l1 > l2 {
return lst2
} else {
return lst1
}
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
let l1 = lst1.reduce(0) { $0 + $1.count }
let l2 = lst2.reduce(0) { $0 + $1.count }
if l1 < l2 {
return lst1
} else if l1 > l2 {
return lst2
} else {
return lst1
}
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
var result = [String]()
var count1 = 0
var count2 = 0
for i in 0..<lst1.count {
count1 += lst1[i].count
}
for i in 0..<lst2.count {
count2 += lst2[i].count
}
if count1 > count2 {
result = lst2
} else if count1 < count2 {
result = lst1
} else {
result = lst1
}
return result
}
```swift
// Write a function that accepts two arrays of strings and returns the array that has
// total number of chars in the all strings of the array less than the other array.
// if the two arrays have the same number of chars, return the first array.
// Examples
// totalMatch(lst1: [] as [String], lst2: [] as [String]) == [] as [String]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "Hi"]) == ["hI", "Hi"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hi", "hi", "admin", "project"]) == ["hi", "admin"]
// totalMatch(lst1: ["hi", "admin"], lst2: ["hI", "hi", "hi"]) == ["hI", "hi", "hi"]
// totalMatch(lst1: ["4"], lst2: ["1", "2", "3", "4", "5"]) == ["4"]
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
var result = [String]()
var count1 = 0
var count2 = 0
for i in 0..<lst1.count {
count1 += lst1[i].count
}
for i in 0..<lst2.count {
count2 += lst2[i].count
}
if count1 > count2 {
result = lst2
} else if count1 < count2 {
result = lst1
} else {
result = lst1
}
return result
}
```
func totalMatch(lst1: [String], lst2: [String]) -> [String] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == 1 && lst2.count == 1 {
if lst1[0].count < lst2[0].count {
return lst1
} else {
return lst2
}
}
var result = [String]()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i].count() < lst2[j].count() {
result.append(lst1[i])
i += 1
} else {
result.append(lst2[j])
j += 1
}
}
while i < lst1.count {
result.append(lst1[i])
i += 1
}
while j < lst2.count {
result.append(lst2[j])
j += 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] {
if lst1.count == 0 || lst2.count == 0 {
return []
}
if lst1.count == 1 && lst2.count == 1 {
if lst1[0].count < lst2[0].count {
return lst1
} else {
return lst2
}
}
var result = [String]()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i].count() < lst2[j].count() {
result.append(lst1[i])
i += 1
} else {
result.append(lst2[j])
j += 1
}
}
while i < lst1.count {
result.append(lst1[i])
i += 1
}
while j < lst2.count {
result.append(lst2[j])
j += 1
}
return result
}
```
if lst1[i].count() < lst2[j].count() { // cannot call value of non-function type 'Int'
if lst1[i].count() < lst2[j].count() { // cannot call value of non-function type 'Int'
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
var a = a
var b = 0
var c = 0
var d = 0
var e = 0
var f = 0
var g = 0
var h = 0
var i = 0
var j = 0
var k = 0
var l = 0
var m = 0
var n = 0
var o = 0
var p = 0
var q = 0
var r = 0
var s = 0
var t = 0
var u = 0
var v = 0
var w = 0
var x = 0
var y = 0
var z = 0
var aa = 0
var bb = 0
var cc = 0
var dd = 0
var ee = 0
var ff = 0
var gg = 0
var hh = 0
var ii = 0
var jj = 0
var kk = 0
var ll = 0
var mm = 0
var nn = 0
var oo = 0
var pp = 0
var qq = 0
var rr = 0
var ss = 0
var tt = 0
var uu = 0
var vv = 0
var ww = 0
var xx = 0
var yy = 0
var zz = 0
var aaa = 0
var bbb = 0
var ccc = 0
var ddd = 0
var eee = 0
var fff = 0
var ggg = 0
var hhh = 0
var iii = 0
var jjj = 0
var kkk = 0
var lll = 0
var mmm = 0
var nnn = 0
var ooo = 0
var ppp = 0
var qqq = 0
var rrr = 0
var sss = 0
var ttt = 0
var uuu = 0
var vvv = 0
var wwww = 0
var xxxx = 0
var yyyy = 0
var zzzz = 0
var aaaa = 0
var bbbb = 0
var cccc = 0
var dddd = 0
var eeee = 0
var ffff = 0
var gggg = 0
var hhhh = 0
var iiii = 0
var jjjj = 0
var kkkk = 0
var llll = 0
var mmmm = 0
var nnnn = 0
var oooo = 0
var pppp = 0
var qqqq = 0
var rrrr = 0
var ssss = 0
var tttt = 0
var uuuu = 0
var vvvv = 0
var wwwww = 0
var xxxxx = 0
var yyyyy = 0
var zzzzz = 0
var aaaaa = 0
var bbbbb = 0
var ccccc = 0
var ddddd = 0
var eeeee = 0
var fffff = 0
var ggggg = 0
var hhhhh = 0
var iiiiin = 0
var jjjjj = 0
var kkkkk = 0
var lllll = 0
var mmmmm = 0
var nnnnn = 0
var ooooo = 0
var ppppp = 0
var qqqqq = 0
var rrrrr = 0
var sssss = 0
var ttttt = 0
var uuuuu = 0
var vvvv
XCTAssertTrue(isMultiplyPrime(a: 5) == false) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 30) == true) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 8) == true) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 10) == false) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 125) == true) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 105) == true) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 126) == false) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 729) == false) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 891) == false) // cannot find 'isMultiplyPrime' in scope
XCTAssertTrue(isMultiplyPrime(a: 1001) == true) // cannot find 'isMultiplyPrime' in scope
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
return false
}
var num = a
var i = 2
while i * i <= num {
if num % i == 0 {
return false
}
i += 1
}
return true
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
return false
}
var num = a
var i = 2
while i * i <= num {
if num % i == 0 {
return false
}
i += 1
}
return true
}
```
var num = a // variable 'num' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
return false
}
var i = 2
var j = 2
var k = 2
var aa = a
while aa > 1 {
while aa % i == 0 {
aa /= i
j = i
i = 2
}
while aa % j == 0 {
aa /= j
k = j
j = 2
}
i += 1
j += 1
}
return aa == 1 && i == 2 && j == 2
}
```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 {
if a < 100 {
return false
}
var i = 2
var j = 2
var k = 2
var aa = a
while aa > 1 {
while aa % i == 0 {
aa /= i
j = i
i = 2
}
while aa % j == 0 {
aa /= j
k = j
j = 2
}
i += 1
j += 1
}
return aa == 1 && i == 2 && j == 2
}
```
var k = 2 // variable 'k' was written to, but never read
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
return false
}
var i = 2
while i * i <= a {
if a % i == 0 {
return false
}
i += 1
}
return true
}
class Solution {
func isUgly(_ num: Int) -> Bool {
if num <= 0 {
return false
}
var num = num
var factors = [2, 3, 5]
for factor in factors {
while num % factor == 0 {
num = num / factor
}
}
return num == 1
}
}
```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 {
if a < 100 {
return false
}
var i = 2
while i * i <= a {
if a % i == 0 {
return false
}
i += 1
}
return true
}
```
### 解题思路
### 代码
```swift
class Solution {
func isUgly(_ num: Int) -> Bool {
if num <= 0 {
return false
}
var num = num
var factors = [2, 3, 5]
for factor in factors {
while num % factor == 0 {
num = num / factor
}
}
return num == 1
}
}
```
var factors = [2, 3, 5] // variable 'factors' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
var num = a
var count = 0
while count < 3 {
if primes.contains(num % 10) {
num /= 10
} else {
return false
}
count += 1
}
return true
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
var num = a
var count = 0
while count < 3 {
if primes.contains(num % 10) {
num /= 10
} else {
return false
}
count += 1
}
return true
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var a = a
var i = 0
while i < primes.count {
if a % primes[i] == 0 {
a = a / primes[i]
i = 0
} else {
i += 1
}
}
return a == 1
}
```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 a = a
var i = 0
while i < primes.count {
if a % primes[i] == 0 {
a = a / primes[i]
i = 0
} else {
i += 1
}
}
return a == 1
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
return false
}
var num = a
var i = 2
var isMultiply = false
while i * i <= num {
if num % i == 0 {
num /= i
isMultiply = true
} else {
i += 1
}
}
return isMultiply
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
if a < 100 {
return false
}
var num = a
var i = 2
var isMultiply = false
while i * i <= num {
if num % i == 0 {
num /= i
isMultiply = true
} else {
i += 1
}
}
return isMultiply
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
// write your code here
return false
}
```swift
// Write a function that returns true if the given number is the multiplication of 3 prime numbers
// and false otherwise.
// Knowing that (a) is less then 100.
// Example:
// 30 = 2 * 3 * 5
// isMultiplyPrime(a: 30) == true
func isMultiplyPrime(a: Int) -> Bool {
// write your code here
return false
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
var num = a
var count = 0
while count < 9 {
if primes.contains(num) {
count += 1
} else {
break
}
num /= 10
}
return count == 9
}
```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 num = a
var count = 0
while count < 9 {
if primes.contains(num) {
count += 1
} else {
break
}
num /= 10
}
return count == 9
}
```
// XCTAssertTrue failed
func isMultiplyPrime(a: Int) -> Bool {
let primes = [2, 3, 5]
var num = a
var i = 0
while i < primes.count {
if num % primes[i] == 0 {
num /= primes[i]
} else {
i -= 1
}
i += 1
}
return num == 1
}
```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]
var num = a
var i = 0
while i < primes.count {
if num % primes[i] == 0 {
num /= primes[i]
} else {
i -= 1
}
i += 1
}
return num == 1
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == n {
return true
}
if x % n != 0 {
return false
}
return isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == n {
return true
}
if x % n != 0 {
return false
}
return isSimplePower(x: x / n, n: n)
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else {
return false
}
guard x != 1 else {
return true
}
guard x % n == 0 else {
return false
}
guard x / n != 1 else {
return true
}
return isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else {
return false
}
guard x != 1 else {
return true
}
guard x % n == 0 else {
return false
}
guard x / n != 1 else {
return true
}
return isSimplePower(x: x / n, n: n)
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == 0 {
return false
}
if n == 1 {
return true
}
if n == 0 {
return false
}
if x % n != 0 {
return false
}
return isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
if x == 1 {
return true
}
if x == 0 {
return false
}
if n == 1 {
return true
}
if n == 0 {
return false
}
if x % n != 0 {
return false
}
return isSimplePower(x: x / n, n: n)
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0 else {
return false
}
guard n > 0 else {
return false
}
var temp = x
var count = 0
while temp != 1 {
if temp % n == 0 {
temp /= n
} else {
return false
}
count += 1
}
return count == 1
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0 else {
return false
}
guard n > 0 else {
return false
}
var temp = x
var count = 0
while temp != 1 {
if temp % n == 0 {
temp /= n
} else {
return false
}
count += 1
}
return count == 1
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
var temp = x
var count = 0
while temp > 1 {
if temp % n == 0 {
temp /= n
} else {
return false
}
count += 1
}
return count == 1
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
var temp = x
var count = 0
while temp > 1 {
if temp % n == 0 {
temp /= n
} else {
return false
}
count += 1
}
return count == 1
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0 else {
return false
}
guard n > 0 else {
return false
}
guard x % n == 0 else {
return false
}
return x / n == n
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0 else {
return false
}
guard n > 0 else {
return false
}
guard x % n == 0 else {
return false
}
return x / n == n
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else {
return true
}
guard x > 0 else {
return false
}
guard n > 0 else {
return false
}
guard x % n == 0 else {
return false
}
var temp = n
while temp < x {
temp *= n
}
return temp == x
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else {
return true
}
guard x > 0 else {
return false
}
guard n > 0 else {
return false
}
guard x % n == 0 else {
return false
}
var temp = n
while temp < x {
temp *= n
}
return temp == x
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else { return true }
guard x != 1 else { return true }
guard n != 1 else { return false }
guard x % n == 0 else { return false }
guard x / n != 1 else { return true }
return isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else { return true }
guard x != 1 else { return true }
guard n != 1 else { return false }
guard x % n == 0 else { return false }
guard x / n != 1 else { return true }
return isSimplePower(x: x / n, n: n)
}
```
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else {
return true
}
guard x != 1 else {
return n == 1
}
guard x % n == 0 else {
return false
}
return isSimplePower(x: x / n, n: n)
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x != 0 else {
return true
}
guard x != 1 else {
return n == 1
}
guard x % n == 0 else {
return false
}
return isSimplePower(x: x / n, n: n)
}
```
// XCTAssertTrue failed
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0, n > 0 else {
return false
}
var temp = x
var count = 0
while temp % n == 0 {
temp /= n
count += 1
}
return count == 1
}
```swift
// Your task is to write a function that returns true if a number x is a simple
// power of n and false in other cases.
// x is a simple power of n if n**int=x
// For example:
// isSimplePower(x: 1, n: 4) == true
// isSimplePower(x: 2, n: 2) == true
// isSimplePower(x: 8, n: 2) == true
// isSimplePower(x: 3, n: 2) == false
// isSimplePower(x: 3, n: 1) == false
// isSimplePower(x: 5, n: 3) == false
func isSimplePower(x: Int, n: Int) -> Bool {
guard x > 0, n > 0 else {
return false
}
var temp = x
var count = 0
while temp % n == 0 {
temp /= n
count += 1
}
return count == 1
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
let a = abs(a)
let n = Int(sqrt(Double(a)))
return n * n * n == a
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let a = abs(a)
let n = Int(sqrt(Double(a)))
return n * n * n == a
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
if a == 0 {
return true
}
let n = Int(pow(Double(a), 1.0 / 3))
return n * n * n == 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 true
}
let n = Int(pow(Double(a), 1.0 / 3))
return n * n * n == a
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
let a = abs(a)
let n = Int(sqrt(Double(a)))
return a == n * n * n
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let a = abs(a)
let n = Int(sqrt(Double(a)))
return a == n * n * n
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
let n = Int(pow(Double(a), 1.0 / 3))
return a == Int(pow(Double(n), 3))
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let n = Int(pow(Double(a), 1.0 / 3))
return a == Int(pow(Double(n), 3))
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
let n = Int(pow(Double(a), 1.0/3.0))
return a == Int(pow(Double(n), 3))
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let n = Int(pow(Double(a), 1.0/3.0))
return a == Int(pow(Double(n), 3))
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
if a == 0 {
return true
}
let sqrt = sqrt(a)
let sqrtInt = Int(sqrt)
if sqrtInt * sqrtInt * sqrtInt == a {
return true
}
return false
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
if a == 0 {
return true
}
let sqrt = sqrt(a)
let sqrtInt = Int(sqrt)
if sqrtInt * sqrtInt * sqrtInt == a {
return true
}
return false
}
```
let sqrt = sqrt(a) // cannot convert value of type 'Int' to expected argument type 'Double'
func iscube(a: Int) -> Bool {
let n = a
let cube = n * n * n
let sqrt = Int(sqrt(Double(cube)))
return sqrt * sqrt * sqrt == cube
}
```swift
// Write a function that takes an integer a and returns true
// if this ingeger is a cube of some integer number.
// Note: you may assume the input is always valid.
// Examples:
// iscube(a: 1) == true
// iscube(a: 2) == false
// iscube(a: -1) == true
// iscube(a: 64) == true
// iscube(a: 0) == true
// iscube(a: 180) == false
func iscube(a: Int) -> Bool {
let n = a
let cube = n * n * n
let sqrt = Int(sqrt(Double(cube)))
return sqrt * sqrt * sqrt == cube
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
if a < 0 {
return iscube(a: -a)
}
var a = a
var b = 0
while a > 0 {
b += a % 10
a /= 10
}
return b == 0 || b == 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 {
if a < 0 {
return iscube(a: -a)
}
var a = a
var b = 0
while a > 0 {
b += a % 10
a /= 10
}
return b == 0 || b == 1
}
```
// XCTAssertTrue failed
func iscube(a: Int) -> Bool {
if a == 0 {
return true
}
let n = Int(pow(Double(a), 1.0/3))
return n * n * n == 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 true
}
let n = Int(pow(Double(a), 1.0/3))
return n * n * n == a
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func iscube(a: Int) -> Bool {
if a == 0 {
return true
}
let n = Int(pow(Double(a), 1.0/3))
return a == n * n * n
}
```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 true
}
let n = Int(pow(Double(a), 1.0/3))
return a == n * n * n
}
```
// Fatal error: Double value cannot be converted to Int because it is either infinite or NaN
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(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 {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(c) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(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 {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(c) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(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 {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(c) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
var result = 0
for c in num {
let n = Int(String(c))!
if n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 {
result += 1
}
}
return result
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var result = 0
for c in num {
let n = Int(String(c))!
if n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 {
result += 1
}
}
return result
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(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 {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(c) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(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 {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(c) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(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 {
let hex = "0123456789ABCDEF"
var count = 0
for c in num {
if hex.contains(c) {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func hexKey(num: String) -> Int {
let hexDigits = ["2", "3", "5", "7", "B", "D"]
var count = 0
for char in num {
if hexDigits.contains(String(char)) {
count += 1
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
let hexDigits = ["2", "3", "5", "7", "B", "D"]
var count = 0
for char in num {
if hexDigits.contains(String(char)) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
let hexDigits = ["2", "3", "5", "7", "B", "D"]
var count = 0
for c in num {
if hexDigits.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 {
let hexDigits = ["2", "3", "5", "7", "B", "D"]
var count = 0
for c in num {
if hexDigits.contains(String(c)) {
count += 1
}
}
return count
}
```
func hexKey(num: String) -> Int {
var count = 0
let hex = "0123456789ABCDEF"
for c in num {
if hex.contains(c) {
if hex.index(of: c)! % 2 == 0 {
count += 1
}
}
}
return count
}
```swift
// You have been tasked to write a function that receives
// a hexadecimal number as a string and counts the number of hexadecimal
// digits that are primes (prime number, or a prime, is a natural number
// greater than 1 that is not a product of two smaller natural numbers).
// Hexadecimal digits are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F.
// Prime numbers are 2, 3, 5, 7, 11, 13, 17,...
// So you have to determine a number of the following digits: 2, 3, 5, 7,
// B (=decimal 11), D (=decimal 13).
// Note: you may assume the input is always correct or empty string,
// and symbols A,B,C,D,E,F are always uppercase.
// Examples:
// hexKey(num: "AB") == 1
// hexKey(num: "1077E") == 2
// hexKey(num: "ABED1A33") == 4
// hexKey(num: "123456789ABCDEF0") == 6
// hexKey(num: "2020") == 2
func hexKey(num: String) -> Int {
var count = 0
let hex = "0123456789ABCDEF"
for c in num {
if hex.contains(c) {
if hex.index(of: c)! % 2 == 0 {
count += 1
}
}
}
return count
}
```
if hex.index(of: c)! % 2 == 0 { // cannot convert value of type 'String.Index' to expected argument type 'Int'
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var decimal = decimal
while decimal > 0 {
result.insert("db", at: result.startIndex)
result.append(String(decimal % 2))
decimal /= 2
}
return String(result.reversed())
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var result = ""
var decimal = decimal
while decimal > 0 {
result.insert("db", at: result.startIndex)
result.append(String(decimal % 2))
decimal /= 2
}
return String(result.reversed())
}
```
result.insert("db", at: result.startIndex) // no exact matches in call to instance method 'insert'
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
let db = "db"
return db + binary + db
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
let binary = String(decimal, radix: 2)
let db = "db"
return db + binary + db
}
```
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal & 1) + binary
decimal >>= 1
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal & 1) + binary
decimal >>= 1
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var n = decimal
while n > 0 {
result.insert("1", at: result.startIndex)
n = n >> 1
}
result.insert("0", at: result.startIndex)
return "db" + String(result) + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var result = ""
var n = decimal
while n > 0 {
result.insert("1", at: result.startIndex)
n = n >> 1
}
result.insert("0", at: result.startIndex)
return "db" + String(result) + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var n = decimal
while n > 0 {
binary.insert("1", at: binary.startIndex)
n = n >> 1
}
binary.insert("0", at: binary.startIndex)
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 n = decimal
while n > 0 {
binary.insert("1", at: binary.startIndex)
n = n >> 1
}
binary.insert("0", at: binary.startIndex)
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var result = ""
var n = decimal
while n > 0 {
result.insert("1", at: result.startIndex)
n = n >> 1
}
result.insert("0", at: result.startIndex)
return "db" + result + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var result = ""
var n = decimal
while n > 0 {
result.insert("1", at: result.startIndex)
n = n >> 1
}
result.insert("0", at: result.startIndex)
return "db" + result + "db"
}
```
// XCTAssertTrue failed
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```swift
// You will be given a number in decimal form and your task is to convert it to
// binary format. The function should return a string, with each character representing a binary
// number. Each character in the string will be '0' or '1'.
// There will be an extra couple of characters 'db' at the beginning and at the end of the string.
// The extra characters are there to help with the format.
// Examples:
// decimalToBinary(decimal: 15) == "db1111db"
// decimalToBinary(decimal: 32) == "db100000db"
func decimalToBinary(decimal: Int) -> String {
var binary = ""
var decimal = decimal
while decimal > 0 {
binary = String(decimal % 2) + binary
decimal /= 2
}
return "db" + binary + "db"
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var str = s
var dict = [Character: Int]()
while !isHappy(str: &str) {
if dict[str.first!] != nil {
return false
}
dict[str.first!] = 1
str = String(str.dropFirst())
}
return true
}
func isHappy(str: inout String) -> Bool {
var str = str
var dict = [Character: Int]()
while !isHappy(str: &str) {
if dict[str.first!] != nil {
return false
}
dict[str.first!] = 1
str = String(str.dropFirst())
}
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 str = s
var dict = [Character: Int]()
while !isHappy(str: &str) {
if dict[str.first!] != nil {
return false
}
dict[str.first!] = 1
str = String(str.dropFirst())
}
return true
}
func isHappy(str: inout String) -> Bool {
var str = str
var dict = [Character: Int]()
while !isHappy(str: &str) {
if dict[str.first!] != nil {
return false
}
dict[str.first!] = 1
str = String(str.dropFirst())
}
return true
}
func isHappy(str: inout String) -> Bool {
var str = str
var dict = [Character: Int]()
while !isHappy(str: &str) {
if dict[str.first!] != nil {
return false
}
dict[str.first!] = 1
str = String(str.dropFirst())
}
return true
}
```
while !isHappy(str: &str) { // function call causes an infinite recursion
func isHappy(s: String) -> Bool {
var str = s
var set = Set<Character>()
while !isHappy(str: &str) {
if str.count < 3 {
return false
}
for c in str {
if set.contains(c) {
return false
}
set.insert(c)
}
str = String(str.dropFirst())
}
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 str = s
var set = Set<Character>()
while !isHappy(str: &str) {
if str.count < 3 {
return false
}
for c in str {
if set.contains(c) {
return false
}
set.insert(c)
}
str = String(str.dropFirst())
}
return true
}
```
while !isHappy(str: &str) { // '&' used with non-inout argument of type 'String'
while !isHappy(str: &str) { // incorrect argument label in call (have 'str:', expected 's:')
func isHappy(s: String) -> Bool {
var s = s
var result = 0
while s.count > 0 {
let c = s.removeFirst()
result += Int(c.asciiValue!) - 48
if s.count > 0 {
let c1 = s.removeFirst()
result += Int(c1.asciiValue!) - 48
if s.count > 0 {
let c2 = s.removeFirst()
result += Int(c2.asciiValue!) - 48
s.insert(c2, at: 0)
s.insert(c1, at: 0)
}
}
s.insert(c, at: 0)
}
var result2 = result
while result2 > 0 {
let c = result2 % 10
result2 /= 10
if result2 == 0 {
return c == 1
}
result2 += c * c
}
return false
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var s = s
var result = 0
while s.count > 0 {
let c = s.removeFirst()
result += Int(c.asciiValue!) - 48
if s.count > 0 {
let c1 = s.removeFirst()
result += Int(c1.asciiValue!) - 48
if s.count > 0 {
let c2 = s.removeFirst()
result += Int(c2.asciiValue!) - 48
s.insert(c2, at: 0)
s.insert(c1, at: 0)
}
}
s.insert(c, at: 0)
}
var result2 = result
while result2 > 0 {
let c = result2 % 10
result2 /= 10
if result2 == 0 {
return c == 1
}
result2 += c * c
}
return false
}
```
s.insert(c2, at: 0) // cannot convert value of type 'Int' to expected argument type 'String.Index'
s.insert(c1, at: 0) // cannot convert value of type 'Int' to expected argument type 'String.Index'
s.insert(c, at: 0) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func isHappy(s: String) -> Bool {
let chars = Array(s)
var set = Set<Character>()
var sum = 0
for i in 0..<chars.count {
let char = chars[i]
if set.contains(char) {
return false
}
set.insert(char)
sum += Int(char.asciiValue!)!
}
while sum != 1 {
var temp = sum
var sum = 0
while temp > 0 {
sum += Int(String(temp%10))!
temp /= 10
}
if sum == 4 {
return false
}
if sum == 1 {
return true
}
}
return false
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
var set = Set<Character>()
var sum = 0
for i in 0..<chars.count {
let char = chars[i]
if set.contains(char) {
return false
}
set.insert(char)
sum += Int(char.asciiValue!)!
}
while sum != 1 {
var temp = sum
var sum = 0
while temp > 0 {
sum += Int(String(temp%10))!
temp /= 10
}
if sum == 4 {
return false
}
if sum == 1 {
return true
}
}
return false
}
```
sum += Int(char.asciiValue!)! // missing argument label 'exactly:' in call
func isHappy(s: String) -> Bool {
var dict = [Character: Int]()
var result = 0
for c in s {
if dict[c] != nil {
result += dict[c]!
} else {
dict[c] = 1
}
}
return result == 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 dict = [Character: Int]()
var result = 0
for c in s {
if dict[c] != nil {
result += dict[c]!
} else {
dict[c] = 1
}
}
return result == 1
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var chars = [Character]()
for char in s {
chars.append(char)
}
var prev = chars
var curr = chars
for _ in 0..<2 {
curr = [Character]()
for i in 0..<prev.count {
let char = prev[i]
var count = 0
for j in i..<prev.count {
if prev[j] == char {
count += 1
}
}
if count == 0 {
curr.append(char)
}
}
prev = curr
}
return prev.count >= 3 && prev.count == curr.count
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var chars = [Character]()
for char in s {
chars.append(char)
}
var prev = chars
var curr = chars
for _ in 0..<2 {
curr = [Character]()
for i in 0..<prev.count {
let char = prev[i]
var count = 0
for j in i..<prev.count {
if prev[j] == char {
count += 1
}
}
if count == 0 {
curr.append(char)
}
}
prev = curr
}
return prev.count >= 3 && prev.count == curr.count
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var s = s
s = s.replacingOccurrences(of: " ", with: "")
var arr = Array(s)
var map = [Character: Int]()
for i in 0..<arr.count {
if map[arr[i]] != nil {
return false
}
map[arr[i]] = i
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var s = s
s = s.replacingOccurrences(of: " ", with: "")
var arr = Array(s)
var map = [Character: Int]()
for i in 0..<arr.count {
if map[arr[i]] != nil {
return false
}
map[arr[i]] = i
}
return true
}
```
var arr = Array(s) // variable 'arr' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var set = Set<Character>()
var str = s
while str.count >= 3 {
let count = str.count
var temp = ""
for i in 0..<count {
let c = str[str.index(str.startIndex, offsetBy: i)]
if !set.contains(c) {
temp.append(c)
set.insert(c)
}
}
str = temp
}
return str.count >= 3
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
var set = Set<Character>()
var str = s
while str.count >= 3 {
let count = str.count
var temp = ""
for i in 0..<count {
let c = str[str.index(str.startIndex, offsetBy: i)]
if !set.contains(c) {
temp.append(c)
set.insert(c)
}
}
str = temp
}
return str.count >= 3
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
let chars = Array(s)
var seen = Set<Character>()
var cur = 0
while cur < chars.count {
let c = chars[cur]
if seen.contains(c) {
return false
}
seen.insert(c)
cur += 1
}
return true
}
```swift
// You are given a string s.
// Your task is to check if the string is hapswift or not.
// A string is hapswift if its length is at least 3 and every 3 consecutive letters are distinct
// For example:
// isHappy(s: "a") == false
// isHappy(s: "aa") == false
// isHappy(s: "abcd") == true
// isHappy(s: "aabb") == false
// isHappy(s: "adb") == true
// isHappy(s: "xyy") == false
func isHappy(s: String) -> Bool {
let chars = Array(s)
var seen = Set<Character>()
var cur = 0
while cur < chars.count {
let c = chars[cur]
if seen.contains(c) {
return false
}
seen.insert(c)
cur += 1
}
return true
}
```
// XCTAssertTrue failed
func isHappy(s: String) -> Bool {
var str = s
var result = true
var temp = ""
while result {
for char in str {
temp.append(char)
}
str = temp
temp = ""
var count = 0
for char in str {
if count == 0 {
count += 1
continue
}
if char == str[str.index(str.startIndex, offsetBy: count - 1)] {
result = false
break
}
count += 1
}
}
return result
}
```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 str = s
var result = true
var temp = ""
while result {
for char in str {
temp.append(char)
}
str = temp
temp = ""
var count = 0
for char in str {
if count == 0 {
count += 1
continue
}
if char == str[str.index(str.startIndex, offsetBy: count - 1)] {
result = false
break
}
count += 1
}
}
return result
}
```
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for gpa in grades {
if gpa >= 4.0 {
result.append("A+")
} else if gpa >= 3.7 {
result.append("A")
} else if gpa >= 3.3 {
result.append("A-")
} else if gpa >= 3.0 {
result.append("B+")
} else if gpa >= 2.7 {
result.append("B")
} else if gpa >= 2.3 {
result.append("B-")
} else if gpa >= 2.0 {
result.append("C+")
} else if gpa >= 1.7 {
result.append("C")
} else if gpa >= 1.3 {
result.append("C-")
} else if gpa >= 1.0 {
result.append("D+")
} else if gpa >= 0.7 {
result.append("D")
} else if gpa >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for gpa in grades {
if gpa >= 4.0 {
result.append("A+")
} else if gpa >= 3.7 {
result.append("A")
} else if gpa >= 3.3 {
result.append("A-")
} else if gpa >= 3.0 {
result.append("B+")
} else if gpa >= 2.7 {
result.append("B")
} else if gpa >= 2.3 {
result.append("B-")
} else if gpa >= 2.0 {
result.append("C+")
} else if gpa >= 1.7 {
result.append("C")
} else if gpa >= 1.3 {
result.append("C-")
} else if gpa >= 1.0 {
result.append("D+")
} else if gpa >= 0.7 {
result.append("D")
} else if gpa >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
let letterGrades = ["A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E"]
var result = [String]()
for i in 0..<grades.count {
let grade = grades[i]
let index = letterGrades.index(of: "E")!
for j in 0..<letterGrades.count {
if letterGrades[j] == "E" {
break
}
if grade >= Double(j) / 10.0 && grade < Double(j + 1) / 10.0 {
result.append(letterGrades[j])
break
}
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
let letterGrades = ["A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D+", "D", "D-", "E"]
var result = [String]()
for i in 0..<grades.count {
let grade = grades[i]
let index = letterGrades.index(of: "E")!
for j in 0..<letterGrades.count {
if letterGrades[j] == "E" {
break
}
if grade >= Double(j) / 10.0 && grade < Double(j + 1) / 10.0 {
result.append(letterGrades[j])
break
}
}
}
return result
}
```
let index = letterGrades.index(of: "E")! // initialization of immutable value 'index' was never used; consider replacing with assignment to '_' or removing it
let index = letterGrades.index(of: "E")! // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.3 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.3 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.3 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.3 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
let letterGrades = [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"]
var result = [String]()
for grade in grades {
for key in letterGrades.keys {
if grade >= key {
result.append(letterGrades[key]!)
break
}
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
let letterGrades = [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"]
var result = [String]()
for grade in grades {
for key in letterGrades.keys {
if grade >= key {
result.append(letterGrades[key]!)
break
}
}
}
return result
}
```
let letterGrades = [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"] // dictionary literal of type '[Double : String]' has duplicate entries for floating-point literal key '0.0'
// Fatal error: Dictionary literal contains duplicate keys
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for gpa in grades {
switch gpa {
case 4.0:
result.append("A+")
case 3.7:
result.append("A")
case 3.3:
result.append("A-")
case 3.0:
result.append("B+")
case 2.7:
result.append("B")
case 2.3:
result.append("B-")
case 2.0:
result.append("C+")
case 1.7:
result.append("C")
case 1.3:
result.append("C-")
case 1.0:
result.append("D+")
case 0.7:
result.append("D")
case 0.3:
result.append("D-")
case 0.0:
result.append("E")
default:
break
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
let grades = grades.sorted()
var result = [String]()
for gpa in grades {
switch gpa {
case 4.0:
result.append("A+")
case 3.7:
result.append("A")
case 3.3:
result.append("A-")
case 3.0:
result.append("B+")
case 2.7:
result.append("B")
case 2.3:
result.append("B-")
case 2.0:
result.append("C+")
case 1.7:
result.append("C")
case 1.3:
result.append("C-")
case 1.0:
result.append("D+")
case 0.7:
result.append("D")
case 0.3:
result.append("D-")
case 0.0:
result.append("E")
default:
break
}
}
return result
}
```
// XCTAssertTrue failed
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```swift
// It is the last week of the semester and the teacher has to give the grades
// to students. The teacher has been making her own algorithm for grading.
// The only problem is, she has lost the code she used for grading.
// She has given you an array of GPAs for some students and you have to write
// a function that can output an array of letter grades using the following table:
// GPA | Letter grade
// 4.0 A+
// > 3.7 A
// > 3.3 A-
// > 3.0 B+
// > 2.7 B
// > 2.3 B-
// > 2.0 C+
// > 1.7 C
// > 1.3 C-
// > 1.0 D+
// > 0.7 D
// > 0.0 D-
// 0.0 E
// Example:
// numericalLetterGrade(grades: [4.0, 3, 1.7, 2, 3.5]) == ["A+", "B", "C-", "C", "A-"]
func numericalLetterGrade(grades: [Double]) -> [String] {
var result = [String]()
for grade in grades {
if grade >= 4.0 {
result.append("A+")
} else if grade >= 3.7 {
result.append("A")
} else if grade >= 3.3 {
result.append("A-")
} else if grade >= 3.0 {
result.append("B+")
} else if grade >= 2.7 {
result.append("B")
} else if grade >= 2.3 {
result.append("B-")
} else if grade >= 2.0 {
result.append("C+")
} else if grade >= 1.7 {
result.append("C")
} else if grade >= 1.3 {
result.append("C-")
} else if grade >= 1.0 {
result.append("D+")
} else if grade >= 0.7 {
result.append("D")
} else if grade >= 0.0 {
result.append("D-")
} else {
result.append("E")
}
}
return result
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return true
}
let firstChar = string.first!
let restString = string.substring(from: 1)
let restChar = restString.first!
if firstChar == restChar {
return primeLength(string: restString)
} else {
return primeLength(string: restString) && primeLength(string: string)
}
}
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return true
}
let firstChar = string.first!
let restString = string.substring(from: 1)
let restChar = restString.first!
if firstChar == restChar {
return primeLength(string: restString)
} else {
let restLength = restString.count
let restFirstChar = restString.first!
let restRestString = restString.substring(from: 1)
let restRestChar = restRestString.first!
if restFirstChar == restRestChar {
return primeLength(string: restRestString) && primeLength(string: string)
} else {
return primeLength(string: restString) && primeLength(string: string)
}
}
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return true
}
let firstChar = string.first!
let restString = string.substring(from: 1)
let restChar = restString.first!
if firstChar == restChar {
return primeLength(string: restString)
} else {
return primeLength(string: restString) && primeLength(string: string)
}
}
```
### 解法二
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let length = string.count
if length == 1 {
return true
}
let firstChar = string.first!
let restString = string.substring(from: 1)
let restChar = restString.first!
if firstChar == restChar {
return primeLength(string: restString)
} else {
let restLength = restString.count
let restFirstChar = restString.first!
let restRestString = restString.substring(from: 1)
let restRestChar = restRestString.first!
if restFirstChar == restRestChar {
return primeLength(string: restRestString) && primeLength(string: string)
} else {
return primeLength(string: restString) && primeLength(string: string)
}
}
}
```
let restString = string.substring(from: 1) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func primeLength(string: String) -> Bool { // invalid redeclaration of 'primeLength(string:)'
let restString = string.substring(from: 1) // cannot convert value of type 'Int' to expected argument type 'String.Index'
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
if count == 3 {
return string.contains("1") || string.contains("0") || string.contains("2")
}
if count == 4 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4")
}
if count == 5 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5")
}
if count == 6 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6")
}
if count == 7 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7")
}
if count == 8 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8")
}
if count == 9 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8") || string.contains("9")
}
return false
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
if count == 3 {
return string.contains("1") || string.contains("0") || string.contains("2")
}
if count == 4 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4")
}
if count == 5 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5")
}
if count == 6 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6")
}
if count == 7 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7")
}
if count == 8 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8")
}
if count == 9 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8") || string.contains("9")
}
return false
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") ? false : true
}
if count == 3 {
return string.contains("01") ? false : true
}
let str = Array(string)
for i in 2..<count {
if str[i] == "0" {
continue
}
if str[i] == "1" {
return false
}
if str[i] == "2" {
if count % 2 == 0 {
return false
}
continue
}
let start = i
var j = 2
while j * j <= i {
if i % j == 0 {
return false
}
j += 1
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") ? false : true
}
if count == 3 {
return string.contains("01") ? false : true
}
let str = Array(string)
for i in 2..<count {
if str[i] == "0" {
continue
}
if str[i] == "1" {
return false
}
if str[i] == "2" {
if count % 2 == 0 {
return false
}
continue
}
let start = i
var j = 2
while j * j <= i {
if i % j == 0 {
return false
}
j += 1
}
}
return true
}
```
let start = i // initialization of immutable value 'start' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
if count == 3 {
return string.contains("1") || string.contains("0") || string.contains("2")
}
if count == 4 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4")
}
if count == 5 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5")
}
if count == 6 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6")
}
if count == 7 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7")
}
if count == 8 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8")
}
if count == 9 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8") || string.contains("9")
}
return false
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
if count == 3 {
return string.contains("1") || string.contains("0") || string.contains("2")
}
if count == 4 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4")
}
if count == 5 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5")
}
if count == 6 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6")
}
if count == 7 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7")
}
if count == 8 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8")
}
if count == 9 {
return string.contains("1") || string.contains("0") || string.contains("2") || string.contains("4") || string.contains("5") || string.contains("6") || string.contains("7") || string.contains("8") || string.contains("9")
}
return false
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let stringArray = Array(string)
let count = stringArray.count
if count == 1 {
return true
}
if count == 2 {
return stringArray[0] != stringArray[1]
}
if count == 3 {
return stringArray[0] != stringArray[1] && stringArray[1] != stringArray[2] && stringArray[0] != stringArray[2]
}
for i in 2..<count {
if stringArray[i] == stringArray[0] {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let stringArray = Array(string)
let count = stringArray.count
if count == 1 {
return true
}
if count == 2 {
return stringArray[0] != stringArray[1]
}
if count == 3 {
return stringArray[0] != stringArray[1] && stringArray[1] != stringArray[2] && stringArray[0] != stringArray[2]
}
for i in 2..<count {
if stringArray[i] == stringArray[0] {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
for i in 3..<count {
if count % i == 0 {
return false
}
}
return true
}
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
let num = Int(pow(Double(count), 0.5))
for i in 3..<num {
if count % i == 0 {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
for i in 3..<count {
if count % i == 0 {
return false
}
}
return true
}
```
### 解法二
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
for i in 3..<count {
if count % i == 0 {
return false
}
}
return true
}
```
### 解法三
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
let num = Int(pow(Double(count), 0.5))
for i in 3..<num {
if count % i == 0 {
return false
}
}
return true
}
```
### 解法四
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
let num = Int(pow(Double(count), 0.5))
for i in 3..<num {
if count % i == 0 {
return false
}
}
return true
}
```
### 解法五
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 || count == 0 {
return false
}
if count == 2 {
return true
}
if count % 2 == 0 {
return false
}
let num = Int(pow(Double(count), 0.5))
for i in 3..<num {
if count % i == 0 {
return false
}
}
return true
}
```
### 解法六
```swift
// Write a function that takes a string and returns true if the string
func primeLength(string: String) -> Bool { // invalid redeclaration of 'primeLength(string:)'
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") ? false : true
}
let array = Array(string)
for i in 2..<count {
if array[i] == "1" {
return false
}
if array[i] == "0" {
continue
}
if array[i] == "2" {
continue
}
if array[i] == "3" {
continue
}
if array[i] == "4" {
continue
}
if array[i] == "5" {
continue
}
if array[i] == "6" {
continue
}
if array[i] == "7" {
continue
}
if array[i] == "8" {
continue
}
if array[i] == "9" {
continue
}
if array[i] == "a" {
continue
}
if array[i] == "b" {
continue
}
if array[i] == "c" {
continue
}
if array[i] == "d" {
continue
}
if array[i] == "e" {
continue
}
if array[i] == "f" {
continue
}
if array[i] == "g" {
continue
}
if array[i] == "h" {
continue
}
if array[i] == "i" {
continue
}
if array[i] == "j" {
continue
}
if array[i] == "k" {
continue
}
if array[i] == "l" {
continue
}
if array[i] == "m" {
continue
}
if array[i] == "n" {
continue
}
if array[i] == "o" {
continue
}
if array[i] == "p" {
continue
}
if array[i] == "q" {
continue
}
if array[i] == "r" {
continue
}
if array[i] == "s" {
continue
}
if array[i] == "t" {
continue
}
if array[i] == "u" {
continue
}
if array[i] == "v" {
continue
}
if array[i] == "w" {
continue
}
if array[i] == "x" {
continue
}
if array[i] == "y" {
continue
}
if array[i] == "z" {
continue
}
return false
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") ? false : true
}
let array = Array(string)
for i in 2..<count {
if array[i] == "1" {
return false
}
if array[i] == "0" {
continue
}
if array[i] == "2" {
continue
}
if array[i] == "3" {
continue
}
if array[i] == "4" {
continue
}
if array[i] == "5" {
continue
}
if array[i] == "6" {
continue
}
if array[i] == "7" {
continue
}
if array[i] == "8" {
continue
}
if array[i] == "9" {
continue
}
if array[i] == "a" {
continue
}
if array[i] == "b" {
continue
}
if array[i] == "c" {
continue
}
if array[i] == "d" {
continue
}
if array[i] == "e" {
continue
}
if array[i] == "f" {
continue
}
if array[i] == "g" {
continue
}
if array[i] == "h" {
continue
}
if array[i] == "i" {
continue
}
if array[i] == "j" {
continue
}
if array[i] == "k" {
continue
}
if array[i] == "l" {
continue
}
if array[i] == "m" {
continue
}
if array[i] == "n" {
continue
}
if array[i] == "o" {
continue
}
if array[i] == "p" {
continue
}
if array[i] == "q" {
continue
}
if array[i] == "r" {
continue
}
if array[i] == "s" {
continue
}
if array[i] == "t" {
continue
}
if array[i] == "u" {
continue
}
if array[i] == "v" {
continue
}
if array[i] == "w" {
continue
}
if array[i] == "x" {
continue
}
if array[i] == "y" {
continue
}
if array[i] == "z" {
continue
}
return false
}
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let stringArray = Array(string)
let stringLength = stringArray.count
if stringLength == 1 {
return true
}
if stringLength == 2 {
return stringArray[0] != stringArray[1]
}
if stringLength == 3 {
return stringArray[0] != stringArray[1] && stringArray[1] != stringArray[2] && stringArray[0] != stringArray[2]
}
for i in 2..<stringLength {
if stringArray[i] == stringArray[i - 1] {
return false
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let stringArray = Array(string)
let stringLength = stringArray.count
if stringLength == 1 {
return true
}
if stringLength == 2 {
return stringArray[0] != stringArray[1]
}
if stringLength == 3 {
return stringArray[0] != stringArray[1] && stringArray[1] != stringArray[2] && stringArray[0] != stringArray[2]
}
for i in 2..<stringLength {
if stringArray[i] == stringArray[i - 1] {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
let str = Array(string)
for i in 2..<count {
if str[i] == "1" || str[i] == "0" {
continue
}
var j = i + 1
while j < count {
if str[j] == "1" || str[j] == "0" {
j += 1
continue
}
if str[i] == str[j] {
return false
}
j += 1
}
}
return true
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
let str = Array(string)
for i in 2..<count {
if str[i] == "1" || str[i] == "0" {
continue
}
var j = i + 1
while j < count {
if str[j] == "1" || str[j] == "0" {
j += 1
continue
}
if str[i] == str[j] {
return false
}
j += 1
}
}
return true
}
```
// XCTAssertTrue failed
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
let array = Array(string)
for i in 2..<count {
if array[i] == "0" || array[i] == "1" {
continue
}
var j = 2
while j < i {
if i % j == 0 {
break
}
j += 1
}
if j == i {
return true
}
}
return false
}
```swift
// Write a function that takes a string and returns true if the string
// length is a prime number or false otherwise
// Examples
// primeLength(string: "Hello") == true
// primeLength(string: "abcdcba") == true
// primeLength(string: "kittens") == true
// primeLength(string: "orange") == false
func primeLength(string: String) -> Bool {
let count = string.count
if count == 1 {
return true
}
if count == 2 {
return string.contains("1") || string.contains("0")
}
let array = Array(string)
for i in 2..<count {
if array[i] == "0" || array[i] == "1" {
continue
}
var j = 2
while j < i {
if i % j == 0 {
break
}
j += 1
}
if j == i {
return true
}
}
return false
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func starts
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += countOfN(n: n, start: i, end: i)
}
return result
}
func countOfN(n: Int, start: Int, end: Int) -> Int {
var result = 0
for i in start...end {
let num = Int(pow(Double(10), Double(n-1)))
result += countOfN(n: n-1, start: i, end: i*num)
}
return result
}
func countOfN(n: Int, start: Int, end: Int) -> Int {
var result = 0
if n == 1 {
return end - start + 1
}
for i in start...end {
result += countOfN(n: n-1, start: i, end: i*10-1)
}
return result
}
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
for j in 1...9 {
dp[j] += dp[j-1]
}
dp[0] += dp[9]
}
var result = 0
for i in 1...9 {
result += dp[i]
}
return result
}
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
for j in 0...9 {
dp[j] += dp[j-1]
}
dp[0] += dp[9]
}
var result = 0
for i in 1...9 {
result += dp[i]
}
return result
}
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
dp[0] += dp[9]
for j in 0...9 {
dp[j] += dp[j-1]
}
}
var result = 0
for i in 1...9 {
result += dp[i]
}
return result
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += countOfN(n: n, start: i, end: i)
}
return result
}
func countOfN(n: Int, start: Int, end: Int) -> Int {
var result = 0
for i in start...end {
let num = Int(pow(Double(10), Double(n-1)))
result += countOfN(n: n-1, start: i, end: i*num)
}
return result
}
```
### 解法二:递归
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += countOfN(n: n, start: i, end: i)
}
return result
}
func countOfN(n: Int, start: Int, end: Int) -> Int {
var result = 0
if n == 1 {
return end - start + 1
}
for i in start...end {
result += countOfN(n: n-1, start: i, end: i*10-1)
}
return result
}
```
### 解法三:动态规划
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
for j in 1...9 {
dp[j] += dp[j-1]
}
dp[0] += dp[9]
}
var result = 0
for i in 1...9 {
result += dp[i]
}
return result
}
```
### 解法四:动态规划优化
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
for j in 0...9 {
dp[j] += dp[j-1]
}
dp[0] += dp[9]
}
var result = 0
for i in 1...9 {
result += dp[i]
}
return result
}
```
### 解法五:动态规划优化
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
dp[0] += dp[9]
for j in 0...9 {
dp[j] += dp[j-1]
}
}
var result = 0
for i in 1...9 {
result += dp[i]
}
return result
}
```
### 解法六:动态规划优化
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var dp = Array(repeating: 0, count: 10)
dp[1] = 1
for i in 2...n {
dp[0] += dp[9]
for j in 0...9 {
dp[j] += dp[
func countOfN(n: Int, start: Int, end: Int) -> Int { // invalid redeclaration of 'countOfN(n:start:end:)'
func startsOneEnds(n: Int) -> Int { // invalid redeclaration of 'startsOneEnds(n:)'
func startsOneEnds(n: Int) -> Int { // invalid redeclaration of 'startsOneEnds(n:)'
func startsOneEnds(n: Int) -> Int { // invalid redeclaration of 'startsOneEnds(n:)'
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...end {
result += startsOne(n: n -
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
let one = 1
let two = 10
let three = 100
let four = 1000
let five = 10000
let six = 100000
let seven = 1000000
let eight = 10000000
let nine = 100000000
let ten = 1000000000
var count = 0
if n >= two {
count += startsOneEnds(n: n - two)
}
if n >= three {
count += startsOneEnds(n: n - three)
}
if n >= four {
count += startsOneEnds(n: n - four)
}
if n >= five {
count += startsOneEnds(n: n - five)
}
if n >= six {
count += startsOneEnds(n: n - six)
}
if n >= seven {
count += startsOneEnds(n: n - seven)
}
if n >= eight {
count += startsOneEnds(n: n - eight)
}
if n >= nine {
count += startsOneEnds(n: n - nine)
}
if n >= ten {
count += startsOneEnds(n: n - ten)
}
if n == 10 {
count += 1
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
let one = 1
let two = 10
let three = 100
let four = 1000
let five = 10000
let six = 100000
let seven = 1000000
let eight = 10000000
let nine = 100000000
let ten = 1000000000
var count = 0
if n >= two {
count += startsOneEnds(n: n - two)
}
if n >= three {
count += startsOneEnds(n: n - three)
}
if n >= four {
count += startsOneEnds(n: n - four)
}
if n >= five {
count += startsOneEnds(n: n - five)
}
if n >= six {
count += startsOneEnds(n: n - six)
}
if n >= seven {
count += startsOneEnds(n: n - seven)
}
if n >= eight {
count += startsOneEnds(n: n - eight)
}
if n >= nine {
count += startsOneEnds(n: n - nine)
}
if n >= ten {
count += startsOneEnds(n: n - ten)
}
if n == 10 {
count += 1
}
return count
}
```
let one = 1 // initialization of immutable value 'one' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n - 1, start: i, end: i)
}
return result
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += startsOne(n: n, start: i, end: i)
}
return result
}
func startsOne(n: Int, start: Int, end: Int) -> Int {
if n == 1 {
return 1
}
var result = 0
for i in start...9 {
result += startsOne(n: n -
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func starts
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
var count = 0
for i in 1...9 {
count += startsOneEnds(n - 1)
}
return count
}
func startsOneEndsDp(_ n: Int) -> Int {
if n == 1 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
for i in 2...n {
dp[i] = dp[i - 1] + 9 * dp[i - 1]
}
return dp[n]
}
func startsOneEndsRecursive(_ n: Int) -> Int {
if n == 1 {
return 1
}
return startsOneEndsRecursive(n - 1) + 9 * startsOneEndsRecursive(n - 1)
}
func startsOneEndsMath(_ n: Int) -> Int {
let n = n - 1
let a = n / 2
let b = n % 2
return (a + 1) * (a + 2) * b + b
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 1
}
var count = 0
for i in 1...9 {
count += startsOneEnds(n - 1)
}
return count
}
```
### 解法二:动态规划
```swift
func startsOneEndsDp(_ n: Int) -> Int {
if n == 1 {
return 1
}
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 1
for i in 2...n {
dp[i] = dp[i - 1] + 9 * dp[i - 1]
}
return dp[n]
}
```
### 解法三:递归
```swift
func startsOneEndsRecursive(_ n: Int) -> Int {
if n == 1 {
return 1
}
return startsOneEndsRecursive(n - 1) + 9 * startsOneEndsRecursive(n - 1)
}
```
### 解法四:数学
```swift
func startsOneEndsMath(_ n: Int) -> Int {
let n = n - 1
let a = n / 2
let b = n % 2
return (a + 1) * (a + 2) * b + b
}
```
count += startsOneEnds(n - 1) // missing argument label 'n:' in call
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 9
}
let count = 9 * startsOneEnds(n: n - 1)
if n % 2 == 0 {
return count + 1
}
return count
}
func startsOneEnds(n: Int) -> Int {
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 9
if n % 2 == 0 {
dp[2] = 9
} else {
dp[2] = 10
}
for i in 3...n {
dp[i] = dp[i - 1] * 9 + (i % 2 == 0 ? 1 : 2)
}
return dp[n]
}
func startsOneEnds(n: Int) -> Int {
let count = 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
if n % 2 == 0 {
return count
}
return count + 1
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var count = 0
for i in 1...9 {
for j in 1...9 {
if i == 1 || j == 1 {
count += 1
}
}
}
return count
}
```
### 解法二:递归
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
if n == 1 {
return 9
}
let count = 9 * startsOneEnds(n: n - 1)
if n % 2 == 0 {
return count + 1
}
return count
}
```
### 解法三:动态规划
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var dp = [Int](repeating: 0, count: n + 1)
dp[1] = 9
if n % 2 == 0 {
dp[2] = 9
} else {
dp[2] = 10
}
for i in 3...n {
dp[i] = dp[i - 1] * 9 + (i % 2 == 0 ? 1 : 2)
}
return dp[n]
}
```
### 解法四:数学
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
let count = 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
if n % 2 == 0 {
return count
}
return count + 1
}
```
### 解法五:数学
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
let count = 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
if n % 2 == 0 {
return count
}
return count + 1
}
```
### 解法六:数学
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
let count = 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
if n % 2 == 0 {
return count
}
return count + 1
}
```
### 解法七:数学
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
let count = 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
if n % 2 == 0 {
return count
}
return count + 1
}
```
### 解法八:数学
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
let count = 9 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2
if n % 2 == 0 {
return count
}
return count + 1
}
```
### 解法九:数学
```swift
// Given a positive integer n, return the count of the numbers of
func startsOneEnds(n: Int) -> Int { // invalid redeclaration of 'startsOneEnds(n:)'
func startsOneEnds(n: Int) -> Int { // invalid redeclaration of 'startsOneEnds(n:)'
func startsOneEnds(n: Int) -> Int { // invalid redeclaration of 'startsOneEnds(n:)'
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += (i * 9 * Int(pow(Double(10), Double(n - 1)))).truncatingRemainder(dividingBy: 10)
}
return result
}
```swift
// Given a positive integer n, return the count of the numbers of n-digit
// positive integers that start or end with 1.
func startsOneEnds(n: Int) -> Int {
var result = 0
for i in 1...9 {
result += (i * 9 * Int(pow(Double(10), Double(n - 1)))).truncatingRemainder(dividingBy: 10)
}
return result
}
```
result += (i * 9 * Int(pow(Double(10), Double(n - 1)))).truncatingRemainder(dividingBy: 10) // value of type 'Int' has no member 'truncatingRemainder'
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
return result
}
func solve(N: Int) -> String {
var N = N
var result = ""
if N == 0 {
return "0"
}
result = String(N % 2) + result
N = N / 2
return solve(N: N) + result
}
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N & 1) + result
N = N >> 1
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
return result
}
```
#### 解法二:递归
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
if N == 0 {
return "0"
}
result = String(N % 2) + result
N = N / 2
return solve(N: N) + result
}
```
#### 解法三:数学
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
return result
}
```
#### 解法四:位运算
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N & 1) + result
N = N >> 1
}
return result
}
```
#### 解法五:数学
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
return result
}
```
#### 解法六:数学
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
func solve(N: Int) -> String { // invalid redeclaration of 'solve(N:)'
func solve(N: Int) -> String { // invalid redeclaration of 'solve(N:)'
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result.append(String(n % 2))
n /= 2
}
return result.reversed()
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result.append(String(n % 2))
n /= 2
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result.append("\(n % 2)")
n /= 2
}
return result.reversed()
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result.append("\(n % 2)")
n /= 2
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N /= 2
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result.append(String(n & 1))
n >>= 1
}
return result.reversed()
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result.append(String(n & 1))
n >>= 1
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n % 2) + result
n /= 2
}
return result
}
func solve(N: Int) -> String {
var n = N
var result = ""
if n == 0 {
return "0"
}
result = String(n % 2) + result
n /= 2
return solve(N: n) + result
}
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n & 1) + result
n >>= 1
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n % 2) + result
n /= 2
}
return result
}
```
### 解法二:递归
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
if n == 0 {
return "0"
}
result = String(n % 2) + result
n /= 2
return solve(N: n) + result
}
```
### 解法三:迭代
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n % 2) + result
n /= 2
}
return result
}
```
### 解法四:位运算
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n & 1) + result
n >>= 1
}
return result
}
```
### 解法五:位运算
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n & 1) + result
n >>= 1
}
return result
}
```
### 解法六:位运算
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n & 1) + result
n >>= 1
}
return result
func solve(N: Int) -> String { // invalid redeclaration of 'solve(N:)'
func solve(N: Int) -> String { // invalid redeclaration of 'solve(N:)'
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var N = N
var result = ""
while N > 0 {
result = String(N % 2) + result
N = N / 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n % 2) + result
n = n / 2
}
return result
}
class Solution {
func reverseBits(_ n: Int) -> Int {
var n = n
n = (n >> 16) | (n << 16)
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
return n
}
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n % 2) + result
n = n / 2
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func reverseBits(_ n: Int) -> Int {
var n = n
n = (n >> 16) | (n << 16)
n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8)
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4)
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2)
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1)
return n
}
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var num = N
var result = ""
while num > 0 {
result = String(num % 2) + result
num /= 2
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var num = N
var result = ""
while num > 0 {
result = String(num % 2) + result
num /= 2
}
return result
}
```
// XCTAssertTrue failed
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n & 1) + result
n >>= 1
}
return result
}
```swift
// Given a positive integer N, return the total sum of its digits in binary.
// Example
// Variables:
// @N integer
// Constraints: 0 ≤ N ≤ 10000.
// Output:
// a string of binary number
// solve(N: 1000) == "1"
// solve(N: 150) == "110"
// solve(N: 147) == "1100"
func solve(N: Int) -> String {
var n = N
var result = ""
while n > 0 {
result = String(n & 1) + result
n >>= 1
}
return result
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
class Solution {
func addToArrayForm(_ lst: [Int], _ inc: Int) -> [Int] {
var result = lst
var i = lst.count - 1
while i >= 0 {
result[i] += inc
if result[i] >= 10 {
result[i] -= 10
if i == 0 {
result.insert(1, at: 0)
} else {
result[i - 1] += 1
}
}
i -= 1
}
return result
}
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func addToArrayForm(_ lst: [Int], _ inc: Int) -> [Int] {
var result = lst
var i = lst.count - 1
while i >= 0 {
result[i] += inc
if result[i] >= 10 {
result[i] -= 10
if i == 0 {
result.insert(1, at: 0)
} else {
result[i - 1] += 1
}
}
i -= 1
}
return result
}
}
```
XCTAssertTrue(Solution.add(lst: [4, 88]) == 88) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 5, 6, 7, 2, 122]) == 122) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 0, 6, 7]) == 0) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 4, 6, 8]) == 12) // type 'Solution' has no member 'add'
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
class Solution {
func addToArrayForm(_ lst: [Int], _ inc: Int) -> [Int] {
var result = lst
var carry = inc
for i in stride(from: result.count - 1, through: 0, by: -1) {
let sum = result[i] + carry
result[i] = sum % 10
carry = sum / 10
}
if carry > 0 {
result.insert(carry, at: 0)
}
return result
}
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func addToArrayForm(_ lst: [Int], _ inc: Int) -> [Int] {
var result = lst
var carry = inc
for i in stride(from: result.count - 1, through: 0, by: -1) {
let sum = result[i] + carry
result[i] = sum % 10
carry = sum / 10
}
if carry > 0 {
result.insert(carry, at: 0)
}
return result
}
}
```
XCTAssertTrue(Solution.add(lst: [4, 88]) == 88) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 5, 6, 7, 2, 122]) == 122) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 0, 6, 7]) == 0) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 4, 6, 8]) == 12) // type 'Solution' has no member 'add'
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
class Solution {
func addToArrayForm(_ A: [Int], _ K: Int) -> [Int] {
var result = [Int]()
var K = K
for i in A.reversed() {
result.append(i + K % 10)
K /= 10
}
while K > 0 {
result.append(K % 10)
K /= 10
}
result.reverse()
return result
}
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func addToArrayForm(_ A: [Int], _ K: Int) -> [Int] {
var result = [Int]()
var K = K
for i in A.reversed() {
result.append(i + K % 10)
K /= 10
}
while K > 0 {
result.append(K % 10)
K /= 10
}
result.reverse()
return result
}
}
```
XCTAssertTrue(Solution.add(lst: [4, 88]) == 88) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 5, 6, 7, 2, 122]) == 122) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 0, 6, 7]) == 0) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 4, 6, 8]) == 12) // type 'Solution' has no member 'add'
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
class Solution {
func addToArrayForm(_ lst: [Int], _ inc: Int) -> [Int] {
var result = lst
var index = lst.count - 1
var carry = inc
while index >= 0 {
let sum = lst[index] + carry
result[index] = sum % 10
carry = sum / 10
index -= 1
}
if carry > 0 {
result.insert(carry, at: 0)
}
return result
}
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
### 解题思路
### 代码
```swift
class Solution {
func addToArrayForm(_ lst: [Int], _ inc: Int) -> [Int] {
var result = lst
var index = lst.count - 1
var carry = inc
while index >= 0 {
let sum = lst[index] + carry
result[index] = sum % 10
carry = sum / 10
index -= 1
}
if carry > 0 {
result.insert(carry, at: 0)
}
return result
}
}
```
XCTAssertTrue(Solution.add(lst: [4, 88]) == 88) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 5, 6, 7, 2, 122]) == 122) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 0, 6, 7]) == 0) // type 'Solution' has no member 'add'
XCTAssertTrue(Solution.add(lst: [4, 4, 6, 8]) == 12) // type 'Solution' has no member 'add'
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 {
result += lst[i]
}
if i % 2 == 1 {
result += lst[i]
}
}
return result
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if lst[i] % 2 == 0 {
result += lst[i]
}
if i % 2 == 1 {
result += lst[i]
}
}
return result
}
```
// XCTAssertTrue failed
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```swift
// Given a non-empty array of integers lst. add the even elements that are at odd indices..
// Examples:
// add(lst: [4, 2, 6, 7]) == 2
func add(lst: [Int]) -> Int {
var result = 0
for i in 0..<lst.count {
if i % 2 == 0 {
result += lst[i]
}
}
return result
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let words = words.map { String($0.sorted()) }
return words.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let words = words.map { String($0.sorted()) }
return words.joined(separator: " ")
}
```
let words = words.map { String($0.sorted()) } // invalid redeclaration of 'words'
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.map { String($0.sorted()) }
return sortedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.map { String($0.sorted()) }
return sortedWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let orderedWords = words.map { String(describing: $0.sorted()) }
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let orderedWords = words.map { String(describing: $0.sorted()) }
return orderedWords.joined(separator: " ")
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.sorted { (word1, word2) -> Bool in
return word1 < word2
}
return sortedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.sorted { (word1, word2) -> Bool in
return word1 < word2
}
return sortedWords.joined(separator: " ")
}
```
// XCTAssertTrue failed
func antiShuffle(s: String) -> String {
let str = s.split(separator: " ").map { String($0.sorted()) }
return str.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let str = s.split(separator: " ").map { String($0.sorted()) }
return str.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
result += word.sorted { $0.asciiValue! < $1.asciiValue! }.joined(separator: "")
result += " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
result += word.sorted { $0.asciiValue! < $1.asciiValue! }.joined(separator: "")
result += " "
}
return result.trimmingCharacters(in: .whitespaces)
}
```
result += word.sorted { $0.asciiValue! < $1.asciiValue! }.joined(separator: "") // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.map { String($0.sorted()) }
return sortedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.map { String($0.sorted()) }
return sortedWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let orderedWords = words.map { String($0.sorted()) }
return orderedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let orderedWords = words.map { String($0.sorted()) }
return orderedWords.joined(separator: " ")
}
```
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
result += word.sorted { $0.asciiValue! < $1.asciiValue! }.joined(separator: "")
result += " "
}
return result.trimmingCharacters(in: CharacterSet.whitespaces)
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
var result = ""
for word in words {
result += word.sorted { $0.asciiValue! < $1.asciiValue! }.joined(separator: "")
result += " "
}
return result.trimmingCharacters(in: CharacterSet.whitespaces)
}
```
result += word.sorted { $0.asciiValue! < $1.asciiValue! }.joined(separator: "") // referencing instance method 'joined(separator:)' on 'BidirectionalCollection' requires the types 'String.Element' (aka 'Character') and 'String' be equivalent
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.map { String($0.sorted()) }
return sortedWords.joined(separator: " ")
}
```swift
// Write a function that takes a string and returns an ordered version of it.
// Ordered version of string, is a string where all words (separated by space)
// are replaced by a new word where all the characters arranged in
// ascending order based on ascii value.
// Note: You should keep the order of words and blank spaces in the sentence.
// For example:
// antiShuffle(s: "Hi") == "Hi"
// antiShuffle(s: "hello") == "ehllo"
// antiShuffle(s: "Hello World!!!") == "Hello !!!Wdlor"
func antiShuffle(s: String) -> String {
let words = s.components(separatedBy: " ")
let sortedWords = words.map { String($0.sorted()) }
return sortedWords.joined(separator: " ")
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (row, rowArray) in lst.enumerated() {
for (col, value) in rowArray.enumerated().reversed() {
if value == x {
result.append((row, col))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (row, rowArray) in lst.enumerated() {
for (col, value) in rowArray.enumerated().reversed() {
if value == x {
result.append((row, col))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for row in lst {
if row.contains(x) {
result.append((lst.index(of: row) ?? 0, row.index(of: x) ?? 0))
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for row in lst {
if row.contains(x) {
result.append((lst.index(of: row) ?? 0, row.index(of: x) ?? 0))
}
}
return result
}
```
result.append((lst.index(of: row) ?? 0, row.index(of: x) ?? 0)) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
result.append((lst.index(of: row) ?? 0, row.index(of: x) ?? 0)) // 'index(of:)' is deprecated: renamed to 'firstIndex(of:)'
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, item) in row.enumerated().reversed() {
if item == x {
result.append((i, j))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, item) in row.enumerated().reversed() {
if item == x {
result.append((i, j))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
if row.contains(x) {
result.append((index, row.firstIndex(of: x)!))
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
if row.contains(x) {
result.append((index, row.firstIndex(of: x)!))
}
}
return result
}
```
// XCTAssertTrue failed
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated().reversed() {
if value == x {
result.append((index, column))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, value) in row.enumerated().reversed() {
if value == x {
result.append((index, column))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (row, rowList) in lst.enumerated() {
for (col, value) in rowList.enumerated().reversed() {
if value == x {
result.append((row, col))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (row, rowList) in lst.enumerated() {
for (col, value) in rowList.enumerated().reversed() {
if value == x {
result.append((row, col))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, num) in row.enumerated().reversed() {
if num == x {
result.append((i, j))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (i, row) in lst.enumerated() {
for (j, num) in row.enumerated().reversed() {
if num == x {
result.append((i, j))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, element) in row.enumerated().reversed() {
if element == x {
result.append((index, column))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (index, row) in lst.enumerated() {
for (column, element) in row.enumerated().reversed() {
if element == x {
result.append((index, column))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (row, rowArray) in lst.enumerated() {
for (col, value) in rowArray.enumerated().reversed() {
if value == x {
result.append((row, col))
}
}
}
return result
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var result = [(Int, Int)]()
for (row, rowArray) in lst.enumerated() {
for (col, value) in rowArray.enumerated().reversed() {
if value == x {
result.append((row, col))
}
}
}
return result
}
```
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var res = [(Int, Int)]()
for (i, row) in lst.enumerated() {
if row.contains(x) {
res.append((i, row.firstIndex(of: x)!))
}
}
return res.sorted { (a, b) -> Bool in
a.0 < b.0 || (a.0 == b.0 && a.1 > b.1)
}
}
```swift
// You are given a 2 dimensional data, as a nested arrays,
// which is similar to matrix, however, unlike matrices,
// each row may contain a different number of columns.
// Given lst, and integer x, find integers x in the array,
// and return array of tuples, [(x1, y1), (x2, y2) ...] such that
// each tuple is a coordinate - (row, columns), starting with 0.
// Sort coordinates initially by rows in ascending order.
// Also, sort coordinates of the row by columns in descending order.
// Examples:
// getRow(lst: [[1, 2, 3, 4, 5, 6], [1, 2, 3, 4, 1, 6], [1, 2, 3, 4, 5, 1]], x: 1) == [(0, 0), (1, 4), (1, 0), (2, 5), (2, 0)]
// getRow(lst: [] as [[Int]], x: 1) == [] as [(Int, Int)]
// getRow(lst: [[] as [Int], [1], [1, 2, 3]], x: 3) == [(2, 2)]
func getRow(lst: [[Int]], x: Int) -> [(Int, Int)] {
var res = [(Int, Int)]()
for (i, row) in lst.enumerated() {
if row.contains(x) {
res.append((i, row.firstIndex(of: x)!))
}
}
return res.sorted { (a, b) -> Bool in
a.0 < b.0 || (a.0 == b.0 && a.1 > b.1)
}
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if array.count == 1 {
return array
}
var array = array
var left = 0
var right = array.count - 1
while left < right {
if array[left] + array[right] % 2 == 0 {
swap(&array, left, right)
left += 1
} else {
right -= 1
}
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if array.count == 1 {
return array
}
var array = array
var left = 0
var right = array.count - 1
while left < right {
if array[left] + array[right] % 2 == 0 {
swap(&array, left, right)
left += 1
} else {
right -= 1
}
}
return array
}
```
swap(&array, left, right) // extra argument in call
swap(&array, left, right) // cannot convert value of type 'Int' to expected argument type '[Int]'
func sortArray(array: [Int]) -> [Int] {
if array.count <= 1 {
return array
}
var result = array
var left = 0
var right = array.count - 1
while left < right {
if result[left] + result[right] % 2 == 0 {
result.swapAt(left, right)
left += 1
} else {
right -= 1
}
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count <= 1 {
return array
}
var result = array
var left = 0
var right = array.count - 1
while left < right {
if result[left] + result[right] % 2 == 0 {
result.swapAt(left, right)
left += 1
} else {
right -= 1
}
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if array.count == 1 {
return array
}
var result = array
var left = 0
var right = array.count - 1
while left < right {
if result[left] + result[right] % 2 == 0 {
result.swapAt(left, right)
right -= 1
} else {
left += 1
}
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if array.count == 1 {
return array
}
var result = array
var left = 0
var right = array.count - 1
while left < right {
if result[left] + result[right] % 2 == 0 {
result.swapAt(left, right)
right -= 1
} else {
left += 1
}
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
guard array.count > 0 else {
return []
}
var result = array
result.sort { (first, last) -> Bool in
return (first + last) % 2 == 0
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 0 else {
return []
}
var result = array
result.sort { (first, last) -> Bool in
return (first + last) % 2 == 0
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var array = array
var left = 0
var right = array.count - 1
while left < right {
let sum = array[left] + array[right]
if sum % 2 == 0 {
swap(&array, left, right)
right -= 1
} else {
left += 1
}
}
return array
}
func swap(_ array: inout [Int], _ left: Int, _ right: Int) {
let temp = array[left]
array[left] = array[right]
array[right] = temp
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var array = array
var left = 0
var right = array.count - 1
while left < right {
let sum = array[left] + array[right]
if sum % 2 == 0 {
swap(&array, left, right)
right -= 1
} else {
left += 1
}
}
return array
}
func swap(_ array: inout [Int], _ left: Int, _ right: Int) {
let temp = array[left]
array[left] = array[right]
array[right] = temp
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
let count = array.count
if count == 0 {
return []
}
if count == 1 {
return array
}
var result = array
var left = 0
var right = count - 1
while left < right {
let leftValue = result[left]
let rightValue = result[right]
if leftValue + rightValue > 0 {
result[left] = rightValue
result[right] = leftValue
left += 1
right -= 1
} else {
left += 1
}
}
if left == right && left % 2 == 1 {
result.swapAt(left, 0)
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
let count = array.count
if count == 0 {
return []
}
if count == 1 {
return array
}
var result = array
var left = 0
var right = count - 1
while left < right {
let leftValue = result[left]
let rightValue = result[right]
if leftValue + rightValue > 0 {
result[left] = rightValue
result[right] = leftValue
left += 1
right -= 1
} else {
left += 1
}
}
if left == right && left % 2 == 1 {
result.swapAt(left, 0)
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
var array = array
var sum = 0
for i in 0..<array.count {
sum += array[i]
if i == array.count - 1 {
break
}
if sum % 2 == 0 {
array.swapAt(i, i + 1)
}
}
return array
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
var array = array
var sum = 0
for i in 0..<array.count {
sum += array[i]
if i == array.count - 1 {
break
}
if sum % 2 == 0 {
array.swapAt(i, i + 1)
}
}
return array
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if array.count == 1 {
return array
}
var result = array
result = result.sorted { (first, last) -> Bool in
let sum = first + last
if sum % 2 == 0 {
return true
} else {
return false
}
}
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
if array.count == 1 {
return array
}
var result = array
result = result.sorted { (first, last) -> Bool in
let sum = first + last
if sum % 2 == 0 {
return true
} else {
return false
}
}
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
guard array.count > 0 else {
return []
}
return sortArray(array: array, start: 0, end: array.count - 1)
}
func sortArray(array: [Int], start: Int, end: Int) -> [Int] {
guard start < end else {
return [array[start]]
}
let mid = (start + end) / 2
let left = sortArray(array: array, start: start, end: mid)
let right = sortArray(array: array, start: mid + 1, end: end)
return merge(left: left, right: right)
}
func merge(left: [Int], right: [Int]) -> [Int] {
var result = [Int]()
var leftIndex = 0
var rightIndex = 0
while leftIndex < left.count && rightIndex < right.count {
if left[leftIndex] > right[rightIndex] {
result.append(right[rightIndex])
rightIndex += 1
} else {
result.append(left[leftIndex])
leftIndex += 1
}
}
result.append(contentsOf: left[leftIndex..<left.count])
result.append(contentsOf: right[rightIndex..<right.count])
return result
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
guard array.count > 0 else {
return []
}
return sortArray(array: array, start: 0, end: array.count - 1)
}
func sortArray(array: [Int], start: Int, end: Int) -> [Int] {
guard start < end else {
return [array[start]]
}
let mid = (start + end) / 2
let left = sortArray(array: array, start: start, end: mid)
let right = sortArray(array: array, start: mid + 1, end: end)
return merge(left: left, right: right)
}
func merge(left: [Int], right: [Int]) -> [Int] {
var result = [Int]()
var leftIndex = 0
var rightIndex = 0
while leftIndex < left.count && rightIndex < right.count {
if left[leftIndex] > right[rightIndex] {
result.append(right[rightIndex])
rightIndex += 1
} else {
result.append(left[leftIndex])
leftIndex += 1
}
}
result.append(contentsOf: left[leftIndex..<left.count])
result.append(contentsOf: right[rightIndex..<right.count])
return result
}
```
// XCTAssertTrue failed
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var array = array
let sum = array.reduce(0, +)
let mid = array.count / 2
if sum % 2 == 0 {
array.sort { $0 > $1 }
} else {
array.sort { $0 < $1 }
}
return Array(array[0..<mid])
}
```swift
// Given an array of non-negative integers, return a coswift of the given array after sorting,
// you will sort the given array in ascending order if the sum( first index value, last index value) is odd,
// or sort it in descending order if the sum( first index value, last index value) is even.
// Note:
// * don't change the given array.
// Examples:
// sortArray(array: [] as [Int]) == [] as [Int]
// sortArray(array: [5]) == [5]
// sortArray(array: [2, 4, 3, 0, 1, 5]) == [0, 1, 2, 3, 4, 5]
// sortArray(array: [2, 4, 3, 0, 1, 5, 6]) == [6, 5, 4, 3, 2, 1, 0]
func sortArray(array: [Int]) -> [Int] {
if array.count == 0 {
return []
}
var array = array
let sum = array.reduce(0, +)
let mid = array.count / 2
if sum % 2 == 0 {
array.sort { $0 > $1 }
} else {
array.sort { $0 < $1 }
}
return Array(array[0..<mid])
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!)) // cannot force unwrap value of non-optional type 'Character'
func encrypt(s: String) -> String {
var result = ""
for c in s {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
var result = ""
for c in s {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!)) // cannot force unwrap value of non-optional type 'Character'
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!)) // cannot force unwrap value of non-optional type 'Character'
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for char in chars {
let index = Int(char.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for char in chars {
let index = Int(char.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!)) // cannot force unwrap value of non-optional type 'Character'
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
result.append(newChar)
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
let newChar = Character(UnicodeScalar(newIndex + 97)!)
result.append(newChar)
}
return result
}
```
func encrypt(s: String) -> String {
let a = Array(s)
var b = Array(s)
for i in 0..<a.count {
b[i] = Character(UnicodeScalar(Int(a[i].asciiValue! + 2 * 2) % 26 + 97)!)
}
return String(b)
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let a = Array(s)
var b = Array(s)
for i in 0..<a.count {
b[i] = Character(UnicodeScalar(Int(a[i].asciiValue! + 2 * 2) % 26 + 97)!)
}
return String(b)
}
```
// XCTAssertTrue failed
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!)) // cannot force unwrap value of non-optional type 'Character'
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for c in chars {
let index = Int(c.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!))
}
return result
}
```
result.append(String(Character(UnicodeScalar(newIndex + 97)!)!)) // cannot force unwrap value of non-optional type 'Character'
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let chars = Array(s)
var result = ""
for char in chars {
let index = alphabet.index(of: char) ?? 0
let newIndex = (index + 2 * 2) % alphabet.count
result.append(alphabet[newIndex])
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz"
let chars = Array(s)
var result = ""
for char in chars {
let index = alphabet.index(of: char) ?? 0
let newIndex = (index + 2 * 2) % alphabet.count
result.append(alphabet[newIndex])
}
return result
}
```
let index = alphabet.index(of: char) ?? 0 // binary operator '??' cannot be applied to operands of type 'String.Index?' and 'Int'
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for char in chars {
let index = Int(char.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)))
}
return result
}
```swift
// Create a function encrypt that takes a string as an argument and
// returns a string encrypted with the alphabet being rotated.
// The alphabet should be rotated in a manner such that the letters
// shift down by two multiplied to two places.
// For example:
// encrypt(s: "hi") == "lm"
// encrypt(s: "asdfghjkl") == "ewhjklnop"
// encrypt(s: "gf") == "kj"
// encrypt(s: "et") == "ix"
func encrypt(s: String) -> String {
let chars = Array(s)
var result = ""
for char in chars {
let index = Int(char.asciiValue!) - 97
let newIndex = (index + 2 * 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + 97)!)))
}
return result
}
```
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else {
return nil
}
var lst = lst
lst.sort()
var left = 0
var right = lst.count - 1
while left < right {
let mid = left + (right - left) / 2
if lst[mid] < lst[right] {
right = mid
} else {
left = mid + 1
}
}
return lst[left]
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else {
return nil
}
var lst = lst
lst.sort()
var left = 0
var right = lst.count - 1
while left < right {
let mid = left + (right - left) / 2
if lst[mid] < lst[right] {
right = mid
} else {
left = mid + 1
}
}
return lst[left]
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
var lst = lst
var min = lst.first!
var secondMin = lst.first!
for i in 1..<lst.count {
let num = lst[i]
if num < min {
secondMin = min
min = num
} else if num < secondMin && num != min {
secondMin = num
}
}
if min == secondMin {
return nil
}
for i in 0..<lst.count {
if lst[i] == secondMin {
return lst[i + 1]
}
}
return nil
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
var lst = lst
var min = lst.first!
var secondMin = lst.first!
for i in 1..<lst.count {
let num = lst[i]
if num < min {
secondMin = min
min = num
} else if num < secondMin && num != min {
secondMin = num
}
}
if min == secondMin {
return nil
}
for i in 0..<lst.count {
if lst[i] == secondMin {
return lst[i + 1]
}
}
return nil
}
```
var lst = lst // variable 'lst' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
if first == second {
return lst[2]
}
return second
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
if first == second {
return lst[2]
}
return second
}
```
// Fatal error: Index out of range
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
var lst = lst
lst.sort()
if lst[0] == lst[1] {
return nil
}
let index = lst.firstIndex(of: lst[0])!
if index == lst.count - 1 {
return nil
}
return lst[index + 1]
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
var lst = lst
lst.sort()
if lst[0] == lst[1] {
return nil
}
let index = lst.firstIndex(of: lst[0])!
if index == lst.count - 1 {
return nil
}
return lst[index + 1]
}
```
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
var lst = lst
var min = lst[0]
var secondMin = lst[0]
for i in 1..<lst.count {
if lst[i] < min {
secondMin = min
min = lst[i]
} else if lst[i] < secondMin && lst[i] != min {
secondMin = lst[i]
}
}
if secondMin == min {
return nil
}
for i in 0..<lst.count {
if lst[i] == secondMin {
return lst[i + 1]
}
}
return nil
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
if lst.count == 0 {
return nil
}
var lst = lst
var min = lst[0]
var secondMin = lst[0]
for i in 1..<lst.count {
if lst[i] < min {
secondMin = min
min = lst[i]
} else if lst[i] < secondMin && lst[i] != min {
secondMin = lst[i]
}
}
if secondMin == min {
return nil
}
for i in 0..<lst.count {
if lst[i] == secondMin {
return lst[i + 1]
}
}
return nil
}
```
var lst = lst // variable 'lst' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else {
return nil
}
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
if first == second {
return lst[2]
}
return second
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else {
return nil
}
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
if first == second {
return lst[2]
}
return second
}
```
// Fatal error: Index out of range
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else {
return nil
}
var lst = lst
lst.sort()
for i in 0..<lst.count {
if lst[i] < lst[lst.count - 1] {
return lst[i]
}
}
return nil
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else {
return nil
}
var lst = lst
lst.sort()
for i in 0..<lst.count {
if lst[i] < lst[lst.count - 1] {
return lst[i]
}
}
return nil
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
guard first < second else { return nil }
for i in 1..<lst.count {
if lst[i] > first && lst[i] < second {
return lst[i]
}
}
return nil
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
guard first < second else { return nil }
for i in 1..<lst.count {
if lst[i] > first && lst[i] < second {
return lst[i]
}
}
return nil
}
```
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
var lst = lst
var n = lst.count
if n < 2 {
return nil
}
var i = 0
while i < n - 1 {
if lst[i] < lst[i + 1] {
break
}
i += 1
}
if i == n - 1 {
return nil
}
var j = n - 1
while j > 0 {
if lst[j] > lst[i] {
break
}
j -= 1
}
let tmp = lst[i]
lst[i] = lst[j]
lst[j] = tmp
return lst[i + 1]
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
var lst = lst
var n = lst.count
if n < 2 {
return nil
}
var i = 0
while i < n - 1 {
if lst[i] < lst[i + 1] {
break
}
i += 1
}
if i == n - 1 {
return nil
}
var j = n - 1
while j > 0 {
if lst[j] > lst[i] {
break
}
j -= 1
}
let tmp = lst[i]
lst[i] = lst[j]
lst[j] = tmp
return lst[i + 1]
}
```
var n = lst.count // variable 'n' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
if first == second {
return lst[2]
}
return second
}
```swift
// You are given an array of integers.
// Write a function next_smallest() that returns the 2nd smallest element of the array.
// Return nil if there is no such element.
// nextSmallest(lst: [1, 2, 3, 4, 5]) == 2
// nextSmallest(lst: [5, 1, 4, 3, 2]) == 2
// nextSmallest(lst: [] as [Int]) == nil
// nextSmallest(lst: [1, 1]) == nil
func nextSmallest(lst: [Int]) -> Int? {
guard lst.count > 1 else { return nil }
var lst = lst
lst.sort()
let first = lst[0]
let second = lst[1]
if first == second {
return lst[2]
}
return second
}
```
// Fatal error: Index out of range
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
var count = 0
let sentences = S.split(separator: ".")
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
var count = 0
let sentences = S.split(separator: ".")
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.split(separator: ".")
var count = 0
for word in words {
if word.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: ".")
var count = 0
for word in words {
if word.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.split(separator: ".")
var count = 0
for word in words {
if word.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: ".")
var count = 0
for word in words {
if word.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.split(separator: " ")
var count = 0
for word in words {
if word == "I" {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".")
var count = 0
for word in words {
if word.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let words = S.components(separatedBy: ".")
var count = 0
for word in words {
if word.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```swift
// You'll be given a string of words, and your task is to count the number
// of boredoms. A boredom is a sentence that starts with the word "I".
// Sentences are delimited by '.', '?' or '!'.
// For example:
// isBored(S: "Hello world") == 0
// isBored(S: "The sky is blue. The sun is shining. I love this weather") == 1
func isBored(S: String) -> Int {
let sentences = S.split(separator: ".")
var count = 0
for sentence in sentences {
if sentence.hasPrefix("I") {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || x == z + y {
return true
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || x == z + y {
return true
}
return false
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```
### 解法二
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let sumInt = Int(sum)
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
return sumInt == xInt || sumInt == yInt || sumInt == zInt
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let sumInt = Int(sum)
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
return sumInt == xInt || sumInt == yInt || sumInt == zInt
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(x) == sum || Double(y) == sum || Double(z) == sum
return isInt && isSum
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(x) == sum || Double(y) == sum || Double(z) == sum
return isInt && isSum
}
```
### 解法二
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(x) == sum || Double(y) == sum || Double(z) == sum
return isInt && isSum
}
```
### 解法三
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(x) == sum || Double(y) == sum || Double(z) == sum
return isInt && isSum
}
```
### 解法四
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(x) == sum || Double(y) == sum || Double(z) == sum
return isInt && isSum
}
```
### 解法五
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x)
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(sum) == sum
return isInt && isSum
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let isInt = Double(x) == x && Double(y) == y && Double(z) == z
let isSum = Double(sum) == sum
return isInt && isSum
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// 1. Check if all numbers are integers.
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber {
// 2. Check if one of the numbers is equal to the sum of the other two.
if x == y + z || x == z + y {
return true
}
}
return false
}
```
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
if x.isWholeNumber && y.isWholeNumber && z.isWholeNumber { // value of type 'Double' has no member 'isWholeNumber'
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// Write your code here.
let sum = x + y + z
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
let sumInt = Int(sum)
if xInt == sumInt || yInt == sumInt || zInt == sumInt {
return true
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
// Write your code here.
let sum = x + y + z
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
let sumInt = Int(sum)
if xInt == sumInt || yInt == sumInt || zInt == sumInt {
return true
}
return false
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let sumInt = Int(sum)
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
if sumInt == xInt || sumInt == yInt || sumInt == zInt {
return true
} else {
return false
}
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let sumInt = Int(sum)
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
if sumInt == xInt || sumInt == yInt || sumInt == zInt {
return true
} else {
return false
}
}
```
### 解法二
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
let sum = x + y + z
let sumInt = Int(sum)
let xInt = Int(x)
let yInt = Int(y)
let zInt = Int(z)
if sumInt == xInt || sumInt == yInt || sumInt == zInt {
return true
} else {
return false
}
}
```
// XCTAssertTrue failed
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || x == z + y {
return true
}
return false
}
```swift
// Create a function that takes 3 numbers.
// Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
// Returns false in any other cases.
// Examples
// anyInt(x: 5, y: 2, z: 7) == true
// anyInt(x: 3, y: 2, z: 2) == false
// anyInt(x: 3, y: -2, z: 1) == true
// anyInt(x: 3.6, y: -2.2, z: 2) == false
func anyInt(x: Double, y: Double, z: Double) -> Bool {
if x == y + z || x == z + y {
return true
}
return false
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var result = ""
for char in message {
let index = Int(char.asciiValue!) - 97
if char.isVowel {
result.append(Character(UnicodeScalar(index + 2)!)!)
} else {
result.append(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
let index = Int(char.asciiValue!) - 97
if char.isVowel {
result.append(Character(UnicodeScalar(index + 2)!)!)
} else {
result.append(char)
}
}
return result
}
```
if char.isVowel { // value of type 'Character' has no member 'isVowel'
result.append(Character(UnicodeScalar(index + 2)!)!) // cannot force unwrap value of non-optional type 'Character'
func encode(message: String) -> String {
let chars = Array(message)
var result = ""
for char in chars {
let index = chars.firstIndex(of: char) ?? -1
if index != -1 && char.isLowerCase {
result.append(String(chars[index + 2]))
} else {
result.append(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let chars = Array(message)
var result = ""
for char in chars {
let index = chars.firstIndex(of: char) ?? -1
if index != -1 && char.isLowerCase {
result.append(String(chars[index + 2]))
} else {
result.append(char)
}
}
return result
}
```
if index != -1 && char.isLowerCase { // value of type 'String.Element' (aka 'Character') has no member 'isLowerCase'
func encode(message: String) -> String {
var result = ""
for char in message {
let index = char.lowercased().firstIndex(of: char.lowercased())!
let newIndex = (index + 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + Character("a").asciiValue!)))!)
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
let index = char.lowercased().firstIndex(of: char.lowercased())!
let newIndex = (index + 2) % 26
result.append(String(Character(UnicodeScalar(newIndex + Character("a").asciiValue!)))!)
}
return result
}
```
let index = char.lowercased().firstIndex(of: char.lowercased())! // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
result.append(String(Character(UnicodeScalar(newIndex + Character("a").asciiValue!)))!) // cannot force unwrap value of non-optional type 'String'
func encode(message: String) -> String {
let arr = message.map { String($0) }
var res = ""
for c in arr {
let idx = "aeiouAEIOU".firstIndex(of: c)
if idx != nil {
let newIdx = (idx! + 2) % "aeiouAEIOU".count
res += "aeiouAEIOU"[newIdx]
} else {
res += c
}
}
return res
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let arr = message.map { String($0) }
var res = ""
for c in arr {
let idx = "aeiouAEIOU".firstIndex(of: c)
if idx != nil {
let newIdx = (idx! + 2) % "aeiouAEIOU".count
res += "aeiouAEIOU"[newIdx]
} else {
res += c
}
}
return res
}
```
let idx = "aeiouAEIOU".firstIndex(of: c) // cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
func encode(message: String) -> String {
let arr = Array(message)
var newArr = arr
for i in 0..<arr.count {
let c = arr[i]
if c.isLowercase {
newArr[i] = c.lowercased().uppercased()
} else if c.isUppercase {
newArr[i] = c.uppercased().lowercased()
}
}
return newArr.joined()
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let arr = Array(message)
var newArr = arr
for i in 0..<arr.count {
let c = arr[i]
if c.isLowercase {
newArr[i] = c.lowercased().uppercased()
} else if c.isUppercase {
newArr[i] = c.uppercased().lowercased()
}
}
return newArr.joined()
}
```
newArr[i] = c.lowercased().uppercased() // cannot assign value of type 'String' to subscript of type 'String.Element' (aka 'Character')
newArr[i] = c.uppercased().lowercased() // cannot assign value of type 'String' to subscript of type 'String.Element' (aka 'Character')
return newArr.joined() // no exact matches in call to instance method 'joined'
func encode(message: String) -> String {
var result = ""
for char in message {
let index = Int(char.asciiValue!) - 97
if char.isVowel {
let newIndex = (index + 2) % 26
result.append(String(UnicodeScalar(newIndex + 97)))
} else {
result.append(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
let index = Int(char.asciiValue!) - 97
if char.isVowel {
let newIndex = (index + 2) % 26
result.append(String(UnicodeScalar(newIndex + 97)))
} else {
result.append(char)
}
}
return result
}
```
if char.isVowel { // value of type 'Character' has no member 'isVowel'
result.append(String(UnicodeScalar(newIndex + 97))) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
func encode(message: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in message {
if vowels.contains(String(char.lowercased())) {
let index = vowels.firstIndex(of: String(char.lowercased()))!
let newIndex = (index + 2) % vowels.count
result.append(vowels[newIndex])
} else {
result.append(char.lowercased())
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
var result = ""
for char in message {
if vowels.contains(String(char.lowercased())) {
let index = vowels.firstIndex(of: String(char.lowercased()))!
let newIndex = (index + 2) % vowels.count
result.append(vowels[newIndex])
} else {
result.append(char.lowercased())
}
}
return result
}
```
// XCTAssertTrue failed
func encode(message: String) -> String {
var result = ""
for char in message {
let code = Int(char.asciiValue!)
if char.isVowel {
result.append(String(UnicodeScalar(code + 2)))
} else {
result.append(String(UnicodeScalar(code)))
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
var result = ""
for char in message {
let code = Int(char.asciiValue!)
if char.isVowel {
result.append(String(UnicodeScalar(code + 2)))
} else {
result.append(String(UnicodeScalar(code)))
}
}
return result
}
```
if char.isVowel { // value of type 'Character' has no member 'isVowel'
result.append(String(UnicodeScalar(code + 2))) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
result.append(String(UnicodeScalar(code))) // no exact matches in call to initializer
func encode(message: String) -> String {
let chars = Array(message)
var result = ""
for char in chars {
let index = Int(char.asciiValue!) - 97
if char.isVowel {
let newIndex = (index + 2) % 26
result.append(String(UnicodeScalar(newIndex + 97)))
} else {
result.append(char)
}
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let chars = Array(message)
var result = ""
for char in chars {
let index = Int(char.asciiValue!) - 97
if char.isVowel {
let newIndex = (index + 2) % 26
result.append(String(UnicodeScalar(newIndex + 97)))
} else {
result.append(char)
}
}
return result
}
```
if char.isVowel { // value of type 'String.Element' (aka 'Character') has no member 'isVowel'
result.append(String(UnicodeScalar(newIndex + 97))) // value of optional type 'UnicodeScalar?' (aka 'Optional<Unicode.Scalar>') must be unwrapped to a value of type 'UnicodeScalar' (aka 'Unicode.Scalar')
func encode(message: String) -> String {
let arr = Array(message)
var result = ""
for char in arr {
let index = Int(char.asciiValue!) - 97
let nextIndex = (index + 2) % 26
let nextChar = Character(UnicodeScalar(nextIndex + 97)!)
result.append(nextChar)
}
return result
}
```swift
// Write a function that takes a message, and encodes in such a
// way that it swaps case of all letters, replaces all vowels in
// the message with the letter that appears 2 places ahead of that
// vowel in the english alphabet.
// Assume only letters.
// Examples:
// encode(message: "test") == "TGST"
// encode(message: "This is a message") == "tHKS KS C MGSSCGG"
func encode(message: String) -> String {
let arr = Array(message)
var result = ""
for char in arr {
let index = Int(char.asciiValue!) - 97
let nextIndex = (index + 2) % 26
let nextChar = Character(UnicodeScalar(nextIndex + 97)!)
result.append(nextChar)
}
return result
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst = lst.sorted()
var sum = 0
for i in lst {
if i > 0 {
sum += i
}
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst = lst.sorted()
var sum = 0
for i in lst {
if i > 0 {
sum += i
}
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst.sort()
var result = 0
for i in lst.reversed() {
if i == 0 {
continue
}
result += i
var temp = i
while temp > 0 {
result += temp % 10
temp /= 10
}
}
return result
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst.sort()
var result = 0
for i in lst.reversed() {
if i == 0 {
continue
}
result += i
var temp = i
while temp > 0 {
result += temp % 10
temp /= 10
}
}
return result
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
let lst = lst.sorted(by: >)
var sum = 0
for i in lst {
if i % 2 == 0 {
continue
}
sum += i
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
let lst = lst.sorted(by: >)
var sum = 0
for i in lst {
if i % 2 == 0 {
continue
}
sum += i
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
let lst = lst.sorted(by: >)
var res = 0
for i in lst {
if i % 2 == 0 {
continue
}
res += i
}
return res
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
let lst = lst.sorted(by: >)
var res = 0
for i in lst {
if i % 2 == 0 {
continue
}
res += i
}
return res
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst.sort()
var result = 0
for i in lst.reversed() {
if i > 0 {
result += i
} else {
break
}
}
return result
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst.sort()
var result = 0
for i in lst.reversed() {
if i > 0 {
result += i
} else {
break
}
}
return result
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst = lst.sorted(by: >)
var sum = 0
for i in lst {
if i % 2 == 0 {
continue
}
sum += i
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst = lst.sorted(by: >)
var sum = 0
for i in lst {
if i % 2 == 0 {
continue
}
sum += i
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst.sort()
var result = 0
for i in lst.reversed() {
if i < 10 {
result += i
break
}
var temp = i
while temp % 10 == 0 {
temp /= 10
}
result += temp
}
return result
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var lst = lst
lst.sort()
var result = 0
for i in lst.reversed() {
if i < 10 {
result += i
break
}
var temp = i
while temp % 10 == 0 {
temp /= 10
}
result += temp
}
return result
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var result = 0
var lst = lst
for i in lst {
if i < 10 {
result += i
} else {
var temp = i
while temp > 0 {
result += temp % 10
temp /= 10
}
}
}
return result
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var result = 0
var lst = lst
for i in lst {
if i < 10 {
result += i
} else {
var temp = i
while temp > 0 {
result += temp % 10
temp /= 10
}
}
}
return result
}
```
var lst = lst // variable 'lst' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
let max = lst.max()!
var arr = [Int]()
var num = max
while num > 0 {
arr.append(num % 10)
num /= 10
}
var sum = 0
for i in arr {
sum += i
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
let max = lst.max()!
var arr = [Int]()
var num = max
while num > 0 {
arr.append(num % 10)
num /= 10
}
var sum = 0
for i in arr {
sum += i
}
return sum
}
```
// XCTAssertTrue failed
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
var sum = 0
for i in lst {
if i > max {
max = i
}
}
var str = String(max)
for c in str {
sum += Int(c.asciiValue!) - 48
}
return sum
}
```swift
// You are given an array of integers.
// You need to find the largest prime value and return the sum of its digits.
// Examples:
// skjkasdkd(lst: [0, 3, 2, 1, 3, 5, 7, 4, 5, 5, 5, 2, 181, 32, 4, 32, 3, 2, 32, 324, 4, 3]) == 10
// skjkasdkd(lst: [1, 0, 1, 8, 2, 4597, 2, 1, 3, 40, 1, 2, 1, 2, 4, 2, 5, 1]) == 25
// skjkasdkd(lst: [1, 3, 1, 32, 5107, 34, 83278, 109, 163, 23, 2323, 32, 30, 1, 9, 3]) == 13
// skjkasdkd(lst: [0, 724, 32, 71, 99, 32, 6, 0, 5, 91, 83, 0, 5, 6]) == 11
// skjkasdkd(lst: [0, 81, 12, 3, 1, 21]) == 3
// skjkasdkd(lst: [0, 8, 1, 2, 1, 7]) == 7
func skjkasdkd(lst: [Int]) -> Int {
var max = 0
var sum = 0
for i in lst {
if i > max {
max = i
}
}
var str = String(max)
for c in str {
sum += Int(c.asciiValue!) - 48
}
return sum
}
```
var str = String(max) // variable 'str' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i < n {
if isPrime(i) {
result.append(i)
}
i += 1
}
return result
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i < n {
if isPrime(i) {
result.append(i)
}
i += 1
}
return result
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
if isPrime(i) { // missing argument label 'n:' in call
func countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
if isPrime(i) {
result.append(i)
}
}
return result
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...num {
if num % i == 0 {
return false
}
}
return true
}
```
if isPrime(i) { // missing argument label 'num:' in call
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i < n {
if isPrime(i) {
result.append(i)
}
i += 1
}
return result
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
var i = 2
while i < n {
if isPrime(i) {
result.append(i)
}
i += 1
}
return result
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
if isPrime(i) { // missing argument label 'n:' in call
func countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result: [Int] = []
for i in 2...n {
var isPrime = true
for j in 2...i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```swift
// Implement a function that takes an non-negative integer and returns an array of the first n
// integers that are prime numbers and less than n.
// for example:
// countUpTo(n: 5) == [2, 3]
// countUpTo(n: 11) == [2, 3, 5, 7]
// countUpTo(n: 0) == [] as [Int]
// countUpTo(n: 20) == [2, 3, 5, 7, 11, 13, 17, 19]
// countUpTo(n: 1) == [] as [Int]
// countUpTo(n: 18) == [2, 3, 5, 7, 11, 13, 17]
func countUpTo(n: Int) -> [Int] {
var result = [Int]()
for i in 2...n {
var isPrime = true
for j in 2..<i {
if i % j == 0 {
isPrime = false
break
}
}
if isPrime {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
var result = 0
if a != 0 {
result += multiply(a: a, b: b * 10)
}
if b != 0 {
result += multiply(a: a * 10, b: b)
}
return result
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
var result = 0
if a != 0 {
result += multiply(a: a, b: b * 10)
}
if b != 0 {
result += multiply(a: a * 10, b: b)
}
return result
}
```
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return (a * b)
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return (a * b)
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return a * b
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return (a * b)
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
let a = a % 10
let b = b % 10
return (a * b)
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
var result = 0
for _ in 0..<a {
result += b
}
return result
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
var result = 0
for _ in 0..<a {
result += b
}
return result
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var res = 0
while a > 0 {
if a & 1 == 1 {
res += b
}
b <<= 1
a >>= 1
}
return res
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var res = 0
while a > 0 {
if a & 1 == 1 {
res += b
}
b <<= 1
a >>= 1
}
return res
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
var res = 0
var i = 0
while a > 0 {
if a & 1 == 1 {
res += b << i
}
b <<= 1
i += 1
a >>= 1
}
return res
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
if a < 0 {
a = -a
}
if b < 0 {
b = -b
}
var res = 0
var i = 0
while a > 0 {
if a & 1 == 1 {
res += b << i
}
b <<= 1
i += 1
a >>= 1
}
return res
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var res = 0
while a > 0 {
if a % 10 != 0 {
res += b % 10
}
b *= 10
a /= 10
}
return res
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var res = 0
while a > 0 {
if a % 10 != 0 {
res += b % 10
}
b *= 10
a /= 10
}
return res
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var result = 0
while a > 0 {
if a % 10 != 0 {
result += b % 10
}
b /= 10
a /= 10
}
return result
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var result = 0
while a > 0 {
if a % 10 != 0 {
result += b % 10
}
b /= 10
a /= 10
}
return result
}
```
// XCTAssertTrue failed
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var res = 0
while a > 0 {
if a & 1 == 1 {
res += b
}
b <<= 1
a >>= 1
}
return res
}
```swift
// Complete the function that takes two integers and returns
// the product of their unit digits.
// Assume the input is always valid.
// Examples:
// multiply(a: 148, b: 412) == 16
// multiply(a: 19, b: 28) == 72
// multiply(a: 2020, b: 1851) == 0
// multiply(a: 14, b: -15) == 20
func multiply(a: Int, b: Int) -> Int {
var a = a
var b = b
var res = 0
while a > 0 {
if a & 1 == 1 {
res += b
}
b <<= 1
a >>= 1
}
return res
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isUppercase {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isVowel {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isVowel {
count += 1
}
}
return count
}
func countVowels(s: String) -> Int {
var count = 0
for c in s {
if c.isVowel {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isUppercase {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isVowel {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isVowel {
count += 1
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for c in s {
if c.isVowel {
count += 1
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for c in s {
if c.isVowel {
count += 1
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for c in s {
if c.isVowel {
count += 1
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dBBE") == 0
func countVowels(s: String) -> Int {
var count = 0
for c in s {
if c.isVowel {
count += 1
}
}
return count
}
```
```swift
// Given a string s, count the number of vowels in even indices.
// For example:
// countVowels(s: "aBCdEf") == 1
// countVowels(s: "abcdefg") == 6
// countVowels(s: "dB
if c.isVowel { // value of type 'String.Element' (aka 'Character') has no member 'isVowel'
func countVowels(s: String) -> Int { // invalid redeclaration of 'countVowels(s:)'
if c.isVowel { // value of type 'String.Element' (aka 'Character') has no member 'isVowel'
func countVowels(s: String) -> Int { // invalid redeclaration of 'countVowels(s:)'
if c.isVowel { // value of type 'Character' has no member 'isVowel'
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
func countUpper(s: String) -> Int {
let regex = "\\p{Lu}"
let count = s.filter { (char) -> Bool in
return char.isLetter && regex.range(of: String(char)).count > 0
}.count
return count
}
func countUpper(s: String) -> Int {
let vowels = "AEIOUaeiou"
let count = s.filter { (char) -> Bool in
return vowels.contains(String(char))
}.count
return count
}
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase && count % 2 == 0 {
count += 1
}
}
return count
}
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
```
### 解法二:正则表达式
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let regex = "\\p{Lu}"
let count = s.filter { (char) -> Bool in
return char.isLetter && regex.range(of: String(char)).count > 0
}.count
return count
}
```
### 解法三:字符串替换
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let vowels = "AEIOUaeiou"
let count = s.filter { (char) -> Bool in
return vowels.contains(String(char))
}.count
return count
}
```
### 解法四:字符串遍历
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
```
### 解法五:字符串遍历
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase && count % 2 == 0 {
count += 1
}
}
return count
}
```
### 解法六:字符串遍历
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase {
count += 1
}
}
return count
}
```
### 解法七:字符串遍历
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase && count % 2 ==
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
return char.isLetter && regex.range(of: String(char)).count > 0 // referencing property 'count' on 'Range' requires that 'String.Index' conform to 'Strideable'
return char.isLetter && regex.range(of: String(char)).count > 0 // referencing property 'count' on 'Range' requires that 'String.Index.Stride' conform to 'SignedInteger'
return char.isLetter && regex.range(of: String(char)).count > 0 // value of optional type 'Range<String.Index>?' must be unwrapped to refer to member 'count' of wrapped base type 'Range<String.Index>'
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
func countUpper(s: String) -> Int {
let count = s.count
var count = 0
for i in 0..<count {
let c = s[s.index(s.startIndex, offsetBy: i)]
if c.isUppercase {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let count = s.count
var count = 0
for i in 0..<count {
let c = s[s.index(s.startIndex, offsetBy: i)]
if c.isUppercase {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
```
var count = 0 // invalid redeclaration of 'count'
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase {
if index % 2 == 0 {
count += 1
}
}
}
return count
}
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase {
if count % 2 == 0 {
count += 1
}
}
}
return count
}
func countUpper(s: String) -> Int {
let regex = "[AEIOU]"
let count = s.replacingOccurrences(of: regex, with: "").count
return count / 2
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase {
if index % 2 == 0 {
count += 1
}
}
}
return count
}
```
### 方法二:遍历计数
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for char in s {
if char.isUppercase {
if count % 2 == 0 {
count += 1
}
}
}
return count
}
```
### 方法三:正则表达式
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let regex = "[AEIOU]"
let count = s.replacingOccurrences(of: regex, with: "").count
return count / 2
}
```
### 方法四:正则表达式
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let regex = "[AEIOU]"
let count = s.replacingOccurrences(of: regex, with: "").count
return count / 2
}
```
### 方法五:正则表达式
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let regex = "[AEIOU]"
let count = s.replacingOccurrences(of: regex, with: "").count
return count / 2
}
```
### 方法六:正则表达式
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let regex = "[AEIOU]"
let count = s.replacingOccurrences(of: regex, with: "").count
return count / 2
}
```
### 方法七:正则表达式
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let regex = "[AEIOU]"
let count = s.replacingOccurrences(of: regex, with: "").count
return count / 2
}
```
### 方法八:
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
func countUpper(s: String) -> Int { // invalid redeclaration of 'countUpper(s:)'
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isUppercase && i % 2 == 0 {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isUppercase && i % 2 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isUppercase {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (i, c) in s.enumerated() {
if c.isUppercase {
if i % 2 == 0 {
count += 1
}
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
let count = s.count
var result = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
result += 1
}
}
return result
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let count = s.count
var result = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
result += 1
}
}
return result
}
```
let count = s.count // initialization of immutable value 'count' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
var count = 0
for (index, char) in s.enumerated() {
if char.isUppercase && index % 2 == 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countUpper(s: String) -> Int {
let count = s.count
var result = 0
for i in 0..<count {
if s[s.index(s.startIndex, offsetBy: i)] == "A" || s[s.index(s.startIndex, offsetBy: i)] == "E" || s[s.index(s.startIndex, offsetBy: i)] == "I" || s[s.index(s.startIndex, offsetBy: i)] == "O" || s[s.index(s.startIndex, offsetBy: i)] == "U" {
if i % 2 == 0 {
result += 1
}
}
}
return result
}
```swift
// Given a string s, count the number of uppercase vowels in even indices.
// For example:
// countUpper(s: "aBCdEf") == 1
// countUpper(s: "abcdefg") == 0
// countUpper(s: "dBBE") == 0
func countUpper(s: String) -> Int {
let count = s.count
var result = 0
for i in 0..<count {
if s[s.index(s.startIndex, offsetBy: i)] == "A" || s[s.index(s.startIndex, offsetBy: i)] == "E" || s[s.index(s.startIndex, offsetBy: i)] == "I" || s[s.index(s.startIndex, offsetBy: i)] == "O" || s[s.index(s.startIndex, offsetBy: i)] == "U" {
if i % 2 == 0 {
result += 1
}
}
}
return result
}
```
func closestInteger(value: String) -> Int {
let num = Double(value)
let absNum = abs(num)
let intNum = Int(absNum)
let intNumPlusOne = intNum + 1
let intNumMinusOne = intNum - 1
let absIntNumPlusOne = abs(intNumPlusOne)
let absIntNumMinusOne = abs(intNumMinusOne)
let absNumPlusOne = absNum + 1
let absNumMinusOne = absNum - 1
if absNumPlusOne < absNumMinusOne {
return absIntNumPlusOne
} else {
return absIntNumMinusOne
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let absNum = abs(num)
let intNum = Int(absNum)
let intNumPlusOne = intNum + 1
let intNumMinusOne = intNum - 1
let absIntNumPlusOne = abs(intNumPlusOne)
let absIntNumMinusOne = abs(intNumMinusOne)
let absNumPlusOne = absNum + 1
let absNumMinusOne = absNum - 1
if absNumPlusOne < absNumMinusOne {
return absIntNumPlusOne
} else {
return absIntNumMinusOne
}
}
```
let absNum = abs(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff > 0.5 {
return int + 1
}
return int
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff > 0.5 {
return int + 1
}
return int
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // cannot convert value of type 'Double?' to expected argument type 'Int'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
if abs(num - int) < 0.5 {
return int
} else {
return int + (num > int ? 1 : -1)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
if abs(num - int) < 0.5 {
return int
} else {
return int + (num > int ? 1 : -1)
}
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
if abs(num - int) < 0.5 { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return int + (num > int ? 1 : -1) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(int))
if diff > 0.5 {
return int + 1
} else {
return int
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(int))
if diff > 0.5 {
return int + 1
} else {
return int
}
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(int)) // cannot convert value of type 'Double?' to expected argument type 'Int'
func closestInteger(value: String) -> Int {
let num = Double(value)
let integer = Int(num)
let float = num - integer
if float > 0.5 {
return integer + 1
} else {
return integer
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let integer = Int(num)
let float = num - integer
if float > 0.5 {
return integer + 1
} else {
return integer
}
}
```
let integer = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff < 0.5 {
return int
} else if diff < 1 {
return int + 1
} else {
return int - 1
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff < 0.5 {
return int
} else if diff < 1 {
return int + 1
} else {
return int - 1
}
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // cannot convert value of type 'Double?' to expected argument type 'Int'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff < 0.5 {
return int
} else {
return int + (diff > 0.5 ? 1 : -1)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff < 0.5 {
return int
} else {
return int + (diff > 0.5 ? 1 : -1)
}
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // cannot convert value of type 'Double?' to expected argument type 'Int'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff < 0.5 {
return int
} else {
return int + (diff > 0.5 ? 1 : -1)
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
let diff = abs(num - Int(num))
if diff < 0.5 {
return int
} else {
return int + (diff > 0.5 ? 1 : -1)
}
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
let diff = abs(num - Int(num)) // cannot convert value of type 'Double?' to expected argument type 'Int'
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
if abs(num - int) < 0.5 {
return int
} else {
return int > num ? int - 1 : int + 1
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
let num = Double(value)
let int = Int(num)
if abs(num - int) < 0.5 {
return int
} else {
return int > num ? int - 1 : int + 1
}
}
```
let int = Int(num) // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
if abs(num - int) < 0.5 { // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
return int > num ? int - 1 : int + 1 // value of optional type 'Double?' must be unwrapped to a value of type 'Double'
func closestInteger(value: String) -> Int {
var num = Int(value)!
let left = num - 1
let right = num + 1
let leftAbs = abs(left)
let rightAbs = abs(right)
if leftAbs < rightAbs {
return left
} else {
return right
}
}
```swift
// Create a function that takes a value (string) representing a number
// and returns the closest integer to it. If the number is equidistant
// from two integers, round it away from zero.
// Examples
// Note:
// Rounding away from zero means that if the given number is equidistant
// from two integers, the one you should return is the one that is the
// farthest from zero. For example closest_integer("14.5") should
// return 15 and closest_integer("-14.5") should return -15.
// closestInteger(value: "10") == 10
// closestInteger(value: "15.3") == 15
func closestInteger(value: String) -> Int {
var num = Int(value)!
let left = num - 1
let right = num + 1
let leftAbs = abs(left)
let rightAbs = abs(right)
if leftAbs < rightAbs {
return left
} else {
return right
}
}
```
var num = Int(value)! // variable 'num' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
result.append(n)
for i in 1..<n {
result.append(result[i] % 2 == 0 ? result[i] + 1 : result[i] + 2)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
result.append(n)
for i in 1..<n {
result.append(result[i] % 2 == 0 ? result[i] + 1 : result[i] + 2)
}
return result
}
```
// Fatal error: Index out of range
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(getNextLevel(n: i))
}
return result
}
func getNextLevel(n: Int) -> Int {
if n % 2 == 0 {
return n + 1
} else {
return n + 2
}
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(getNextLevel(n: i))
}
return result
}
func getNextLevel(n: Int) -> Int {
if n % 2 == 0 {
return n + 1
} else {
return n + 2
}
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 + 1)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 + 1)
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(getNextLevel(n: i))
}
return result
}
func getNextLevel(n: Int) -> Int {
if n % 2 == 0 {
return n + 1
} else {
return n + 2
}
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(getNextLevel(n: i))
}
return result
}
func getNextLevel(n: Int) -> Int {
if n % 2 == 0 {
return n + 1
} else {
return n + 2
}
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(i * 2)
} else {
result.append(i * 2 + 1)
}
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(i * 2)
} else {
result.append(i * 2 + 1)
}
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i * 2 - 1)
}
return result
}
```
// XCTAssertTrue failed
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
result.append(n)
var n = n
while n > 1 {
n = n % 2 == 0 ? n / 2 : n / 2 + 1
result.append(n)
}
return result
}
```swift
// Given a positive integer n, you have to make a pile of n levels of stones.
// The first level has n stones.
// The number of stones in the next level is:
// - the next odd number if n is odd.
// - the next even number if n is even.
// Return the number of stones in each level in an array, where element at index
// i represents the number of stones in the level (i+1).
// Examples:
// makeAPile(n: 3) == [3, 5, 7]
func makeAPile(n: Int) -> [Int] {
var result = [Int]()
result.append(n)
var n = n
while n > 1 {
n = n % 2 == 0 ? n / 2 : n / 2 + 1
result.append(n)
}
return result
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let str = s.trimmingCharacters(in: .whitespaces)
let arr = str.components(separatedBy: ",")
var res = [String]()
for str in arr {
res.append(contentsOf: str.components(separatedBy: " "))
}
return res
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let str = s.trimmingCharacters(in: .whitespaces)
let arr = str.components(separatedBy: ",")
var res = [String]()
for str in arr {
res.append(contentsOf: str.components(separatedBy: " "))
}
return res
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
return words.flatMap { String($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
return words.flatMap { String($0) }
}
```
return words.flatMap { String($0) } // 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
return words.flatMap { String($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
return words.flatMap { String($0) }
}
```
return words.flatMap { String($0) } // 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
let result = words.flatMap { String($0) }
return result
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
let result = words.flatMap { String($0) }
return result
}
```
return result // cannot convert return expression of type '[String.Element]' (aka 'Array<Character>') to return type '[String]'
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
var result = [String]()
for word in words {
result.append(word.trimmingCharacters(in: .whitespaces))
}
return result
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
var result = [String]()
for word in words {
result.append(word.trimmingCharacters(in: .whitespaces))
}
return result
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let str = s.trimmingCharacters(in: .whitespacesAndNewlines)
let strArr = str.components(separatedBy: ",")
var resultArr = [String]()
for str in strArr {
let strArr = str.components(separatedBy: " ")
for s in strArr {
resultArr.append(s)
}
}
return resultArr
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let str = s.trimmingCharacters(in: .whitespacesAndNewlines)
let strArr = str.components(separatedBy: ",")
var resultArr = [String]()
for str in strArr {
let strArr = str.components(separatedBy: " ")
for s in strArr {
resultArr.append(s)
}
}
return resultArr
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
var result = [String]()
for word in words {
let trimmedWord = word.trimmingCharacters(in: .whitespaces)
if trimmedWord.count > 0 {
result.append(trimmedWord)
}
}
return result
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
var result = [String]()
for word in words {
let trimmedWord = word.trimmingCharacters(in: .whitespaces)
if trimmedWord.count > 0 {
result.append(trimmedWord)
}
}
return result
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
return words.flatMap { String($0) }
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
return words.flatMap { String($0) }
}
```
return words.flatMap { String($0) } // 'flatMap' is deprecated: Please use compactMap(_:) for the case where closure returns an optional value
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
let result = words.reduce([], { $0 + $1.components(separatedBy: " ") })
return result
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
let result = words.reduce([], { $0 + $1.components(separatedBy: " ") })
return result
}
```
// XCTAssertTrue failed
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
var result = [String]()
for word in words {
result.append(contentsOf: word.components(separatedBy: " "))
}
return result
}
```swift
// You will be given a string of words separated by commas or spaces. Your task is
// to split the string into words and return an array of the words.
// For example:
// wordsString(s: "Hi, my name is John") == ["Hi", "my", "name", "is", "John"]
// wordsString(s: "One, two, three, four, five, six") == ["One", "two", "three", "four", "five", "six"]
func wordsString(s: String) -> [String] {
let words = s.components(separatedBy: ",")
var result = [String]()
for word in words {
result.append(contentsOf: word.components(separatedBy: " "))
}
return result
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 1 {
x += 1
}
if y % 2 == 1 {
y += 1
}
if x > y {
return -1
}
return x + (y - x) / 2
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 1 {
x += 1
}
if y % 2 == 1 {
y += 1
}
if x > y {
return -1
}
return x + (y - x) / 2
}
```
x += 1 // left side of mutating operator isn't mutable: 'x' is a 'let' constant
y += 1 // left side of mutating operator isn't mutable: 'y' is a 'let' constant
func chooseNum(x: Int, y: Int) -> Int {
let max = max(x, y)
let min = min(x, y)
if min % 2 == 0 {
return min
}
let result = min + 1
while result <= max {
if result % 2 == 0 {
return result
}
result += 1
}
return -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
let max = max(x, y)
let min = min(x, y)
if min % 2 == 0 {
return min
}
let result = min + 1
while result <= max {
if result % 2 == 0 {
return result
}
result += 1
}
return -1
}
```
result += 1 // left side of mutating operator isn't mutable: 'result' is a 'let' constant
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
let min = min(x, y)
let max = max(x, y)
for i in stride(from: min, to: max, by: 2) {
return i
}
return -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
let min = min(x, y)
let max = max(x, y)
for i in stride(from: min, to: max, by: 2) {
return i
}
return -1
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
let max = max(x, y)
let min = min(x, y)
if min % 2 == 0 {
return min
}
let result = min + 1
while result <= max {
if result % 2 == 0 {
return result
}
result += 1
}
return -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
let max = max(x, y)
let min = min(x, y)
if min % 2 == 0 {
return min
}
let result = min + 1
while result <= max {
if result % 2 == 0 {
return result
}
result += 1
}
return -1
}
```
result += 1 // left side of mutating operator isn't mutable: 'result' is a 'let' constant
func chooseNum(x: Int, y: Int) -> Int {
let min = min(x, y)
let max = max(x, y)
if min % 2 == 0 {
return min
}
for i in min+1...max {
if i % 2 == 0 {
return i
}
}
return -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
let min = min(x, y)
let max = max(x, y)
if min % 2 == 0 {
return min
}
for i in min+1...max {
if i % 2 == 0 {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if x > y {
return -1
}
let mid = (x + y) / 2
if mid % 2 == 0 {
return mid
}
return chooseNum(x: mid + 1, y: y)
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if x > y {
return -1
}
let mid = (x + y) / 2
if mid % 2 == 0 {
return mid
}
return chooseNum(x: mid + 1, y: y)
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
if y % 2 == 0 {
return max(x, y)
} else {
return x
}
} else {
if y % 2 == 0 {
return y
} else {
return max(x, y)
}
}
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
if y % 2 == 0 {
return max(x, y)
} else {
return x
}
} else {
if y % 2 == 0 {
return y
} else {
return max(x, y)
}
}
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
if x > y {
return -1
}
var i = x
while i <= y {
if i % 2 == 0 {
return i
}
i += 1
}
return -1
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
if x > y {
return -1
}
var i = x
while i <= y {
if i % 2 == 0 {
return i
}
i += 1
}
return -1
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
if x == y {
return x
}
if x > y {
return -1
}
return chooseNum(x: x + 1, y: y)
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
if x % 2 == 0 {
return x
}
if y % 2 == 0 {
return y
}
if x == y {
return x
}
if x > y {
return -1
}
return chooseNum(x: x + 1, y: y)
}
```
// XCTAssertTrue failed
func chooseNum(x: Int, y: Int) -> Int {
let a = x % 2 == 0 ? x : x + 1
let b = y % 2 == 0 ? y : y + 1
return a > b ? -1 : a
}
```swift
// This function takes two positive numbers x and y and returns the
// biggest even integer number that is in the range [x, y] inclusive. If
// there's no such number, then the function should return -1.
// For example:
// chooseNum(x: 12, y: 15) == 14
// chooseNum(x: 13, y: 12) == -1
func chooseNum(x: Int, y: Int) -> Int {
let a = x % 2 == 0 ? x : x + 1
let b = y % 2 == 0 ? y : y + 1
return a > b ? -1 : a
}
```
// XCTAssertTrue failed
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let avg = sum / 2
let rounded = avg.rounded()
return .success(String(format: "0b%lx", ln: rounded))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let avg = sum / 2
let rounded = avg.rounded()
return .success(String(format: "0b%lx", ln: rounded))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let rounded = avg.rounded() // value of type 'Int' has no member 'rounded'
return .success(String(format: "0b%lx", ln: rounded)) // extraneous argument label 'ln:' in call
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let average = sum / 2
let rounded = average.rounded()
return .success(String(format: "0b%08lx", rounded))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let average = sum / 2
let rounded = average.rounded()
return .success(String(format: "0b%08lx", rounded))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let rounded = average.rounded() // value of type 'Int' has no member 'rounded'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let roundedAvg = Int(avg)
guard roundedAvg == avg else { return .failure(roundedAvg) }
return .success(String(Int(avg, radix: 2)))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let roundedAvg = Int(avg)
guard roundedAvg == avg else { return .failure(roundedAvg) }
return .success(String(Int(avg, radix: 2)))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
return .success(String(Int(avg, radix: 2))) // initializer 'init(_:radix:)' requires that 'Int' conform to 'StringProtocol'
return .success(String(Int(avg, radix: 2))) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let avg = (n + m) / 2
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let avg = (n + m) / 2
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0 else {
return .failure(n)
}
let sum = n + m
let avg = sum / 2
let roundedAvg = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg))
return .success(binary)
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0 else {
return .failure(n)
}
let sum = n + m
let avg = sum / 2
let roundedAvg = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg))
return .success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg)) // cannot find 'lldb_format_binary' in scope
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0 else { return .failure(0) }
guard n <= m else { return .failure(-1) }
let avg = (n + m) / 2
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0 else { return .failure(0) }
guard n <= m else { return .failure(-1) }
let avg = (n + m) / 2
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0, n <= m else { return .failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let roundedAvg = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg))
return .success(binary)
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0, n <= m else { return .failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let roundedAvg = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg))
return .success(binary)
}
```
### 解法二:二分查找
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n > 0, m > 0, n <= m else { return .failure(-1) }
let sum = (n + m) * (m - n + 1) / 2
let avg = sum / (m - n + 1)
let roundedAvg = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg))
return .success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let binary = String(format: "0b%@", lldb_format_binary(value: roundedAvg)) // cannot find 'lldb_format_binary' in scope
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let avg = (n + m) / 2
return .success(String(avg, radix: 2))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let avg = (n + m) / 2
return .success(String(avg, radix: 2))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let avg = sum / 2
let rounded = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(lldb_create_integer(lldb_get_target_byte_size(), rounded)))
return .success(binary)
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let avg = sum / 2
let rounded = Int(avg)
let binary = String(format: "0b%@", lldb_format_binary(lldb_create_integer(lldb_get_target_byte_size(), rounded)))
return .success(binary)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let binary = String(format: "0b%@", lldb_format_binary(lldb_create_integer(lldb_get_target_byte_size(), rounded))) // cannot find 'lldb_create_integer' in scope
let binary = String(format: "0b%@", lldb_format_binary(lldb_create_integer(lldb_get_target_byte_size(), rounded))) // cannot find 'lldb_format_binary' in scope
let binary = String(format: "0b%@", lldb_format_binary(lldb_create_integer(lldb_get_target_byte_size(), rounded))) // cannot find 'lldb_get_target_byte_size' in scope
extension Int: Error {
}
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let avg = sum / 2
let roundedAvg = Int(rounded(avg))
return .success(String(format: "0b%@", binary: roundedAvg))
}
func binary(_ n: Int) -> String {
return String(format: "0b%@", binary: n)
}
func rounded(_ n: Double) -> Int {
return Int(round(n))
}
```swift
extension Int: Error {}
// You are given two positive integers n and m, and your task is to compute the
// average of the integers from n through m (including n and m).
// Round the answer to the nearest integer and convert that to binary.
// If n is greater than m, return -1.
// Example:
// roundedAvg(n: 1, m: 5) == .success("0b11")
// roundedAvg(n: 7, m: 5) == .failure(-1)
// roundedAvg(n: 10, m: 20) == .success("0b1111")
// roundedAvg(n: 20, m: 33) == .success("0b11010")
func roundedAvg(n: Int, m: Int) -> Result<String, Int> {
guard n <= m else { return .failure(-1) }
let sum = n + m
let avg = sum / 2
let roundedAvg = Int(rounded(avg))
return .success(String(format: "0b%@", binary: roundedAvg))
}
func binary(_ n: Int) -> String {
return String(format: "0b%@", binary: n)
}
func rounded(_ n: Double) -> Int {
return Int(round(n))
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
let roundedAvg = Int(rounded(avg)) // cannot convert value of type 'Int' to expected argument type 'Double'
return .success(String(format: "0b%@", binary: roundedAvg)) // extraneous argument label 'binary:' in call
return String(format: "0b%@", binary: n) // extraneous argument label 'binary:' in call
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i == 0 {
continue
}
var temp = i
var isEven = false
while temp > 0 {
if temp % 2 == 0 {
isEven = true
break
}
temp /= 10
}
if !isEven {
result.append(i)
}
}
return result.sorted()
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i == 0 {
continue
}
var temp = i
var isEven = false
while temp > 0 {
if temp % 2 == 0 {
isEven = true
break
}
temp /= 10
}
if !isEven {
result.append(i)
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i == 0 {
continue
}
var temp = i
var flag = true
while temp > 0 {
if temp % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
result.append(i)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for i in x {
if i == 0 {
continue
}
var temp = i
var flag = true
while temp > 0 {
if temp % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
result.append(i)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var temp = num
var hasEven = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
hasEven = true
break
}
temp /= 10
}
if !hasEven {
result.append(num)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var temp = num
var hasEven = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
hasEven = true
break
}
temp /= 10
}
if !hasEven {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var temp = num
var hasEvenDigit = false
while temp > 0 {
if temp % 10 % 2 == 0 {
hasEvenDigit = true
break
}
temp /= 10
}
if !hasEvenDigit {
result.append(num)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var temp = num
var hasEvenDigit = false
while temp > 0 {
if temp % 10 % 2 == 0 {
hasEvenDigit = true
break
}
temp /= 10
}
if !hasEvenDigit {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num == 0 {
continue
}
var temp = num
var hasEvenDigit = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
hasEvenDigit = true
break
}
temp /= 10
}
if !hasEvenDigit {
result.append(num)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num == 0 {
continue
}
var temp = num
var hasEvenDigit = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
hasEvenDigit = true
break
}
temp /= 10
}
if !hasEvenDigit {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num < 10 {
result.append(num)
} else {
var temp = num
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
result.append(num)
}
}
}
return result.sorted()
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num < 10 {
result.append(num)
} else {
var temp = num
var flag = true
while temp > 0 {
if temp % 10 % 2 == 0 {
flag = false
break
}
temp /= 10
}
if flag {
result.append(num)
}
}
}
return result.sorted()
}
```
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num == 0 {
continue
}
var temp = num
var hasEven = false
while temp > 0 {
if temp % 10 % 2 == 0 {
hasEven = true
break
}
temp /= 10
}
if !hasEven {
result.append(num)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num == 0 {
continue
}
var temp = num
var hasEven = false
while temp > 0 {
if temp % 10 % 2 == 0 {
hasEven = true
break
}
temp /= 10
}
if !hasEven {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num == 0 {
continue
}
var temp = num
var hasEven = false
while temp > 0 {
if temp % 2 == 0 {
hasEven = true
break
}
temp /= 10
}
if !hasEven {
result.append(num)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
if num == 0 {
continue
}
var temp = num
var hasEven = false
while temp > 0 {
if temp % 2 == 0 {
hasEven = true
break
}
temp /= 10
}
if !hasEven {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var temp = num
var hasEvenDigit = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
hasEvenDigit = true
break
}
temp /= 10
}
if !hasEvenDigit {
result.append(num)
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
for num in x {
var temp = num
var hasEvenDigit = false
while temp > 0 {
let digit = temp % 10
if digit % 2 == 0 {
hasEvenDigit = true
break
}
temp /= 10
}
if !hasEvenDigit {
result.append(num)
}
}
return result
}
```
// XCTAssertTrue failed
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
var temp = x
for i in 0..<temp.count {
if temp[i] % 2 == 0 {
temp[i] = 0
}
}
for i in 0..<temp.count {
if temp[i] != 0 {
result.append(temp[i])
}
}
return result
}
```swift
// Given an array of positive integers x. return a sorted array of all
// elements that hasn't any even digit.
// Note: Returned array should be sorted in increasing order.
// For example:
// uniqueDigits(x: [15, 33, 1422, 1]) == [1, 15, 33]
// uniqueDigits(x: [152, 323, 1422, 10]) == [] as [Int]
func uniqueDigits(x: [Int]) -> [Int] {
var result = [Int]()
var temp = x
for i in 0..<temp.count {
if temp[i] % 2 == 0 {
temp[i] = 0
}
}
for i in 0..<temp.count {
if temp[i] != 0 {
result.append(temp[i])
}
}
return result
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let map = [1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]
var result = [String]()
for num in arr {
if num > 0 && num <= 9 {
result.append(map[num]!)
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
let map = [1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]
var result = [String]()
for num in arr {
if num > 0 && num <= 9 {
result.append(map[num]!)
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let nums = arr.filter { $0 > 0 && $0 < 10 }
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
let result = nums.map { names[$0 - 1] }
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
let nums = arr.filter { $0 > 0 && $0 < 10 }
let names = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"]
let result = nums.map { names[$0 - 1] }
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let dict = [1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]
var result = [String]()
for num in arr {
if num > 0 && num < 10 {
result.append(dict[num]!)
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
let dict = [1: "One", 2: "Two", 3: "Three", 4: "Four", 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"]
var result = [String]()
for num in arr {
if num > 0 && num < 10 {
result.append(dict[num]!)
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
let map = ["One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9]
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(map[String(i)]!)
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
let map = ["One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5, "Six": 6, "Seven": 7, "Eight": 8, "Nine": 9]
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(map[String(i)]!)
}
}
return result.reversed()
}
```
result.append(map[String(i)]!) // cannot convert value of type 'Int' to expected argument type 'String'
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i > 0 && i < 10 {
result.append(String(i))
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for num in arr {
if num > 0 && num < 10 {
result.append(num.description)
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for num in arr {
if num > 0 && num < 10 {
result.append(num.description)
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
return result.reversed()
}
```swift
// Given an array of integers, sort the integers that are between 1 and 9 inclusive,
// reverse the resulting array, and then replace each digit by its corresponding name from
// "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine".
// For example:
// If the array is empty, return an empty array:
// If the array has any strange number ignore it:
// byLength(arr: [2, 1, 1, 4, 5, 8, 2, 3]) == ["Eight", "Five", "Four", "Three", "Two", "Two", "One", "One"]
// byLength(arr: [] as [Int]) == [] as [String]
// byLength(arr: [1, -1, 55]) == ["One"]
func byLength(arr: [Int]) -> [String] {
var result = [String]()
for i in arr {
if i >= 1 && i <= 9 {
result.append(String(i))
}
}
return result.reversed()
}
```
// XCTAssertTrue failed
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func sum(i: Int) -> Int {
var sum = 0
for j in 1...i {
sum += j
}
return sum
}
func factorial(i: Int) -> Int {
var result = 1
for j in 1...i {
result *= j
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func sum(i: Int) -> Int {
var sum = 0
for j in 1...i {
sum += j
}
return sum
}
func factorial(i: Int) -> Int {
var result = 1
for j in 1...i {
result *= j
}
return result
}
```
result.append(factorial(i)) // missing argument label 'i:' in call
result.append(sum(i)) // missing argument label 'i:' in call
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func sum(i: Int) -> Int {
var sum = 0
for j in 1...i {
sum += j
}
return sum
}
func factorial(i: Int) -> Int {
var result = 1
for j in 1...i {
result *= j
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func sum(i: Int) -> Int {
var sum = 0
for j in 1...i {
sum += j
}
return sum
}
func factorial(i: Int) -> Int {
var result = 1
for j in 1...i {
result *= j
}
return result
}
```
result.append(factorial(i)) // missing argument label 'i:' in call
result.append(sum(i)) // missing argument label 'i:' in call
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
if n == 0 {
return 1
}
return n * factorial(n - 1)
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
if n == 0 {
return 1
}
return n * factorial(n - 1)
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0 ? factorial(i) : sum(i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0 ? factorial(i) : sum(i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
if n == 0 {
return 1
}
return n * factorial(n - 1)
}
func sum(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
if n == 0 {
return 1
}
return n * factorial(n - 1)
}
func sum(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0 ? factorial(i) : sum(i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
result.append(i % 2 == 0 ? factorial(i) : sum(i))
}
return result
}
func factorial(_ n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
func sum(_ n: Int) -> Int {
var result = 0
for i in 1...n {
result += i
}
return result
}
```
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
if n == 1 {
return 1
}
return n * factorial(n - 1)
}
func sum(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```swift
// Implement the function f that takes n as a parameter,
// and returns an array of size n, such that the value of the element at index i is the factorial of i if i is even
// or the sum of numbers from 1 to i otherwise.
// i starts from 1.
// the factorial of i is the multiplication of the numbers from 1 to i (1 * 2 * ... * i).
// Example:
// f(n: 5) == [1, 2, 6, 24, 15]
func f(n: Int) -> [Int] {
var result = [Int]()
for i in 1...n {
if i % 2 == 0 {
result.append(factorial(i))
} else {
result.append(sum(i))
}
}
return result
}
func factorial(_ n: Int) -> Int {
if n == 1 {
return 1
}
return n * factorial(n - 1)
}
func sum(_ n: Int) -> Int {
var sum = 0
for i in 1...n {
sum += i
}
return sum
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let isPalindrome = isPalindrome(i)
if isPalindrome {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let isPalindrome = isPalindrome(i)
if isPalindrome {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(n: Int) -> Bool {
var num = n
var reverse = 0
while num > 0 {
reverse = reverse * 10 + num % 10
num /= 10
}
return n == reverse
}
```
let isPalindrome = isPalindrome(i) // missing argument label 'n:' in call
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(num: Int) -> Bool {
var num = num
var res = 0
while num > 0 {
res = res * 10 + num % 10
num /= 10
}
return res == num
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(num: Int) -> Bool {
var num = num
var res = 0
while num > 0 {
res = res * 10 + num % 10
num /= 10
}
return res == num
}
```
if isPalindrome(i) { // missing argument label 'num:' in call
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let isPalindrome = isPalindrome(i)
if isPalindrome {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(i: Int) -> Bool {
var i = i
var res = 0
while i > 0 {
res = res * 10 + i % 10
i /= 10
}
return res == i
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let isPalindrome = isPalindrome(i)
if isPalindrome {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(i: Int) -> Bool {
var i = i
var res = 0
while i > 0 {
res = res * 10 + i % 10
i /= 10
}
return res == i
}
```
let isPalindrome = isPalindrome(i) // missing argument label 'i:' in call
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(num: Int) -> Bool {
var num = num
var res = 0
while num > 0 {
res = res * 10 + num % 10
num /= 10
}
return res == num
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(num: Int) -> Bool {
var num = num
var res = 0
while num > 0 {
res = res * 10 + num % 10
num /= 10
}
return res == num
}
```
if isPalindrome(i) { // missing argument label 'num:' in call
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if isPalindrome(str: str) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(str: String) -> Bool {
let s = Array(str)
var left = 0
var right = s.count - 1
while left < right {
if s[left] != s[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if isPalindrome(str: str) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(str: String) -> Bool {
let s = Array(str)
var left = 0
var right = s.count - 1
while left < right {
if s[left] != s[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if isPalindrome(str) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ str: String) -> Bool {
let chars = Array(str)
var left = 0
var right = chars.count - 1
while left < right {
if chars[left] != chars[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0
var odd = 0
for i in 1...n {
let str = String(i)
if isPalindrome(str) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ str: String) -> Bool {
let chars = Array(str)
var left = 0
var right = chars.count - 1
while left < right {
if chars[left] != chars[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let s = String(i)
if isPalindrome(s) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ s: String) -> Bool {
let s = Array(s)
var left = 0, right = s.count - 1
while left < right {
if s[left] != s[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let s = String(i)
if isPalindrome(s) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ s: String) -> Bool {
let s = Array(s)
var left = 0, right = s.count - 1
while left < right {
if s[left] != s[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let s = String(i)
if isPalindrome(s) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ s: String) -> Bool {
let s = s.map { String($0) }
let n = s.count
for i in 0..<n/2 {
if s[i] != s[n-1-i] {
return false
}
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let s = String(i)
if isPalindrome(s) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ s: String) -> Bool {
let s = s.map { String($0) }
let n = s.count
for i in 0..<n/2 {
if s[i] != s[n-1-i] {
return false
}
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let s = String(i)
if isPalindrome(s) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ s: String) -> Bool {
let s = Array(s)
var l = 0, r = s.count - 1
while l < r {
if s[l] != s[r] {
return false
}
l += 1
r -= 1
}
return true
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
let s = String(i)
if isPalindrome(s) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ s: String) -> Bool {
let s = Array(s)
var l = 0, r = s.count - 1
while l < r {
if s[l] != s[r] {
return false
}
l += 1
r -= 1
}
return true
}
```
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var res = 0
while num > 0 {
res = res * 10 + num % 10
num /= 10
}
return res == n
}
```swift
// Given a positive integer n, return a tuple that has the number of even and odd
// integer palindromes that fall within the range(1, n), inclusive.
// Example 1:
// Explanation:
// Integer palindrome are 1, 2, 3. one of them is even, and two of them are odd.
// Example 2:
// Explanation:
// Integer palindrome are 1, 2, 3, 4, 5, 6, 7, 8, 9, 11. four of them are even, and 6 of them are odd.
// Note:
// 1. 1 <= n <= 10^3
// 2. returned tuple has the number of even and odd integer palindromes respectively.
// evenOddPalindrome(n: 3) == (1, 2)
// evenOddPalindrome(n: 12) == (4, 6)
func evenOddPalindrome(n: Int) -> (Int, Int) {
var even = 0, odd = 0
for i in 1...n {
if isPalindrome(i) {
if i % 2 == 0 {
even += 1
} else {
odd += 1
}
}
}
return (even, odd)
}
func isPalindrome(_ n: Int) -> Bool {
var num = n
var res = 0
while num > 0 {
res = res * 10 + num % 10
num /= 10
}
return res == n
}
```
func countNums(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count {
var sum = 0
for j in 0..<arr[i] {
sum += abs(arr[i]) % 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count {
var sum = 0
for j in 0..<arr[i] {
sum += abs(arr[i]) % 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
for j in 0..<arr[i] { // immutable value 'j' was never used; consider replacing with '_' or removing it
// Fatal error: Range requires lowerBound <= upperBound
func countNums(arr: [Int]) -> Int {
var sum = 0
for num in arr {
sum += num
if sum > 0 {
sum = 0
}
}
return sum
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var sum = 0
for num in arr {
sum += num
if sum > 0 {
sum = 0
}
}
return sum
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var temp = num
while temp > 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var temp = num
while temp > 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var temp = num
while temp != 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var temp = num
while temp != 0 {
sum += temp % 10
temp /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for num in arr {
var sum = 0
var n = num
while n != 0 {
sum += n % 10
n /= 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var sum = 0
for num in arr {
var temp = num
while temp > 0 {
if temp > 0 {
sum += 1
}
temp = temp / 10
}
}
return sum
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var sum = 0
for num in arr {
var temp = num
while temp > 0 {
if temp > 0 {
sum += 1
}
temp = temp / 10
}
}
return sum
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count {
var sum = 0
for j in 0..<arr[i] {
sum += abs(arr[i]) % 10
}
if sum > 0 {
count += 1
}
}
return count
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var count = 0
for i in 0..<arr.count {
var sum = 0
for j in 0..<arr[i] {
sum += abs(arr[i]) % 10
}
if sum > 0 {
count += 1
}
}
return count
}
```
for j in 0..<arr[i] { // immutable value 'j' was never used; consider replacing with '_' or removing it
// Fatal error: Range requires lowerBound <= upperBound
func countNums(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
var temp = arr[i]
while temp != 0 {
if temp > 0 {
sum += 1
}
temp = temp / 10
}
}
return sum
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
var temp = arr[i]
while temp != 0 {
if temp > 0 {
sum += 1
}
temp = temp / 10
}
}
return sum
}
```
// XCTAssertTrue failed
func countNums(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
let num = arr[i]
if num > 0 {
sum += 1
}
if num < 0 {
let abs = abs(num)
let digits = abs.description.compactMap { Int(String($0))! }
for digit in digits {
if digit > 0 {
sum += 1
}
}
}
}
return sum
}
```swift
// Write a function count_nums which takes an array of integers and returns
// the number of elements which has a sum of digits > 0.
// If a number is negative, then its first signed digit will be negative:
// e.g. -123 has signed digits -1, 2, and 3.
// countNums(arr: [] as [Int]) == 0
// countNums(arr: [-1, 11, -11]) == 1
// countNums(arr: [1, 1, 2]) == 3
func countNums(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
let num = arr[i]
if num > 0 {
sum += 1
}
if num < 0 {
let abs = abs(num)
let digits = abs.description.compactMap { Int(String($0))! }
for digit in digits {
if digit > 0 {
sum += 1
}
}
}
}
return sum
}
```
// XCTAssertTrue failed
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
if count == 1 {
return true
}
return false
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var arr = arr
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
if count == 1 {
return true
}
return false
}
```
var arr = arr // variable 'arr' was never mutated; consider changing to 'let' constant
// Fatal error: Index out of range
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```swift
// We have an array 'arr' of N integers arr[1], arr[2], ..., arr[N].The
// numbers in the array will be randomly ordered. Your task is to determine if
// it is possible to get an array sorted in non-decreasing order by performing
// the following operation on the given array:
// You are allowed to perform right shift operation any number of times.
// One right shift operation means shifting all elements of the array by one
// position in the right direction. The last element of the array will be moved to
// the starting position in the array i.e. 0th index.
// If it is possible to obtain the sorted array by performing the above operation
// then return true else return false.
// If the given array is empty then return true.
// Note: The given array is guaranteed to have unique elements.
// For Example:
// Explanation: By performin 2 right shift operations, non-decreasing order can
// be achieved for the given array.
// Explanation:It is not possible to get non-decreasing order for the given
// array by performing any number of right shift operations.
// moveOneBall(arr: [3, 4, 5, 1, 2]) == true
// moveOneBall(arr: [3, 5, 4, 1, 2]) == false
func moveOneBall(arr: [Int]) -> Bool {
var count = 0
for i in 0..<arr.count {
if arr[i] > arr[i+1] {
count += 1
}
}
return count == 1
}
```
// Fatal error: Index out of range
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 1 {
i += 1
} else if lst2[j] % 2 == 1 {
j += 1
} else {
i += 1
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 1 {
i += 1
} else if lst2[j] % 2 == 1 {
j += 1
} else {
i += 1
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] == lst2[j] {
i += 1
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] == lst2[j] {
i += 1
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
j += 1
} else {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
j += 1
} else {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] == lst2[j] {
i += 1
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] == lst2[j] {
i += 1
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 1 {
i += 1
continue
}
if lst2[j] % 2 == 1 {
j += 1
continue
}
if lst1[i] == lst2[j] {
i += 1
j += 1
} else if lst1[i] < lst2[j] {
i += 1
} else {
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 1 {
i += 1
continue
}
if lst2[j] % 2 == 1 {
j += 1
continue
}
if lst1[i] == lst2[j] {
i += 1
j += 1
} else if lst1[i] < lst2[j] {
i += 1
} else {
j += 1
}
}
if i < lst1.count || j < lst2.count {
return "NO"
}
return "YES"
}
```
// XCTAssertTrue failed
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
// 1. 先判断两个数组的长度是否相等
guard lst1.count == lst2.count else {
return "NO"
}
// 2. 判断两个数组是否相等
guard lst1 == lst2 else {
return "NO"
}
// 3. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 4. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 5. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 6. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 7. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 8. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 9. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 10. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 11. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 12. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 13. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 14. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 15. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 16. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 17. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 18. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 19. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 20. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 21. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 22. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 23. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 24. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 25. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 26. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
// 27. 判断两个数组是否相等
guard lst1.count > 0 else {
return "YES"
}
//
XCTAssertTrue(exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES") // cannot find 'exchange' in scope
XCTAssertTrue(exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO") // cannot find 'exchange' in scope
XCTAssertTrue(exchange(lst1: [1, 2, 3, 4], lst2: [2, 1, 4, 3]) == "YES") // cannot find 'exchange' in scope
XCTAssertTrue(exchange(lst1: [5, 7, 3], lst2: [2, 6, 4]) == "YES") // cannot find 'exchange' in scope
XCTAssertTrue(exchange(lst1: [5, 7, 3], lst2: [2, 6, 3]) == "NO") // cannot find 'exchange' in scope
XCTAssertTrue(exchange(lst1: [3, 2, 6, 1, 8, 9], lst2: [3, 5, 5, 1, 1, 1]) == "NO") // cannot find 'exchange' in scope
XCTAssertTrue(exchange(lst1: [100, 200], lst2: [200, 200]) == "YES") // cannot find 'exchange' in scope
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
j += 1
} else {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
} else if lst2[j] % 2 == 0 {
j += 1
} else {
return "NO"
}
}
return "YES"
}
```
// XCTAssertTrue failed
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
let n = lst1.count
let m = lst2.count
if n != m {
return "NO"
}
var i = 0
var j = 0
while i < n && j < m {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < n && j < m && lst1[i] % 2 == 0 && lst2[j] % 2 == 0 {
i += 1
j += 1
}
}
if i == n && j == m {
return "YES"
}
return "NO"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
let n = lst1.count
let m = lst2.count
if n != m {
return "NO"
}
var i = 0
var j = 0
while i < n && j < m {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < n && j < m && lst1[i] % 2 == 0 && lst2[j] % 2 == 0 {
i += 1
j += 1
}
}
if i == n && j == m {
return "YES"
}
return "NO"
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] != lst2[j] {
return "NO"
}
}
return "YES"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] != lst2[j] {
return "NO"
}
}
return "YES"
}
```
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] % 2 == 0 && lst2[j] % 2 == 0 {
i += 1
j += 1
}
}
if i == lst1.count && j == lst2.count {
return "YES"
}
return "NO"
}
```swift
// In this problem, you will implement a function that takes two arrays of numbers,
// and determines whether it is possible to perform an exchange of elements
// between them to make lst1 an array of only even numbers.
// There is no limit on the number of exchanged elements between lst1 and lst2.
// If it is possible to exchange elements between the lst1 and lst2 to make
// all the elements of lst1 to be even, return "YES".
// Otherwise, return "NO".
// For example:
// It is assumed that the input arrays will be non-empty.
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 2, 3, 4]) == "YES"
// exchange(lst1: [1, 2, 3, 4], lst2: [1, 5, 3, 4]) == "NO"
func exchange(lst1: [Int], lst2: [Int]) -> String {
var lst1 = lst1
var lst2 = lst2
lst1.sort()
lst2.sort()
var i = 0
var j = 0
while i < lst1.count && j < lst2.count {
if lst1[i] % 2 == 0 {
i += 1
}
if lst2[j] % 2 == 0 {
j += 1
}
if i < lst1.count && j < lst2.count && lst1[i] % 2 == 0 && lst2[j] % 2 == 0 {
i += 1
j += 1
}
}
if i == lst1.count && j == lst2.count {
return "YES"
}
return "NO"
}
```
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dict = [String : Int]()
for str in array {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var dict = [String : Int]()
for str in array {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```
if dict[str] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str]! += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let strArr = test.split(separator: " ")
for str in strArr {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let strArr = test.split(separator: " ")
for str in strArr {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```
if dict[str] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str]! += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let arr = test.split(separator: " ")
for str in arr {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let arr = test.split(separator: " ")
for str in arr {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```
if dict[str] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str]! += 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var dict = [String : Int]()
for str in array {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var dict = [String : Int]()
for str in array {
if dict[str] == nil {
dict[str] = 1
} else {
dict[str]! += 1
}
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let array = test.split(separator: " ")
for str in array {
dict[str] = (dict[str] ?? 0) + 1
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
var dict = [String : Int]()
let array = test.split(separator: " ")
for str in array {
dict[str] = (dict[str] ?? 0) + 1
}
return dict
}
```
dict[str] = (dict[str] ?? 0) + 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
dict[str] = (dict[str] ?? 0) + 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str] = map[str]! + 1
}
}
return map
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str] = map[str]! + 1
}
}
return map
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str] = map[str]! + 1
}
}
return map
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str] = map[str]! + 1
}
}
return map
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str] = map[str]! + 1
}
}
return map
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ")
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str] = map[str]! + 1
}
}
return map
}
```
if map[str] == nil { // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
map[str] = 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
map[str] = map[str]! + 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
map[str] = map[str]! + 1 // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var dict = [String : Int]()
for str in array {
dict[str] = (dict[str] ?? 0) + 1
}
return dict
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.lowercased().components(separatedBy: " ")
var dict = [String : Int]()
for str in array {
dict[str] = (dict[str] ?? 0) + 1
}
return dict
}
```
// XCTAssertTrue failed
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ").map { String($0) }
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str]! += 1
}
}
return map
}
```swift
// Given a string representing a space separated lowercase letters, return a dictionary
// of the letter with the most repetition and containing the corresponding count.
// If several letters have the same occurrence, return all of them.
// Example:
// histogram(test: "a b c") == ["a" : 1, "b" : 1, "c" : 1]
// histogram(test: "a b b a") == ["a" : 2, "b" : 2]
// histogram(test: "a b c a b") == ["a" : 2, "b" : 2]
// histogram(test: "b b b b a") == ["b" : 4]
// histogram(test: "") == [:] as [String : Int]
func histogram(test: String) -> [String : Int] {
let array = test.split(separator: " ").map { String($0) }
var map = [String : Int]()
for str in array {
if map[str] == nil {
map[str] = 1
} else {
map[str]! += 1
}
}
return map
}
```
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, isPalindrome(result))
}
func isPalindrome(s: String) -> Bool {
let reversed = String(s.reversed())
return s == reversed
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, isPalindrome(result))
}
func isPalindrome(s: String) -> Bool {
let reversed = String(s.reversed())
return s == reversed
}
```
return (result, isPalindrome(result)) // missing argument label 's:' in call
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, isPalindrome(result))
}
func isPalindrome(s: String) -> Bool {
let reversed = String(s.reversed())
return s == reversed
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, isPalindrome(result))
}
func isPalindrome(s: String) -> Bool {
let reversed = String(s.reversed())
return s == reversed
}
```
return (result, isPalindrome(result)) // missing argument label 's:' in call
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
for i in 0..<c.count {
let index = s.firstIndex(of: c[c.index(c.startIndex, offsetBy: i)])
if index != nil {
s.removeSubrange(index!..<index! + 1)
}
}
return (s, isPalindrome(s))
}
func isPalindrome(s: String) -> Bool {
var s = s
let chars = s.lowercased().map { String($0) }
var left = 0
var right = chars.count - 1
while left < right {
if chars[left] != chars[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
for i in 0..<c.count {
let index = s.firstIndex(of: c[c.index(c.startIndex, offsetBy: i)])
if index != nil {
s.removeSubrange(index!..<index! + 1)
}
}
return (s, isPalindrome(s))
}
// isPalindrome
// Given a string s, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
// Example
// isPalindrome(s: "A man, a plan, a canal: Panama") == true
// isPalindrome(s: "race a car") == false
func isPalindrome(s: String) -> Bool {
var s = s
let chars = s.lowercased().map { String($0) }
var left = 0
var right = chars.count - 1
while left < right {
if chars[left] != chars[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
s.removeSubrange(index!..<index! + 1) // binary operator '+' cannot be applied to operands of type 'String.Index' and 'Int'
return (s, isPalindrome(s)) // missing argument label 's:' in call
var s = s // variable 's' was never mutated; consider changing to 'let' constant
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
if s.count == 0 {
return ("", true)
}
if s.count == 1 {
return (s, s == c)
}
if s.count == 2 {
return (s[s.startIndex.offsetBy(1)...], s[s.startIndex] == c)
}
let cArray = Array(c)
var startIndex = s.startIndex
var endIndex = s.endIndex
while startIndex < endIndex {
if s[startIndex] == cArray[0] {
s.removeSubrange(startIndex...startIndex.offsetBy(1))
endIndex -= 1
} else {
startIndex += 1
}
}
return (String(s), isPalindrome(s))
}
func isPalindrome(s: String) -> Bool {
let sArray = Array(s)
var startIndex = sArray.startIndex
var endIndex = sArray.endIndex
while startIndex < endIndex {
if sArray[startIndex] != sArray[endIndex - 1] {
return false
}
startIndex += 1
endIndex -= 1
}
return true
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
if s.count == 0 {
return ("", true)
}
if s.count == 1 {
return (s, s == c)
}
if s.count == 2 {
return (s[s.startIndex.offsetBy(1)...], s[s.startIndex] == c)
}
let cArray = Array(c)
var startIndex = s.startIndex
var endIndex = s.endIndex
while startIndex < endIndex {
if s[startIndex] == cArray[0] {
s.removeSubrange(startIndex...startIndex.offsetBy(1))
endIndex -= 1
} else {
startIndex += 1
}
}
return (String(s), isPalindrome(s))
}
func isPalindrome(s: String) -> Bool {
let sArray = Array(s)
var startIndex = sArray.startIndex
var endIndex = sArray.endIndex
while startIndex < endIndex {
if sArray[startIndex] != sArray[endIndex - 1] {
return false
}
startIndex += 1
endIndex -= 1
}
return true
}
```
return (s[s.startIndex.offsetBy(1)...], s[s.startIndex] == c) // subscript 'subscript(_:)' requires that 'String.Index' conform to 'RangeExpression'
return (s[s.startIndex.offsetBy(1)...], s[s.startIndex] == c) // value of type 'String.Index' has no member 'offsetBy'
s.removeSubrange(startIndex...startIndex.offsetBy(1)) // value of type 'String.Index' has no member 'offsetBy'
endIndex -= 1 // binary operator '-=' cannot be applied to operands of type 'String.Index' and 'Int'
startIndex += 1 // binary operator '+=' cannot be applied to operands of type 'String.Index' and 'Int'
return (String(s), isPalindrome(s)) // missing argument label 's:' in call
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
for char in c {
s = s.replacingOccurrences(of: String(char), with: "")
}
let isPalindrome = s == String(s.reversed())
return (s, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
for char in c {
s = s.replacingOccurrences(of: String(char), with: "")
}
let isPalindrome = s == String(s.reversed())
return (s, isPalindrome)
}
```
var c = c // variable 'c' was never mutated; consider changing to 'let' constant
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```
// XCTAssertTrue failed
func reverseDelete(s: String, c: String) -> (String, Bool) {
let c = Array(c)
var result = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, isPalindrome(result))
}
func isPalindrome(s: String) -> Bool {
let s = Array(s)
var left = 0
var right = s.count - 1
while left < right {
if s[left] != s[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
let c = Array(c)
var result = ""
for char in s {
if !c.contains(char) {
result.append(char)
}
}
return (result, isPalindrome(result))
}
func isPalindrome(s: String) -> Bool {
let s = Array(s)
var left = 0
var right = s.count - 1
while left < right {
if s[left] != s[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
return (result, isPalindrome(result)) // missing argument label 's:' in call
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
var result = ""
for i in 0..<s.count {
if !c.contains(s[s.index(s.startIndex, offsetBy: i)]) {
result.append(s[s.index(s.startIndex, offsetBy: i)])
}
}
return (result, result.isPalindrome())
}
func isPalindrome(_ s: String) -> Bool {
let s = s.lowercased()
let sArray = Array(s)
var left = 0
var right = sArray.count - 1
while left < right {
if sArray[left] != sArray[right] {
return false
}
left += 1
right -= 1
}
return true
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var s = s
var c = c
var result = ""
for i in 0..<s.count {
if !c.contains(s[s.index(s.startIndex, offsetBy: i)]) {
result.append(s[s.index(s.startIndex, offsetBy: i)])
}
}
return (result, result.isPalindrome())
}
// 验证回文
func isPalindrome(_ s: String) -> Bool {
let s = s.lowercased()
let sArray = Array(s)
var left = 0
var right = sArray.count - 1
while left < right {
if sArray[left] != sArray[right] {
return false
}
left += 1
right -= 1
}
return true
}
```
return (result, result.isPalindrome()) // value of type 'String' has no member 'isPalindrome'
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = Array(s)
var c = Array(c)
var i = 0
while i < s.count {
if c.contains(s[i]) {
s.remove(at: i)
} else {
i += 1
}
}
return (String(s), isPalindrome(s))
}
func isPalindrome(s: String) -> Bool {
let s = Array(s)
var i = 0
var j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
let s = Array(s)
var c = Array(c)
var i = 0
while i < s.count {
if c.contains(s[i]) {
s.remove(at: i)
} else {
i += 1
}
}
return (String(s), isPalindrome(s))
}
func isPalindrome(s: String) -> Bool {
let s = Array(s)
var i = 0
var j = s.count - 1
while i < j {
if s[i] != s[j] {
return false
}
i += 1
j -= 1
}
return true
}
```
s.remove(at: i) // cannot use mutating member on immutable value: 's' is a 'let' constant
return (String(s), isPalindrome(s)) // missing argument label 's:' in call
return (String(s), isPalindrome(s)) // cannot convert value of type '[String.Element]' (aka 'Array<Character>') to expected argument type 'String'
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```swift
// Task
// We are given two strings s and c, you have to deleted all the characters in s that are equal to any character in c
// then check if the result string is palindrome.
// A string is called palindrome if it reads the same backward as forward.
// You should return a tuple containing the result string and true/false for the check.
// Example
// reverseDelete(s: "abcde", c: "ae") == ("bcd", false)
// reverseDelete(s: "abcdef", c: "b") == ("acdef", false)
// reverseDelete(s: "abcdedcba", c: "ab") == ("cdedc", true)
func reverseDelete(s: String, c: String) -> (String, Bool) {
var result = ""
var isPalindrome = true
for char in s {
if !c.contains(char) {
result.append(char)
} else {
isPalindrome = false
}
}
return (result, isPalindrome)
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var oddCount = 0
for char in str {
if char.isOdd {
oddCount += 1
}
}
result.append("the number of odd elements \(oddCount)n the str\(oddCount)ng \(oddCount) of the \(oddCount)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var oddCount = 0
for char in str {
if char.isOdd {
oddCount += 1
}
}
result.append("the number of odd elements \(oddCount)n the str\(oddCount)ng \(oddCount) of the \(oddCount)nput.")
}
return result
}
```
if char.isOdd { // value of type 'Character' has no member 'isOdd'
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char.isOdd {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count)n of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char.isOdd {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count)n of the \(count)nput.")
}
return result
}
```
if char.isOdd { // value of type 'Character' has no member 'isOdd'
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char.isOdd {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count)n of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for char in str {
if char.isOdd {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count)n of the \(count)nput.")
}
return result
}
```
if char.isOdd { // value of type 'Character' has no member 'isOdd'
func oddCount(lst: [String]) -> [String] {
return lst.map { String($0.filter { $0.isOdd }.count) }
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map { String($0.filter { $0.isOdd }.count) }
}
```
return lst.map { String($0.filter { $0.isOdd }.count) } // value of type 'String.Element' (aka 'Character') has no member 'isOdd'
func oddCount(lst: [String]) -> [String] {
let count = lst.count
var result = [String]()
for i in 0..<count {
let string = lst[i]
var oddCount = 0
for char in string {
let number = Int(String(char))!
if number % 2 != 0 {
oddCount += 1
}
}
result.append("the number of odd elements \(oddCount)n the str\(i)ng \(i) of the \(i)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
let count = lst.count
var result = [String]()
for i in 0..<count {
let string = lst[i]
var oddCount = 0
for char in string {
let number = Int(String(char))!
if number % 2 != 0 {
oddCount += 1
}
}
result.append("the number of odd elements \(oddCount)n the str\(i)ng \(i) of the \(i)nput.")
}
return result
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
return lst.map { String($0.filter { $0.isOdd }.count) }
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
return lst.map { String($0.filter { $0.isOdd }.count) }
}
```
return lst.map { String($0.filter { $0.isOdd }.count) } // value of type 'String.Element' (aka 'Character') has no member 'isOdd'
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for c in str {
if c.isOdd {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var result = [String]()
for str in lst {
var count = 0
for c in str {
if c.isOdd {
count += 1
}
}
result.append("the number of odd elements \(count)n the str\(count)ng \(count) of the \(count)nput.")
}
return result
}
```
if c.isOdd { // value of type 'Character' has no member 'isOdd'
func oddCount(lst: [String]) -> [String] {
let count = lst.count
var result = [String]()
for i in 0..<count {
let string = lst[i]
var oddCount = 0
for char in string {
if Int(String(char))! % 2 == 1 {
oddCount += 1
}
}
result.append("the number of odd elements \(oddCount)n the str\(i)ng \(i) of the \(i)nput.")
}
return result
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
let count = lst.count
var result = [String]()
for i in 0..<count {
let string = lst[i]
var oddCount = 0
for char in string {
if Int(String(char))! % 2 == 1 {
oddCount += 1
}
}
result.append("the number of odd elements \(oddCount)n the str\(i)ng \(i) of the \(i)nput.")
}
return result
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
var res = [String]()
for str in lst {
var count = 0
for c in str {
if Int(String(c))! % 2 != 0 {
count += 1
}
}
res.append("the number of odd elements \(count)n the str\(count)ng \(count)n of the \(count)nput.")
}
return res
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
var res = [String]()
for str in lst {
var count = 0
for c in str {
if Int(String(c))! % 2 != 0 {
count += 1
}
}
res.append("the number of odd elements \(count)n the str\(count)ng \(count)n of the \(count)nput.")
}
return res
}
```
// XCTAssertTrue failed
func oddCount(lst: [String]) -> [String] {
let arr = lst.map { Int($0)! }
let count = arr.reduce(0) { $0 + ($1 % 2) }
return lst.map { "the number of odd elements \(count)n the str\($0)n of the \(count)nput." }
}
```swift
// Given an array of strings, where each string consists of only digits, return an array.
// Each element i of the output should be "the number of odd elements in the
// string i of the input." where all the i's should be replaced by the number
// of odd digits in the i'th string of the input.
// oddCount(lst: ["1234567"]) == ["the number of odd elements 4n the str4ng 4 of the 4nput."]
// oddCount(lst: ["3", "11111111"]) == ["the number of odd elements 1n the str1ng 1 of the 1nput.", "the number of odd elements 8n the str8ng 8 of the 8nput."]
func oddCount(lst: [String]) -> [String] {
let arr = lst.map { Int($0)! }
let count = arr.reduce(0) { $0 + ($1 % 2) }
return lst.map { "the number of odd elements \(count)n the str\($0)n of the \(count)nput." }
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = 0
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = 0
}
return minSum
}
```
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = 0
}
return minSum
}
```
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = 0
}
return minSum
}
```
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = 0
}
return minSum
}
```
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in nums {
sum += num
minSum = min(minSum, sum)
sum = 0
}
return minSum
}
```
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for num in num
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
var left = 0
for right in 0..<nums.count {
sum += nums[right]
while sum > 0 {
minSum = min(minSum, sum)
sum -= nums[left]
left += 1
}
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = min(dp[i - 1] + nums[i], nums[i])
minSum = min(minSum, dp[i])
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
var preSum = [Int](repeating: 0, count: nums.count + 1)
for i in 0..<nums.count {
sum += nums[i]
preSum[i + 1] = sum
}
for i in 0..<nums.count {
for j in i..<nums.count {
minSum = min(minSum, preSum[j + 1] - preSum[i])
}
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
### 解法二:滑动窗口
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
var left = 0
for right in 0..<nums.count {
sum += nums[right]
while sum > 0 {
minSum = min(minSum, sum)
sum -= nums[left]
left += 1
}
}
return minSum
}
```
### 解法三:动态规划
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
return minSum
}
```
### 解法四:动态规划优化
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = min(dp[i - 1] + nums[i], nums[i])
minSum = min(minSum, dp[i])
}
return minSum
}
```
### 解法五:前缀和
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
var preSum = [Int](repeating: 0, count: nums.count + 1)
for i in 0..<nums.count {
sum += nums[i]
preSum[i + 1] = sum
}
for i in 0..<nums.count {
for j in i..<nums.count {
minSum = min(minSum, preSum[j + 1] - preSum[i])
}
}
return minSum
}
```
### 解法六:前缀和优化
```swift
// Given an array of integers
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = min(dp[i - 1] + nums[i], nums[i])
minSum = min(minSum, dp[i])
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
### 解法二:动态规划
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
return minSum
}
```
### 解法三:动态规划 + 滚动数组
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = min(dp[i - 1] + nums[i], nums[i])
minSum = min(minSum, dp[i])
}
return minSum
}
```
### 解法四:前缀和 + 动态规划
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
### 解法五:前缀和 + 动态规划 + 滚动数组
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
### 解法六:前缀和 + 动态规划 + 滚动数组 + 优化
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = min(dp[i - 1] + nums[i], nums[i])
minSum = min(minSum, dp[i])
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
if sum < 0 {
sum = 0
}
minSum = min(minSum, sum)
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
### 解法二:动态规划
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
return minSum
}
```
### 解法三:动态规划优化
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var dp = [Int](repeating: 0, count: nums.count)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<nums.count {
dp[i] = min(dp[i - 1] + nums[i], nums[i])
minSum = min(minSum, dp[i])
}
return minSum
}
```
### 解法四:滑动窗口
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
minSum = min(minSum, sum)
if sum < 0 {
sum = 0
}
}
return minSum
}
```
### 解法五:滑动窗口优化
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var minSum = Int.max
var sum = 0
for i in 0..<nums.count {
sum += nums[i]
if sum < 0 {
sum = 0
}
minSum = min(minSum, sum)
}
return minSum
}
```
### 解法六:前缀和
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSub
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int { // invalid redeclaration of 'minSubArraySum(nums:)'
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
class Solution {
func minSubArrayLen(_ s: Int, _ nums: [Int]) -> Int {
guard nums.count > 0 else {
return 0
}
var left = 0
var right = 0
var sum = 0
var minLength = Int.max
while right < nums.count {
sum += nums[right]
while sum >= s {
minLength = min(minLength, right - left + 1)
sum -= nums[left]
left += 1
}
right += 1
}
return minLength == Int.max ? 0 : minLength
}
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
### 解题思路
### 代码
```swift
class Solution {
func minSubArrayLen(_ s: Int, _ nums: [Int]) -> Int {
guard nums.count > 0 else {
return 0
}
var left = 0
var right = 0
var sum = 0
var minLength = Int.max
while right < nums.count {
sum += nums[right]
while sum >= s {
minLength = min(minLength, right - left + 1)
sum -= nums[left]
left += 1
}
right += 1
}
return minLength == Int.max ? 0 : minLength
}
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
var sum = 0
var minSum = Int.max
for num in nums {
sum += num
minSum = min(minSum, sum)
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
let n = nums.count
var dp = Array(repeating: 0, count: n)
dp[0] = nums[0]
var minSum = nums[0]
for i in 1..<n {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
if minSum >= 0 {
return minSum
}
var sum = 0
for i in 0..<n {
sum += nums[i]
minSum = min(minSum, sum)
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
let n = nums.count
var dp = Array(repeating: 0, count: n)
dp[0] = nums[0]
var minSum = nums[0]
for i in 1..<n {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
if minSum >= 0 {
return minSum
}
var sum = 0
for i in 0..<n {
sum += nums[i]
minSum = min(minSum, sum)
}
return minSum
}
```
// XCTAssertTrue failed
func minSubArraySum(nums: [Int]) -> Int {
let n = nums.count
var dp = Array(repeating: 0, count: n)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<n {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
if minSum >= 0 {
return minSum
}
var sum = 0
for i in 0..<n {
sum += nums[i]
if sum < 0 {
sum = 0
}
minSum = min(minSum, sum)
}
return minSum
}
```swift
// Given an array of integers nums, find the minimum sum of any non-empty sub-array
// of nums.
// Example
// minSubArraySum(nums: [2, 3, 4, 1, 2, 4]) == 1
// minSubArraySum(nums: [-1, -2, -3]) == -6
func minSubArraySum(nums: [Int]) -> Int {
let n = nums.count
var dp = Array(repeating: 0, count: n)
dp[0] = nums[0]
var minSum = dp[0]
for i in 1..<n {
dp[i] = dp[i - 1] + nums[i]
minSum = min(minSum, dp[i])
}
if minSum >= 0 {
return minSum
}
var sum = 0
for i in 0..<n {
sum += nums[i]
if sum < 0 {
sum = 0
}
minSum = min(minSum, sum)
}
return minSum
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var buckets = grid
var result = 0
for i in 0..<buckets.count {
for j in 0..<buckets[i].count {
if buckets[i][j] == 1 {
let bucket = capacity
var k = i
while k < buckets.count && buckets[k][j] == 1 {
buckets[k][j] = 0
bucket -= 1
k += 1
}
if bucket == 0 {
return -1
}
result += 1
}
}
}
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var buckets = grid
var result = 0
for i in 0..<buckets.count {
for j in 0..<buckets[i].count {
if buckets[i][j] == 1 {
let bucket = capacity
var k = i
while k < buckets.count && buckets[k][j] == 1 {
buckets[k][j] = 0
bucket -= 1
k += 1
}
if bucket == 0 {
return -1
}
result += 1
}
}
}
return result
}
```
bucket -= 1 // left side of mutating operator isn't mutable: 'bucket' is a 'let' constant
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var buckets = grid
var result = 0
for i in 0..<buckets.count {
for j in 0..<buckets[i].count {
if buckets[i][j] == 1 {
result += fill(buckets: &buckets, i: i, j: j, capacity: capacity)
}
}
}
return result
}
func fill(buckets: inout [[Int]], i: Int, j: Int, capacity: Int) -> Int {
var result = 0
var bucket = buckets[i][j]
while bucket > 0 {
if bucket <= capacity {
bucket = 0
result += 1
} else {
bucket -= capacity
result += 1
}
}
buckets[i][j] = bucket
return result
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
var buckets = grid
var result = 0
for i in 0..<buckets.count {
for j in 0..<buckets[i].count {
if buckets[i][j] == 1 {
result += fill(buckets: &buckets, i: i, j: j, capacity: capacity)
}
}
}
return result
}
func fill(buckets: inout [[Int]], i: Int, j: Int, capacity: Int) -> Int {
var result = 0
var bucket = buckets[i][j]
while bucket > 0 {
if bucket <= capacity {
bucket = 0
result += 1
} else {
bucket -= capacity
result += 1
}
}
buckets[i][j] = bucket
return result
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var count = 0
for j in 0..<m {
if buckets[j] > capacity {
count += buckets[j] / capacity
buckets[j] = buckets[j] % capacity
}
}
ans += count
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var count = 0
for j in 0..<m {
if buckets[j] > capacity {
count += buckets[j] / capacity
buckets[j] = buckets[j] % capacity
}
}
ans += count
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var flag = false
for j in 0..<m {
if buckets[j] > capacity {
flag = true
buckets[j] -= capacity
} else {
buckets[j] = 0
}
}
if flag {
ans += 1
}
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var flag = false
for j in 0..<m {
if buckets[j] > capacity {
flag = true
buckets[j] -= capacity
} else {
buckets[j] = 0
}
}
if flag {
ans += 1
}
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: n)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[i] += 1
}
}
}
for i in (0..<n).reversed() {
for j in (0..<m).reversed() {
if grid[i][j] == 1 {
buckets[i] += 1
}
if buckets[i] > capacity {
buckets[i] = capacity
ans += 1
}
}
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: n)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[i] += 1
}
}
}
for i in (0..<n).reversed() {
for j in (0..<m).reversed() {
if grid[i][j] == 1 {
buckets[i] += 1
}
if buckets[i] > capacity {
buckets[i] = capacity
ans += 1
}
}
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
var buckets = Array(repeating: 0, count: n)
var ans = 0
for i in 0..<n {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
buckets[i] += 1
}
}
}
while true {
var flag = false
for i in 0..<n {
if buckets[i] > capacity {
buckets[i] -= capacity
flag = true
} else {
buckets[i] = 0
}
}
if !flag {
break
}
ans += 1
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
var buckets = Array(repeating: 0, count: n)
var ans = 0
for i in 0..<n {
for j in 0..<grid[i].count {
if grid[i][j] == 1 {
buckets[i] += 1
}
}
}
while true {
var flag = false
for i in 0..<n {
if buckets[i] > capacity {
buckets[i] -= capacity
flag = true
} else {
buckets[i] = 0
}
}
if !flag {
break
}
ans += 1
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var k = 0
while k < m {
if buckets[k] > capacity {
buckets[k] -= capacity
ans += 1
} else {
k += 1
}
}
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var k = 0
while k < m {
if buckets[k] > capacity {
buckets[k] -= capacity
ans += 1
} else {
k += 1
}
}
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var k = m - 1
while k >= 0 {
if buckets[k] > capacity {
buckets[k] -= capacity
} else {
buckets[k] = 0
k -= 1
}
}
ans += 1
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var k = m - 1
while k >= 0 {
if buckets[k] > capacity {
buckets[k] -= capacity
} else {
buckets[k] = 0
k -= 1
}
}
ans += 1
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var j = m - 1
while j >= 0 {
if buckets[j] > capacity {
ans += 1
buckets[j] -= capacity
}
j -= 1
}
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
var j = m - 1
while j >= 0 {
if buckets[j] > capacity {
ans += 1
buckets[j] -= capacity
}
j -= 1
}
}
return ans
}
```
// XCTAssertTrue failed
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
for j in 0..<m {
if buckets[j] > capacity {
ans += 1
buckets[j] = 0
}
}
}
return ans
}
```swift
// You are given a rectangular grid of wells. Each row represents a single well,
// and each 1 in a row represents a single unit of water.
// Each well has a corresponding bucket that can be used to extract water from it,
// and all buckets have the same capacity.
// Your task is to use the buckets to empty the wells.
// Output the number of times you need to lower the buckets.
// Example 1:
// Example 2:
// Example 3:
// Constraints:
// * all wells have the same length
// * 1 <= grid.length <= 10^2
// * 1 <= grid[:,1].length <= 10^2
// * grid[i][j] -> 0 | 1
// * 1 <= capacity <= 10
// maxFill(grid: [[0, 0, 1, 0], [0, 1, 0, 0], [1, 1, 1, 1]], capacity: 1) == 6
// maxFill(grid: [[0, 0, 1, 1], [0, 0, 0, 0], [1, 1, 1, 1], [0, 1, 1, 1]], capacity: 2) == 5
// maxFill(grid: [[0, 0, 0], [0, 0, 0]], capacity: 5) == 0
func maxFill(grid: [[Int]], capacity: Int) -> Int {
let n = grid.count
let m = grid[0].count
var buckets = Array(repeating: 0, count: m)
var ans = 0
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
buckets[j] += 1
}
}
for j in 0..<m {
if buckets[j] > capacity {
ans += 1
buckets[j] = 0
}
}
}
return ans
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBits = a.nonzeroBitCount
let bBits = b.nonzeroBitCount
if aBits != bBits {
return aBits < bBits
} else {
return a < b
}
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBits = a.nonzeroBitCount
let bBits = b.nonzeroBitCount
if aBits != bBits {
return aBits < bBits
} else {
return a < b
}
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
return aBinary == bBinary ? a < b : aBinary < bBinary
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
return aBinary == bBinary ? a < b : aBinary < bBinary
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
return aBinary == bBinary ? a < b : aBinary < bBinary
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
return aBinary == bBinary ? a < b : aBinary < bBinary
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
if aBinary != bBinary {
return aBinary < bBinary
} else {
return a < b
}
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
if aBinary != bBinary {
return aBinary < bBinary
} else {
return a < b
}
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
if aBinary == bBinary {
return a > b
} else {
return aBinary < bBinary
}
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
if aBinary == bBinary {
return a > b
} else {
return aBinary < bBinary
}
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
return countOnes(a) < countOnes(b) || countOnes(a) == countOnes(b) && a < b
}
}
func countOnes(_ n: Int) -> Int {
var n = n
var count = 0
while n != 0 {
n &= (n - 1)
count += 1
}
return count
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
return countOnes(a) < countOnes(b) || countOnes(a) == countOnes(b) && a < b
}
}
func countOnes(_ n: Int) -> Int {
var n = n
var count = 0
while n != 0 {
n &= (n - 1)
count += 1
}
return count
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
if aBinary == bBinary {
return a < b
} else {
return aBinary < bBinary
}
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
if aBinary == bBinary {
return a < b
} else {
return aBinary < bBinary
}
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
return aBinary == bBinary ? a < b : aBinary < bBinary
}
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
let aBinary = a.nonzeroBitCount
let bBinary = b.nonzeroBitCount
return aBinary == bBinary ? a < b : aBinary < bBinary
}
}
```
// XCTAssertTrue failed
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
// 1. Sort by number of ones
let onesA = countOnes(a)
let onesB = countOnes(b)
if onesA != onesB {
return onesA < onesB
}
// 2. Sort by decimal value
return a < b
}
}
func countOnes(_ n: Int) -> Int {
var n = n
var count = 0
while n != 0 {
n &= (n - 1)
count += 1
}
return count
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
// 1. Sort by number of ones
let onesA = countOnes(a)
let onesB = countOnes(b)
if onesA != onesB {
return onesA < onesB
}
// 2. Sort by decimal value
return a < b
}
}
func countOnes(_ n: Int) -> Int {
var n = n
var count = 0
while n != 0 {
n &= (n - 1)
count += 1
}
return count
}
```
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
return countOnes(a) < countOnes(b) || (countOnes(a) == countOnes(b) && a < b)
}
}
func countOnes(_ n: Int) -> Int {
var n = n
var count = 0
while n != 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
```swift
// In this Kata, you have to sort an array of non-negative integers according to
// number of ones in their binary representation in ascending order.
// For similar number of ones, sort based on decimal value.
// It must be implemented like this:
// sortArray(arr: [1, 5, 2, 3, 4]) == [1, 2, 3, 4, 5]
// sortArray(arr: [-2, -3, -4, -5, -6]) == [-6, -5, -4, -3, -2]
// sortArray(arr: [1, 0, 2, 3, 4]) == [0, 1, 2, 3, 4]
func sortArray(arr: [Int]) -> [Int] {
return arr.sorted { (a, b) -> Bool in
return countOnes(a) < countOnes(b) || (countOnes(a) == countOnes(b) && a < b)
}
}
func countOnes(_ n: Int) -> Int {
var n = n
var count = 0
while n != 0 {
if n & 1 == 1 {
count += 1
}
n >>= 1
}
return count
}
```
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```
result.append(str) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```
result.append(str) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func selectWords(s: String, n: Int) -> [String] {
let chars = Array(s)
var res = [String]()
for i in 0..<chars.count {
if isConsonant(chars[i], n) {
res.append(String(chars[i..<chars.count]))
}
}
return res
}
func isConsonant(_ ch: Character, _ n: Int) -> Bool {
let ascii = Int(ch.asciiValue!)
if ascii >= 65 && ascii <= 90 {
return false
}
var count = 0
for i in ch..<"z" {
let ascii = Int(i.asciiValue!)
if ascii >= 65 && ascii <= 90 {
count += 1
}
}
return count == n
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let chars = Array(s)
var res = [String]()
for i in 0..<chars.count {
if isConsonant(chars[i], n) {
res.append(String(chars[i..<chars.count]))
}
}
return res
}
func isConsonant(_ ch: Character, _ n: Int) -> Bool {
let ascii = Int(ch.asciiValue!)
if ascii >= 65 && ascii <= 90 {
return false
}
var count = 0
for i in ch..<"z" {
let ascii = Int(i.asciiValue!)
if ascii >= 65 && ascii <= 90 {
count += 1
}
}
return count == n
}
```
for i in ch..<"z" { // referencing instance method 'makeIterator()' on 'Range' requires that 'Character' conform to 'Strideable'
for i in ch..<"z" { // referencing instance method 'next()' on 'Range' requires that 'Character' conform to 'Strideable'
for i in ch..<"z" { // protocol 'Sequence' requires that 'Character' conform to 'Strideable'
func selectWords(s: String, n: Int) -> [String] {
let array = s.components(separatedBy: " ")
let result = array.filter { $0.count == n }
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let array = s.components(separatedBy: " ")
let result = array.filter { $0.count == n }
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let arr = s.split(separator: " ")
var res = [String]()
for str in arr {
if str.count == n {
res.append(str)
}
}
return res
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let arr = s.split(separator: " ")
var res = [String]()
for str in arr {
if str.count == n {
res.append(str)
}
}
return res
}
```
res.append(str) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func selectWords(s: String, n: Int) -> [String] {
let arr = s.split(separator: " ")
var res = [String]()
for str in arr {
if str.count == n {
res.append(str)
}
}
return res
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let arr = s.split(separator: " ")
var res = [String]()
for str in arr {
if str.count == n {
res.append(str)
}
}
return res
}
```
res.append(str) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```
result.append(str) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let array = s.split(separator: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```
result.append(str) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func selectWords(s: String, n: Int) -> [String] {
let array = s.components(separatedBy: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let array = s.components(separatedBy: " ")
var result = [String]()
for str in array {
if str.count == n {
result.append(str)
}
}
return result
}
```
// XCTAssertTrue failed
func selectWords(s: String, n: Int) -> [String] {
let arr = s.components(separatedBy: " ")
var res = [String]()
for str in arr {
if str.count == n {
res.append(str)
}
}
return res
}
```swift
// Given a string s and a natural number n, you have been tasked to implement
// a function that returns an array of all words from string s that contain exactly
// n consonants, in order these words appear in the string s.
// If the string s is empty then the function should return an empty array.
// Note: you may assume the input string contains only letters and spaces.
// Examples:
// selectWords(s: "Mary had a little lamb", n: 4) == ["little"]
// selectWords(s: "Mary had a little lamb", n: 3) == ["Mary", "lamb"]
// selectWords(s: "simple white space", n: 2) == [] as [String]
// selectWords(s: "Hello world", n: 4) == ["world"]
// selectWords(s: "Uncle sam", n: 3) == ["Uncle"]
func selectWords(s: String, n: Int) -> [String] {
let arr = s.components(separatedBy: " ")
var res = [String]()
for str in arr {
if str.count == n {
res.append(str)
}
}
return res
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
var vowel = ""
let vowels = "AEIOU"
let arr = Array(word)
for i in (0..<arr.count).reversed() {
let c = arr[i]
if vowels.contains(c) {
if vowel.count == 0 || vowel != "A" && vowel != "E" && vowel != "I" && vowel != "O" && vowel != "U" {
vowel = c
}
}
}
return vowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowel = ""
let vowels = "AEIOU"
let arr = Array(word)
for i in (0..<arr.count).reversed() {
let c = arr[i]
if vowels.contains(c) {
if vowel.count == 0 || vowel != "A" && vowel != "E" && vowel != "I" && vowel != "O" && vowel != "U" {
vowel = c
}
}
}
return vowel
}
```
vowel = c // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
let chars = Array(word)
var i = chars.count - 1
while i >= 0 {
if vowels.contains(chars[i]) {
return String(chars[i])
}
i -= 1
}
return ""
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
let chars = Array(word)
var i = chars.count - 1
while i >= 0 {
if vowels.contains(chars[i]) {
return String(chars[i])
}
i -= 1
}
return ""
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
let wordArray = Array(word)
var index = 0
var result = ""
while index < wordArray.count {
let current = wordArray[wordArray.count - 1 - index]
if vowels.contains(current) {
if index == 0 || vowels.contains(wordArray[wordArray.count - 2 - index]) {
result = current
}
}
index += 1
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
let wordArray = Array(word)
var index = 0
var result = ""
while index < wordArray.count {
let current = wordArray[wordArray.count - 1 - index]
if vowels.contains(current) {
if index == 0 || vowels.contains(wordArray[wordArray.count - 2 - index]) {
result = current
}
}
index += 1
}
return result
}
```
result = current // cannot assign value of type 'String.Element' (aka 'Character') to type 'String'
func getClosestVowel(word: String) -> String {
var vowel = ""
for (index, char) in word.reversed().enumerated() {
if char.isVowel {
if index == 0 || word[word.index(word.endIndex, offsetBy: -index - 1)].isVowel {
vowel = String(char)
break
}
}
}
return vowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowel = ""
for (index, char) in word.reversed().enumerated() {
if char.isVowel {
if index == 0 || word[word.index(word.endIndex, offsetBy: -index - 1)].isVowel {
vowel = String(char)
break
}
}
}
return vowel
}
```
if char.isVowel { // value of type 'ReversedCollection<String>.Element' (aka 'Character') has no member 'isVowel'
if index == 0 || word[word.index(word.endIndex, offsetBy: -index - 1)].isVowel { // value of type 'Character' has no member 'isVowel'
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var index = 0
var result = ""
for (i, c) in word.reversed().enumerated() {
if vowels.contains(String(c)) {
if index == 0 {
result = String(c)
} else {
result = String(c)
break
}
index += 1
} else {
index = 0
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
var vowels = ["a", "e", "i", "o", "u"]
var index = 0
var result = ""
for (i, c) in word.reversed().enumerated() {
if vowels.contains(String(c)) {
if index == 0 {
result = String(c)
} else {
result = String(c)
break
}
index += 1
} else {
index = 0
}
}
return result
}
```
var vowels = ["a", "e", "i", "o", "u"] // variable 'vowels' was never mutated; consider changing to 'let' constant
for (i, c) in word.reversed().enumerated() { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
var vowel = ""
for i in word.reversed() {
if vowels.contains(String(i)) {
if vowel == "" {
vowel = String(i)
} else {
return vowel
}
}
}
return vowel
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
var vowel = ""
for i in word.reversed() {
if vowels.contains(String(i)) {
if vowel == "" {
vowel = String(i)
} else {
return vowel
}
}
}
return vowel
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let chars = Array(word)
var i = chars.count - 1
while i >= 0 {
let c = chars[i]
if vowels.contains(String(c)) {
return String(c)
}
i -= 1
}
return ""
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let chars = Array(word)
var i = chars.count - 1
while i >= 0 {
let c = chars[i]
if vowels.contains(String(c)) {
return String(c)
}
i -= 1
}
return ""
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
let word = Array(word.reversed())
for i in 0..<word.count {
if vowels.contains(word[i]) {
if i == 0 || vowels.contains(word[i - 1]) {
return String(word[i])
}
}
}
return ""
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = "AEIOU"
let word = Array(word.reversed())
for i in 0..<word.count {
if vowels.contains(word[i]) {
if i == 0 || vowels.contains(word[i - 1]) {
return String(word[i])
}
}
}
return ""
}
```
// XCTAssertTrue failed
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let word = Array(word)
var i = 0
while i < word.count {
if vowels.contains(word[word.count - 1 - i]) {
return word[word.count - 1 - i]
}
i += 1
}
return ""
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let word = Array(word)
var i = 0
while i < word.count {
if vowels.contains(word[word.count - 1 - i]) {
return word[word.count - 1 - i]
}
i += 1
}
return ""
}
```
if vowels.contains(word[word.count - 1 - i]) { // cannot convert value of type 'String.Element' (aka 'Character') to expected argument type 'String'
return word[word.count - 1 - i] // cannot convert return expression of type 'String.Element' (aka 'Character') to return type 'String'
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let word = Array(word)
var index = 0
var result = ""
for i in word.indices.reversed() {
if vowels.contains(String(word[i])) {
if index == 0 {
result = String(word[i])
} else {
if String(word[i]) != result {
result = String(word[i])
}
}
index += 1
}
}
return result
}
```swift
// You are given a word. Your task is to find the closest vowel that stands between
// two consonants from the right side of the word (case sensitive).
// Vowels in the beginning and ending doesn't count. Return empty string if you didn't
// find any vowel met the above condition.
// You may assume that the given string contains English letter only.
// Example:
// getClosestVowel(word: "yogurt") == "u"
// getClosestVowel(word: "FULL") == "U"
// getClosestVowel(word: "quick") == ""
// getClosestVowel(word: "ab") == ""
func getClosestVowel(word: String) -> String {
let vowels = ["a", "e", "i", "o", "u"]
let word = Array(word)
var index = 0
var result = ""
for i in word.indices.reversed() {
if vowels.contains(String(word[i])) {
if index == 0 {
result = String(word[i])
} else {
if String(word[i]) != result {
result = String(word[i])
}
}
index += 1
}
}
return result
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
let n = lst.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dp[i][j] = 1
} else if i > j {
dp[i][j] = dp[j][i]
}
}
}
for i in 0..<n {
for j in 0..<n {
if i < j {
if dp[i][j] == 1 {
dp[i][j] = dp[i][j - 1] || dp[i + 1][j]
} else {
dp[i][j] = dp[i][j - 1]
}
}
}
}
return dp[0][n - 1] ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
let n = lst.count
var dp = Array(repeating: Array(repeating: 0, count: n), count: n)
for i in 0..<n {
for j in 0..<n {
if i == j {
dp[i][j] = 1
} else if i > j {
dp[i][j] = dp[j][i]
}
}
}
for i in 0..<n {
for j in 0..<n {
if i < j {
if dp[i][j] == 1 {
dp[i][j] = dp[i][j - 1] || dp[i + 1][j]
} else {
dp[i][j] = dp[i][j - 1]
}
}
}
}
return dp[0][n - 1] ? "Yes" : "No"
}
```
dp[i][j] = dp[i][j - 1] || dp[i + 1][j] // type 'Int' cannot be used as a boolean; test for '!= 0' instead
dp[i][j] = dp[i][j - 1] || dp[i + 1][j] // cannot assign value of type 'Bool' to subscript of type 'Int'
dp[i][j] = dp[i][j - 1] || dp[i + 1][j] // type 'Int' cannot be used as a boolean; test for '!= 0' instead
return dp[0][n - 1] ? "Yes" : "No" // type 'Int' cannot be used as a boolean; test for '!= 0' instead
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
for char in str {
if char == "(" {
stack.append("(")
} else {
if stack.isEmpty {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
for char in str {
if char == "(" {
stack.append("(")
} else {
if stack.isEmpty {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
for c in str {
if c == "(" {
stack.append("(")
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
for c in str {
if c == "(" {
stack.append("(")
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
}
if stack.isEmpty {
return "Yes"
} else {
return "No"
}
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
} else {
stack.removeLast()
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for char in lst.first! {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.count == 0 ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for char in lst.first! {
if char == "(" {
stack.append(char)
} else {
if stack.count == 0 {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.count == 0 ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
for c in str {
if c == "(" {
stack.append("(")
} else {
if stack.count == 0 {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
}
if stack.count == 0 {
return "Yes"
}
return "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String]()
for str in lst {
for c in str {
if c == "(" {
stack.append("(")
} else {
if stack.count == 0 {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
}
if stack.count == 0 {
return "Yes"
}
return "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst.first! {
if c == "(" {
stack.append(c)
} else {
if stack.isEmpty {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.isEmpty ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst[0] {
if c == "(" {
stack.append(c)
} else {
if stack.count == 0 {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.count == 0 ? "Yes" : "No"
}
```swift
// You are given an array of two strings, both strings consist of open
// parentheses '(' or close parentheses ')' only.
// Your job is to check if it is possible to concatenate the two strings in
// some order, that the resulting string will be good.
// A string S is considered to be good if and only if all parentheses in S
// are balanced. For example: the string '(())()' is good, while the string
// '())' is not.
// Return 'Yes' if there's a way to make a good string, and return 'No' otherwise.
// Examples:
// matchParens(lst: ["()(", ")"]) == "Yes"
// matchParens(lst: [")", ")"]) == "No"
func matchParens(lst: [String]) -> String {
var stack = [String.Element]()
for c in lst[0] {
if c == "(" {
stack.append(c)
} else {
if stack.count == 0 {
return "No"
}
if stack.last! == "(" {
stack.removeLast()
} else {
return "No"
}
}
}
return stack.count == 0 ? "Yes" : "No"
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var maxArr = arr
maxArr.sortInPlace(by: {$0 > $1})
return maxArr[0..<k]
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var maxArr = arr
maxArr.sortInPlace(by: {$0 > $1})
return maxArr[0..<k]
}
```
maxArr.sortInPlace(by: {$0 > $1}) // value of type '[Int]' has no member 'sortInPlace'
return maxArr[0..<k] // no 'subscript' candidates produce the expected contextual result type '[Int]'
func maximum(arr: [Int], k: Int) -> [Int] {
var res = [Int]()
var heap = Heap<Int>()
for i in 0..<arr.count {
if heap.count < k {
heap.insert(arr[i])
} else if arr[i] > heap.peek() {
heap.remove()
heap.insert(arr[i])
}
}
for i in 0..<k {
res.append(heap.remove())
}
return res
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var res = [Int]()
var heap = Heap<Int>()
for i in 0..<arr.count {
if heap.count < k {
heap.insert(arr[i])
} else if arr[i] > heap.peek() {
heap.remove()
heap.insert(arr[i])
}
}
for i in 0..<k {
res.append(heap.remove())
}
return res
}
```
var heap = Heap<Int>() // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = Int.min
for num in arr {
if num > max {
max = num
}
}
for num in arr {
if num == max {
result.append(num)
if result.count == k {
break
}
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = Int.min
for num in arr {
if num > max {
max = num
}
}
for num in arr {
if num == max {
result.append(num)
if result.count == k {
break
}
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = Int.min
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<max {
result.append(max)
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = Int.min
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<max {
result.append(max)
}
return result
}
```
for i in 0..<max { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>()
for num in arr {
maxHeap.insert(num)
if maxHeap.count > k {
maxHeap.remove()
}
}
return maxHeap.heap
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var maxHeap = Heap<Int>()
for num in arr {
maxHeap.insert(num)
if maxHeap.count > k {
maxHeap.remove()
}
}
return maxHeap.heap
}
```
var maxHeap = Heap<Int>() // cannot find 'Heap' in scope
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
result.removeAll()
result.append(max)
} else if arr[i] == max {
result.append(max)
}
if result.count == k {
break
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
result.removeAll()
result.append(max)
} else if arr[i] == max {
result.append(max)
}
if result.count == k {
break
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
for num in arr {
if result.count < k {
result.append(num)
max = max > num ? max : num
} else if result.count == k {
if num > max {
result.removeLast()
result.append(num)
max = num
}
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
for num in arr {
if result.count < k {
result.append(num)
max = max > num ? max : num
} else if result.count == k {
if num > max {
result.removeLast()
result.append(num)
max = num
}
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = Int.min
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<k {
result.append(max)
max -= 1
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = Int.min
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<k {
result.append(max)
max -= 1
}
return result
}
```
for i in 0..<k { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<max {
for j in 0..<arr.count {
if arr[j] == i {
result.append(i)
}
}
}
return result
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var result = [Int]()
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<max {
for j in 0..<arr.count {
if arr[j] == i {
result.append(i)
}
}
}
return result
}
```
// XCTAssertTrue failed
func maximum(arr: [Int], k: Int) -> [Int] {
var res = [Int]()
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<max {
for j in 0..<arr.count {
if arr[j] == i {
res.append(i)
}
}
}
return res
}
```swift
// Given an array arr of integers and a positive integer k, return a sorted array
// of length k with the maximum k numbers in arr.
// Example 1:
// Example 2:
// Example 3:
// Note:
// 1. The length of the array will be in the range of [1, 1000].
// 2. The elements in the array will be in the range of [-1000, 1000].
// 3. 0 <= k <= len(arr)
// maximum(arr: [-3, -4, 5], k: 3) == [-4, -3, 5]
// maximum(arr: [4, -4, 4], k: 2) == [4, 4]
// maximum(arr: [-3, 2, 1, 2, -1, -2, 1], k: 1) == [2]
func maximum(arr: [Int], k: Int) -> [Int] {
var res = [Int]()
var max = 0
for i in 0..<arr.count {
if arr[i] > max {
max = arr[i]
}
}
for i in 0..<max {
for j in 0..<arr.count {
if arr[j] == i {
res.append(i)
}
}
}
return res
}
```
// XCTAssertTrue failed
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 1 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
class Solution {
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 1 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 1 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
### 解题思路
### 代码
```swift
class Solution {
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 == 1 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 != 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 != 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 == 1 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 != 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if lst[i] % 2 != 0 && i % 2 == 0 {
sum += lst[i]
}
}
return sum
}
```
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers, return the sum of all of the odd elements that are in even positions.
// Examples
// solution(lst: [5, 8, 7, 1]) == 12
// solution(lst: [3, 3, 3, 3, 3]) == 9
// solution(lst: [30, 13, 24, 321]) == 0
func solution(lst: [Int]) -> Int {
var sum = 0
for i in 0..<lst.count {
if i % 2 == 0 && lst[i] % 2 != 0 {
sum += lst[i]
}
}
return sum
}
```
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += arr[i]
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += arr[i]
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] > 9 {
sum += arr[i] % 10
sum += arr[i] / 10
} else {
sum += arr[i]
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] > 9 {
sum += arr[i] % 10
sum += arr[i] / 10
} else {
sum += arr[i]
}
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += arr[i]
}
var temp = result
for i in 0..<k {
let num = arr[i]
if num >= 10 {
let num2 = num % 10
let num3 = num / 10
temp += num2
if num3 > 0 {
temp += num3
}
}
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += arr[i]
}
var temp = result
for i in 0..<k {
let num = arr[i]
if num >= 10 {
let num2 = num % 10
let num3 = num / 10
temp += num2
if num3 > 0 {
temp += num3
}
}
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += getDigitSum(num: arr[i])
}
return result
}
func getDigitSum(num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += num % 10
num /= 10
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += getDigitSum(num: arr[i])
}
return result
}
func getDigitSum(num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += num % 10
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += getDigitSum(num: arr[i])
}
return result
}
func getDigitSum(num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += num % 10
num /= 10
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += getDigitSum(num: arr[i])
}
return result
}
func getDigitSum(num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += num % 10
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
let num = arr[i]
if num > 9 {
result += num % 10
result += num / 10
} else {
result += num
}
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
let num = arr[i]
if num > 9 {
result += num % 10
result += num / 10
} else {
result += num
}
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
} else {
sum += arr[i] % 10
sum += arr[i] / 10
}
}
return sum
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var sum = 0
for i in 0..<k {
if arr[i] < 10 {
sum += arr[i]
} else {
sum += arr[i] % 10
sum += arr[i] / 10
}
}
return sum
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += getDigitSum(num: arr[i])
}
return result
}
func getDigitSum(num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += num % 10
num /= 10
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
result += getDigitSum(num: arr[i])
}
return result
}
func getDigitSum(num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += num % 10
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
if arr[i] >= 10 {
result += arr[i] % 10
result += arr[i] / 10
} else {
result += arr[i]
}
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
if arr[i] >= 10 {
result += arr[i] % 10
result += arr[i] / 10
} else {
result += arr[i]
}
}
return result
}
```
// XCTAssertTrue failed
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
if arr[i] > 9 {
result += arr[i] % 10
result += arr[i] / 10
} else {
result += arr[i]
}
}
return result
}
```swift
// Given a non-empty array of integers arr and an integer k, return
// the sum of the elements with at most two digits from the first k elements of arr.
// Example:
// Constraints:
// 1. 1 <= len(arr) <= 100
// 2. 1 <= k <= len(arr)
// addElements(arr: [111, 21, 3, 4000, 5, 6, 7, 8, 9], k: 4) == 24
func addElements(arr: [Int], k: Int) -> Int {
var result = 0
for i in 0..<k {
if arr[i] > 9 {
result += arr[i] % 10
result += arr[i] / 10
} else {
result += arr[i]
}
}
return result
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
result.append(1)
return result.reversed()
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
result.append(1)
return result.reversed()
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
collatz.append(num)
}
return collatz
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var collatz = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
collatz.append(num)
}
return collatz
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
result.append(1)
return result.sorted()
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
result.append(1)
return result.sorted()
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
return result
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
return result
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var result = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
result.append(num)
}
return result
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num > 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
arr.append(1)
return arr.sorted()
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
arr.append(1)
return arr.sorted()
}
```
// XCTAssertTrue failed
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```swift
// Given a positive integer n, return a sorted array that has the odd numbers in collatz sequence.
// The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined
// as follows: start with any positive integer n. Then each term is obtained from the
// previous term as follows: if the previous term is even, the next term is one half of
// the previous term. If the previous term is odd, the next term is 3 times the previous
// term plus 1. The conjecture is that no matter what value of n, the sequence will always reach 1.
// Note:
// 1. Collatz(1) is [1].
// 2. returned array sorted in increasing order.
// For example:
// get_odd_collatz(5) returns [1, 5] # The collatz sequence for 5 is [5, 16, 8, 4, 2, 1], so the odd numbers are only 1, and 5.
// getOddCollatz(n: 5) == [1, 5]
func getOddCollatz(n: Int) -> [Int] {
var arr = [Int]()
var num = n
while num != 1 {
if num % 2 == 0 {
num = num / 2
} else {
num = 3 * num + 1
}
arr.append(num)
}
return arr
}
```
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let year = date!.year
let month = date!.month
let day = date!.day
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let year = date!.year
let month = date!.month
let day = date!.day
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
return true
}
```
let year = date!.year // value of type 'Date' has no member 'year'
let month = date!.month // value of type 'Date' has no member 'month'
let day = date!.day // value of type 'Date' has no member 'day'
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let dateComponents = dateFormatter.dateComponents([.day])
let days = dateComponents.day
let month = dateComponents.month!
let year = dateComponents.year!
if days < 1 || days > 31 {
return false
}
if month < 1 || month > 12 {
return false
}
if month == 2 {
if days < 1 || days > 29 {
return false
}
} else if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if days < 1 || days > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if days < 1 || days > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let dateComponents = dateFormatter.dateComponents([.day])
let days = dateComponents.day
let month = dateComponents.month!
let year = dateComponents.year!
if days < 1 || days > 31 {
return false
}
if month < 1 || month > 12 {
return false
}
if month == 2 {
if days < 1 || days > 29 {
return false
}
} else if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if days < 1 || days > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if days < 1 || days > 30 {
return false
}
}
return true
}
```
let dateComponents = dateFormatter.dateComponents([.day]) // reference to member 'day' cannot be resolved without a contextual type
let dateComponents = dateFormatter.dateComponents([.day]) // value of type 'DateFormatter' has no member 'dateComponents'
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let month = date!.month
let day = date!.day
let year = date!.year
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
if year < 1 || year > 9999 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let month = date!.month
let day = date!.day
let year = date!.year
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
if year < 1 || year > 9999 {
return false
}
return true
}
```
let month = date!.month // value of type 'Date' has no member 'month'
let day = date!.day // value of type 'Date' has no member 'day'
let year = date!.year // value of type 'Date' has no member 'year'
func validDate(date: String) -> Bool {
let dateArr = date.split(separator: "-")
if dateArr.count != 3 {
return false
}
let month = Int(dateArr[0])!
let day = Int(dateArr[1])!
let year = Int(dateArr[2])!
if month < 1 || month > 12 {
return false
}
if day < 1 || day > 31 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
if year < 1000 || year > 9999 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArr = date.split(separator: "-")
if dateArr.count != 3 {
return false
}
let month = Int(dateArr[0])!
let day = Int(dateArr[1])!
let year = Int(dateArr[2])!
if month < 1 || month > 12 {
return false
}
if day < 1 || day > 31 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else {
if day < 1 || day > 31 {
return false
}
}
if year < 1000 || year > 9999 {
return false
}
return true
}
```
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
guard date != nil else {
return false
}
let calendar = Calendar(identifier: .gregorian)
let month = calendar.component(.month, from: date!)
let day = calendar.component(.day, from: date!)
let year = calendar.component(.year, from: date!)
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
guard date != nil else {
return false
}
let calendar = Calendar(identifier: .gregorian)
let month = calendar.component(.month, from: date!)
let day = calendar.component(.day, from: date!)
let year = calendar.component(.year, from: date!)
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
return true
}
```
let year = calendar.component(.year, from: date!) // initialization of immutable value 'year' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let year = date!.year
let month = date!.month
let day = date!.day
let days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 2 {
if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
days[1] = 29
} else {
days[1] = 28
}
}
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > days[month - 1] {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > days[month - 1] {
return false
}
} else {
if day < 1 || day > days[month - 1] {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let year = date!.year
let month = date!.month
let day = date!.day
let days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if month == 2 {
if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 {
days[1] = 29
} else {
days[1] = 28
}
}
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > days[month - 1] {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > days[month - 1] {
return false
}
} else {
if day < 1 || day > days[month - 1] {
return false
}
}
return true
}
```
let year = date!.year // value of type 'Date' has no member 'year'
let month = date!.month // value of type 'Date' has no member 'month'
let day = date!.day // value of type 'Date' has no member 'day'
days[1] = 29 // cannot assign through subscript: 'days' is a 'let' constant
days[1] = 28 // cannot assign through subscript: 'days' is a 'let' constant
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
guard date != nil else {
return false
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(
Set([.year, .month, .day]),
from: date!
)
let month = components.month!
let day = components.day!
let year = components.year!
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
guard date != nil else {
return false
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents(
Set([.year, .month, .day]),
from: date!
)
let month = components.month!
let day = components.day!
let year = components.year!
if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else if month == 4 || month == 6 || month == 9 || month == 11 {
if day < 1 || day > 30 {
return false
}
} else if month == 2 {
if day < 1 || day > 29 {
return false
}
} else {
return false
}
return true
}
```
let year = components.year! // initialization of immutable value 'year' was never used; consider replacing with assignment to '_' or removing it
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.month, .day], from: date!)
let month = components.month!
let day = components.day!
let year = components.year!
if month < 1 || month > 12 {
return false
}
if day < 1 || day > calendar.component(.day, from: date!) {
return false
}
if month == 2 {
if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
if day < 1 || day > 29 {
return false
}
} else {
if day < 1 || day > 28 {
return false
}
}
} else if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else {
if day < 1 || day > 30 {
return false
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let calendar = Calendar(identifier: .gregorian)
let components = calendar.dateComponents([.month, .day], from: date!)
let month = components.month!
let day = components.day!
let year = components.year!
if month < 1 || month > 12 {
return false
}
if day < 1 || day > calendar.component(.day, from: date!) {
return false
}
if month == 2 {
if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) {
if day < 1 || day > 29 {
return false
}
} else {
if day < 1 || day > 28 {
return false
}
}
} else if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else {
if day < 1 || day > 30 {
return false
}
}
return true
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else {
if day < 1 || day > 30 {
return false
}
}
if year < 1000 || year > 3000 {
return false
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateArray = date.split(separator: "-")
if dateArray.count != 3 {
return false
}
let month = Int(dateArray[0])!
let day = Int(dateArray[1])!
let year = Int(dateArray[2])!
if month < 1 || month > 12 {
return false
}
if month == 2 {
if day < 1 || day > 29 {
return false
}
} else if month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12 {
if day < 1 || day > 31 {
return false
}
} else {
if day < 1 || day > 30 {
return false
}
}
if year < 1000 || year > 3000 {
return false
}
return true
}
```
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let month = dateFormatter.dateFormat.components(separatedBy: "-").first!
let day = dateFormatter.dateFormat.components(separatedBy: "-").last!
let year = dateFormatter.dateFormat.components(separatedBy: "-").last!
let days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if Int(month)! < 1 || Int(month)! > 12 {
return false
}
if Int(day)! < 1 || Int(day)! > days[Int(month)! - 1] {
return false
}
if Int(year)! % 4 == 0 && Int(year)! % 100 != 0 || Int(year)! % 400 == 0 {
if Int(month)! == 2 {
if Int(day)! < 1 || Int(day)! > 29 {
return false
}
}
} else {
if Int(month)! == 2 {
if Int(day)! < 1 || Int(day)! > 28 {
return false
}
}
}
return true
}
```swift
// You have to write a function which validates a given date string and
// returns true if the date is valid otherwise false.
// The date is valid if all of the following rules are satisfied:
// 1. The date string is not empty.
// 2. The number of days is not less than 1 or higher than 31 days for months 1,3,5,7,8,10,12. And the number of days is not less than 1 or higher than 30 days for months 4,6,9,11. And, the number of days is not less than 1 or higher than 29 for the month 2.
// 3. The months should not be less than 1 or higher than 12.
// 4. The date should be in the format: mm-dd-yyyy
// validDate(date: "03-11-2000") == true
// validDate(date: "15-01-2012") == false
// validDate(date: "04-0-2040") == false
// validDate(date: "06-04-2020") == true
// validDate(date: "06/04/2020") == false
func validDate(date: String) -> Bool {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm-dd-yyyy"
let date = dateFormatter.date(from: date)
if date == nil {
return false
}
let month = dateFormatter.dateFormat.components(separatedBy: "-").first!
let day = dateFormatter.dateFormat.components(separatedBy: "-").last!
let year = dateFormatter.dateFormat.components(separatedBy: "-").last!
let days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if Int(month)! < 1 || Int(month)! > 12 {
return false
}
if Int(day)! < 1 || Int(day)! > days[Int(month)! - 1] {
return false
}
if Int(year)! % 4 == 0 && Int(year)! % 100 != 0 || Int(year)! % 400 == 0 {
if Int(month)! == 2 {
if Int(day)! < 1 || Int(day)! > 29 {
return false
}
}
} else {
if Int(month)! == 2 {
if Int(day)! < 1 || Int(day)! > 28 {
return false
}
}
}
return true
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result = [String]()
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else if char == "," {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result = [String]()
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else if char == "," {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
var count = 0 // variable 'count' was never mutated; consider changing to 'let' constant
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var i = 0
var j = 0
var result: [String] = []
var count = 0
while i < chars.count {
if chars[i] == " " {
result.append(String(chars[j..<i]))
j = i + 1
}
if chars[i] == "," {
result.append(String(chars[j..<i]))
j = i + 1
}
i += 1
}
if j < i {
result.append(String(chars[j..<i]))
}
for c in result {
count += countOddOccurrences(c)
}
if count == 0 {
return .success(result)
} else {
return .failure(count)
}
}
func countOddOccurrences(_ s: String) -> Int {
var count = 0
for c in s {
let i = Int(c.asciiValue!) - 97
if i % 2 == 1 {
count += 1
}
}
return count
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var i = 0
var j = 0
var result: [String] = []
var count = 0
while i < chars.count {
if chars[i] == " " {
result.append(String(chars[j..<i]))
j = i + 1
}
if chars[i] == "," {
result.append(String(chars[j..<i]))
j = i + 1
}
i += 1
}
if j < i {
result.append(String(chars[j..<i]))
}
for c in result {
count += countOddOccurrences(c)
}
if count == 0 {
return .success(result)
} else {
return .failure(count)
}
}
func countOddOccurrences(_ s: String) -> Int {
var count = 0
for c in s {
let i = Int(c.asciiValue!) - 97
if i % 2 == 1 {
count += 1
}
}
return count
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var res = [String]()
var count = 0
var prev = 0
for (i, c) in chars.enumerated() {
if c.isWhitespace {
res.append(String(chars[prev..<i]))
prev = i + 1
}
}
if prev < chars.count {
res.append(String(chars[prev..<chars.count]))
}
if res.count == 0 {
return .failure(count)
}
for i in 0..<res.count {
let word = res[i]
if word.contains(",") {
res[i] = word.replacingOccurrences(of: ",", with: " ")
}
}
for i in 0..<res.count {
let word = res[i]
for j in word.indices {
let c = word[j]
if c.isLowercase {
count += 1
}
}
}
if count % 2 == 1 {
return .success(res)
}
return .failure(count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var res = [String]()
var count = 0
var prev = 0
for (i, c) in chars.enumerated() {
if c.isWhitespace {
res.append(String(chars[prev..<i]))
prev = i + 1
}
}
if prev < chars.count {
res.append(String(chars[prev..<chars.count]))
}
if res.count == 0 {
return .failure(count)
}
for i in 0..<res.count {
let word = res[i]
if word.contains(",") {
res[i] = word.replacingOccurrences(of: ",", with: " ")
}
}
for i in 0..<res.count {
let word = res[i]
for j in word.indices {
let c = word[j]
if c.isLowercase {
count += 1
}
}
}
if count % 2 == 1 {
return .success(res)
}
return .failure(count)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var result = [String]()
var count = 0
for char in chars {
if char.isWhitespace {
result.append(String(chars[..<count]))
count = 0
} else if char == "," {
result.append(String(chars[..<count]))
count = 0
} else {
count += 1
}
}
if count > 0 {
result.append(String(chars[..<count]))
}
if count % 2 == 1 {
return .success(result)
} else {
return .failure(count)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var result = [String]()
var count = 0
for char in chars {
if char.isWhitespace {
result.append(String(chars[..<count]))
count = 0
} else if char == "," {
result.append(String(chars[..<count]))
count = 0
} else {
count += 1
}
}
if count > 0 {
result.append(String(chars[..<count]))
}
if count % 2 == 1 {
return .success(result)
} else {
return .failure(count)
}
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result = [String]()
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else if char == "," {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result = [String]()
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else if char == "," {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
var count = 0 // variable 'count' was never mutated; consider changing to 'let' constant
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let result = txt.split(separator: " ")
if result.isSuccess {
return .success(result.value)
}
let result = txt.split(separator: ",")
if result.isSuccess {
return .success(result.value)
}
let count = txt.lowercased().filter { !$0.isLetterOrNumber }.count
return .failure(count)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let result = txt.split(separator: " ")
if result.isSuccess {
return .success(result.value)
}
let result = txt.split(separator: ",")
if result.isSuccess {
return .success(result.value)
}
let count = txt.lowercased().filter { !$0.isLetterOrNumber }.count
return .failure(count)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
if result.isSuccess { // value of type '[String.SubSequence]' (aka 'Array<Substring>') has no member 'isSuccess'
return .success(result.value) // value of type '[String.SubSequence]' (aka 'Array<Substring>') has no member 'value'
let result = txt.split(separator: ",") // invalid redeclaration of 'result'
let count = txt.lowercased().filter { !$0.isLetterOrNumber }.count // trailing closure passed to parameter of type 'Predicate<String.Element>' (aka 'Predicate<Character>') that does not accept a closure
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result: [String] = []
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result: [String] = []
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
var count = 0 // variable 'count' was never mutated; consider changing to 'let' constant
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var i = 0
var j = 0
var result = [String]()
while i < chars.count {
if chars[i] == " " {
result.append(String(chars[j...i]))
j = i + 1
}
i += 1
}
result.append(String(chars[j...i]))
if result.count == 1 {
let count = result[0].lowercased().filter { !["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"].contains(String($0)) }.count
return count % 2 == 0 ? .success(result) : .failure(count)
} else {
return .success(result)
}
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var i = 0
var j = 0
var result = [String]()
while i < chars.count {
if chars[i] == " " {
result.append(String(chars[j...i]))
j = i + 1
}
i += 1
}
result.append(String(chars[j...i]))
if result.count == 1 {
let count = result[0].lowercased().filter { !["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"].contains(String($0)) }.count
return count % 2 == 0 ? .success(result) : .failure(count)
} else {
return .success(result)
}
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result: [String] = []
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else if char == "," {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var count = 0
var result: [String] = []
var currentWord = ""
for char in chars {
if char.isWhitespace {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else if char == "," {
if !currentWord.isEmpty {
result.append(currentWord)
currentWord = ""
}
} else {
currentWord.append(char)
}
}
if !currentWord.isEmpty {
result.append(currentWord)
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
var count = 0 // variable 'count' was never mutated; consider changing to 'let' constant
extension Int: Error {
}
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var result = [String]()
var count = 0
for char in chars {
if char == " " {
result.append(String(chars[count..<chars.count]))
count = chars.count
} else if char == "," {
result.append(String(chars[count..<chars.count]))
count = chars.count
}
}
if count < chars.count {
result.append(String(chars[count..<chars.count]))
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```swift
extension Int: Error {}
// Given a string of words, return an array of words split on whitespace, if no whitespaces exists in the text you
// should split on commas ',' if no commas exists you should return the number of lower-case letters with odd order in the
// alphabet, ord('a') = 0, ord('b') = 1, ... ord('z') = 25
// Examples
// splitWords(txt: "Hello world!") == .success(["Hello", "world!"])
// splitWords(txt: "Hello,world!") == .success(["Hello", "world!"])
// splitWords(txt: "abcdef") == .failure(3)
func splitWords(txt: String) -> Result<[String], Int> {
let chars = Array(txt)
var result = [String]()
var count = 0
for char in chars {
if char == " " {
result.append(String(chars[count..<chars.count]))
count = chars.count
} else if char == "," {
result.append(String(chars[count..<chars.count]))
count = chars.count
}
}
if count < chars.count {
result.append(String(chars[count..<chars.count]))
}
if result.count == 0 {
return .failure(count)
}
return .success(result)
}
```
extension Int: Error {} // redundant conformance of 'Int' to protocol 'Error'
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = Int.max
for i in lst {
if i < last {
sorted = false
}
last = i
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = Int.max
for i in lst {
if i < last {
sorted = false
}
last = i
}
return sorted
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
sorted = false
}
last = lst[i]
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
sorted = false
}
last = lst[i]
}
return sorted
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
if lst.count <= 1 {
return true
}
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
if lst.count <= 1 {
return true
}
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
sorted = false
}
last = lst[i]
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
sorted = false
}
last = lst[i]
}
return sorted
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i - 1] {
sorted = false
break
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i - 1] {
sorted = false
break
}
}
return sorted
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
guard lst.count > 1 else {
return true
}
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
return false
}
last = lst[i]
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
guard lst.count > 1 else {
return true
}
var last = lst[0]
for i in 1..<lst.count {
if lst[i] < last {
return false
}
last = lst[i]
}
return true
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i - 1] {
sorted = false
}
}
return sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = true
for i in 1..<lst.count {
if lst[i] < lst[i - 1] {
sorted = false
}
}
return sorted
}
```
// Fatal error: Range requires lowerBound <= upperBound
func isSorted(lst: [Int]) -> Bool {
var sorted = lst
sorted.sort()
return lst == sorted
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var sorted = lst
sorted.sort()
return lst == sorted
}
```
// XCTAssertTrue failed
func isSorted(lst: [Int]) -> Bool {
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```
// Fatal error: Index out of range
func isSorted(lst: [Int]) -> Bool {
if lst.count <= 1 {
return true
}
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```swift
// Given an array of numbers, return whether or not they are sorted
// in ascending order. If array has more than 1 duplicate of the same
// number, return false. Assume no negative numbers and only integers.
// Examples
// isSorted(lst: [5]) == true
// isSorted(lst: [1, 2, 3, 4, 5]) == true
// isSorted(lst: [1, 3, 2, 4, 5]) == false
// isSorted(lst: [1, 2, 3, 4, 5, 6]) == true
// isSorted(lst: [1, 2, 3, 4, 5, 6, 7]) == true
// isSorted(lst: [1, 3, 2, 4, 5, 6, 7]) == false
// isSorted(lst: [1, 2, 2, 3, 3, 4]) == true
// isSorted(lst: [1, 2, 2, 2, 3, 4]) == false
func isSorted(lst: [Int]) -> Bool {
if lst.count <= 1 {
return true
}
var prev = lst[0]
for i in 1..<lst.count {
if lst[i] < prev {
return false
}
prev = lst[i]
}
return true
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
if length == 0 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length == 0 {
return "NO"
}
if length % 2 == 0 {
let mid = start + length / 2
let midInt = mid / 2
let midInt2 = midInt + 1
let midInt3 = midInt - 1
if midInt2.isPrime && midInt3.isPrime {
return "YES"
}
}
return "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
if length == 0 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length == 0 {
return "NO"
}
if length % 2 == 0 {
let mid = start + length / 2
let midInt = mid / 2
let midInt2 = midInt + 1
let midInt3 = midInt - 1
if midInt2.isPrime && midInt3.isPrime {
return "YES"
}
}
return "NO"
}
```
let length = end - start // invalid redeclaration of 'length'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let length = min(end1, end2) - max(start1, start2) + 1
if isPrime(length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(_ num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let length = min(end1, end2) - max(start1, start2) + 1
if isPrime(length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(_ num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2...Int(sqrt(Double(num))) {
if num % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
if length == 0 {
return "NO"
}
let length2 = end2 - start2
if length2 == 0 {
return "NO"
}
let length3 = min(end1, end2) - max(start1, start2)
if length3 < 0 {
return "NO"
}
let length4 = length3 % length
if length4 == 0 {
return "YES"
}
return "NO"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
if length == 0 {
return "NO"
}
let length2 = end2 - start2
if length2 == 0 {
return "NO"
}
let length3 = min(end1, end2) - max(start1, start2)
if length3 < 0 {
return "NO"
}
let length4 = length3 % length
if length4 == 0 {
return "YES"
}
return "NO"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if length == 0 {
return "NO"
}
if length == 1 {
return "YES"
}
if length % 2 == 0 {
return "NO"
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if length == 0 {
return "NO"
}
if length == 1 {
return "YES"
}
if length % 2 == 0 {
return "NO"
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
let length2 = end2 - start2
if length <= 0 || length2 <= 0 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
if length == 1 {
return "YES"
}
if length == 2 {
return "NO"
}
if length == 3 {
return "YES"
}
if length % 2 == 0 {
return "NO"
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
let length2 = end2 - start2
if length <= 0 || length2 <= 0 {
return "NO"
}
let start = max(start1, start2)
let end = min(end1, end2)
let length = end - start
if length <= 0 {
return "NO"
}
if length == 1 {
return "YES"
}
if length == 2 {
return "NO"
}
if length == 3 {
return "YES"
}
if length % 2 == 0 {
return "NO"
}
return "YES"
}
```
let length = end - start // invalid redeclaration of 'length'
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if isPrime(length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if isPrime(length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
// Fatal error: Range requires lowerBound <= upperBound
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let length = min(end1, end2) - max(start1, start2) + 1
if length % 2 == 0 {
return "NO"
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
if start1 > end2 || start2 > end1 {
return "NO"
}
let length = min(end1, end2) - max(start1, start2) + 1
if length % 2 == 0 {
return "NO"
}
return "YES"
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
let length2 = end2 - start2
let start = min(start1, start2)
let end = max(end1, end2)
let length3 = end - start
if length3 < 0 {
return "NO"
}
if length3 == 0 {
return "NO"
}
if length3 == 1 {
return "NO"
}
if length3 % 2 == 0 {
return "NO"
}
return "YES"
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let length = end1 - start1
let length2 = end2 - start2
let start = min(start1, start2)
let end = max(end1, end2)
let length3 = end - start
if length3 < 0 {
return "NO"
}
if length3 == 0 {
return "NO"
}
if length3 == 1 {
return "NO"
}
if length3 % 2 == 0 {
return "NO"
}
return "YES"
}
```
let length = end1 - start1 // initialization of immutable value 'length' was never used; consider replacing with assignment to '_' or removing it
let length2 = end2 - start2 // initialization of immutable value 'length2' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if length == 0 {
return "NO"
}
if length == 1 {
return "YES"
}
if isPrime(length) {
return "YES"
}
return "NO"
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if length == 0 {
return "NO"
}
if length == 1 {
return "YES"
}
if isPrime(length) {
return "YES"
}
return "NO"
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2...Int(sqrt(Double(n))) {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if isPrime(length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// You are given two intervals,
// where each interval is a pair of integers. For example, interval = (start, end) = (1, 2).
// The given intervals are closed which means that the interval (start, end)
// includes both start and end.
// For each given interval, it is assumed that its start is less or equal its end.
// Your task is to determine whether the length of intersection of these two
// intervals is a prime number.
// Example, the intersection of the intervals (1, 3), (2, 4) is (2, 3)
// which its length is 1, which not a prime number.
// If the length of the intersection is a prime number, return "YES",
// otherwise, return "NO".
// If the two intervals don't intersect, return "NO".
// [input/output] samples:
// intersection(interval1: (1, 2), interval2: (2, 3)) == "NO"
// intersection(interval1: (-1, 1), interval2: (0, 4)) == "NO"
// intersection(interval1: (-3, -1), interval2: (-5, 5)) == "YES"
func intersection(interval1: (Int, Int), interval2: (Int, Int)) -> String {
let (start1, end1) = interval1
let (start2, end2) = interval2
let start = max(start1, start2)
let end = min(end1, end2)
if start > end {
return "NO"
}
let length = end - start + 1
if isPrime(length) {
return "YES"
} else {
return "NO"
}
}
func isPrime(_ n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for num in arr {
if num == 0 {
return nil
}
result *= num > 0 ? 1 : -1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for num in arr {
if num == 0 {
return nil
}
result *= num > 0 ? 1 : -1
}
return result
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= numSign(num)
}
return result
}
func numSign(_ num: Int) -> Int {
return num > 0 ? 1 : (num < 0 ? -1 : 0)
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= numSign(num)
}
return result
}
func numSign(_ num: Int) -> Int {
return num > 0 ? 1 : (num < 0 ? -1 : 0)
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for num in arr {
result *= numSign(num)
}
return result
}
func numSign(num: Int) -> Int {
if num > 0 {
return 1
} else if num < 0 {
return -1
} else {
return 0
}
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for num in arr {
result *= numSign(num)
}
return result
}
func numSign(num: Int) -> Int {
if num > 0 {
return 1
} else if num < 0 {
return -1
} else {
return 0
}
}
```
result *= numSign(num) // missing argument label 'num:' in call
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else {
return nil
}
var result = 1
for i in 0..<arr.count {
result *= arr[i] > 0 ? 1 : -1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else {
return nil
}
var result = 1
for i in 0..<arr.count {
result *= arr[i] > 0 ? 1 : -1
}
return result
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else { return nil }
var signs = [Int]()
for num in arr {
if num == 0 {
return 0
}
if num > 0 {
signs.append(1)
} else {
signs.append(-1)
}
}
var res = 1
for sign in signs {
res *= sign
}
return res
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else { return nil }
var signs = [Int]()
for num in arr {
if num == 0 {
return 0
}
if num > 0 {
signs.append(1)
} else {
signs.append(-1)
}
}
var res = 1
for sign in signs {
res *= sign
}
return res
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num > 0 ? 1 : -1
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else { return nil }
var result = 1
for num in arr {
result *= num > 0 ? 1 : -1
}
return result
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else {
return nil
}
var result = 1
var sign = 1
for num in arr {
if num == 0 {
return nil
}
sign = (num > 0) ? 1 : -1
result *= sign
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard !arr.isEmpty else {
return nil
}
var result = 1
var sign = 1
for num in arr {
if num == 0 {
return nil
}
sign = (num > 0) ? 1 : -1
result *= sign
}
return result
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else {
return nil
}
var sign = 1
var res = 1
for num in arr {
if num == 0 {
return nil
}
sign = (sign * num) / abs(num)
res *= sign
}
return res
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
guard arr.count > 0 else {
return nil
}
var sign = 1
var res = 1
for num in arr {
if num == 0 {
return nil
}
sign = (sign * num) / abs(num)
res *= sign
}
return res
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for i in 0..<arr.count {
if arr[i] > 0 {
result *= 1
} else if arr[i] < 0 {
result *= -1
} else {
result *= 0
}
}
return result
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for i in 0..<arr.count {
if arr[i] > 0 {
result *= 1
} else if arr[i] < 0 {
result *= -1
} else {
result *= 0
}
}
return result
}
```
// XCTAssertTrue failed
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for num in arr {
result *= numSign(num: num)
}
return result
}
func numSign(num: Int) -> Int {
if num > 0 {
return 1
} else if num < 0 {
return -1
} else {
return 0
}
}
```swift
// You are given an array arr of integers and you need to return
// sum of magnitudes of integers multiplied by product of all signs
// of each number in the array, represented by 1, -1 or 0.
// Note: return nil for empty arr.
// Example:
// prodSigns(arr: [1, 2, 2, -4]) == 9
// prodSigns(arr: [0, 1]) == 0
// prodSigns(arr: [] as [Int]) == nil
func prodSigns(arr: [Int]) -> Int? {
if arr.isEmpty {
return nil
}
var result = 1
for num in arr {
result *= numSign(num: num)
}
return result
}
func numSign(num: Int) -> Int {
if num > 0 {
return 1
} else if num < 0 {
return -1
} else {
return 0
}
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var res = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: n), count: n)
var queue = [[Int]]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
queue.append([i, j])
visited[i][j] = true
}
}
}
while !queue.isEmpty && k > 0 {
let size = queue.count
for _ in 0..<size {
let cell = queue.removeFirst()
res.append(grid[cell[0]][cell[1]])
for dir in dirs {
let x = cell[0] + dir[0]
let y = cell[1] + dir[1]
if x >= 0 && x < n && y >= 0 && y < n && !visited[x][y] {
visited[x][y] = true
queue.append([x, y])
}
}
}
k -= 1
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var res = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: n), count: n)
var queue = [[Int]]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
queue.append([i, j])
visited[i][j] = true
}
}
}
while !queue.isEmpty && k > 0 {
let size = queue.count
for _ in 0..<size {
let cell = queue.removeFirst()
res.append(grid[cell[0]][cell[1]])
for dir in dirs {
let x = cell[0] + dir[0]
let y = cell[1] + dir[1]
if x >= 0 && x < n && y >= 0 && y < n && !visited[x][y] {
visited[x][y] = true
queue.append([x, y])
}
}
}
k -= 1
}
return res
}
```
k -= 1 // left side of mutating operator isn't mutable: 'k' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let dp = [[Int]](repeating: [Int](repeating: 0, count: m), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
dp[i][j] = 1
}
}
}
for _ in 1...k {
for i in 0..<n {
for j in 0..<m {
for direction in directions {
let ni = i + direction[0]
let nj = j + direction[1]
if ni >= 0 && ni < n && nj >= 0 && nj < m {
dp[i][j] = min(dp[i][j], dp[ni][nj] + 1)
}
}
}
}
}
var ans = [Int]()
for i in 0..<n {
for j in 0..<m {
if dp[i][j] == k {
ans.append(grid[i][j])
}
}
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let dp = [[Int]](repeating: [Int](repeating: 0, count: m), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
dp[i][j] = 1
}
}
}
for _ in 1...k {
for i in 0..<n {
for j in 0..<m {
for direction in directions {
let ni = i + direction[0]
let nj = j + direction[1]
if ni >= 0 && ni < n && nj >= 0 && nj < m {
dp[i][j] = min(dp[i][j], dp[ni][nj] + 1)
}
}
}
}
}
var ans = [Int]()
for i in 0..<n {
for j in 0..<m {
if dp[i][j] == k {
ans.append(grid[i][j])
}
}
}
return ans
}
```
dp[i][j] = 1 // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j] = min(dp[i][j], dp[ni][nj] + 1) // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
for i in 0..<n {
for j in 0..<n {
dp[i][j] = grid[i][j]
}
}
for _ in 0..<k {
var temp = dp
for i in 0..<n {
for j in 0..<n {
for d in directions {
let ni = i + d[0]
let nj = j + d[1]
if ni >= 0 && ni < n && nj >= 0 && nj < n {
temp[i][j] = min(temp[i][j], dp[ni][nj] + grid[i][j])
}
}
}
}
dp = temp
}
for i in 0..<n {
for j in 0..<n {
ans.append(dp[i][j])
}
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
for i in 0..<n {
for j in 0..<n {
dp[i][j] = grid[i][j]
}
}
for _ in 0..<k {
var temp = dp
for i in 0..<n {
for j in 0..<n {
for d in directions {
let ni = i + d[0]
let nj = j + d[1]
if ni >= 0 && ni < n && nj >= 0 && nj < n {
temp[i][j] = min(temp[i][j], dp[ni][nj] + grid[i][j])
}
}
}
}
dp = temp
}
for i in 0..<n {
for j in 0..<n {
ans.append(dp[i][j])
}
}
return ans
}
```
dp[i][j] = grid[i][j] // cannot assign through subscript: 'dp' is a 'let' constant
dp = temp // cannot assign to value: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
var ans = [Int]()
func dfs(x: Int, y: Int, step: Int) {
if step == k {
ans = grid[x][y] < ans ? [grid[x][y]] : ans
return
}
for dir in directions {
let nx = x + dir[0], ny = y + dir[1]
if nx >= 0 && nx < n && ny >= 0 && ny < n && dp[nx][ny] == 0 {
dp[nx][ny] = 1
dfs(x: nx, y: ny, step: step + 1)
dp[nx][ny] = 0
}
}
}
dfs(x: 0, y: 0, step: 0)
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
var ans = [Int]()
func dfs(x: Int, y: Int, step: Int) {
if step == k {
ans = grid[x][y] < ans ? [grid[x][y]] : ans
return
}
for dir in directions {
let nx = x + dir[0], ny = y + dir[1]
if nx >= 0 && nx < n && ny >= 0 && ny < n && dp[nx][ny] == 0 {
dp[nx][ny] = 1
dfs(x: nx, y: ny, step: step + 1)
dp[nx][ny] = 0
}
}
}
dfs(x: 0, y: 0, step: 0)
return ans
}
```
ans = grid[x][y] < ans ? [grid[x][y]] : ans // cannot convert value of type '[Int]' to expected argument type 'Int'
dp[nx][ny] = 1 // cannot assign through subscript: 'dp' is a 'let' constant
dp[nx][ny] = 0 // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
dp[i][j] = 1
}
}
}
for _ in 1...k {
var min = Int.max
for i in 0..<n {
for j in 0..<n {
if dp[i][j] != 0 {
for dir in directions {
let x = i + dir[0]
let y = j + dir[1]
if x >= 0 && x < n && y >= 0 && y < n {
min = min(min, dp[x][y])
}
}
}
}
}
for i in 0..<n {
for j in 0..<n {
if dp[i][j] != 0 && min != Int.max && min + 1 == dp[i][j] {
dp[i][j] = min + 1
ans.append(grid[i][j])
}
}
}
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
dp[i][j] = 1
}
}
}
for _ in 1...k {
var min = Int.max
for i in 0..<n {
for j in 0..<n {
if dp[i][j] != 0 {
for dir in directions {
let x = i + dir[0]
let y = j + dir[1]
if x >= 0 && x < n && y >= 0 && y < n {
min = min(min, dp[x][y])
}
}
}
}
}
for i in 0..<n {
for j in 0..<n {
if dp[i][j] != 0 && min != Int.max && min + 1 == dp[i][j] {
dp[i][j] = min + 1
ans.append(grid[i][j])
}
}
}
}
return ans
}
```
dp[i][j] = 1 // cannot assign through subscript: 'dp' is a 'let' constant
min = min(min, dp[x][y]) // cannot call value of non-function type 'Int'
dp[i][j] = min + 1 // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: n), count: n)
var queue = [[Int]]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
queue.append([i, j])
visited[i][j] = true
}
}
}
while !queue.isEmpty && k > 0 {
let size = queue.count
for _ in 0..<size {
let cell = queue.removeFirst()
let x = cell[0]
let y = cell[1]
for dir in dirs {
let newX = x + dir[0]
let newY = y + dir[1]
if newX >= 0 && newX < n && newY >= 0 && newY < n && !visited[newX][newY] {
visited[newX][newY] = true
queue.append([newX, newY])
ans.append(grid[newX][newY])
k -= 1
}
}
}
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: n), count: n)
var queue = [[Int]]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
queue.append([i, j])
visited[i][j] = true
}
}
}
while !queue.isEmpty && k > 0 {
let size = queue.count
for _ in 0..<size {
let cell = queue.removeFirst()
let x = cell[0]
let y = cell[1]
for dir in dirs {
let newX = x + dir[0]
let newY = y + dir[1]
if newX >= 0 && newX < n && newY >= 0 && newY < n && !visited[newX][newY] {
visited[newX][newY] = true
queue.append([newX, newY])
ans.append(grid[newX][newY])
k -= 1
}
}
}
}
return ans
}
```
k -= 1 // left side of mutating operator isn't mutable: 'k' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
dp[i][j] = 1
}
}
}
for _ in 1...k {
var temp = [Int]()
for i in 0..<n {
for j in 0..<n {
if dp[i][j] == 0 {
continue
}
for direction in directions {
let x = i + direction[0]
let y = j + direction[1]
if x >= 0 && x < n && y >= 0 && y < n {
temp.append(dp[x][y] + 1)
}
}
}
}
temp.sort()
ans.append(temp[0])
for i in 0..<n {
for j in 0..<n {
if dp[i][j] > 0 {
dp[i][j] = temp[0]
}
}
}
}
return ans
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = Array(repeating: Array(repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 1 {
dp[i][j] = 1
}
}
}
for _ in 1...k {
var temp = [Int]()
for i in 0..<n {
for j in 0..<n {
if dp[i][j] == 0 {
continue
}
for direction in directions {
let x = i + direction[0]
let y = j + direction[1]
if x >= 0 && x < n && y >= 0 && y < n {
temp.append(dp[x][y] + 1)
}
}
}
}
temp.sort()
ans.append(temp[0])
for i in 0..<n {
for j in 0..<n {
if dp[i][j] > 0 {
dp[i][j] = temp[0]
}
}
}
}
return ans
}
```
dp[i][j] = 1 // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j] = temp[0] // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 0 {
continue
}
dp[i][j] = grid[i][j]
for dir in directions {
let ni = i + dir[0]
let nj = j + dir[1]
if ni >= 0 && ni < n && nj >= 0 && nj < n {
dp[i][j] = min(dp[i][j], dp[ni][nj] + grid[i][j])
}
}
}
}
var res = [Int]()
for i in 0..<n {
for j in 0..<n {
if dp[i][j] == k {
res.append(grid[i][j])
}
}
}
return res
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let dp = [[Int]](repeating: [Int](repeating: 0, count: n), count: n)
let directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
for i in 0..<n {
for j in 0..<n {
if grid[i][j] == 0 {
continue
}
dp[i][j] = grid[i][j]
for dir in directions {
let ni = i + dir[0]
let nj = j + dir[1]
if ni >= 0 && ni < n && nj >= 0 && nj < n {
dp[i][j] = min(dp[i][j], dp[ni][nj] + grid[i][j])
}
}
}
}
var res = [Int]()
for i in 0..<n {
for j in 0..<n {
if dp[i][j] == k {
res.append(grid[i][j])
}
}
}
return res
}
```
dp[i][j] = grid[i][j] // cannot assign through subscript: 'dp' is a 'let' constant
dp[i][j] = min(dp[i][j], dp[ni][nj] + grid[i][j]) // cannot assign through subscript: 'dp' is a 'let' constant
func minPath(grid: [[Int]], k: Int) -> [Int] {
let N = grid.count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
let values = grid.flatMap { $0 }
let valuesCount = values.count
let target = values[0]
let targetIndex = values.firstIndex(of: target)!
var visited = Array(repeating: false, count: valuesCount)
var queue = [Int]()
queue.append(targetIndex)
visited[targetIndex] = true
var path = [Int]()
path.append(target)
var step = 1
while !queue.isEmpty && step <= k {
let size = queue.count
for _ in 0..<size {
let index = queue.removeFirst()
let value = values[index]
path.append(value)
for dir in dirs {
let row = (index + dir[0]) / N
let col = (index + dir[1]) % N
let neighborIndex = row * N + col
if row >= 0 && row < N && col >= 0 && col < N && !visited[neighborIndex] {
if step == k {
return path
}
queue.append(neighborIndex)
visited[neighborIndex] = true
}
}
}
step += 1
}
return path
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let N = grid.count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
let values = grid.flatMap { $0 }
let valuesCount = values.count
let target = values[0]
let targetIndex = values.firstIndex(of: target)!
var visited = Array(repeating: false, count: valuesCount)
var queue = [Int]()
queue.append(targetIndex)
visited[targetIndex] = true
var path = [Int]()
path.append(target)
var step = 1
while !queue.isEmpty && step <= k {
let size = queue.count
for _ in 0..<size {
let index = queue.removeFirst()
let value = values[index]
path.append(value)
for dir in dirs {
let row = (index + dir[0]) / N
let col = (index + dir[1]) % N
let neighborIndex = row * N + col
if row >= 0 && row < N && col >= 0 && col < N && !visited[neighborIndex] {
if step == k {
return path
}
queue.append(neighborIndex)
visited[neighborIndex] = true
}
}
}
step += 1
}
return path
}
```
// XCTAssertTrue failed
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
var queue = [[Int]]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: m), count: n)
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
queue.append([i, j])
visited[i][j] = true
}
}
}
while queue.count > 0 {
let size = queue.count
for i in 0..<size {
let cell = queue.removeFirst()
for dir in dirs {
let x = cell[0] + dir[0]
let y = cell[1] + dir[1]
if x >= 0 && x < n && y >= 0 && y < m && !visited[x][y] {
if grid[x][y] == k {
return ans + [grid[x][y]]
}
visited[x][y] = true
ans.append(grid[x][y])
queue.append([x, y])
}
}
}
if ans.count == k {
return ans
}
}
return []
}
```swift
// Given a grid with N rows and N columns (N >= 2) and a positive integer k,
// each cell of the grid contains a value. Every integer in the range [1, N * N]
// inclusive appears exactly once on the cells of the grid.
// You have to find the minimum path of length k in the grid. You can start
// from any cell, and in each step you can move to any of the neighbor cells,
// in other words, you can go to cells which share an edge with you current
// cell.
// Please note that a path of length k means visiting exactly k cells (not
// necessarily distinct).
// You CANNOT go off the grid.
// A path A (of length k) is considered less than a path B (of length k) if
// after making the ordered arrays of the values on the cells that A and B go
// through (let's call them lst_A and lst_B), lst_A is lexicographically less
// than lst_B, in other words, there exist an integer index i (1 <= i <= k)
// such that lst_A[i] < lst_B[i] and for any j (1 <= j < i) we have
// lst_A[j] = lst_B[j].
// It is guaranteed that the answer is unique.
// Return an ordered array of the values on the cells that the minimum path go through.
// Examples:
// minPath(grid: [[1, 2, 3], [4, 5, 6], [7, 8, 9]], k: 3) == [1, 2, 1]
// minPath(grid: [[5, 9, 3], [4, 1, 6], [7, 8, 2]], k: 1) == [1]
func minPath(grid: [[Int]], k: Int) -> [Int] {
let n = grid.count
let m = grid[0].count
let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
var ans = [Int]()
var queue = [[Int]]()
var visited = [[Bool]](repeating: [Bool](repeating: false, count: m), count: n)
for i in 0..<n {
for j in 0..<m {
if grid[i][j] == 1 {
queue.append([i, j])
visited[i][j] = true
}
}
}
while queue.count > 0 {
let size = queue.count
for i in 0..<size {
let cell = queue.removeFirst()
for dir in dirs {
let x = cell[0] + dir[0]
let y = cell[1] + dir[1]
if x >= 0 && x < n && y >= 0 && y < m && !visited[x][y] {
if grid[x][y] == k {
return ans + [grid[x][y]]
}
visited[x][y] = true
ans.append(grid[x][y])
queue.append([x, y])
}
}
}
if ans.count == k {
return ans
}
}
return []
}
```
for i in 0..<size { // immutable value 'i' was never used; consider replacing with '_' or removing it
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [Int]()
result.append(3)
if n == 0 {
return result
}
result.append(1)
if n == 1 {
return result
}
result.append(2)
if n == 2 {
return result
}
var pre = 2
var cur = 1
var next = 3
for _ in 3...n {
if _ % 2 == 0 {
pre = cur
cur = next
next = pre + cur
} else {
pre = cur
cur = next
next = cur + pre + cur
}
result.append(next)
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [Int]()
result.append(3)
if n == 0 {
return result
}
result.append(1)
if n == 1 {
return result
}
result.append(2)
if n == 2 {
return result
}
var pre = 2
var cur = 1
var next = 3
for _ in 3...n {
if _ % 2 == 0 {
pre = cur
cur = next
next = pre + cur
} else {
pre = cur
cur = next
next = cur + pre + cur
}
result.append(next)
}
return result
}
```
if _ % 2 == 0 { // '_' can only appear in a pattern or on the left side of an assignment
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n <= 2 {
return result
}
var i = 2
while i <= n {
if i % 2 == 0 {
result.append(result[i - 1] + result[i - 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
i += 1
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n <= 2 {
return result
}
var i = 2
while i <= n {
if i % 2 == 0 {
result.append(result[i - 1] + result[i - 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
i += 1
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
result.append(2)
return result
}
for _ in 3...n {
let temp = result[result.count - 1] + result[result.count - 2] + result[result.count - 3]
result.append(temp)
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
result.append(2)
return result
}
for _ in 3...n {
let temp = result[result.count - 1] + result[result.count - 2] + result[result.count - 3]
result.append(temp)
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var tri = [1, 3, 2]
if n <= 3 {
return tri[0...n]
}
var i = 3
while i <= n {
if i % 2 == 0 {
tri.append(tri[i / 2] + tri[i / 2 + 1])
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i + 1])
}
i += 1
}
return tri
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var tri = [1, 3, 2]
if n <= 3 {
return tri[0...n]
}
var i = 3
while i <= n {
if i % 2 == 0 {
tri.append(tri[i / 2] + tri[i / 2 + 1])
} else {
tri.append(tri[i - 1] + tri[i - 2] + tri[i + 1])
}
i += 1
}
return tri
}
```
return tri[0...n] // no 'subscript' candidates produce the expected contextual result type '[Int]'
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
result.append(2)
return result
}
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i - 1] + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + (i + 1) / 2)
}
}
result.append(result[n - 1] + result[n - 2] + 1)
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
result.append(2)
return result
}
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i - 1] + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + (i + 1) / 2)
}
}
result.append(result[n - 1] + result[n - 2] + 1)
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
return result + [2]
}
for i in 3...n {
if i % 2 == 0 {
result.append(result[i - 1] + result[i - 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i - 3])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
return result + [2]
}
for i in 3...n {
if i % 2 == 0 {
result.append(result[i - 1] + result[i - 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i - 3])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 0 {
return []
}
if n == 1 {
return result
}
if n == 2 {
return result + [8]
}
var i = 2
while i < n {
if i % 2 == 0 {
result.append(result[i - 1] + result[i - 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
i += 1
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 0 {
return []
}
if n == 1 {
return result
}
if n == 2 {
return result + [8]
}
var i = 2
while i < n {
if i % 2 == 0 {
result.append(result[i - 1] + result[i - 2])
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 0 {
return result
}
if n == 1 {
return result
}
if n == 2 {
return result + [8]
}
var i = 2
while i < n {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
i += 1
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 0 {
return result
}
if n == 1 {
return result
}
if n == 2 {
return result + [8]
}
var i = 2
while i < n {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
i += 1
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
result.append(2)
return result
}
for i in 3...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n == 1 {
return result
}
if n == 2 {
result.append(2)
return result
}
for i in 3...n {
if i % 2 == 0 {
result.append(1 + i / 2)
} else {
result.append(result[i - 1] + result[i - 2] + result[i + 1])
}
}
return result
}
```
// Fatal error: Index out of range
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n > 2 {
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i] + result[i - 1])
} else {
result.append(result[i] + result[i - 1] + result[i + 1])
}
}
}
return result
}
```swift
// Everyone knows Fibonacci sequence, it was studied deeply by mathematicians in
// the last couple centuries. However, what people don't know is Tribonacci sequence.
// Tribonacci sequence is defined by the recurrence:
// tri(1) = 3
// tri(n) = 1 + n / 2, if n is even.
// tri(n) = tri(n - 1) + tri(n - 2) + tri(n + 1), if n is odd.
// For example:
// tri(2) = 1 + (2 / 2) = 2
// tri(4) = 3
// tri(3) = tri(2) + tri(1) + tri(4)
// = 2 + 3 + 3 = 8
// You are given a non-negative integer number n, you have to a return an array of the
// first n + 1 numbers of the Tribonacci sequence.
// Examples:
// tri(n: 3) == [1, 3, 2, 8]
func tri(n: Int) -> [Int] {
var result = [1, 3]
if n > 2 {
for i in 2..<n {
if i % 2 == 0 {
result.append(result[i] + result[i - 1])
} else {
result.append(result[i] + result[i - 1] + result[i + 1])
}
}
}
return result
}
```
// Fatal error: Index out of range
func digits(n: Int) -> Int {
var n = n
var res = 1
while n > 0 {
let last = n % 10
if last % 2 == 1 {
res *= last
}
n /= 10
}
return res
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var n = n
var res = 1
while n > 0 {
let last = n % 10
if last % 2 == 1 {
res *= last
}
n /= 10
}
return res
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
result *= last
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
result *= last
}
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var n = n
var result = 1
while n > 0 {
let last = n % 10
if last % 2 == 1 {
result *= last
}
n /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var n = n
var result = 1
while n > 0 {
let last = n % 10
if last % 2 == 1 {
result *= last
}
n /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var res = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
res *= last
}
num /= 10
}
return res
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var res = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
res *= last
}
num /= 10
}
return res
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var num = n
var res = 1
while num > 0 {
let last = num % 10
if last % 2 == 1 {
res *= last
}
num /= 10
}
return res
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var num = n
var res = 1
while num > 0 {
let last = num % 10
if last % 2 == 1 {
res *= last
}
num /= 10
}
return res
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var res = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
res *= last
}
num /= 10
}
return res
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var res = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
res *= last
}
num /= 10
}
return res
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
if num % 2 == 1 {
result *= num
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
if num % 2 == 1 {
result *= num
}
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
result *= last
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
result *= last
}
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var n = n
var result = 1
while n > 0 {
let last = n % 10
if last % 2 == 1 {
result *= last
}
n /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var n = n
var result = 1
while n > 0 {
let last = n % 10
if last % 2 == 1 {
result *= last
}
n /= 10
}
return result
}
```
// XCTAssertTrue failed
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
result *= last
}
num /= 10
}
return result
}
```swift
// Given a positive integer n, return the product of the odd digits.
// Return 0 if all digits are even.
// For example:
// digits(n: 1) == 1
// digits(n: 4) == 0
// digits(n: 235) == 15
func digits(n: Int) -> Int {
var result = 1
var num = n
while num > 0 {
let last = num % 10
if last % 2 == 1 {
result *= last
}
num /= 10
}
return result
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for c in string {
if c == "[" {
stack.append(c)
} else if c == "]" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for c in string {
if c == "[" {
stack.append(c)
} else if c == "]" {
if stack.isEmpty {
return false
} else {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let chars = Array(string)
var stack = [Character]()
for c in chars {
if c == "[" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
if let top = stack.popLast(), top == "[" {
continue
} else {
return false
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
let chars = Array(string)
var stack = [Character]()
for c in chars {
if c == "[" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
if let top = stack.popLast(), top == "[" {
continue
} else {
return false
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for c in string {
if c == "[", let top = stack.last {
if top == "[" {
stack.append("]")
} else {
stack.append(c)
}
} else {
if c == "]" {
stack.removeLast()
} else {
stack.append(c)
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for c in string {
if c == "[", let top = stack.last {
if top == "[" {
stack.append("]")
} else {
stack.append(c)
}
} else {
if c == "]" {
stack.removeLast()
} else {
stack.append(c)
}
}
}
return stack.isEmpty
}
```
// Fatal error: Can't remove last element from an empty collection
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for c in string {
if c == "[" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
if stack.last! == "[" {
stack.removeLast()
} else {
return false
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for c in string {
if c == "[" {
stack.append(c)
} else {
if stack.isEmpty {
return false
}
if stack.last! == "[" {
stack.removeLast()
} else {
return false
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[", let last = stack.last {
if last == "[" {
stack.append("]")
} else {
stack.append("[")
}
} else {
stack.append(char)
}
}
return stack.count == 1 && stack.first! == "]"
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[", let last = stack.last {
if last == "[" {
stack.append("]")
} else {
stack.append("[")
}
} else {
stack.append(char)
}
}
return stack.count == 1 && stack.first! == "]"
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
let top = stack.removeLast()
if top != "[" {
return false
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
let top = stack.removeLast()
if top != "[" {
return false
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[", let last = stack.last {
if last == "[" {
stack.append("]")
} else {
stack.append("[")
}
} else {
if stack.count > 0, stack.last == "[" {
stack.removeLast()
} else {
return false
}
}
}
return stack.count == 0
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[", let last = stack.last {
if last == "[" {
stack.append("]")
} else {
stack.append("[")
}
} else {
if stack.count > 0, stack.last == "[" {
stack.removeLast()
} else {
return false
}
}
}
return stack.count == 0
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
let chars = Array(string)
var stack = [Character]()
for char in chars {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
if char == "]" {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
let chars = Array(string)
var stack = [Character]()
for char in chars {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
if char == "]" {
stack.removeLast()
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[", let last = stack.last {
if last == "[" {
stack.append("]")
} else {
stack.append(char)
}
} else {
stack.append(char)
}
}
return stack.count == 0
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[", let last = stack.last {
if last == "[" {
stack.append("]")
} else {
stack.append(char)
}
} else {
stack.append(char)
}
}
return stack.count == 0
}
```
// XCTAssertTrue failed
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
if let top = stack.popLast() {
if top != "[" {
return false
}
}
}
}
return stack.isEmpty
}
```swift
// Create a function that takes a string as input which contains only square brackets.
// The function should return true if and only if there is a valid subsequence of brackets
// where at least one bracket in the subsequence is nested.
// isNested(string: "[[]]") == true
// isNested(string: "[]]]]]]][[[[[]") == false
// isNested(string: "[][]") == false
// isNested(string: "[]") == false
// isNested(string: "[[][]]") == true
// isNested(string: "[[]][[") == true
func isNested(string: String) -> Bool {
var stack = [String.Element]()
for char in string {
if char == "[" {
stack.append(char)
} else {
if stack.isEmpty {
return false
}
if let top = stack.popLast() {
if top != "[" {
return false
}
}
}
}
return stack.isEmpty
}
```
// XCTAssertTrue failed
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i)) * Int(ceil(i))
}
return sum
}
```
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var result = 0
for i in lst {
result += Int(ceil(i * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for num in lst {
sum += Int(ceil(num * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var result = 0
for i in 0..<lst.count {
result += Int(ceil(lst[i] * 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i * 1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 2.0, 3.0]) == 14) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [1.4, 4.2, 0.0]) == 29) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-2.4, 1.0, 1.0]) == 6) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [100.0, 1.0, 15.0, 2.0]) == 10230) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [10000.0, 10000.0]) == 200000000) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 4.6, 6.3]) == 75) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.4, 17.9, 18.9, 19.9]) == 1086) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [0.0]) == 0) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0]) == 1) // cannot find 'sumSquares' in scope
XCTAssertTrue(sumSquares(lst: [-1.0, 1.0, 0.0]) == 2) // cannot find 'sumSquares' in scope
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i))! * Int(ceil(i))!
}
return sum
}
```swift
// You are given an array of numbers.
// You need to return the sum of squared numbers in the given array,
// round each element in the array to the upper int(Ceiling) first.
// Examples:
// sumSquares(lst: [1.0, 2.0, 3.0]) == 14
// sumSquares(lst: [1.0, 4.0, 9.0]) == 98
// sumSquares(lst: [1.0, 3.0, 5.0, 7.0]) == 84
// sumSquares(lst: [1.4, 4.2, 0.0]) == 29
// sumSquares(lst: [-2.4, 1.0, 1.0]) == 6
func sumSquares(lst: [Double]) -> Int {
var sum = 0
for i in lst {
sum += Int(ceil(i))! * Int(ceil(i))!
}
return sum
}
```
sum += Int(ceil(i))! * Int(ceil(i))! // no exact matches in call to initializer
sum += Int(ceil(i))! * Int(ceil(i))! // no exact matches in call to initializer
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotPartOfWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotPartOfWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotPartOfWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotPartOfWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = Character.isLetter(lastChar)
let lastCharIsNotWord = !Character.isWord(lastChar)
return lastCharIsLetter && lastCharIsNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = Character.isLetter(lastChar)
let lastCharIsNotWord = !Character.isWord(lastChar)
return lastCharIsLetter && lastCharIsNotWord
}
```
let lastCharIsLetter = Character.isLetter(lastChar) // instance member 'isLetter' cannot be used on type 'Character'; did you mean to use a value of this type instead?
let lastCharIsLetter = Character.isLetter(lastChar) // cannot call value of non-function type 'Bool'
let lastCharIsNotWord = !Character.isWord(lastChar) // type 'Character' has no member 'isWord'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotPartOfWord = !lastCharIsLetter || lastCharIsLetter && !lastChar.isLetterOrDigit
return lastCharIsNotPartOfWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotPartOfWord = !lastCharIsLetter || lastCharIsLetter && !lastChar.isLetterOrDigit
return lastCharIsNotPartOfWord
}
```
let lastCharIsNotPartOfWord = !lastCharIsLetter || lastCharIsLetter && !lastChar.isLetterOrDigit // value of type 'String.Element' (aka 'Character') has no member 'isLetterOrDigit'
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotPartOfWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotPartOfWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let lastCharIsLetter = lastChar.isLetter
let lastCharIsNotPartOfWord = !lastChar.isWhitespace
return lastCharIsLetter && lastCharIsNotPartOfWord
}
```
// XCTAssertTrue failed
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```swift
// Create a function that returns true if the last character
// of a given string is an alphabetical character and is not
// a part of a word, and false otherwise.
// Note: "word" is a group of characters separated by space.
// Examples:
// checkIfLastCharIsALetter(txt: "apple pie") == false
// checkIfLastCharIsALetter(txt: "apple pi e") == true
// checkIfLastCharIsALetter(txt: "apple pi e ") == false
// checkIfLastCharIsALetter(txt: "") == false
func checkIfLastCharIsALetter(txt: String) -> Bool {
let lastChar = txt.last!
let isLetter = lastChar.isLetter
let isNotWord = !lastChar.isWhitespace
return isLetter && isNotWord
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
sum += arr[i]
}
if sum % 2 != 0 {
return -1
}
var map = [Int: Int]()
for i in 0..<arr.count {
let complement = sum - 2 * arr[i]
if map[complement] != nil {
return map[complement]! + i + 1
}
map[arr[i]] = i
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var sum = 0
for i in 0..<arr.count {
sum += arr[i]
}
if sum % 2 != 0 {
return -1
}
var map = [Int: Int]()
for i in 0..<arr.count {
let complement = sum - 2 * arr[i]
if map[complement] != nil {
return map[complement]! + i + 1
}
map[arr[i]] = i
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
let n = arr.count
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for i in 0..<n {
let cur = arr[i]
for j in (0..<target).reversed() {
if j < cur {
dp[j] = dp[j] || dp[j - cur]
} else {
dp[j] = dp[j] || dp[target - cur]
}
}
}
return dp[target].map { return target - $0 } ?? -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
let n = arr.count
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for i in 0..<n {
let cur = arr[i]
for j in (0..<target).reversed() {
if j < cur {
dp[j] = dp[j] || dp[j - cur]
} else {
dp[j] = dp[j] || dp[target - cur]
}
}
}
return dp[target].map { return target - $0 } ?? -1
}
```
return dp[target].map { return target - $0 } ?? -1 // value of type 'Bool' has no member 'map'
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for num in arr {
for i in (0..<target).reversed() {
if num <= i && !dp[i - num] {
dp[i] = true
}
}
}
for i in (0..<target).reversed() {
if dp[i] {
return i
}
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for num in arr {
for i in (0..<target).reversed() {
if num <= i && !dp[i - num] {
dp[i] = true
}
}
}
for i in (0..<target).reversed() {
if dp[i] {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
let n = arr.count
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for num in arr {
for i in (0..<target).reversed() {
if num <= i {
dp[i] = dp[i] || dp[i - num]
}
}
}
for i in (0..<target).reversed() {
if dp[i] {
return i
}
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
let n = arr.count
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for num in arr {
for i in (0..<target).reversed() {
if num <= i {
dp[i] = dp[i] || dp[i - num]
}
}
}
for i in (0..<target).reversed() {
if dp[i] {
return i
}
}
return -1
}
```
let n = arr.count // initialization of immutable value 'n' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for i in 0..<arr.count {
for j in target...arr[i] {
dp[j] = dp[j] || dp[j - arr[i]]
}
}
for i in target...target {
if dp[i] {
return i
}
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
let sum = arr.reduce(0, +)
if sum % 2 != 0 {
return -1
}
let target = sum / 2
var dp = Array(repeating: false, count: target + 1)
dp[0] = true
for i in 0..<arr.count {
for j in target...arr[i] {
dp[j] = dp[j] || dp[j - arr[i]]
}
}
for i in target...target {
if dp[i] {
return i
}
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var sum = 0
var max = 0
for i in 0..<arr.count {
sum += arr[i]
max = max > arr[i] ? max : arr[i]
}
if sum % max == 0 {
return sum / max - 1
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var sum = 0
var max = 0
for i in 0..<arr.count {
sum += arr[i]
max = max > arr[i] ? max : arr[i]
}
if sum % max == 0 {
return sum / max - 1
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
var sum = 0
var max = 0
for i in 0..<arr.count {
sum += arr[i]
max = max > arr[i] ? max : arr[i]
}
if sum % max == 0 {
return sum / max - 1
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
var sum = 0
var max = 0
for i in 0..<arr.count {
sum += arr[i]
max = max > arr[i] ? max : arr[i]
}
if sum % max == 0 {
return sum / max - 1
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
// 1. 先求和
let sum = arr.reduce(0, +)
// 2. 求出平均值
let avg = sum / arr.count
// 3. 求出余数
let remainder = sum - avg * arr.count
// 4. 判断余数是否为0
if remainder != 0 {
return -1
}
// 5. 求出最大值
var max = 0
for num in arr {
max = max > num ? max : num
}
// 6. 求出最大值和平均值的差
let diff = max - avg
// 7. 遍历数组,如果当前元素大于平均值,则求出当前元素和平均值的差,如果差值小于等于最大值和平均值的差,则返回当前元素的下标
for (index, num) in arr.enumerated() {
if num > avg {
let diff = num - avg
if diff <= diff {
return index
}
}
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
// 1. 先求和
let sum = arr.reduce(0, +)
// 2. 求出平均值
let avg = sum / arr.count
// 3. 求出余数
let remainder = sum - avg * arr.count
// 4. 判断余数是否为0
if remainder != 0 {
return -1
}
// 5. 求出最大值
var max = 0
for num in arr {
max = max > num ? max : num
}
// 6. 求出最大值和平均值的差
let diff = max - avg
// 7. 遍历数组,如果当前元素大于平均值,则求出当前元素和平均值的差,如果差值小于等于最大值和平均值的差,则返回当前元素的下标
for (index, num) in arr.enumerated() {
if num > avg {
let diff = num - avg
if diff <= diff {
return index
}
}
}
return -1
}
```
let diff = max - avg // initialization of immutable value 'diff' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
let sorted = arr.sorted()
var sum = 0
for i in 0..<sorted.count {
let num = sorted[i]
let target = sum - num
if target < 0 {
return -1
}
if target == 0 {
return i
}
sum += num
}
return -1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
let sorted = arr.sorted()
var sum = 0
for i in 0..<sorted.count {
let num = sorted[i]
let target = sum - num
if target < 0 {
return -1
}
if target == 0 {
return i
}
sum += num
}
return -1
}
```
// XCTAssertTrue failed
func canArrange(arr: [Int]) -> Int {
let sorted = arr.sorted()
var sum = 0
for i in 0..<sorted.count {
if sum + sorted[i] > sorted[sorted.count - 1] {
return -1
}
sum += sorted[i]
}
return sorted.count - 1
}
```swift
// Create a function which returns the largest index of an element which
// is not greater than or equal to the element immediately preceding it. If
// no such element exists then return -1. The given array will not contain
// duplicate values.
// Examples:
// canArrange(arr: [1, 2, 4, 3, 5]) == 3
// canArrange(arr: [1, 2, 3]) == -1
func canArrange(arr: [Int]) -> Int {
let sorted = arr.sorted()
var sum = 0
for i in 0..<sorted.count {
if sum + sorted[i] > sorted[sorted.count - 1] {
return -1
}
sum += sorted[i]
}
return sorted.count - 1
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.isEmpty {
return (nil, nil)
}
var negative = Int.min
var positive = Int.max
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
if lst.isEmpty {
return (nil, nil)
}
var negative = Int.min
var positive = Int.max
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = -1
for num in lst {
if num < 0 {
if negative == -1 || negative < num {
negative = num
}
} else {
if positive == -1 || positive > num {
positive = num
}
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = -1
for num in lst {
if num < 0 {
if negative == -1 || negative < num {
negative = num
}
} else {
if positive == -1 || positive > num {
positive = num
}
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = Int.min
var positive = Int.max
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = Int.min
var positive = Int.max
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
if negative == -1 || negative < i {
negative = i
}
} else {
if positive == 1 || positive > i {
positive = i
}
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
if negative == -1 || negative < i {
negative = i
}
} else {
if positive == 1 || positive > i {
positive = i
}
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
if negative.isEmpty && positive.isEmpty {
return (nil, nil)
}
if negative.isEmpty {
return (nil, positive.min()!)
}
if positive.isEmpty {
return (negative.max()!, nil)
}
return (negative.max()!, positive.min()!)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
let negative = lst.filter { $0 < 0 }
let positive = lst.filter { $0 > 0 }
if negative.isEmpty && positive.isEmpty {
return (nil, nil)
}
if negative.isEmpty {
return (nil, positive.min()!)
}
if positive.isEmpty {
return (negative.max()!, nil)
}
return (negative.max()!, positive.min()!)
}
```
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = Int.min
var positive = Int.max
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = Int.min
var positive = Int.max
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
// write your code here
var negative = Int.min
var positive = Int.max
for num in lst {
if num < 0 {
negative = max(negative, num)
} else {
positive = min(positive, num)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
// write your code here
var negative = Int.min
var positive = Int.max
for num in lst {
if num < 0 {
negative = max(negative, num)
} else {
positive = min(positive, num)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```swift
// Create a function that returns a tuple (a, b), where 'a' is
// the largest of negative integers, and 'b' is the smallest
// of positive integers in an array.
// If there is no negative or positive integers, return them as nil.
// Examples:
// largestSmallestIntegers(lst: [2, 4, 1, 3, 5, 7]) == (nil, 1)
// largestSmallestIntegers(lst: [] as [Int]) == (nil, nil)
// largestSmallestIntegers(lst: [0]) == (nil, nil)
func largestSmallestIntegers(lst: [Int]) -> (Int?, Int?) {
var negative = -1
var positive = 1
for i in lst {
if i < 0 {
negative = max(negative, i)
} else {
positive = min(positive, i)
}
}
return (negative, positive)
}
```
// XCTAssertTrue failed
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(a), let .intValue(b)):
return a > b ? a : b
case (let .doubleValue(a), let .doubleValue(b)):
return a > b ? a : b
case (let .stringValue(a), let .stringValue(b)):
return a > b ? a : b
default:
return nil
}
}
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(a), let .intValue(b)):
return a > b ? a : b
case (let .doubleValue(a), let .doubleValue(b)):
return a > b ? a : b
case (let .stringValue(a), let .stringValue(b)):
return a > b ? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(a), let .intValue(b)):
return a > b ? a : b
case (let .doubleValue(a), let .doubleValue(b)):
return a > b ? a : b
case (let .stringValue(a), let .stringValue(b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compare(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compare(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compare(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compare(a: .stringValue("1"), b: .intValue(1)) == nil
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(a), let .intValue(b)):
return a > b ? a : b
case (let .doubleValue(a), let .doubleValue(b)):
return a > b ? a : b
case (let .stringValue(a), let .stringValue(b)):
return a > b ? a : b
default:
return nil
}
}
```
### 解法二
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(a), let .intValue(b)):
return a > b ? a : b
case (let .doubleValue(a), let .doubleValue(b)):
return a > b ? a : b
case (let .stringValue(a), let .stringValue(b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compare(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compare(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compare(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compare(a: .stringValue("1"), b: .intValue(1)) == nil
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(a), let .intValue(b)):
return a > b ? a : b
case (let .doubleValue(a), let .doubleValue(b)):
return a > b ? a : b
case (let .stringValue(a), let .stringValue(b)):
return a >
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
let aStringArray = aString.split(separator: ",")
let bStringArray = bString.split(separator: ",")
let aIntArray = aStringArray.map { Int(String($0))! }
let bIntArray = bStringArray.map { Int(String($0))! }
if aIntArray.count > bIntArray.count {
return a
} else if aIntArray.count < bIntArray.count {
return b
} else {
let aIntArrayMax = aIntArray.max()
let bIntArrayMax = bIntArray.max()
return aIntArrayMax > bIntArrayMax ? .intValue(aIntArrayMax!) : .intValue(bIntArrayMax!)
}
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
let aStringArray = aString.split(separator: ",")
let bStringArray = bString.split(separator: ",")
let aIntArray = aStringArray.map { Int(String($0))! }
let bIntArray = bStringArray.map { Int(String($0))! }
if aIntArray.count > bIntArray.count {
return a
} else if aIntArray.count < bIntArray.count {
return b
} else {
let aIntArrayMax = aIntArray.max()
let bIntArrayMax = bIntArray.max()
return aIntArrayMax > bIntArrayMax ? .intValue(aIntArrayMax!) : .intValue(bIntArrayMax!)
}
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
let aStringArray = aString.split(separator: ",")
let bStringArray = bString.split(separator: ",")
let aIntArray = aStringArray.map { Int(String($0))! }
let bIntArray = bStringArray.map { Int(String($0))! }
if aIntArray.count > bIntArray.count {
return a
} else if aIntArray.count < bIntArray.count {
return b
} else {
let aIntArrayMax = aIntArray.max()
let bIntArrayMax = bIntArray.max()
return aIntArrayMax > bIntArrayMax ? .intValue(aIntArrayMax!) : .intValue(bIntArrayMax!) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
return aIntArrayMax > bIntArrayMax ? .intValue(aIntArrayMax!) : .intValue(bIntArrayMax!) // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its
// given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compare(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compare(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compare(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compare(a: .stringValue("1"), b: .intValue(1)) == nil
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its
// given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compare(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compare(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compare(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compare(a: .stringValue("1"), b: .intValue(1)) == nil
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its
// given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compare(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compare(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compare(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compare(a: .stringValue("1"), b: .intValue(1)) == nil
func compare(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its
// given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compare(a
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_):
return a
case .doubleValue(_):
return nil
case .stringValue(_):
return nil
}
case .doubleValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return a
case .stringValue(_):
return nil
}
case .stringValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return nil
case .stringValue(_):
return a
}
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_):
return a
case .doubleValue(_):
return nil
case .stringValue(_):
return nil
}
case .doubleValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return a
case .stringValue(_):
return nil
}
case .stringValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return nil
case .stringValue(_):
return a
}
}
}
func compareAll(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var maxValue: Value? = nil
for value in a {
if maxValue == nil {
maxValue = value
} else {
maxValue = compareTwo(a: maxValue!, b: value)
}
}
return maxValue
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_):
return a
case .doubleValue(_):
return nil
case .stringValue(_):
return nil
}
case .doubleValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return a
case .stringValue(_):
return nil
}
case .stringValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return nil
case .stringValue(_):
return a
}
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_):
return a
case .doubleValue(_):
return nil
case .stringValue(_):
return nil
}
case .doubleValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return a
case .stringValue(_):
return nil
}
case .stringValue(_):
switch b {
case .intValue(_):
return nil
case .doubleValue(_):
return nil
case .stringValue(_):
return a
}
}
}
// Create a function that takes a list of real numbers, and returns the largest variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareAll(a: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareAll(a: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareAll(a: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareAll(a: [.stringValue("1"), .intValue(1)]) == nil
func compareAll(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var maxValue: Value? = nil
for value in a {
if maxValue == nil {
maxValue = value
} else {
maxValue = compareTwo(a: maxValue!, b: value)
}
}
return maxValue
}
// Create a function that takes a list of real numbers, and returns the largest variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareAll(a: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareAll(a: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareAll(a: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareAll(a: [.stringValue("1"), .intValue(1)]) == nil
func compareAll2(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var maxValue: Value? = nil
for value in a {
if maxValue == nil {
maxValue =
// XCTAssertTrue failed
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: [Value], b: [Value]) -> [Value]? {
guard !a.isEmpty && !b.isEmpty else { return nil }
guard a.count == b.count else { return nil }
var result: [Value] = []
for i in 0..<a.count {
let value = compareOne(a: a[i], b: b[i])
result.append(value!)
}
return result
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two arrays of real numbers, and returns the
// largest value in each array.
// Return nil if the arrays are empty or if the arrays have different lengths.
// Note: If an array is represented as a string, the array might be . or ,
// compareTwo(a: [1, 2, 3], b: [4, 5, 6]) == [4, 5, 6]
// compareTwo(a: [1, 2, 3], b: [4, 5]) == nil
// compareTwo(a: [1, 2, 3], b: ["4,5"]) == [4, 5]
func compareTwo(a: [Value], b: [Value]) -> [Value]? {
guard !a.isEmpty && !b.isEmpty else { return nil }
guard a.count == b.count else { return nil }
var result: [Value] = []
for i in 0..<a.count {
let value = compareOne(a: a[i], b: b[i])
result.append(value!)
}
return result
}
```
```cpp
class Solution {
public:
enum Value {
intValue,
doubleValue,
stringValue
};
Value valueType(const string& s) {
if (s.empty()) {
return Value::stringValue;
}
if (s.find('.') != string::npos) {
return Value::doubleValue;
}
return Value::intValue;
}
Value valueType(const string& s, int& i) {
if (s.empty()) {
return Value::stringValue;
}
if (s[i] == '.') {
++i;
return Value::doubleValue;
}
if (s[i] == ',') {
++i;
return Value::intValue;
}
return Value::stringValue;
}
Value valueType(const string& s, int& i, int& j) {
if (s.empty()) {
return Value::stringValue;
}
if (s[i] == '.') {
++i;
return Value::doubleValue;
}
if (s[i] == ',') {
++i;
return Value::intValue;
}
j = s.find(',', i);
if (j == string::npos) {
j = s.size();
}
return Value::stringValue;
}
Value valueType(const string& s, int& i, int& j, int& k) {
if (s.empty()) {
return Value::stringValue;
}
if (s[i] == '.') {
++i;
return Value::doubleValue;
}
if (s[i] == ',') {
++i;
return Value::intValue;
}
j = s.find(',', i);
if (j == string::npos) {
j = s.size();
}
k = s.find(',', j);
if (k == string::npos) {
k = s.size();
}
return Value::stringValue;
}
Value valueType(const string& s, int& i, int& j, int& k, int& l) {
if (s.empty()) {
return Value::stringValue;
}
if (s[i] == '.') {
++i;
return Value::doubleValue;
}
if (s[i] == ',') {
++i;
return Value::intValue;
}
j = s.find(',', i);
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? .intValue(a) : .intValue(b)
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? .doubleValue(a) : .doubleValue(b)
case (.stringValue(let a), .stringValue(let b)):
return a > b ? .stringValue(a) : .stringValue(b)
default:
return nil
}
}
func compareTwo(a: String, b: String) -> Value? {
let aValue = Value.intValue(Int(a) ?? 0) ?? Value.doubleValue(Double(a) ?? 0) ?? Value.stringValue(a)
let bValue = Value.intValue(Int(b) ?? 0) ?? Value.doubleValue(Double(b) ?? 0) ?? Value.stringValue(b)
return compareOne(a: aValue, b: bValue)
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? .intValue(a) : .intValue(b)
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? .doubleValue(a) : .doubleValue(b)
case (.stringValue(let a), .stringValue(let b)):
return a > b ? .stringValue(a) : .stringValue(b)
default:
return nil
}
}
// Create a function that takes two real numbers represented as strings,
// and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
func compareTwo(a: String, b: String) -> Value? {
let aValue = Value.intValue(Int(a) ?? 0) ?? Value.doubleValue(Double(a) ?? 0) ?? Value.stringValue(a)
let bValue = Value.intValue(Int(b) ?? 0) ?? Value.doubleValue(Double(b) ?? 0) ?? Value.stringValue(b)
return compareOne(a: aValue, b: bValue)
}
```
let aValue = Value.intValue(Int(a) ?? 0) ?? Value.doubleValue(Double(a) ?? 0) ?? Value.stringValue(a) // left side of nil coalescing operator '??' has non-optional type 'Value', so the right side is never used
let aValue = Value.intValue(Int(a) ?? 0) ?? Value.doubleValue(Double(a) ?? 0) ?? Value.stringValue(a) // left side of nil coalescing operator '??' has non-optional type 'Value', so the right side is never used
let bValue = Value.intValue(Int(b) ?? 0) ?? Value.doubleValue(Double(b) ?? 0) ?? Value.stringValue(b) // left side of nil coalescing operator '??' has non-optional type 'Value', so the right side is never used
let bValue = Value.intValue(Int(b) ?? 0) ?? Value.doubleValue(Double(b) ?? 0) ?? Value.stringValue(b) // left side of nil coalescing operator '??' has non-optional type 'Value', so the right side is never used
// XCTAssertTrue failed
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(aValue), let .intValue(bValue)):
return .intValue(max(aValue, bValue))
case (let .doubleValue(aValue), let .doubleValue(bValue)):
return .doubleValue(max(aValue, bValue))
case (let .stringValue(aValue), let .stringValue(bValue)):
return .stringValue(max(aValue, bValue))
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
if let aValue = a.intValue {
if let bValue = b.intValue {
return compareOne(a: .intValue(max(aValue, bValue)), b: b)
}
}
if let aValue = a.doubleValue {
if let bValue = b.doubleValue {
return compareOne(a: .doubleValue(max(aValue, bValue)), b: b)
}
}
if let aValue = a.stringValue {
if let bValue = b.stringValue {
return compareOne(a: .stringValue(max(aValue, bValue)), b: b)
}
}
return nil
}
func compareAll(a: [Value]) -> Value? {
if a.count == 0 {
return nil
}
var maxValue: Value? = nil
for value in a {
if let value = compareTwo(a: value, b: maxValue!) {
maxValue = value
}
}
return maxValue
}
func compareAll2(a: [Value]) -> Value? {
if a.count == 0 {
return nil
}
var maxValue: Value? = nil
for value in a {
if let value = compareTwo(a: value, b: maxValue!) {
maxValue = value
}
}
return maxValue
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (let .intValue(aValue), let .intValue(bValue)):
return .intValue(max(aValue, bValue))
case (let .doubleValue(aValue), let .doubleValue(bValue)):
return .doubleValue(max(aValue, bValue))
case (let .stringValue(aValue), let .stringValue(bValue)):
return .stringValue(max(aValue, bValue))
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its
// given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
if let aValue = a.intValue {
if let bValue = b.intValue {
return compareOne(a: .intValue(max(aValue, bValue)), b: b)
}
}
if let aValue = a.doubleValue {
if let bValue = b.doubleValue {
return compareOne(a: .doubleValue(max(aValue, bValue)), b: b)
}
}
if let aValue = a.stringValue {
if let bValue = b.stringValue {
return compareOne(a: .stringValue(max(aValue, bValue)), b: b)
}
}
return nil
}
// Create a function that takes a list of real numbers, and returns the largest variable
// in its given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareAll(a: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareAll(a: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareAll(a: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareAll(a: [.stringValue("1"), .intValue(1)]) == nil
func compareAll(a: [Value]) -> Value? {
if a.count == 0 {
return nil
}
var maxValue: Value? = nil
for value in a {
if let value = compareTwo(a: value, b: maxValue!) {
maxValue = value
}
}
return maxValue
}
// Create a function that takes a list of real numbers, and returns the largest variable
// in its given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareAll(a: [.intValue(1), .doubleValue(2.5)]) == .doubleValue(2.5)
// compareAll(a: [.intValue(1), .stringValue("2,3")]) == .stringValue("2,3")
// compareAll(a: [.stringValue("5,1"), .stringValue("6")]) == .stringValue("6")
// compareAll(a: [.stringValue("1"), .intValue(1)]) == nil
func compareAll2(a: [Value]) -> Value? {
if a.count == 0 {
return nil
}
var maxValue: Value? = nil
for value in a {
if let value = compareTwo(a: value, b: maxValue!) {
maxValue = value
}
}
return maxValue
}
// Create a function that takes a list of real numbers, and returns the largest variable
if let aValue = a.intValue { // enum case 'intValue' cannot be used as an instance member
if let bValue = b.intValue { // enum case 'intValue' cannot be used as an instance member
if let aValue = a.doubleValue { // enum case 'doubleValue' cannot be used as an instance member
if let bValue = b.doubleValue { // enum case 'doubleValue' cannot be used as an instance member
if let aValue = a.stringValue { // enum case 'stringValue' cannot be used as an instance member
if let bValue = b.stringValue { // enum case 'stringValue' cannot be used as an instance member
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return compareOne(a: aString, b: bString)
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return compareTwo(a: aString, b: bString)
default:
return nil
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return aString > bString ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return compareOne(a: aString, b: bString)
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return compareTwo(a: aString, b: bString)
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let aInt), .intValue(let bInt)):
return aInt > bInt ? a : b
case (.doubleValue(let aDouble), .doubleValue(let bDouble)):
return aDouble > bDouble ? a : b
case (.stringValue(let aString), .stringValue(let bString)):
return compareTwo(a: aString, b: b
return compareOne(a: aString, b: bString) // cannot convert value of type 'String' to expected argument type 'Value'
return compareOne(a: aString, b: bString) // cannot convert value of type 'String' to expected argument type 'Value'
func compareTwo(a: Value, b: Value) -> Value? { // invalid redeclaration of 'compareTwo(a:b:)'
return compareTwo(a: aString, b: bString) // cannot convert value of type 'String' to expected argument type 'Value'
return compareTwo(a: aString, b: bString) // cannot convert value of type 'String' to expected argument type 'Value'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
func largestOf(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var largest = a.first!
for i in a.dropFirst() {
let result = compareTwo(a: largest, b: i)
if result != nil {
largest = result!
}
}
return largest
}
func smallestOf(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var smallest = a.first!
for i in a.dropFirst() {
let result = compareTwo(a: smallest, b: i)
if result != nil {
smallest = result!
}
}
return smallest
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes two real numbers, and returns the larger variable in its
// given variable type. Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch (a, b) {
case (.intValue(let a), .intValue(let b)):
return a > b ? a : b
case (.doubleValue(let a), .doubleValue(let b)):
return a > b ? a : b
case (.stringValue(let a), .stringValue(let b)):
return a > b ? a : b
default:
return nil
}
}
// Create a function that takes a list of real numbers, and returns the largest variable in its
// given variable type. Return nil if the list is empty.
// Note: If a real number is represented as a string, the floating point might be . or ,
// largestOf(a: [.intValue(1), .doubleValue(2.5), .stringValue("5,1")]) == .doubleValue(2.5)
// largestOf(a: [.intValue(1), .stringValue("2,3"), .stringValue("6")]) == .stringValue("6")
// largestOf(a: [.stringValue("1"), .intValue(1)]) == nil
func largestOf(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var largest = a.first!
for i in a.dropFirst() {
let result = compareTwo(a: largest, b: i)
if result != nil {
largest = result!
}
}
return largest
}
// Create a function that takes a list of real numbers, and returns the smallest variable in its
// given variable type. Return nil if the list is empty.
// Note: If a real number is represented as a string, the floating point might be . or ,
// smallestOf(a: [.intValue(1), .doubleValue(2.5), .stringValue("5,1")]) == .intValue(1)
// smallestOf(a: [.intValue(1), .stringValue("2,3"), .stringValue("6")]) == .stringValue("2,3")
// smallestOf(a: [.stringValue("1"), .intValue(1)]) == nil
func smallestOf(a: [Value]) -> Value? {
if a.isEmpty {
return nil
}
var smallest = a.first!
for i in a.dropFirst() {
let result = compareTwo(a: smallest, b: i)
if result != nil {
smallest = result!
}
}
return smallest
}
// Create a function that takes a list of real numbers, and returns the sum of their values.
// Return nil if the list is empty.
// Note: If a real number is represented as a string, the floating point might be . or ,
// sumOf(a: [.intValue(1), .doubleValue(2.5), .stringValue("5,1")]) == .doubleValue(8.5)
// sumOf(a: [.intValue(1), .stringValue("2,3"), .stringValue("6")]) == .doubleValue(9)
// sumOf(
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Int' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'Double' to return type 'Value?'
return a > b ? a : b // cannot convert return expression of type 'String' to return type 'Value?'
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_): return .intValue(max(a.intValue, b.intValue))
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue)))
}
case .doubleValue(_):
switch b {
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue)))
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue))
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue)))
}
case .stringValue(_):
switch b {
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue)))
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue))
}
}
}
func compareTwo(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_): return .intValue(max(a.intValue, b.intValue))
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue)))
}
case .doubleValue(_):
switch b {
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue)))
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue))
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue)))
}
case .stringValue(_):
switch b {
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue)))
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue))
}
}
}
```swift
enum Value: Equatable, Hashable {
case intValue(Int)
case doubleValue(Double)
case stringValue(String)
}
// Create a function that takes integers, floats, or strings representing
// real numbers, and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareOne(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareOne(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareOne(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareOne(a: .stringValue("1"), b: .intValue(1)) == nil
func compareOne(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_): return .intValue(max(a.intValue, b.intValue))
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue)))
}
case .doubleValue(_):
switch b {
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue)))
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue))
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue)))
}
case .stringValue(_):
switch b {
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue)))
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue))
}
}
}
// Create a function that takes two values and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_): return .intValue(max(a.intValue, b.intValue))
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue)))
}
case .doubleValue(_):
switch b {
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue)))
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue))
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue)))
}
case .stringValue(_):
switch b {
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue)))
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue)))
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue))
}
}
}
// Create a function that takes two values and returns the larger variable in its given variable type.
// Return nil if the values are equal.
// Note: If a real number is represented as a string, the floating point might be . or ,
// compareTwo(a: .intValue(1), b: .doubleValue(2.5)) == .doubleValue(2.5)
// compareTwo(a: .intValue(1), b: .stringValue("2,3")) == .stringValue("2,3")
// compareTwo(a: .stringValue("5,1"), b: .stringValue("6")) == .stringValue("6")
// compareTwo(a: .stringValue("1"), b: .intValue(1)) == nil
func compareTwo(a: Value, b: Value) -> Value? {
switch a {
case .intValue(_):
switch b {
case .intValue(_): return .intValue(max(a.intValue, b.intValue))
case .doubleValue(_): return .doubleValue(max(a.
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // type '(Int) -> Value' cannot conform to 'Comparable'
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // cannot convert value of type '(Int) -> Value' to expected argument type 'Int'
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // cannot convert value of type '(Int) -> Value' to expected argument type 'Int'
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // no exact matches in call to initializer
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // cannot convert value of type 'Int' to expected argument type 'Double'
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // enum case 'intValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // cannot convert value of type 'Int' to expected argument type 'String'
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // enum case 'intValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // cannot convert value of type '(Int) -> Value' to expected argument type 'Int'
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // no exact matches in call to initializer
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // enum case 'stringValue' cannot be used as an instance member
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // cannot convert value of type '(Double) -> Value' to expected argument type 'Double'
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // no exact matches in call to initializer
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // type '(Double) -> Value' cannot conform to 'Comparable'
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // cannot convert value of type '(Double) -> Value' to expected argument type 'Double'
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // enum case 'doubleValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // enum case 'doubleValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // no exact matches in call to initializer
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // cannot convert value of type '(Double) -> Value' to expected argument type 'Double'
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // enum case 'stringValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // cannot convert value of type 'Double' to expected argument type 'String'
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // cannot convert value of type '(String) -> Value' to expected argument type 'String'
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // enum case 'stringValue' cannot be used as an instance member
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // no exact matches in call to initializer
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // no exact matches in call to initializer
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // enum case 'stringValue' cannot be used as an instance member
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // cannot convert value of type '(String) -> Value' to expected argument type 'String'
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // type '(String) -> Value' cannot conform to 'Comparable'
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // cannot convert value of type '(String) -> Value' to expected argument type 'String'
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // enum case 'stringValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // enum case 'stringValue' cannot be used as an instance member
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // cannot convert value of type '(Int) -> Value' to expected argument type 'Int'
case .intValue(_): return .intValue(max(a.intValue, b.intValue)) // type '(Int) -> Value' cannot conform to 'Comparable'
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // cannot convert value of type '(Int) -> Value' to expected argument type 'Int'
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // no exact matches in call to initializer
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // enum case 'intValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.intValue, Int(b.doubleValue))) // cannot convert value of type 'Int' to expected argument type 'Double'
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // cannot convert value of type '(Int) -> Value' to expected argument type 'Int'
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // enum case 'stringValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // no exact matches in call to initializer
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // cannot convert value of type 'Int' to expected argument type 'String'
case .stringValue(_): return .stringValue(max(a.intValue, Int(b.stringValue))) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // cannot convert value of type '(Double) -> Value' to expected argument type 'Double'
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // enum case 'doubleValue' cannot be used as an instance member
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // no exact matches in call to initializer
case .intValue(_): return .doubleValue(max(a.doubleValue, Double(b.intValue))) // enum case 'intValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // cannot convert value of type '(Double) -> Value' to expected argument type 'Double'
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // type '(Double) -> Value' cannot conform to 'Comparable'
case .doubleValue(_): return .doubleValue(max(a.doubleValue, b.doubleValue)) // enum case 'doubleValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // enum case 'doubleValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // enum case 'stringValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // no exact matches in call to initializer
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // cannot convert value of type 'Double' to expected argument type 'String'
case .stringValue(_): return .stringValue(max(a.doubleValue, Double(b.stringValue))) // cannot convert value of type '(Double) -> Value' to expected argument type 'Double'
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // no exact matches in call to initializer
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // enum case 'stringValue' cannot be used as an instance member
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // enum case 'intValue' cannot be used as an instance member
case .intValue(_): return .stringValue(max(a.stringValue, String(b.intValue))) // cannot convert value of type '(String) -> Value' to expected argument type 'String'
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // cannot convert value of type '(String) -> Value' to expected argument type 'String'
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // enum case 'doubleValue' cannot be used as an instance member
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // no exact matches in call to initializer
case .doubleValue(_): return .stringValue(max(a.stringValue, String(b.doubleValue))) // enum case 'stringValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // enum case 'stringValue' cannot be used as an instance member
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // cannot convert value of type '(String) -> Value' to expected argument type 'String'
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // type '(String) -> Value' cannot conform to 'Comparable'
case .stringValue(_): return .stringValue(max(a.stringValue, b.stringValue)) // enum case 'stringValue' cannot be used as an instance member
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
if sum == n {
return true
}
}
return false
}
func isEqualToSumEven(n: Int) -> Bool {
if n == 0 {
return true
}
if n < 4 {
return false
}
for i in 2...n {
if i % 2 == 0 {
if isEqualToSumEven(n: n - i) {
return true
}
}
}
return false
}
func isEqualToSumEven(n: Int) -> Bool {
if n < 4 {
return false
}
let sum = n - 2 * (n / 2)
return sum % 4 == 0
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
if sum == n {
return true
}
}
return false
}
```
### 解法二:递归
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n == 0 {
return true
}
if n < 4 {
return false
}
for i in 2...n {
if i % 2 == 0 {
if isEqualToSumEven(n: n - i) {
return true
}
}
}
return false
}
```
### 解法三:数学
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n < 4 {
return false
}
let sum = n - 2 * (n / 2)
return sum % 4 == 0
}
```
### 解法四:数学
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n < 4 {
return false
}
let sum = n - 2 * (n / 2)
return sum % 4 == 0
}
```
### 解法五:数学
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n < 4 {
return false
}
let sum = n - 2 * (n / 2)
return sum % 4 == 0
}
```
### 解法六:数学
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n < 4 {
return false
}
let sum = n - 2 * (n / 2)
return sum % 4 == 0
}
```
### 解法七:数学
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n < 4 {
return false
}
let sum = n - 2 * (n / 2)
return sum % 4 == 0
}
```
### 解法八:数学
```swift
// Evaluate whether the given number n can be written as the
func isEqualToSumEven(n: Int) -> Bool { // invalid redeclaration of 'isEqualToSumEven(n:)'
func isEqualToSumEven(n: Int) -> Bool { // invalid redeclaration of 'isEqualToSumEven(n:)'
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法二
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法三
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法四
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法五
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法六
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法七
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
var i = 2
while sum < n {
sum += i
i += 2
}
return sum == n
}
```
### 解法八
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var num = n
var sum = 0
while num > 0 {
let temp = num % 2
if temp == 0 {
sum += temp
}
num = num / 2
}
return sum == 4
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var num = n
var sum = 0
while num > 0 {
let temp = num % 2
if temp == 0 {
sum += temp
}
num = num / 2
}
return sum == 4
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
class Solution {
func sumEvenAfterQueries(_ A: [Int], _ queries: [[Int]]) -> [Int] {
var sum = 0
for i in A {
if i % 2 == 0 {
sum += i
}
}
var result = [Int]()
for query in queries {
let index = query[0]
let value = query[1]
if A[index] % 2 == 0 {
sum -= A[index]
}
A[index] += value
if A[index] % 2 == 0 {
sum += A[index]
}
result.append(sum)
}
return result
}
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```
### 解题思路
### 代码
```swift
class Solution {
func sumEvenAfterQueries(_ A: [Int], _ queries: [[Int]]) -> [Int] {
var sum = 0
for i in A {
if i % 2 == 0 {
sum += i
}
}
var result = [Int]()
for query in queries {
let index = query[0]
let value = query[1]
if A[index] % 2 == 0 {
sum -= A[index]
}
A[index] += value
if A[index] % 2 == 0 {
sum += A[index]
}
result.append(sum)
}
return result
}
}
```
A[index] += value // left side of mutating operator isn't mutable: 'A' is a 'let' constant
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
class Solution {
func isEqualToSumOfParts(_ n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```
### 解题思路
### 代码
```swift
class Solution {
func isEqualToSumOfParts(_ n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
if n % 2 != 0 {
return false
}
var sum = 0
for i in 2...n {
if sum == n {
return true
}
if sum > n {
return false
}
sum += i
}
return false
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
if n % 2 != 0 {
return false
}
var sum = 0
for i in 2...n {
if sum == n {
return true
}
if sum > n {
return false
}
sum += i
}
return false
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var sum = 0
for i in 2...n {
if i % 2 == 0 {
sum += i
}
}
return sum == n
}
```
// XCTAssertTrue failed
func isEqualToSumEven(n: Int) -> Bool {
var num = n
var sum = 0
while num > 0 {
let temp = num % 2
if temp == 0 {
sum += temp
}
num /= 2
}
return sum == 4
}
```swift
// Evaluate whether the given number n can be written as the sum of exactly 4 positive even numbers
// Example
// isEqualToSumEven(n: 4) == false
// isEqualToSumEven(n: 6) == false
// isEqualToSumEven(n: 8) == true
func isEqualToSumEven(n: Int) -> Bool {
var num = n
var sum = 0
while num > 0 {
let temp = num % 2
if temp == 0 {
sum += temp
}
num /= 2
}
return sum == 4
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
func specialFactorial(n: Int) -> Int {
if n == 1 {
return 1
}
return n * specialFactorial(n: n - 1)
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
### 解法二:递归
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
if n == 1 {
return 1
}
return n * specialFactorial(n: n - 1)
}
```
### 解法三:迭代
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
### 解法四:数学
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
func specialFactorial(n: Int) -> Int { // invalid redeclaration of 'specialFactorial(n:)'
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```
### 解法二
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```
### 解法二
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 2...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
for i in 1...n {
result *= i
}
return result
}
```
// XCTAssertTrue failed
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```swift
// The Brazilian factorial is defined as:
// brazilian_factorial(n) = n! * (n-1)! * (n-2)! * ... * 1!
// where n > 0
// For example:
// The function will receive an integer as input and should return the special
// factorial of this integer.
// specialFactorial(n: 4) == 288
func specialFactorial(n: Int) -> Int {
var result = 1
var i = 1
while i <= n {
result *= i
i += 1
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var lastChar = " "
for char in text {
if char == " " {
if lastChar == " " {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(char)
}
lastChar = char
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var lastChar = " "
for char in text {
if char == " " {
if lastChar == " " {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(char)
}
lastChar = char
}
return result
}
```
lastChar = char // cannot assign value of type 'Character' to type 'String'
func fixSpaces(text: String) -> String {
let array = Array(text)
var result = ""
var count = 0
for char in array {
if char == " " {
count += 1
if count > 2 {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(char)
count = 0
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
let array = Array(text)
var result = ""
var count = 0
for char in array {
if char == " " {
count += 1
if count > 2 {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(char)
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for c in text {
if c == " " {
count += 1
} else {
if count > 2 {
result.append("_")
}
result.append(c)
count = 0
}
}
if count > 2 {
result.append("_")
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for c in text {
if c == " " {
count += 1
} else {
if count > 2 {
result.append("_")
}
result.append(c)
count = 0
}
}
if count > 2 {
result.append("_")
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for c in text {
if c == " " {
count += 1
if count > 2 {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(c)
count = 0
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for c in text {
if c == " " {
count += 1
if count > 2 {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(c)
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let str = text.replacingOccurrences(of: " ", with: "_")
var result = ""
var count = 0
for c in str {
if c == "_" {
count += 1
} else {
if count > 2 {
result.append("_")
result.append("-")
count = 0
}
result.append(c)
count = 0
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
let str = text.replacingOccurrences(of: " ", with: "_")
var result = ""
var count = 0
for c in str {
if c == "_" {
count += 1
} else {
if count > 2 {
result.append("_")
result.append("-")
count = 0
}
result.append(c)
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
if count > 2 {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(char)
count = 0
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
if count > 2 {
result.append("-")
} else {
result.append("_")
}
} else {
result.append(char)
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
let str = text.replacingOccurrences(of: " ", with: "_")
var result = ""
var count = 0
for c in str {
if c == "_" {
count += 1
} else {
if count > 2 {
result += "-"
} else {
result += String(c)
}
count = 0
}
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
let str = text.replacingOccurrences(of: " ", with: "_")
var result = ""
var count = 0
for c in str {
if c == "_" {
count += 1
} else {
if count > 2 {
result += "-"
} else {
result += String(c)
}
count = 0
}
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 2 {
result.append("_")
}
result.append(char)
count = 0
}
}
if count > 2 {
result.append("_")
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 2 {
result.append("_")
}
result.append(char)
count = 0
}
}
if count > 2 {
result.append("_")
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 2 {
result.append("_")
}
result.append(char)
count = 0
}
}
if count > 2 {
result.append("_")
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var result = ""
var count = 0
for char in text {
if char == " " {
count += 1
} else {
if count > 2 {
result.append("_")
}
result.append(char)
count = 0
}
}
if count > 2 {
result.append("_")
}
return result
}
```
// XCTAssertTrue failed
func fixSpaces(text: String) -> String {
var text = text
var count = 0
var result = ""
for c in text {
if c == " " {
count += 1
} else {
if count > 2 {
result += "-"
} else {
result += String(c)
}
count = 0
}
}
if count > 2 {
result += "-"
}
return result
}
```swift
// Given a string text, replace all spaces in it with underscores,
// and if a string has more than 2 consecutive spaces,
// then replace all consecutive spaces with -
// fixSpaces(text: " Example") == "Example"
// fixSpaces(text: " Example 1") == "Example_1"
// fixSpaces(text: " Example 2") == "_Example_2"
// fixSpaces(text: " Example 3") == "_Example-3"
func fixSpaces(text: String) -> String {
var text = text
var count = 0
var result = ""
for c in text {
if c == " " {
count += 1
} else {
if count > 2 {
result += "-"
} else {
result += String(c)
}
count = 0
}
}
if count > 2 {
result += "-"
}
return result
}
```
var text = text // variable 'text' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
guard fileNameArr.count == 2 else {
return "No"
}
guard fileNameArr[0].count > 0 else {
return "No"
}
guard fileNameArr[0].first!.isLetter else {
return "No"
}
guard fileNameArr[1] == "txt" || fileNameArr[1] == "exe" || fileNameArr[1] == "dll" else {
return "No"
}
let count = fileName.count
let dotIndex = fileName.firstIndex(of: ".")!
let lastIndex = count - 1
guard count > 4 && count < 10 && dotIndex != lastIndex && fileName[dotIndex + 1] != "." else {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
guard fileNameArr.count == 2 else {
return "No"
}
guard fileNameArr[0].count > 0 else {
return "No"
}
guard fileNameArr[0].first!.isLetter else {
return "No"
}
guard fileNameArr[1] == "txt" || fileNameArr[1] == "exe" || fileNameArr[1] == "dll" else {
return "No"
}
let count = fileName.count
let dotIndex = fileName.firstIndex(of: ".")!
let lastIndex = count - 1
guard count > 4 && count < 10 && dotIndex != lastIndex && fileName[dotIndex + 1] != "." else {
return "No"
}
return "Yes"
}
```
guard count > 4 && count < 10 && dotIndex != lastIndex && fileName[dotIndex + 1] != "." else { // cannot convert value of type 'String.Index' to expected argument type 'Int'
guard count > 4 && count < 10 && dotIndex != lastIndex && fileName[dotIndex + 1] != "." else { // referencing operator function '!=' on 'BinaryInteger' requires that 'String.Index' conform to 'BinaryInteger'
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
if fileNameArr.count != 2 {
return "No"
}
if fileNameArr[0].count == 0 || fileNameArr[0][0] < "a" || fileNameArr[0][0] > "z" {
return "No"
}
if fileNameArr[1] != "txt" && fileNameArr[1] != "exe" && fileNameArr[1] != "dll" {
return "No"
}
let arr = Array(fileNameArr[0])
if arr.count > 3 {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
if fileNameArr.count != 2 {
return "No"
}
if fileNameArr[0].count == 0 || fileNameArr[0][0] < "a" || fileNameArr[0][0] > "z" {
return "No"
}
if fileNameArr[1] != "txt" && fileNameArr[1] != "exe" && fileNameArr[1] != "dll" {
return "No"
}
let arr = Array(fileNameArr[0])
if arr.count > 3 {
return "No"
}
return "Yes"
}
```
if fileNameArr[0].count == 0 || fileNameArr[0][0] < "a" || fileNameArr[0][0] > "z" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if fileNameArr[0].count == 0 || fileNameArr[0][0] < "a" || fileNameArr[0][0] > "z" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
if fileNameArray.count != 2 {
return "No"
}
if fileNameArray[0].count == 0 {
return "No"
}
if fileNameArray[1] != "txt" && fileNameArray[1] != "exe" && fileNameArray[1] != "dll" {
return "No"
}
let firstChar = fileNameArray[0][0]
if !firstChar.isLetter || firstChar.isNumber {
return "No"
}
let lastChar = fileNameArray[0][fileNameArray[0].count - 1]
if lastChar.isNumber {
return "No"
}
let count = fileNameArray[0].count
if count > 3 {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
if fileNameArray.count != 2 {
return "No"
}
if fileNameArray[0].count == 0 {
return "No"
}
if fileNameArray[1] != "txt" && fileNameArray[1] != "exe" && fileNameArray[1] != "dll" {
return "No"
}
let firstChar = fileNameArray[0][0]
if !firstChar.isLetter || firstChar.isNumber {
return "No"
}
let lastChar = fileNameArray[0][fileNameArray[0].count - 1]
if lastChar.isNumber {
return "No"
}
let count = fileNameArray[0].count
if count > 3 {
return "No"
}
return "Yes"
}
```
let firstChar = fileNameArray[0][0] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
let lastChar = fileNameArray[0][fileNameArray[0].count - 1] // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
if fileNameArray.count != 2 {
return "No"
}
if fileNameArray[0].count == 0 || fileNameArray[1].count == 0 {
return "No"
}
if fileNameArray[0][0] < "a" || fileNameArray[0][0] > "z" {
return "No"
}
if fileNameArray[1] != "txt" && fileNameArray[1] != "exe" && fileNameArray[1] != "dll" {
return "No"
}
if fileNameArray[0].count > 3 {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
if fileNameArray.count != 2 {
return "No"
}
if fileNameArray[0].count == 0 || fileNameArray[1].count == 0 {
return "No"
}
if fileNameArray[0][0] < "a" || fileNameArray[0][0] > "z" {
return "No"
}
if fileNameArray[1] != "txt" && fileNameArray[1] != "exe" && fileNameArray[1] != "dll" {
return "No"
}
if fileNameArray[0].count > 3 {
return "No"
}
return "Yes"
}
```
if fileNameArray[0][0] < "a" || fileNameArray[0][0] > "z" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
if fileNameArray[0][0] < "a" || fileNameArray[0][0] > "z" { // 'subscript(_:)' is unavailable: cannot subscript String with an Int, use a String.Index instead.
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
guard fileNameArray.count == 2 else {
return "No"
}
guard fileNameArray[0].count > 0 else {
return "No"
}
guard fileNameArray[0].first!.isLetter else {
return "No"
}
guard fileNameArray[1] == "txt" || fileNameArray[1] == "exe" || fileNameArray[1] == "dll" else {
return "No"
}
guard fileNameArray[0].count <= 3 else {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
guard fileNameArray.count == 2 else {
return "No"
}
guard fileNameArray[0].count > 0 else {
return "No"
}
guard fileNameArray[0].first!.isLetter else {
return "No"
}
guard fileNameArray[1] == "txt" || fileNameArray[1] == "exe" || fileNameArray[1] == "dll" else {
return "No"
}
guard fileNameArray[0].count <= 3 else {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
guard fileNameArray.count == 2 else {
return "No"
}
guard fileNameArray[0].count > 0, fileNameArray[0].first!.isLetter, fileNameArray[0].first!.isLowercase else {
return "No"
}
guard fileNameArray[1] == "txt" || fileNameArray[1] == "exe" || fileNameArray[1] == "dll" else {
return "No"
}
guard fileNameArray[0].count <= 3 else {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
guard fileNameArray.count == 2 else {
return "No"
}
guard fileNameArray[0].count > 0, fileNameArray[0].first!.isLetter, fileNameArray[0].first!.isLowercase else {
return "No"
}
guard fileNameArray[1] == "txt" || fileNameArray[1] == "exe" || fileNameArray[1] == "dll" else {
return "No"
}
guard fileNameArray[0].count <= 3 else {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
guard fileNameArray.count == 2 else {
return "No"
}
guard fileNameArray[0].count > 0 else {
return "No"
}
guard fileNameArray[0].first!.isLetter else {
return "No"
}
guard fileNameArray[1] == "txt" || fileNameArray[1] == "exe" || fileNameArray[1] == "dll" else {
return "No"
}
let count = fileName.count
let count1 = fileName.components(separatedBy: ".").first!.count
let count2 = fileName.components(separatedBy: ".").last!.count
guard count > count1 + count2 else {
return "No"
}
guard count1 > 3 else {
return "No"
}
guard count2 > 3 else {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArray = fileName.components(separatedBy: ".")
guard fileNameArray.count == 2 else {
return "No"
}
guard fileNameArray[0].count > 0 else {
return "No"
}
guard fileNameArray[0].first!.isLetter else {
return "No"
}
guard fileNameArray[1] == "txt" || fileNameArray[1] == "exe" || fileNameArray[1] == "dll" else {
return "No"
}
let count = fileName.count
let count1 = fileName.components(separatedBy: ".").first!.count
let count2 = fileName.components(separatedBy: ".").last!.count
guard count > count1 + count2 else {
return "No"
}
guard count1 > 3 else {
return "No"
}
guard count2 > 3 else {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
if fileNameArr.count != 2 {
return "No"
}
if fileNameArr[0].count == 0 {
return "No"
}
if fileNameArr[1] != "txt" && fileNameArr[1] != "exe" && fileNameArr[1] != "dll" {
return "No"
}
let fileNameArr1 = fileNameArr[0].components(separatedBy: ".")
if fileNameArr1.count > 3 {
return "No"
}
if fileNameArr1[0].count == 0 {
return "No"
}
if !fileNameArr1[0].first!.isLetter {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
if fileNameArr.count != 2 {
return "No"
}
if fileNameArr[0].count == 0 {
return "No"
}
if fileNameArr[1] != "txt" && fileNameArr[1] != "exe" && fileNameArr[1] != "dll" {
return "No"
}
let fileNameArr1 = fileNameArr[0].components(separatedBy: ".")
if fileNameArr1.count > 3 {
return "No"
}
if fileNameArr1[0].count == 0 {
return "No"
}
if !fileNameArr1[0].first!.isLetter {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let arr = fileName.components(separatedBy: ".")
guard arr.count == 2 else {
return "No"
}
guard arr[0].count > 0 else {
return "No"
}
guard arr[0].first!.isLetter else {
return "No"
}
guard arr[1] == "txt" || arr[1] == "exe" || arr[1] == "dll" else {
return "No"
}
let str = String(arr[0].dropFirst())
guard str.count <= 3 else {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let arr = fileName.components(separatedBy: ".")
guard arr.count == 2 else {
return "No"
}
guard arr[0].count > 0 else {
return "No"
}
guard arr[0].first!.isLetter else {
return "No"
}
guard arr[1] == "txt" || arr[1] == "exe" || arr[1] == "dll" else {
return "No"
}
let str = String(arr[0].dropFirst())
guard str.count <= 3 else {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
if fileNameArr.count != 2 {
return "No"
}
if fileNameArr[0].count == 0 {
return "No"
}
if fileNameArr[1] != "txt" && fileNameArr[1] != "exe" && fileNameArr[1] != "dll" {
return "No"
}
if fileNameArr[0].count > 3 {
return "No"
}
if !fileNameArr[0].first!.isLetter {
return "No"
}
return "Yes"
}
```swift
// Create a function which takes a string representing a file's name, and returns
// 'Yes' if the the file's name is valid, and returns 'No' otherwise.
// A file's name is considered to be valid if and only if all the following conditions
// are met:
// - There should not be more than three digits ('0'-'9') in the file's name.
// - The file's name contains exactly one dot '.'
// - The substring before the dot should not be empty, and it starts with a letter from
// the latin alphapet ('a'-'z' and 'A'-'Z').
// - The substring after the dot should be one of these: ['txt', 'exe', 'dll']
// Examples:
// fileNameCheck(fileName: "example.txt") == "Yes"
// fileNameCheck(fileName: "1example.dll") == "No"
func fileNameCheck(fileName: String) -> String {
let fileName = fileName.lowercased()
let fileNameArr = fileName.components(separatedBy: ".")
if fileNameArr.count != 2 {
return "No"
}
if fileNameArr[0].count == 0 {
return "No"
}
if fileNameArr[1] != "txt" && fileNameArr[1] != "exe" && fileNameArr[1] != "dll" {
return "No"
}
if fileNameArr[0].count > 3 {
return "No"
}
if !fileNameArr[0].first!.isLetter {
return "No"
}
return "Yes"
}
```
// XCTAssertTrue failed
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = [String]()
for word in words {
if isPrime(num: Int(word.count)) {
result.append(word)
}
}
return result.joined(separator: " ")
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = [String]()
for word in words {
if isPrime(num: Int(word.count)) {
result.append(word)
}
}
return result.joined(separator: " ")
}
func isPrime(num: Int) -> Bool {
if num <= 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
result.append(word) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
var result = [String]()
for word in words {
let length = word.count
if primes.contains(length) {
result.append(word)
}
}
return result.joined(separator: " ")
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
var result = [String]()
for word in words {
let length = word.count
if primes.contains(length) {
result.append(word)
}
}
return result.joined(separator: " ")
}
```
result.append(word) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let result = words.filter { isPrime(num: Int(String($0))) }
return result.joined(separator: " ")
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let result = words.filter { isPrime(num: Int(String($0))) }
return result.joined(separator: " ")
}
func isPrime(num: Int) -> Bool {
if num < 2 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
let result = words.filter { isPrime(num: Int(String($0))) } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101]
var result = ""
for word in words {
if primes.contains(word.count) {
result.append(word)
result.append(" ")
}
}
return String(result.dropLast())
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101]
var result = ""
for word in words {
if primes.contains(word.count) {
result.append(word)
result.append(" ")
}
}
return String(result.dropLast())
}
```
result.append(word) // no exact matches in call to instance method 'append'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let result = words.filter { isPrime(number: Int(String($0))) }
return result.joined(separator: " ")
}
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
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let result = words.filter { isPrime(number: Int(String($0))) }
return result.joined(separator: " ")
}
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
}
```
let result = words.filter { isPrime(number: Int(String($0))) } // value of optional type 'Int?' must be unwrapped to a value of type 'Int'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(num: Int(word.count)) {
result += word + " "
}
}
return String(result.dropLast())
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(num: Int(word.count)) {
result += word + " "
}
}
return String(result.dropLast())
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
var result = [String]()
var words = sentence.split(separator: " ")
for word in words {
if isPrime(num: Int(word.count)) {
result.append(word)
}
}
return result.joined(separator: " ")
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
var result = [String]()
var words = sentence.split(separator: " ")
for word in words {
if isPrime(num: Int(word.count)) {
result.append(word)
}
}
return result.joined(separator: " ")
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
result.append(word) // cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primeNumbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101]
var result = ""
for word in words {
if primeNumbers.contains(word.count) {
result += word + " "
}
}
return String(result.dropLast())
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primeNumbers = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101]
var result = ""
for word in words {
if primeNumbers.contains(word.count) {
result += word + " "
}
}
return String(result.dropLast())
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(num: Int(word.count)) {
result += word + " "
}
}
return String(result.dropLast())
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
var result = ""
for word in words {
if isPrime(num: Int(word.count)) {
result += word + " "
}
}
return String(result.dropLast())
}
func isPrime(num: Int) -> Bool {
if num == 1 {
return false
}
for i in 2..<num {
if num % i == 0 {
return false
}
}
return true
}
```
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
let result = words.map { word in
let wordLength = word.count
if primes.contains(wordLength) {
return word
}
return ""
}
return result.joined(separator: " ")
}
```swift
// You are given a string representing a sentence,
// the sentence contains some words separated by a space,
// and you have to return a string that contains the words from the original sentence,
// whose lengths are prime numbers,
// the order of the words in the new string should be the same as the original one.
// Example 1:
// Example 2:
// Constraints:
// * 1 <= len(sentence) <= 100
// * sentence contains only letters
// wordsInSentence(sentence: "This is a test") == "is"
// wordsInSentence(sentence: "lets go for swimming") == "go for"
func wordsInSentence(sentence: String) -> String {
let words = sentence.split(separator: " ")
let primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
let result = words.map { word in
let wordLength = word.count
if primes.contains(wordLength) {
return word
}
return ""
}
return result.joined(separator: " ")
}
```
// XCTAssertTrue failed
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNum = Int(x[0])!
let xDen = Int(x[1])!
let nNum = Int(n[0])!
let nDen = Int(n[1])!
let xNum = xNum * nDen
let xDen = xDen * nNum
let xNum = xNum % xDen
if xNum == 0 {
return true
}
return false
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let xNum = Int(x[0])!
let xDen = Int(x[1])!
let nNum = Int(n[0])!
let nDen = Int(n[1])!
let xNum = xNum * nDen
let xDen = xDen * nNum
let xNum = xNum % xDen
if xNum == 0 {
return true
}
return false
}
```
let xNum = xNum * nDen // invalid redeclaration of 'xNum'
let xDen = xDen * nNum // invalid redeclaration of 'xDen'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n % 1 == 0
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n % 1 == 0
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n % 1 == 0
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n % 1 == 0
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n % 1 == 0
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n % 1 == 0
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
return x * n == Int(x * n) // no exact matches in call to initializer
return x * n == Int(x * n) // binary operator '==' cannot be applied to operands of type 'Duration' and 'Int'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
return x * n == Int(x * n) // binary operator '==' cannot be applied to operands of type 'Duration' and 'Int'
return x * n == Int(x * n) // no exact matches in call to initializer
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
return x * n == Int(x * n) // binary operator '==' cannot be applied to operands of type 'Duration' and 'Int'
return x * n == Int(x * n) // no exact matches in call to initializer
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
return x * n == Int(x * n) // binary operator '==' cannot be applied to operands of type 'Duration' and 'Int'
return x * n == Int(x * n) // no exact matches in call to initializer
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
return x * n == Int(x * n) // no exact matches in call to initializer
return x * n == Int(x * n) // binary operator '==' cannot be applied to operands of type 'Duration' and 'Int'
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```swift
// Your task is to implement a function that will simplify the expression
// x * n. The function returns true if x * n evaluates to a whole number and false
// otherwise. Both x and n, are string representation of a fraction, and have the following format,
// <numerator>/<denominator> where both numerator and denominator are positive whole numbers.
// You can assume that x, and n are valid fractions, and do not have zero as denominator.
// simplify(x: "1/5", n: "5/1") == true
// simplify(x: "1/6", n: "2/1") == false
// simplify(x: "7/10", n: "10/2") == false
func simplify(x: String, n: String) -> Bool {
let x = x.split(separator: "/")
let n = n.split(separator: "/")
let x = Int(x[0])! / Int(x[1])!
let n = Int(n[0])! / Int(n[1])!
return x * n == Int(x * n)
}
```
let x = Int(x[0])! / Int(x[1])! // invalid redeclaration of 'x'
let n = Int(n[0])! / Int(n[1])! // invalid redeclaration of 'n'
return x * n == Int(x * n) // no exact matches in call to initializer
return x * n == Int(x * n) // binary operator '==' cannot be applied to operands of type 'Duration' and 'Int'
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { (a, b) -> Bool in
let aSum = a.sumOfDigits, bSum = b.sumOfDigits
return aSum < bSum || (aSum == bSum && a < b)
}
return nums
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { (a, b) -> Bool in
let aSum = a.sumOfDigits, bSum = b.sumOfDigits
return aSum < bSum || (aSum == bSum && a < b)
}
return nums
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```
return aSum < bSum || (aSum == bSum && a < b) // function produces expected type 'Int'; did you mean to call it with '()'?
return aSum < bSum || (aSum == bSum && a < b) // function produces expected type 'Int'; did you mean to call it with '()'?
return aSum < bSum || (aSum == bSum && a < b) // function produces expected type 'Int'; did you mean to call it with '()'?
return aSum < bSum || (aSum == bSum && a < b) // function produces expected type 'Int'; did you mean to call it with '()'?
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return sorted
}
extension Int {
func sumOfDigits() -> Int {
var sum = 0
var number = self
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return sorted
}
extension Int {
func sumOfDigits() -> Int {
var sum = 0
var number = self
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return nums
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return nums
}
// MARK: - Helper
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return nums
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return nums
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let sum = nums.map { Int(String($0))! }.reduce(0, +)
return nums.sorted { num1, num2 in
let sum1 = Int(String(num1))!
let sum2 = Int(String(num2))!
return sum1 + sum2 == sum ? num1 < num2 : sum1 + sum2 < sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sum = nums.map { Int(String($0))! }.reduce(0, +)
return nums.sorted { num1, num2 in
let sum1 = Int(String(num1))!
let sum2 = Int(String(num2))!
return sum1 + sum2 == sum ? num1 < num2 : sum1 + sum2 < sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { (a, b) -> Bool in
let sumA = Int(String(a))!.reduce(0, +)
let sumB = Int(String(b))!.reduce(0, +)
return sumA < sumB
}
return sorted
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { (a, b) -> Bool in
let sumA = Int(String(a))!.reduce(0, +)
let sumB = Int(String(b))!.reduce(0, +)
return sumA < sumB
}
return sorted
}
```
let sumA = Int(String(a))!.reduce(0, +) // value of type 'Int' has no member 'reduce'
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { (a, b) -> Bool in
let sumA = a.sumOfDigits()
let sumB = b.sumOfDigits()
return sumA < sumB || (sumA == sumB && a < b)
}
return sorted
}
extension Int {
func sumOfDigits() -> Int {
var sum = 0
var number = self
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { (a, b) -> Bool in
let sumA = a.sumOfDigits()
let sumB = b.sumOfDigits()
return sumA < sumB || (sumA == sumB && a < b)
}
return sorted
}
// MARK: - Extension
extension Int {
func sumOfDigits() -> Int {
var sum = 0
var number = self
while number > 0 {
sum += number % 10
number /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return sorted
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { num1, num2 in
let sum1 = num1.sumOfDigits()
let sum2 = num2.sumOfDigits()
return sum1 < sum2
}
return sorted
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { (a, b) -> Bool in
let sumA = a.sumOfDigits()
let sumB = b.sumOfDigits()
return sumA < sumB || (sumA == sumB && a < b)
}
return sorted
}
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let sorted = nums.sorted { (a, b) -> Bool in
let sumA = a.sumOfDigits()
let sumB = b.sumOfDigits()
return sumA < sumB || (sumA == sumB && a < b)
}
return sorted
}
// MARK: - Extension
extension Int {
func sumOfDigits() -> Int {
var num = self
var sum = 0
while num > 0 {
sum += num % 10
num /= 10
}
return sum
}
}
```
// XCTAssertTrue failed
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { (a, b) -> Bool in
let aDigits = digits(num: a)
let bDigits = digits(num: b)
return aDigits.reduce(0, +) < bDigits.reduce(0, +)
}
return nums
}
func digits(num: Int) -> [Int] {
var num = num
var digits = [Int]()
while num > 0 {
digits.append(num % 10)
num /= 10
}
return digits.reversed()
}
```swift
// Write a function which sorts the given array of integers
// in ascending order according to the sum of their digits.
// Note: if there are several items with similar sum of their digits,
// order them based on their index in original array.
// For example:
// orderByPoints(nums: [1, 11, -1, -11, -12]) == [-1, -11, 1, -12, 11]
// orderByPoints(nums: [] as [Int]) == [] as [Int]
func orderByPoints(nums: [Int]) -> [Int] {
let nums = nums.sorted { (a, b) -> Bool in
let aDigits = digits(num: a)
let bDigits = digits(num: b)
return aDigits.reduce(0, +) < bDigits.reduce(0, +)
}
return nums
}
func digits(num: Int) -> [Int] {
var num = num
var digits = [Int]()
while num > 0 {
digits.append(num % 10)
num /= 10
}
return digits.reversed()
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 != 0 && num % 10 != 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 != 0 && num % 10 != 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.filter { (num) -> Bool in
return num > 10 && num % 2 == 1 && num % 10 != 0
}.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.filter { (num) -> Bool in
return num > 10 && num % 2 == 1 && num % 10 != 0
}.count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
return nums.filter { (num) -> Bool in
return num > 10 && num % 10 != 0 && num % 10 != 1 && num % 10 != 3 && num % 10 != 5 && num % 10 != 7 && num % 10 != 9
}.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
return nums.filter { (num) -> Bool in
return num > 10 && num % 10 != 0 && num % 10 != 1 && num % 10 != 3 && num % 10 != 5 && num % 10 != 7 && num % 10 != 9
}.count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 != 0 && num % 10 != 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 10 != 0 && num % 10 != 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 == 1 && num % 10 == 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 == 1 && num % 10 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
let filter = nums.filter { (num) -> Bool in
return num > 10 && num % 2 == 1 && num % 10 != 0
}
return filter.count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
let filter = nums.filter { (num) -> Bool in
return num > 10 && num % 2 == 1 && num % 10 != 0
}
return filter.count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 == 1 && num % 10 == 1 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 == 1 && num % 10 == 1 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```swift
// Write a function that takes an array of numbers as input and returns
// the number of elements in the array that are greater than 10 and both
// first and last digits of a number are odd (1, 3, 5, 7, 9).
// For example:
// specialFilter(nums: [15, -73, 14, -15]) == 1
// specialFilter(nums: [33, -2, -3, 45, 21, 109]) == 2
func specialFilter(nums: [Int]) -> Int {
var count = 0
for num in nums {
if num > 10 && num % 2 != 0 && num % 10 != 0 {
count += 1
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 0..<n {
a[i] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 0..<n {
a[i] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = [Int]()
for i in 1...n {
a.append(i * i - i + 1)
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n {
for j in i+1..<n {
for k in j+1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n - 2 {
for j in i + 1..<n - 1 {
for k in j + 1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```swift
// You are given a positive integer n. You have to create an integer array a of length n.
// For each i (1 ≤ i ≤ n), the value of a[i] = i * i - i + 1.
// Return the number of triples (a[i], a[j], a[k]) of a where i < j < k,
// and a[i] + a[j] + a[k] is a multiple of 3.
// Example :
// Explanation:
// a = [1, 3, 7, 13, 21]
// The only valid triple is (1, 7, 13).
// getMaxTriples(n: 5) == 1
func getMaxTriples(n: Int) -> Int {
var a = Array(repeating: 0, count: n)
for i in 1...n {
a[i - 1] = i * i - i + 1
}
var count = 0
for i in 0..<n - 2 {
for j in i + 1..<n - 1 {
for k in j + 1..<n {
if a[i] + a[j] + a[k] % 3 == 0 {
count += 1
}
}
}
}
return count
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var newList = lst
for i in 0..<newList.count {
if newList[i].count % 2 == 1 {
newList.remove(at: i)
i -= 1
}
}
return newList.sorted(by: {$0.count < $1.count})
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var newList = lst
for i in 0..<newList.count {
if newList[i].count % 2 == 1 {
newList.remove(at: i)
i -= 1
}
}
return newList.sorted(by: {$0.count < $1.count})
}
```
i -= 1 // left side of mutating operator isn't mutable: 'i' is a 'let' constant
func sortedListSum(lst: [String]) -> [String] {
var result = lst
for i in 0..<result.count {
if result[i].count % 2 == 1 {
result.remove(at: i)
i -= 1
}
}
result.sort()
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
for i in 0..<result.count {
if result[i].count % 2 == 1 {
result.remove(at: i)
i -= 1
}
}
result.sort()
return result
}
```
i -= 1 // left side of mutating operator isn't mutable: 'i' is a 'let' constant
func sortedListSum(lst: [String]) -> [String] {
var result = lst
for i in 0..<result.count {
if result[i].count % 2 == 1 {
result.remove(at: i)
i -= 1
}
}
result.sort { (s1, s2) -> Bool in
return s1.count > s2.count
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
for i in 0..<result.count {
if result[i].count % 2 == 1 {
result.remove(at: i)
i -= 1
}
}
result.sort { (s1, s2) -> Bool in
return s1.count > s2.count
}
return result
}
```
i -= 1 // left side of mutating operator isn't mutable: 'i' is a 'let' constant
func sortedListSum(lst: [String]) -> [String] {
var result = lst
for i in 0..<result.count {
if result[i].count % 2 != 0 {
result.remove(at: i)
i -= 1
}
}
result.sort { (s1, s2) -> Bool in
if s1.count != s2.count {
return s1.count < s2.count
} else {
return s1 < s2
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
for i in 0..<result.count {
if result[i].count % 2 != 0 {
result.remove(at: i)
i -= 1
}
}
result.sort { (s1, s2) -> Bool in
if s1.count != s2.count {
return s1.count < s2.count
} else {
return s1 < s2
}
}
return result
}
```
i -= 1 // left side of mutating operator isn't mutable: 'i' is a 'let' constant
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result.removeAll { (str) -> Bool in
return str.count % 2 == 1
}
result.sort { (str1, str2) -> Bool in
return str1.count < str2.count
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result.removeAll { (str) -> Bool in
return str.count % 2 == 1
}
result.sort { (str1, str2) -> Bool in
return str1.count < str2.count
}
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result.sort { $0.count > $1.count }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result.sort { $0.count > $1.count }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result.sort { $0.count < $1.count }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result.sort { $0.count < $1.count }
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
let newArray = lst.sorted { (str1, str2) -> Bool in
if str1.count != str2.count {
return str1.count < str2.count
} else {
return str1 < str2
}
}
return newArray
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
let newArray = lst.sorted { (str1, str2) -> Bool in
if str1.count != str2.count {
return str1.count < str2.count
} else {
return str1 < str2
}
}
return newArray
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
let list = lst.sorted(by: {$0.count < $1.count})
var result = [String]()
for item in list {
if item.count % 2 == 0 {
result.append(item)
}
}
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
let list = lst.sorted(by: {$0.count < $1.count})
var result = [String]()
for item in list {
if item.count % 2 == 0 {
result.append(item)
}
}
return result
}
```
// XCTAssertTrue failed
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result = result.sorted { $0.count > $1.count }
return result
}
```swift
// Write a function that accepts an array of strings as a parameter,
// deletes the strings that have odd lengths from it,
// and returns the resulted array with a sorted order,
// The array is always an array of strings and never an array of numbers,
// and it may contain duplicates.
// The order of the array should be ascending by length of each word, and you
// should return the array sorted by that rule.
// If two words have the same length, sort the array alphabetically.
// The function should return an array of strings in sorted order.
// You may assume that all words will have the same length.
// For example:
// sortedListSum(lst: ["aa", "a", "aaa"]) == ["aa"]
// sortedListSum(lst: ["ab", "a", "aaa", "cd"]) == ["ab", "cd"]
func sortedListSum(lst: [String]) -> [String] {
var result = lst
result = result.filter { $0.count % 2 == 0 }
result = result.sorted { $0.count > $1.count }
return result
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is a prime number.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法二
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is a prime number.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法三
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is a prime number.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法四
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is a prime number.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法五
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x:
if isPrime(n) { // missing argument label 'n:' in call
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
return x
}
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
if n % 7 == 0 {
return y
}
return x
}
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
if n % 7 == 0 {
return y
}
if n % 11 == 0 {
return y
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法二:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
return x
}
```
### 解法三:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
if n % 7 == 0 {
return y
}
return x
}
```
### 解法四:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
if n % 7 == 0 {
return y
}
if n % 11 == 0 {
return y
}
return x
}
```
### 解法五:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
if n % 3 == 0 {
return y
}
if n % 5 == 0 {
return y
}
if n % 7 ==
func xOrY(n: Int, x: Int, y: Int) -> Int { // invalid redeclaration of 'xOrY(n:x:y:)'
func xOrY(n: Int, x: Int, y: Int) -> Int { // invalid redeclaration of 'xOrY(n:x:y:)'
func xOrY(n: Int, x: Int, y: Int) -> Int { // invalid redeclaration of 'xOrY(n:x:y:)'
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function which checks if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法二
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function which checks if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法三
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function which checks if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法四
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function which checks if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法五
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x:
if isPrime(n) { // missing argument label 'n:' in call
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法二:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法三:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法四:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n == 1 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法五:
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 1
if isPrime(n) { // missing argument label 'n:' in call
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0 ? y : x
}
func isPrime(n: Int) -> Bool {
return n > 1 && n % 2 != 0 && allSquares(n)
}
func allSquares(n: Int) -> Bool {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
return n % 2 == 0 ? y : x
}
```
### 2. 判断素数
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
return n > 1 && n % 2 != 0 && allSquares(n)
}
func allSquares(n: Int) -> Bool {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
### 3. 判断素数
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
return n > 1 && n % 2 != 0 && allSquares(n)
}
func allSquares(n: Int) -> Bool {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
### 4. 判断素数
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
return n > 1 && n % 2 != 0 && allSquares(n)
}
func allSquares(n: Int) -> Bool {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
### 5. 判断素数
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
return n > 1 && n % 2 != 0 && allSquares(n)
}
func allSquares(n: Int) -> Bool {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
### 6. 判断素数
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
return n > 1 && n % 2 != 0 && allSquares(n)
}
func allSquares(n: Int) -> Bool {
var i = 2
while i * i <= n {
if n % i == 0 {
return false
}
i += 1
}
return true
}
```
### 7. 判断素数
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n
return n > 1 && n % 2 != 0 && allSquares(n) // missing argument label 'n:' in call
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
class Solution {
func xorOperation(_ n: Int, _ start: Int) -> Int {
var result = 0
for i in 0..<n {
result ^= start + 2 * i
}
return result
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解题思路
### 代码
```swift
class Solution {
func xorOperation(_ n: Int, _ start: Int) -> Int {
var result = 0
for i in 0..<n {
result ^= start + 2 * i
}
return result
}
}
```
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法二
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法三
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法四
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法五
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法六
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
if n == 2 {
return x
}
if n % 2 == 0 {
return y
}
return x
}
```
### 解法七
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
//
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
let divisor = n / 2
let remainder = n % 2
if remainder == 0 {
return x
} else {
return y
}
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if n == 1 {
return y
}
let divisor = n / 2
let remainder = n % 2
if remainder == 0 {
return x
} else {
return y
}
}
```
let divisor = n / 2 // initialization of immutable value 'divisor' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法二
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法三
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法四
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34, y: 12) == 34
// xOrY(n: 15, x: 8, y: 5) == 5
func xOrY(n: Int, x: Int, y: Int) -> Int {
if isPrime(n: n) {
return x
} else {
return y
}
}
// A function to check if a number is prime or not.
// Examples:
// isPrime(n: 7) == true
// isPrime(n: 15) == false
func isPrime(n: Int) -> Bool {
if n < 2 {
return false
}
for i in 2..<n {
if n % i == 0 {
return false
}
}
return true
}
```
### 解法五
```swift
// A simple program which should return the value of x if n is
// a prime number and should return the value of y otherwise.
// Examples:
// xOrY(n: 7, x: 34,
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i.isIntegral {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i.isIntegral {
sum += i * i
}
}
return sum
}
```
if i.isIntegral { // value of type 'Double' has no member 'isIntegral'
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 != 0 {
sum += i * i
}
}
return sum
}
```
if i % 2 != 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.isIntegral == false {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i.isIntegral == false {
sum += i * i
}
}
return sum
}
```
if i > 0 && i.isIntegral == false { // value of type 'Double' has no member 'isIntegral'
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 1 == 0 {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num > 0 && num % 1 == 0 {
sum += num * num
}
}
return sum
}
```
if num > 0 && num % 1 == 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 1 == 0 {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 1 == 0 {
sum += i * i
}
}
return sum
}
```
if i > 0 && i % 1 == 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 1 == 0 {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i > 0 && i % 1 == 0 {
sum += i * i
}
}
return sum
}
```
if i > 0 && i % 1 == 0 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 {
sum += num * num
}
}
return sum
}
```
if num % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 {
sum += num * num
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 {
sum += num * num
}
}
return sum
}
```
if num % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 1 {
sum += i * i
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for i in lst {
if i % 2 == 1 {
sum += i * i
}
}
return sum
}
```
if i % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += i * i // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 {
sum += num * num
}
}
return sum
}
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
var left = 0
var right = lst.count - 1
while left < right {
if lst[left] % 2 == 1 {
sum += lst[left] * lst[left]
}
if lst[right] % 2 == 1 {
sum += lst[right] * lst[right]
}
left += 1
right -= 1
}
if left == right && lst[left] % 2 == 1 {
sum += lst[left] * lst[left]
}
return sum
}
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
var preSum = [0]
for num in lst {
preSum.append(preSum.last! + num)
}
for i in 0..<lst.count {
if lst[i] % 2 == 1 {
sum += preSum[i] * preSum[i]
}
}
return sum
}
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
for num in lst {
if num % 2 == 1 {
sum += num * num
}
}
return sum
}
```
### 解法二:双指针
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
var left = 0
var right = lst.count - 1
while left < right {
if lst[left] % 2 == 1 {
sum += lst[left] * lst[left]
}
if lst[right] % 2 == 1 {
sum += lst[right] * lst[right]
}
left += 1
right -= 1
}
if left == right && lst[left] % 2 == 1 {
sum += lst[left] * lst[left]
}
return sum
}
```
### 解法三:前缀和
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
var preSum = [0]
for num in lst {
preSum.append(preSum.last! + num)
}
for i in 0..<lst.count {
if lst[i] % 2 == 1 {
sum += preSum[i] * preSum[i]
}
}
return sum
}
```
### 解法四:前缀和
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2, 0]) == 0
// doubleTheDifference(lst: [9, -2]) == 81
// doubleTheDifference(lst: [0]) == 0
func doubleTheDifference(lst: [Double]) -> Int {
var sum = 0
var preSum = [0]
for num in lst {
preSum.append(preSum.last! + num)
}
for i in 0..<lst.count {
if lst[i] % 2 == 1 {
sum += preSum[i] * preSum[i]
}
}
return sum
}
```
### 解法五:前缀和
```swift
// Given an array of numbers, return the sum of squares of the numbers
// in the array that are odd. Ignore numbers that are negative or not integers.
// If the input array is empty, return 0.
// doubleTheDifference(lst: [1, 3, 2, 0]) == 10
// doubleTheDifference(lst: [-1, -2,
if num % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += num * num // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int { // invalid redeclaration of 'doubleTheDifference(lst:)'
if lst[left] % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += lst[left] * lst[left] // cannot convert value of type 'Double' to expected argument type 'Int'
if lst[right] % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += lst[right] * lst[right] // cannot convert value of type 'Double' to expected argument type 'Int'
if left == right && lst[left] % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
sum += lst[left] * lst[left] // cannot convert value of type 'Double' to expected argument type 'Int'
func doubleTheDifference(lst: [Double]) -> Int { // invalid redeclaration of 'doubleTheDifference(lst:)'
preSum.append(preSum.last! + num) // cannot convert value of type 'Double' to expected argument type 'Int'
if lst[i] % 2 == 1 { // '%' is unavailable: For floating point numbers use truncatingRemainder instead
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, guess) in guess.enumerated() {
result.append(abs(guess - game[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, guess) in guess.enumerated() {
result.append(abs(guess - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (index, guessValue) in guess.enumerated() {
let scoreValue = game[index]
if guessValue == scoreValue {
result.append(0)
} else {
result.append(abs(guessValue - scoreValue))
}
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (index, guessValue) in guess.enumerated() {
let scoreValue = game[index]
if guessValue == scoreValue {
result.append(0)
} else {
result.append(abs(guessValue - scoreValue))
}
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, g) in guess.enumerated() {
result.append(abs(g - game[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, g) in guess.enumerated() {
result.append(abs(g - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, guessValue) in guess.enumerated() {
let scoreValue = game[i]
result.append(abs(guessValue - scoreValue))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, guessValue) in guess.enumerated() {
let scoreValue = game[i]
result.append(abs(guessValue - scoreValue))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, guess) in guess.enumerated() {
result.append(abs(guess - game[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, guess) in guess.enumerated() {
result.append(abs(guess - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, g) in guess.enumerated() {
result.append(abs(g - game[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for (i, g) in guess.enumerated() {
result.append(abs(g - game[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```swift
// I think we all remember that feeling when the result of some long-awaited
// event is finally known. The feelings and thoughts you have at that moment are
// definitely worth noting down and comparing.
// Your task is to determine if a person correctly guessed the results of a number of matches.
// You are given two arrays of scores and guesses of equal length, where each index shows a match.
// Return an array of the same length denoting how far off each guess was. If they have guessed correctly,
// the value is 0, and if not, the value is the absolute difference between the guess and the score.
// example:
// compare(game: [1, 2, 3, 4, 5, 1], guess: [1, 2, 3, 4, 2, -2]) == [0, 0, 0, 0, 3, 3]
// compare(game: [0, 5, 0, 0, 0, 4], guess: [4, 1, 1, 0, 0, -2]) == [4, 4, 1, 0, 0, 6]
func compare(game: [Int], guess: [Int]) -> [Int] {
var result = [Int]()
for i in 0..<game.count {
result.append(abs(game[i] - guess[i]))
}
return result
}
```
func Strongest_Extension(className: String, extensions: [String]) -> String {
let className = className.lowercased()
let extensions = extensions.map { $0.lowercased() }
let extensions = extensions.sorted { (extension1, extension2) -> Bool in
let count1 = extension1.filter { $0.isUppercase }.count
let count2 = extension2.filter { $0.isUppercase }.count
return count1 < count2
}
let extension = extensions.first!
let extensionName = className + "." + extension
return extensionName
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let className = className.lowercased()
let extensions = extensions.map { $0.lowercased() }
let extensions = extensions.sorted { (extension1, extension2) -> Bool in
let count1 = extension1.filter { $0.isUppercase }.count
let count2 = extension2.filter { $0.isUppercase }.count
return count1 < count2
}
let extension = extensions.first!
let extensionName = className + "." + extension
return extensionName
}
```
let extensions = extensions.sorted { (extension1, extension2) -> Bool in // invalid redeclaration of 'extensions'
let extension = extensions.first! // keyword 'extension' cannot be used as an identifier here
let extensionName = className + "." + extension // declaration is only valid at file scope
let extensionName = className + "." + extension // consecutive statements on a line must be separated by ';'
let extensionName = className + "." + extension // expected expression after operator
let extensionName = className + "." + extension // expected '{' in extension
return extensionName // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var max = 0
for extension in extensions {
let strength = extension.uppercase().count - extension.lowercased().count
if strength > max {
max = strength
result = extension
}
}
return "\(className).\(result)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var max = 0
for extension in extensions {
let strength = extension.uppercase().count - extension.lowercased().count
if strength > max {
max = strength
result = extension
}
}
return "\(className).\(result)"
}
```
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
let strength = extension.uppercase().count - extension.lowercased().count // expected '{' in extension
let strength = extension.uppercase().count - extension.lowercased().count // expected type name in extension declaration
let strength = extension.uppercase().count - extension.lowercased().count // expected initial value after '='
let strength = extension.uppercase().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let strength = extension.uppercase().count - extension.lowercased().count // declaration is only valid at file scope
let strength = extension.uppercase().count - extension.lowercased().count // expected type name in extension declaration
let strength = extension.uppercase().count - extension.lowercased().count // expected '{' in extension
let strength = extension.uppercase().count - extension.lowercased().count // declaration is only valid at file scope
result = extension // declaration is only valid at file scope
result = extension // expected expression in assignment
result = extension // expected '{' in extension
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = ""
var max = 0
for ext in extensions {
let strength = (ext.uppercase().count - ext.lowercased().count)
if strength > max {
max = strength
result = className + "." + ext
} else if strength == max {
result = className + "." + ext
}
}
return result
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = ""
var max = 0
for ext in extensions {
let strength = (ext.uppercase().count - ext.lowercased().count)
if strength > max {
max = strength
result = className + "." + ext
} else if strength == max {
result = className + "." + ext
}
}
return result
}
```
let strength = (ext.uppercase().count - ext.lowercased().count) // value of type 'String' has no member 'uppercase'
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result: String = ""
var maxStrength: Int = 0
for extension in extensions {
let strength: Int = extension.uppercase().count - extension.lowercased().count
if strength > maxStrength {
maxStrength = strength
result = className + "." + extension
}
}
return result
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result: String = ""
var maxStrength: Int = 0
for extension in extensions {
let strength: Int = extension.uppercase().count - extension.lowercased().count
if strength > maxStrength {
maxStrength = strength
result = className + "." + extension
}
}
return result
}
```
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
let strength: Int = extension.uppercase().count - extension.lowercased().count // expected type name in extension declaration
let strength: Int = extension.uppercase().count - extension.lowercased().count // declaration is only valid at file scope
let strength: Int = extension.uppercase().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let strength: Int = extension.uppercase().count - extension.lowercased().count // expected initial value after '='
let strength: Int = extension.uppercase().count - extension.lowercased().count // expected type name in extension declaration
let strength: Int = extension.uppercase().count - extension.lowercased().count // declaration is only valid at file scope
let strength: Int = extension.uppercase().count - extension.lowercased().count // expected '{' in extension
let strength: Int = extension.uppercase().count - extension.lowercased().count // expected '{' in extension
result = className + "." + extension // declaration is only valid at file scope
result = className + "." + extension // expected '{' in extension
result = className + "." + extension // expected expression after operator
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var max = 0
for extension in extensions {
let strength = extension.uppercase().count - extension.lowercased().count
if strength > max {
max = strength
result = "\(className).\(extension)"
}
}
return result
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var max = 0
for extension in extensions {
let strength = extension.uppercase().count - extension.lowercased().count
if strength > max {
max = strength
result = "\(className).\(extension)"
}
}
return result
}
```
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
let strength = extension.uppercase().count - extension.lowercased().count // expected '{' in extension
let strength = extension.uppercase().count - extension.lowercased().count // expected type name in extension declaration
let strength = extension.uppercase().count - extension.lowercased().count // expected initial value after '='
let strength = extension.uppercase().count - extension.lowercased().count // consecutive statements on a line must be separated by ';'
let strength = extension.uppercase().count - extension.lowercased().count // declaration is only valid at file scope
let strength = extension.uppercase().count - extension.lowercased().count // expected type name in extension declaration
let strength = extension.uppercase().count - extension.lowercased().count // expected '{' in extension
let strength = extension.uppercase().count - extension.lowercased().count // declaration is only valid at file scope
result = "\(className).\(extension)" // expected expression in list of expressions
func Strongest_Extension(className: String, extensions: [String]) -> String {
let className = className.lowercased()
let extensions = extensions.map { $0.lowercased() }
let strength = extensions.map { (extension: String) -> Int in
let count = extension.filter { $0.isUppercase }.count
let lowerCount = extension.filter { $0.isLowercase }.count
return count - lowerCount
}
let maxStrength = strength.max()!
let maxStrengthIndex = strength.firstIndex(of: maxStrength)!
return className + "." + extensions[maxStrengthIndex]
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let className = className.lowercased()
let extensions = extensions.map { $0.lowercased() }
let strength = extensions.map { (extension: String) -> Int in
let count = extension.filter { $0.isUppercase }.count
let lowerCount = extension.filter { $0.isLowercase }.count
return count - lowerCount
}
let maxStrength = strength.max()!
let maxStrengthIndex = strength.firstIndex(of: maxStrength)!
return className + "." + extensions[maxStrengthIndex]
}
```
let count = extension.filter { $0.isUppercase }.count // declaration is only valid at file scope
let count = extension.filter { $0.isUppercase }.count // expected '{' in extension
let count = extension.filter { $0.isUppercase }.count // expected initial value after '='
let count = extension.filter { $0.isUppercase }.count // consecutive statements on a line must be separated by ';'
let count = extension.filter { $0.isUppercase }.count // expected type name in extension declaration
let lowerCount = extension.filter { $0.isLowercase }.count // declaration is only valid at file scope
let lowerCount = extension.filter { $0.isLowercase }.count // expected initial value after '='
let lowerCount = extension.filter { $0.isLowercase }.count // consecutive statements on a line must be separated by ';'
let lowerCount = extension.filter { $0.isLowercase }.count // expected type name in extension declaration
let lowerCount = extension.filter { $0.isLowercase }.count // expected '{' in extension
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var max = 0
for extension in extensions {
let count = extension.count
let strength = count - extension.filter { $0.isUpperCase }.count
if strength > max {
max = strength
result = extension
}
}
return "\(className).\(result)"
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var max = 0
for extension in extensions {
let count = extension.count
let strength = count - extension.filter { $0.isUpperCase }.count
if strength > max {
max = strength
result = extension
}
}
return "\(className).\(result)"
}
```
for extension in extensions { // expected pattern
for extension in extensions { // expected '{' to start the body of for-each loop
for extension in extensions { // expected Sequence expression for for-each loop
let count = extension.count // expected type name in extension declaration
let count = extension.count // consecutive statements on a line must be separated by ';'
let count = extension.count // expected initial value after '='
let count = extension.count // expected '{' in extension
let count = extension.count // declaration is only valid at file scope
let strength = count - extension.filter { $0.isUpperCase }.count // declaration is only valid at file scope
let strength = count - extension.filter { $0.isUpperCase }.count // expected expression after operator
let strength = count - extension.filter { $0.isUpperCase }.count // expected '{' in extension
let strength = count - extension.filter { $0.isUpperCase }.count // consecutive statements on a line must be separated by ';'
let strength = count - extension.filter { $0.isUpperCase }.count // expected type name in extension declaration
result = extension // expected '{' in extension
result = extension // expected expression in assignment
result = extension // declaration is only valid at file scope
} // expected type name in extension declaration
func Strongest_Extension(className: String, extensions: [String]) -> String {
var maxStrength = 0
var maxStr = ""
for str in extensions {
let strength = (str.uppercase().count - str.lowercase().count)
if strength > maxStrength {
maxStrength = strength
maxStr = str
} else if strength == maxStrength {
if str < maxStr {
maxStr = str
}
}
}
return className + "." + maxStr
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var maxStrength = 0
var maxStr = ""
for str in extensions {
let strength = (str.uppercase().count - str.lowercase().count)
if strength > maxStrength {
maxStrength = strength
maxStr = str
} else if strength == maxStrength {
if str < maxStr {
maxStr = str
}
}
}
return className + "." + maxStr
}
```
let strength = (str.uppercase().count - str.lowercase().count) // value of type 'String' has no member 'lowercase'
let strength = (str.uppercase().count - str.lowercase().count) // value of type 'String' has no member 'uppercase'
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var maxStrength = 0
for ext in extensions {
let strength = (ext.uppercased().count - ext.lowercased().count)
if strength > maxStrength {
maxStrength = strength
result = className + "." + ext
}
}
return result
}
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
var result = className
var maxStrength = 0
for ext in extensions {
let strength = (ext.uppercased().count - ext.lowercased().count)
if strength > maxStrength {
maxStrength = strength
result = className + "." + ext
}
}
return result
}
```
// XCTAssertTrue failed
```swift
// You will be given the name of a class (a string) and an array of extensions.
// The extensions are to be used to load additional classes to the class. The
// strength of the extension is as follows: Let CAP be the number of the uppercase
// letters in the extension's name, and let SM be the number of lowercase letters
// in the extension's name, the strength is given by the fraction CAP - SM.
// You should find the strongest extension and return a string in this
// format: ClassName.StrongestExtensionName.
// If there are two or more extensions with the same strength, you should
// choose the one that comes first in the array.
// For example, if you are given "Slices" as the class and an array of the
// extensions: ['SErviNGSliCes', 'Cheese', 'StuFfed'] then you should
// return 'Slices.SErviNGSliCes' since 'SErviNGSliCes' is the strongest extension
// (its strength is -1).
// Example:
// Strongest_Extension(className: "myClass", extensions: ["AA", "Be", "CC"]) == "my_class.AA"
func Strongest_Extension(className: String, extensions: [String]) -> String {
let className = className.lowercased()
let extensions = extensions.map { $0.lowercased() }
let extensions = extensions.map { (String($0.prefix(1)), String($0.suffix(1))) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0).count - String($0.1).count) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0.1)) }
let extensions = extensions.map { (String($0.0), String($0
XCTAssertTrue(Strongest_Extension(className: "Watashi", extensions: ["tEN", "niNE", "eIGHt8OKe"]) == "Watashi.eIGHt8OKe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Boku123", extensions: ["nani", "NazeDa", "YEs.WeCaNe", "32145tggg"]) == "Boku123.YEs.WeCaNe") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__YESIMHERE", extensions: ["t", "eMptY", "nothing", "zeR00", "NuLl__", "123NoooneB321"]) == "__YESIMHERE.NuLl__") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "K", extensions: ["Ta", "TAR", "t234An", "cosSo"]) == "K.TAR") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "__HAHA", extensions: ["Tab", "123", "781345", "--"]) == "__HAHA.123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "YameRore", extensions: ["HhAas", "okIWILL123", "WorkOut", "Fails", "--"]) == "YameRore.okIWILL123") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "finNNalLLly", extensions: ["Die", "NowW", "Wow", "WoW"]) == "finNNalLLly.WoW") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "", extensions: ["Bb", "91245"]) == ".Bb") // cannot find 'Strongest_Extension' in scope
XCTAssertTrue(Strongest_Extension(className: "Sp", extensions: ["671235", "Bb"]) == "Sp.671235") // cannot find 'Strongest_Extension' in scope
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
let bs = b.suffix(b.count - 1)
let bs2 = b.prefix(b.count - 1)
let bs3 = b.prefix(1)
let bs4 = b.suffix(1)
let bs5 = b.suffix(b.count - 2)
let bs6 = b.prefix(b.count - 2)
let bs7 = b.prefix(1)
let bs8 = b.suffix(1)
let bs9 = b.suffix(b.count - 3)
let bs10 = b.prefix(b.count - 3)
let bs11 = b.prefix(1)
let bs12 = b.suffix(1)
let bs13 = b.suffix(b.count - 4)
let bs14 = b.prefix(b.count - 4)
let bs15 = b.prefix(1)
let bs16 = b.suffix(1)
let bs17 = b.suffix(b.count - 5)
let bs18 = b.prefix(b.count - 5)
let bs19 = b.prefix(1)
let bs20 = b.suffix(1)
let bs21 = b.suffix(b.count - 6)
let bs22 = b.prefix(b.count - 6)
let bs23 = b.prefix(1)
let bs24 = b.suffix(1)
let bs25 = b.suffix(b.count - 7)
let bs26 = b.prefix(b.count - 7)
let bs27 = b.prefix(1)
let bs28 = b.suffix(1)
let bs29 = b.suffix(b.count - 8)
let bs30 = b.prefix(b.count - 8)
let bs31 = b.prefix(1)
let bs32 = b.suffix(1)
let bs33 = b.suffix(b.count - 9)
let bs34 = b.prefix(b.count - 9)
let bs35 = b.prefix(1)
let bs36 = b.suffix(1)
let bs37 = b.suffix(b.count - 10)
let bs38 = b.prefix(b.count - 10)
let bs39 = b.prefix(1)
let bs40 = b.suffix(1)
let bs41 = b.suffix(b.count - 11)
let bs42 = b.prefix(b.count - 11)
let bs43 = b.prefix(1)
let bs44 = b.suffix(1)
let bs45 = b.suffix(b.count - 12)
let bs46 = b.prefix(b.count - 12)
let bs47 = b.prefix(1)
let bs48 = b.suffix(1)
let bs49 = b.suffix(b.count - 13)
let bs50 = b.prefix(b.count - 13)
let bs51 = b.prefix(1)
let bs52 = b.suffix(1)
let bs53 = b.suffix(b.count - 14)
let bs54 = b.prefix(b.count - 14)
let bs55 = b.prefix(1)
let bs56 = b.suffix(1)
let bs57 = b.suffix(b.count - 15)
XCTAssertTrue(cycpatternCheck(a: "xyzw", b: "xyw") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "yello", b: "ell") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "whattup", b: "ptut") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "efef", b: "fee") == true) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "abab", b: "aabb") == false) // cannot find 'cycpatternCheck' in scope
XCTAssertTrue(cycpatternCheck(a: "winemtt", b: "tinem") == true) // cannot find 'cycpatternCheck' in scope
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
let n = a.count
let m = b.count
if n < m {
return false
}
let aa = Array(a)
let bb = Array(b)
for i in 0..<n - m + 1 {
if aa[i] == bb[0] {
var j = 0
var k = i
while j < m && aa[k] == bb[j] {
j += 1
k += 1
if k == n {
return true
}
}
}
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
let n = a.count
let m = b.count
if n < m {
return false
}
let aa = Array(a)
let bb = Array(b)
for i in 0..<n - m + 1 {
if aa[i] == bb[0] {
var j = 0
var k = i
while j < m && aa[k] == bb[j] {
j += 1
k += 1
if k == n {
return true
}
}
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if m > n {
return false
}
var i = 0
var j = 0
while i < n {
if a[i] == b[j] {
j += 1
if j == m {
return true
}
} else {
i -= j
j = 0
}
i += 1
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if m > n {
return false
}
var i = 0
var j = 0
while i < n {
if a[i] == b[j] {
j += 1
if j == m {
return true
}
} else {
i -= j
j = 0
}
i += 1
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let aCount = a.count
let bCount = b.count
if aCount != bCount {
return false
}
var aIndex = 0
var bIndex = 0
while aIndex < aCount {
if a[aIndex] == b[bIndex] {
if bIndex == bCount - 1 {
return true
}
bIndex += 1
} else {
aIndex += 1
bIndex = 0
}
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let aCount = a.count
let bCount = b.count
if aCount != bCount {
return false
}
var aIndex = 0
var bIndex = 0
while aIndex < aCount {
if a[aIndex] == b[bIndex] {
if bIndex == bCount - 1 {
return true
}
bIndex += 1
} else {
aIndex += 1
bIndex = 0
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased(), b = b.lowercased()
let aLen = a.count, bLen = b.count
if aLen < bLen {
return false
}
if aLen == bLen {
return a == b
}
for i in 0..<aLen {
let start = a.index(a.startIndex, offsetBy: i)
let end = a.index(a.startIndex, offsetBy: i + bLen)
let subStr = String(a[start..<end])
if subStr == b || subStr == String(b.reversed()) {
return true
}
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased(), b = b.lowercased()
let aLen = a.count, bLen = b.count
if aLen < bLen {
return false
}
if aLen == bLen {
return a == b
}
for i in 0..<aLen {
let start = a.index(a.startIndex, offsetBy: i)
let end = a.index(a.startIndex, offsetBy: i + bLen)
let subStr = String(a[start..<end])
if subStr == b || subStr == String(b.reversed()) {
return true
}
}
return false
}
```
// Fatal error: String index is out of bounds
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
let n = a.count
let m = b.count
if m > n {
return false
}
let aArr = Array(a)
let bArr = Array(b)
for i in 0..<n-m+1 {
if aArr[i] == bArr[0] {
var j = 0
while j < m {
if aArr[i+j] != bArr[j] {
break
}
j += 1
}
if j == m {
return true
}
}
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = a.lowercased()
let b = b.lowercased()
let n = a.count
let m = b.count
if m > n {
return false
}
let aArr = Array(a)
let bArr = Array(b)
for i in 0..<n-m+1 {
if aArr[i] == bArr[0] {
var j = 0
while j < m {
if aArr[i+j] != bArr[j] {
break
}
j += 1
}
if j == m {
return true
}
}
}
return false
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if n < m {
return false
}
var dp = Array(repeating: Array(repeating: 0, count: m), count: n)
for i in 0..<n {
for j in 0..<m {
if a[i] == b[j] {
if i == 0 || j == 0 {
dp[i][j] = 1
} else {
dp[i][j] = dp[i-1][j-1]
}
}
}
}
return dp[n-1][m-1] > 0
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if n < m {
return false
}
var dp = Array(repeating: Array(repeating: 0, count: m), count: n)
for i in 0..<n {
for j in 0..<m {
if a[i] == b[j] {
if i == 0 || j == 0 {
dp[i][j] = 1
} else {
dp[i][j] = dp[i-1][j-1]
}
}
}
}
return dp[n-1][m-1] > 0
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if m > n {
return false
}
var i = 0
var j = 0
while i < n && j < m {
if a[i] == b[j] {
i += 1
j += 1
} else {
i = i - j + 1
j = 0
}
}
return j == m
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if m > n {
return false
}
var i = 0
var j = 0
while i < n && j < m {
if a[i] == b[j] {
i += 1
j += 1
} else {
i = i - j + 1
j = 0
}
}
return j == m
}
```
// XCTAssertTrue failed
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let aCount = a.count
let bCount = b.count
if aCount < bCount {
return false
}
var i = 0
var j = 0
var k = 0
while i < aCount {
if a[i] == b[j] {
k = 0
while j < bCount {
if a[i + k] != b[j] {
break
}
k += 1
j += 1
}
if j == bCount {
return true
}
}
i += 1
j = 0
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let aCount = a.count
let bCount = b.count
if aCount < bCount {
return false
}
var i = 0
var j = 0
var k = 0
while i < aCount {
if a[i] == b[j] {
k = 0
while j < bCount {
if a[i + k] != b[j] {
break
}
k += 1
j += 1
}
if j == bCount {
return true
}
}
i += 1
j = 0
}
return false
}
```
// Fatal error: Index out of range
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if m > n {
return false
}
var i = 0
var j = 0
var k = 0
while i < n {
if a[i] == b[j] {
k = 0
while j < m && a[i + k] == b[j] {
k += 1
j += 1
}
if j == m {
return true
}
j = 0
}
i += 1
}
return false
}
```swift
// You are given 2 words. You need to return true if the second word or any of its rotations is a substring in the first word
// cycpatternCheck(a: "abcd", b: "abd") == false
// cycpatternCheck(a: "hello", b: "ell") == true
// cycpatternCheck(a: "whassup", b: "psus") == false
// cycpatternCheck(a: "abab", b: "baa") == true
// cycpatternCheck(a: "efef", b: "eeff") == false
// cycpatternCheck(a: "himenss", b: "simen") == true
func cycpatternCheck(a: String, b: String) -> Bool {
let a = Array(a)
let b = Array(b)
let n = a.count
let m = b.count
if m > n {
return false
}
var i = 0
var j = 0
var k = 0
while i < n {
if a[i] == b[j] {
k = 0
while j < m && a[i + k] == b[j] {
k += 1
j += 1
}
if j == m {
return true
}
j = 0
}
i += 1
}
return false
}
```
// Fatal error: Index out of range
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
num /= 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
num /= 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let numStr = String(num)
var evenCount = 0
var oddCount = 0
for char in numStr {
let charInt = Int(String(char))!
if charInt % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
class Solution {
func evenOddCount(_ num: Int) -> (Int, Int) {
let numStr = String(num)
var evenCount = 0
var oddCount = 0
for char in numStr {
let charInt = Int(String(char))!
if charInt % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let numStr = String(num)
var evenCount = 0
var oddCount = 0
for char in numStr {
let charInt = Int(String(char))!
if charInt % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
```
### 解题思路
### 代码
```swift
class Solution {
func evenOddCount(_ num: Int) -> (Int, Int) {
let numStr = String(num)
var evenCount = 0
var oddCount = 0
for char in numStr {
let charInt = Int(String(char))!
if charInt % 2 == 0 {
evenCount += 1
} else {
oddCount += 1
}
}
return (evenCount, oddCount)
}
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
num /= 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
num /= 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var n = num
while n > 0 {
if n % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
n /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var n = num
while n > 0 {
if n % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
n /= 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(num)
var even = 0
var odd = 0
for c in str {
let n = Int(String(c))!
if n % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
let str = String(num)
var even = 0
var odd = 0
for c in str {
let n = Int(String(c))!
if n % 2 == 0 {
even += 1
} else {
odd += 1
}
}
return (even, odd)
}
```
// Fatal error: Unexpectedly found nil while unwrapping an Optional value
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
if num % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
if num % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
if num % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
if num % 10 % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
class Solution {
func countBits(_ num: Int) -> [Int] {
var result = [Int]()
for i in 0..<num+1 {
result.append(count(i))
}
return result
}
func count(_ num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += 1
num &= (num - 1)
}
return result
}
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
### 解题思路
### 代码
```swift
class Solution {
func countBits(_ num: Int) -> [Int] {
var result = [Int]()
for i in 0..<num+1 {
result.append(count(i))
}
return result
}
func count(_ num: Int) -> Int {
var result = 0
var num = num
while num > 0 {
result += 1
num &= (num - 1)
}
return result
}
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var temp = num
while temp > 0 {
let last = temp % 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
temp /= 10
}
return (even, odd)
}
class Solution {
func countBits(_ num: Int) -> [Int] {
var res = [Int](repeating: 0, count: num + 1)
for i in 1...num {
res[i] = res[i >> 1] + (i & 1)
}
return res
}
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var temp = num
while temp > 0 {
let last = temp % 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
temp /= 10
}
return (even, odd)
}
```
### 解题思路
### 代码
```swift
class Solution {
func countBits(_ num: Int) -> [Int] {
var res = [Int](repeating: 0, count: num + 1)
for i in 1...num {
res[i] = res[i >> 1] + (i & 1)
}
return res
}
}
```
// XCTAssertTrue failed
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```swift
// Given an integer. return a tuple that has the number of even and odd digits respectively.
// Example:
// evenOddCount(num: -12) == (1, 1)
// evenOddCount(num: 123) == (1, 2)
func evenOddCount(num: Int) -> (Int, Int) {
var even = 0
var odd = 0
var num = num
while num > 0 {
let last = num % 10
if last % 2 == 0 {
even += 1
} else {
odd += 1
}
num /= 10
}
return (even, odd)
}
```
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let num = number
let dic = [1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i"]
var res = ""
for (key, value) in dic {
if num >= key {
let count = num / key
res += String(repeating: value, count: count)
num = num % key
}
}
return res
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let num = number
let dic = [1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i"]
var res = ""
for (key, value) in dic {
if num >= key {
let count = num / key
res += String(repeating: value, count: count)
num = num % key
}
}
return res
}
```
num = num % key // cannot assign to value: 'num' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var result = ""
for (value, roman) in roman {
let count = num / value
if count > 0 {
result += String(repeating: roman, count: count)
num -= value * count
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var result = ""
for (value, roman) in roman {
let count = num / value
if count > 0 {
result += String(repeating: roman, count: count)
num -= value * count
}
}
return result
}
```
num -= value * count // left side of mutating operator isn't mutable: 'num' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result.append("m")
num -= 1000
} else if num >= 900 {
result.append("cm")
num -= 900
} else if num >= 500 {
result.append("d")
num -= 500
} else if num >= 400 {
result.append("cd")
num -= 400
} else if num >= 100 {
result.append("c")
num -= 100
} else if num >= 90 {
result.append("xc")
num -= 90
} else if num >= 50 {
result.append("l")
num -= 50
} else if num >= 40 {
result.append("xl")
num -= 40
} else if num >= 10 {
result.append("x")
num -= 10
} else if num >= 9 {
result.append("ix")
num -= 9
} else if num >= 5 {
result.append("v")
num -= 5
} else if num >= 4 {
result.append("iv")
num -= 4
} else if num >= 1 {
result.append("i")
num -= 1
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
while num > 0 {
if num >= 1000 {
result.append("m")
num -= 1000
} else if num >= 900 {
result.append("cm")
num -= 900
} else if num >= 500 {
result.append("d")
num -= 500
} else if num >= 400 {
result.append("cd")
num -= 400
} else if num >= 100 {
result.append("c")
num -= 100
} else if num >= 90 {
result.append("xc")
num -= 90
} else if num >= 50 {
result.append("l")
num -= 50
} else if num >= 40 {
result.append("xl")
num -= 40
} else if num >= 10 {
result.append("x")
num -= 10
} else if num >= 9 {
result.append("ix")
num -= 9
} else if num >= 5 {
result.append("v")
num -= 5
} else if num >= 4 {
result.append("iv")
num -= 4
} else if num >= 1 {
result.append("i")
num -= 1
}
}
return result
}
```
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var romanStr = ""
for (value, symbol) in roman {
let count = num / value
if count > 0 {
romanStr += String(repeating: symbol, count: count)
num -= count * value
}
}
return romanStr
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var romanStr = ""
for (value, symbol) in roman {
let count = num / value
if count > 0 {
romanStr += String(repeating: symbol, count: count)
num -= count * value
}
}
return romanStr
}
```
num -= count * value // left side of mutating operator isn't mutable: 'num' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var result = ""
var num = number
for (value, roman) in roman {
while num >= value {
result += roman
num -= value
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var result = ""
var num = number
for (value, roman) in roman {
while num >= value {
result += roman
num -= value
}
}
return result
}
```
func intToMiniRoman(number: Int) -> String {
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var result = ""
var num = number
for (value, symbol) in roman {
while num >= value {
result += symbol
num -= value
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var result = ""
var num = number
for (value, symbol) in roman {
while num >= value {
result += symbol
num -= value
}
}
return result
}
```
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i"]
var result = ""
for (k, v) in roman {
let count = num / k
if count > 0 {
result += String(repeating: v, count: count)
num = num % k
}
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [1000: "m", 900: "cm", 500: "d", 400: "cd", 100: "c", 90: "xc", 50: "l", 40: "xl", 10: "x", 9: "ix", 5: "v", 4: "iv", 1: "i"]
var result = ""
for (k, v) in roman {
let count = num / k
if count > 0 {
result += String(repeating: v, count: count)
num = num % k
}
}
return result
}
```
num = num % k // cannot assign to value: 'num' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var romanStr = ""
for (value, romanStr) in roman {
while num >= value {
num -= value
romanStr += String(romanStr)
}
}
return romanStr
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let num = number
let roman = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var romanStr = ""
for (value, romanStr) in roman {
while num >= value {
num -= value
romanStr += String(romanStr)
}
}
return romanStr
}
```
num -= value // left side of mutating operator isn't mutable: 'num' is a 'let' constant
romanStr += String(romanStr) // left side of mutating operator isn't mutable: 'romanStr' is a 'let' constant
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["I", "V", "X", "L", "C", "D", "M"]
var mini = ["1", "5", "10", "50", "100", "500", "1000"]
var index = 0
while num > 0 {
let temp = num % 10
if temp == 9 {
result.insert(contentsOf: roman[index], at: result.startIndex)
result.insert(contentsOf: roman[index + 1], at: result.startIndex)
} else if temp == 4 {
result.insert(contentsOf: roman[index], at: result.startIndex)
result.insert(contentsOf: roman[index + 2], at: result.startIndex)
} else if temp >= 5 {
result.insert(contentsOf: roman[index + 1], at: result.startIndex)
for _ in 0..<(temp - 5) {
result.insert(contentsOf: roman[index], at: result.startIndex)
}
} else {
for _ in 0..<(temp) {
result.insert(contentsOf: roman[index], at: result.startIndex)
}
}
num /= 10
index += 2
}
return result
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
var result = ""
var num = number
var roman = ["I", "V", "X", "L", "C", "D", "M"]
var mini = ["1", "5", "10", "50", "100", "500", "1000"]
var index = 0
while num > 0 {
let temp = num % 10
if temp == 9 {
result.insert(contentsOf: roman[index], at: result.startIndex)
result.insert(contentsOf: roman[index + 1], at: result.startIndex)
} else if temp == 4 {
result.insert(contentsOf: roman[index], at: result.startIndex)
result.insert(contentsOf: roman[index + 2], at: result.startIndex)
} else if temp >= 5 {
result.insert(contentsOf: roman[index + 1], at: result.startIndex)
for _ in 0..<(temp - 5) {
result.insert(contentsOf: roman[index], at: result.startIndex)
}
} else {
for _ in 0..<(temp) {
result.insert(contentsOf: roman[index], at: result.startIndex)
}
}
num /= 10
index += 2
}
return result
}
```
var roman = ["I", "V", "X", "L", "C", "D", "M"] // variable 'roman' was never mutated; consider changing to 'let' constant
var mini = ["1", "5", "10", "50", "100", "500", "1000"] // initialization of variable 'mini' was never used; consider replacing with assignment to '_' or removing it
// XCTAssertTrue failed
func intToMiniRoman(number: Int) -> String {
let romanNumeralMap = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var romanNumeral = ""
var num = number
for (value, roman) in romanNumeralMap {
while num >= value {
romanNumeral += roman
num -= value
}
if num == 0 {
break
}
}
return romanNumeral
}
```swift
// Given a positive integer, obtain its roman numeral equivalent as a string,
// and return it in lowercase.
// Restrictions: 1 <= num <= 1000
// Examples:
// intToMiniRoman(number: 19) == "xix"
// intToMiniRoman(number: 152) == "clii"
// intToMiniRoman(number: 426) == "cdxxvi"
func intToMiniRoman(number: Int) -> String {
let romanNumeralMap = [
(1000, "m"),
(900, "cm"),
(500, "d"),
(400, "cd"),
(100, "c"),
(90, "xc"),
(50, "l"),
(40, "xl"),
(10, "x"),
(9, "ix"),
(5, "v"),
(4, "iv"),
(1, "i")
]
var romanNumeral = ""
var num = number
for (value, roman) in romanNumeralMap {
while num >= value {
romanNumeral += roman
num -= value
}
if num == 0 {
break
}
}
return romanNumeral
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a + b <= c || a + c <= b || b + c <= a {
return false
}
if a == b && b == c {
return true
}
if a == b || b == c || a == c {
return false
}
return a * a + b * b == c * c || b * b + c * c == a * a || a * a + c * c == b * b
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a + b <= c || a + c <= b || b + c <= a {
return false
}
if a == b && b == c {
return true
}
if a == b || b == c || a == c {
return false
}
return a * a + b * b == c * c || b * b + c * c == a * a || a * a + c * c == b * b
}
```
// XCTAssertTrue failed
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a + b <= c || a + c <= b || b + c <= a {
return false
}
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a + b <= c || a + c <= b || b + c <= a {
return false
}
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a + b <= c || a + c <= b || b + c <= a {
return false
}
if a == b && b == c {
return true
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c || a == c {
return false
}
if a == b || b == c
XCTAssertTrue(rightAngleTriangle(a: 3, b: 4, c: 5) == true) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 1, b: 2, c: 3) == false) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 10, b: 6, c: 8) == true) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 2, b: 2, c: 2) == false) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 7, b: 24, c: 25) == true) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 10, b: 5, c: 7) == false) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 5, b: 12, c: 13) == true) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 15, b: 8, c: 17) == true) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 48, b: 55, c: 73) == true) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 1, b: 1, c: 1) == false) // cannot find 'rightAngleTriangle' in scope
XCTAssertTrue(rightAngleTriangle(a: 2, b: 2, c: 10) == false) // cannot find 'rightAngleTriangle' in scope
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a > b && a > c {
return b * b + c * c == a * a
} else if b > a && b > c {
return a * a + c * c == b * b
} else {
return a * a + b * b == c * c
}
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
if a > b && a > c {
return b * b + c * c == a * a
} else if b > a && b > c {
return a * a + c * c == b * b
} else {
return a * a + b * b == c * c
}
}
```
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```swift
// Given the lengths of the three sides of a triangle. Return true if the three
// sides form a right-angled triangle, false otherwise.
// A right-angled triangle is a triangle in which one angle is right angle or
// 90 degree.
// Example:
// rightAngleTriangle(a: 3, b: 4, c: 5) == true
// rightAngleTriangle(a: 1, b: 2, c: 3) == false
func rightAngleTriangle(a: Int, b: Int, c: Int) -> Bool {
return a * a + b * b == c * c || a * a + c * c == b * b || b * b + c * c == a * a
}
```
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueChars()
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueChars()
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```
let count = word.countOfUniqueChars() // value of type 'String' has no member 'countOfUniqueChars'
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let count = word.countOfUniqueCharacters()
if count > max {
max = count
result = word
} else if count == max {
if word < result {
result = word
}
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let count = word.countOfUniqueCharacters()
if count > max {
max = count
result = word
} else if count == max {
if word < result {
result = word
}
}
}
return result
}
```
let count = word.countOfUniqueCharacters() // value of type 'String' has no member 'countOfUniqueCharacters'
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let count = word.countOfUniqueCharacters()
if count > max {
max = count
result = word
} else if count == max {
if word < result {
result = word
}
}
}
return result
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var result = ""
for word in words {
let count = word.countOfUniqueCharacters()
if count > max {
max = count
result = word
} else if count == max {
if word < result {
result = word
}
}
}
return result
}
```
let count = word.countOfUniqueCharacters() // value of type 'String' has no member 'countOfUniqueCharacters'
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueChars()
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueChars()
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```
let count = word.countOfUniqueChars() // value of type 'String' has no member 'countOfUniqueChars'
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueCharacters()
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueCharacters()
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```
let count = word.countOfUniqueCharacters() // value of type 'String' has no member 'countOfUniqueCharacters'
func findMax(words: [String]) -> String {
var maxWord = ""
var maxCount = 0
for word in words {
let count = word.countOfUniqueChars()
if count > maxCount {
maxWord = word
maxCount = count
} else if count == maxCount {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var maxWord = ""
var maxCount = 0
for word in words {
let count = word.countOfUniqueChars()
if count > maxCount {
maxWord = word
maxCount = count
} else if count == maxCount {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```
let count = word.countOfUniqueChars() // value of type 'String' has no member 'countOfUniqueChars'
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.unicodeScalars.count
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.unicodeScalars.count
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.unicodeScalars.count
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.unicodeScalars.count
if count > max {
max = count
maxWord = word
} else if count == max {
if word < maxWord {
maxWord = word
}
}
}
return maxWord
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueCharacters(ignoring: " ")
if count > max {
max = count
maxWord = word
}
}
return maxWord
}
extension String {
func countOfUniqueCharacters(ignoring: Character) -> Int {
var count = 0
var set = Set<Character>()
for char in self {
if char != ignoring {
if !set.contains(char) {
count += 1
set.insert(char)
}
}
}
return count
}
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
var max = 0
var maxWord = ""
for word in words {
let count = word.countOfUniqueCharacters(ignoring: " ")
if count > max {
max = count
maxWord = word
}
}
return maxWord
}
// MARK: - Count of Unique Characters
extension String {
func countOfUniqueCharacters(ignoring: Character) -> Int {
var count = 0
var set = Set<Character>()
for char in self {
if char != ignoring {
if !set.contains(char) {
count += 1
set.insert(char)
}
}
}
return count
}
}
```
// XCTAssertTrue failed
func findMax(words: [String]) -> String {
let words = words.map { String($0) }
let wordCount = words.map { String($0).count }
let uniqueCharacters = words.map { String($0).reduce(0) { $0 + ($1.count == 1) } }
let maxIndex = words.enumerated().filter { uniqueCharacters[$0.offset] == wordCount[$0.offset] }.max { $0.offset < $1.offset }?.offset ?? 0
return words[maxIndex]
}
```swift
// Write a function that accepts an array of strings.
// The array contains different words. Return the word with maximum number
// of unique characters. If multiple strings have maximum number of unique
// characters, return the one which comes first in lexicographical order.
// findMax(words: ["name", "of", "string"]) == "string"
// findMax(words: ["name", "enam", "game"]) == "enam"
// findMax(words: ["aaaaaaa", "bb", "cc"]) == "aaaaaaa"
func findMax(words: [String]) -> String {
let words = words.map { String($0) }
let wordCount = words.map { String($0).count }
let uniqueCharacters = words.map { String($0).reduce(0) { $0 + ($1.count == 1) } }
let maxIndex = words.enumerated().filter { uniqueCharacters[$0.offset] == wordCount[$0.offset] }.max { $0.offset < $1.offset }?.offset ?? 0
return words[maxIndex]
}
```
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number
var left = remaining
if need > left {
total += left
left = 0
} else {
left -= need
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number
var left = remaining
if need > left {
total += left
left = 0
} else {
left -= need
}
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number
var left = remaining
if total >= need {
total -= need
left -= need
} else {
total = number
left = 0
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number
var left = remaining
if total >= need {
total -= need
left -= need
} else {
total = number
left = 0
}
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var left = remaining - need
if left < 0 {
left = 0
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
var total = number + need
var left = remaining - need
if left < 0 {
left = 0
}
return [total, left]
}
```
var total = number + need // variable 'total' was never mutated; consider changing to 'let' constant
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
if left < 0 {
return [total, 0]
}
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
if left < 0 {
return [total, 0]
}
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
if number >= need {
return [number + need, remaining - need]
} else {
return [number + remaining, 0]
}
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
if number >= need {
return [number + need, remaining - need]
} else {
return [number + remaining, 0]
}
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```
// XCTAssertTrue failed
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```swift
// You're a hungry rabbit, and you already have eaten a certain number of carrots,
// but now you need to eat more carrots to complete the day's meals.
// you should return an array of [ total number of eaten carrots after your meals,
// the number of carrots left after your meals ]
// if there are not enough remaining carrots, you will eat all remaining carrots, but will still be hungry.
// Example:
// Variables:
// @number : integer
// the number of carrots that you have eaten.
// @need : integer
// the number of carrots that you need to eat.
// @remaining : integer
// the number of remaining carrots thet exist in stock
// Constrain:
// * 0 <= number <= 1000
// * 0 <= need <= 1000
// * 0 <= remaining <= 1000
// Have fun :)
// eat(number: 5, need: 6, remaining: 10) == [11, 4]
// eat(number: 4, need: 8, remaining: 9) == [12, 1]
// eat(number: 1, need: 10, remaining: 10) == [11, 0]
// eat(number: 2, need: 11, remaining: 5) == [7, 0]
func eat(number: Int, need: Int, remaining: Int) -> [Int] {
let total = number + need
let left = remaining - need
return [total, left]
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = result ** operands[i]
default:
return -1
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = result ** operands[i]
default:
return -1
}
}
return result
}
```
result = result ** operands[i] // no operator '**' is defined; did you mean 'pow(_:_:)'?
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = result ** operands[i]
default:
return -1
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = result ** operands[i]
default:
return -1
}
}
return result
}
```
result = result ** operands[i] // no operator '**' is defined; did you mean 'pow(_:_:)'?
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.last!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.last!
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! ** num)
default:
return -1
}
}
}
return stack.last!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! ** num)
default:
return -1
}
}
}
return stack.last!
}
```
stack.append(stack.popLast()! ** num) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! ** num)
default:
return -1
}
}
}
return stack.last!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! ** num)
default:
return -1
}
}
}
return stack.last!
}
```
stack.append(stack.popLast()! ** num) // no operator '**' is defined; did you mean 'pow(_:_:)'?
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.popLast()!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.popLast()!
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
switch op {
case "+":
stack.append(stack.popLast()! + operands[i])
case "-":
stack.append(stack.popLast()! - operands[i])
case "*":
stack.append(stack.popLast()! * operands[i])
case "//":
stack.append(stack.popLast()! / operands[i])
case "**":
stack.append(stack.popLast()! * operands[i])
default:
return -1
}
}
}
return stack.popLast()!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
switch op {
case "+":
stack.append(stack.popLast()! + operands[i])
case "-":
stack.append(stack.popLast()! - operands[i])
case "*":
stack.append(stack.popLast()! * operands[i])
case "//":
stack.append(stack.popLast()! / operands[i])
case "**":
stack.append(stack.popLast()! * operands[i])
default:
return -1
}
}
}
return stack.popLast()!
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.popLast()!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.popLast()!
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
return -1
}
}
return result
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var result = operands[0]
for i in 1..<operands.count {
switch operators[i - 1] {
case "+":
result += operands[i]
case "-":
result -= operands[i]
case "*":
result *= operands[i]
case "//":
result /= operands[i]
case "**":
result = Int(pow(Double(result), Double(operands[i])))
default:
return -1
}
}
return result
}
```
// XCTAssertTrue failed
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.last!
}
```swift
// Given two arrays operators, and operands. The first array has basic algebra operations, and
// the second array is an array of integers. Use the two given arrays to build the algebric
// expression and return the evaluation of this expression.
// The basic algebra operations:
// Addition ( + )
// Subtraction ( - )
// Multiplication ( * )
// Floor division ( // )
// Exponentiation ( ** )
// Example:
// operator['+', '*', '-']
// array = [2, 3, 4, 5]
// result = 2 + 3 * 4 - 5
// => result = 9
// Note:
// The length of operator array is equal to the length of operand array minus one.
// Operand is an array of of non-negative integers.
// Operator array has at least one operator, and operand array has at least two operands.
func doAlgebra(operators: [String], operands: [Int]) -> Int {
guard operators.count == operands.count - 1 else {
return -1
}
var stack = [Int]()
for i in 0..<operands.count {
if i == 0 {
stack.append(operands[i])
} else {
let op = operators[i - 1]
let num = operands[i]
switch op {
case "+":
stack.append(stack.popLast()! + num)
case "-":
stack.append(stack.popLast()! - num)
case "*":
stack.append(stack.popLast()! * num)
case "//":
stack.append(stack.popLast()! / num)
case "**":
stack.append(stack.popLast()! * num)
default:
return -1
}
}
}
return stack.last!
}
```
// XCTAssertTrue failed
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for c in s {
if c.isLetter {
result.append(c.isLowercase ? c.uppercased() : c.lowercased())
} else {
result.append(c)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for c in s {
if c.isLetter {
result.append(c.isLowercase ? c.uppercased() : c.lowercased())
} else {
result.append(c)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.lowercased().reversed())
} else {
result.append(char.lowercased())
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.lowercased().reversed())
} else {
result.append(char.lowercased())
}
}
return result.reversed()
}
```
result.append(char.lowercased().reversed()) // no exact matches in call to instance method 'append'
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```swift
// You are given a string s.
// if s[i] is a letter, reverse its case from lower to upper or vise versa,
// otherwise keep it as it is.
// If the string contains no letters, reverse the string.
// The function should return the resulted string.
// Examples
// solve(s: "1234") == "4321"
// solve(s: "ab") == "AB"
// solve(s: "#a@C") == "#A@c"
func solve(s: String) -> String {
var result = ""
for char in s {
if char.isLetter {
result.append(char.isLowercase ? char.uppercased() : char.lowercased())
} else {
result.append(char)
}
}
return result.reversed()
}
```
return result.reversed() // no 'reversed' candidates produce the expected contextual result type 'String'
import CommonCrypto
func stringToMd5(text: String) -> String? {
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```
let md5 = MD5(data: data!) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let bytes = text.utf8.map({ Int(UnicodeScalar($0).value) })
let data = Data(bytes: bytes)
let md5 = MD5(data: data)
return md5.hexString
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let bytes = text.utf8.map({ Int(UnicodeScalar($0).value) })
let data = Data(bytes: bytes)
let md5 = MD5(data: data)
return md5.hexString
}
```
let data = Data(bytes: bytes) // type of expression is ambiguous without a type annotation
let md5 = MD5(data: data) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let md5 = MD5.md5(text)
return md5
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let md5 = MD5.md5(text)
return md5
}
```
let md5 = MD5.md5(text) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
let md5 = NSString(string: md5OfData(data: data))
return md5
}
func md5OfData(data: NSData) -> String {
let md5 = NSString(string: md5OfData(data: data))
return md5
}
func md5OfData(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
if text.isEmpty {
return nil
}
let data = text.dataUsingEncoding(NSUTF8StringEncoding)
let md5 = NSString(string: md5OfData(data: data))
return md5
}
func md5OfData(data: NSData) -> String {
let md5 = NSString(string: md5OfData(data: data))
return md5
}
func md5OfData(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NSData) -> String {
let md5 = MD5(data: data)
return md5
}
func MD5(data: NS
let data = text.dataUsingEncoding(NSUTF8StringEncoding) // value of type 'String' has no member 'dataUsingEncoding'
return md5 // 'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?
func md5OfData(data: NSData) -> String { // invalid redeclaration of 'md5OfData(data:)'
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5.hash(of: data!)
return String(md5)
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5.hash(of: data!)
return String(md5)
}
```
### 解题思路
### 代码
```swift
class Solution {
func addOne(_ num: Int) -> Int {
let numStr = String(num)
let numArr = Array(numStr)
let last = numArr.last!
let lastInt = Int(last)
let lastIntPlusOne = lastInt + 1
let lastIntPlusOneStr = String(lastIntPlusOne)
var newArr = numArr
newArr[newArr.count - 1] = lastIntPlusOneStr
let newStr = newArr.joined()
return Int(newStr)!
}
func add(_ num1: Int, _ num2: Int) -> Int {
var num1 = num1
var num2 = num2
var carry = 0
while num2 != 0 {
let sum = num1 + num2 + carry
num1 = sum % 10
carry = sum / 10
num2 = num2 / 10
}
return num1 + carry
}
func addStr(_ num1: String, _ num2: String) -> String {
var num1 = num1
var num2 = num2
var carry = 0
while !num2.isEmpty {
let sum = Int(num1.removeLast())! + Int(num2.removeLast())! + carry
num1 = String(sum % 10)
carry = sum / 10
}
while !num1.isEmpty {
let sum = Int(num1.removeLast())! + carry
num1 = String(sum % 10)
carry = sum / 10
}
if carry != 0 {
num1 = String(carry) + num1
}
return num1
}
func multiply(_ num1: Int, _ num2: Int) -> Int {
var num1 = num1
var num2 = num2
var result = 0
while num2 != 0 {
if num2 % 2 != 0 {
result = add(result, num1)
}
num1 = add(num1, num1)
num2 = num2 / 2
}
return result
}
func multiplyStr(_ num1: String, _ num2: String) -> String {
var num1 = num1
var num2 = num2
var result = "0"
while !num2.isEmpty {
if num2.last! == "1" {
result = addStr(result, num1)
}
num1 = addStr(num1, num1)
num2 = num2.removeLast()
}
return result
}
func divide(_ num1: Int, _ num2: Int) -> Int {
var num1 = num1
var num2 = num2
var result = 0
while num1 >= num2 {
var temp = 1
while temp * 2 <= num1 {
temp = temp * 2
}
result = result + temp
num1 = num1 - temp
}
return result
}
func divideStr(_ num1: String, _ num2: String) -> String {
var num1 = num1
var num2 = num2
var result = "0"
while !num1.isEmpty {
var temp = "0"
var i = 0
while !temp.isEmpty && temp != "1" {
i = i + 1
temp = String(multiplyStr(temp, "2"))
}
result = String(addStr(result, String(multiplyStr(num2, String(i)))))
num1 = num1.removeLast()
}
return result
}
func multiplyInt(_ num1:
let md5 = MD5.hash(of: data!) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```
### 参考
- [https://stackoverflow.com/questions/1131220/how-to-get-md5-hash-of-a-string-in-ios](https://stackoverflow.com/questions/1131220/how-to-get-md5-hash-of-a-string-in-ios)
- [https://gist.github.com/mikl/936626](https://gist.github.com/mikl/936626)
- [https://github.com/kylef/md5](https://github.com/kylef/md5)
- [https://github.com/kylef/swifternalizer](https://github.com/kylef/swifternalizer)
- [https://github.com/kylef/md5/blob/master/Sources/MD5/MD5.swift](https://github.com/kylef/md5/blob/master/Sources/MD5/MD5.swift)
- [https://github.com/kylef/swifternalizer/blob/master/Sources/swifternalizer/MD5.swift](https://github.com/kylef/swifternalizer/blob/master/Sources/swifternalizer/MD5.swift)
### 参考
- [https://stackoverflow.com/questions/1131220/how-to-get-md5-hash-of-a-string-in-ios](https://stackoverflow.com/questions/1131220/how-to-get-md5-hash-of-a-string-in-ios)
- [https://gist.github.com/mikl/936626](https://gist.github.com/mikl/936626)
- [https://github.com/kylef/md5](https://github.com/kylef/md5)
- [https://github.com/kylef/swifternalizer](https://github.com/kylef/swifternalizer)
- [https://github.com/kylef/md5/blob/master/Sources/MD5/MD5.swift](https://github.com/kylef/md5/blob/master/Sources/MD5/MD5.swift)
- [https://github.com/kylef/swifternalizer/blob/master/Sources/swifternalizer/MD5.swift](https://github.com/kylef/swifternalizer/blob/master/Sources/swifternalizer/MD5.swift)
let md5 = MD5(data: data!) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```
### 解题思路
### 代码
```swift
class MD5 {
var md5: String
init(data: Data) {
let md5 = MD5.md5Data(data: data)
self.md5 = md5
}
init(string: String) {
let data = string.data(using: .utf8)
let md5 = MD5.md5Data(data: data!)
self.md5 = md5
}
static func md5Data(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return md5
}
static func md5Digest(data: Data) -> String {
let md5 = MD5.md5(data: data)
return md5
}
static func md5(data: Data) -> String {
let md5 = MD5.md5Digest(data: data)
return
let md5 = MD5(data: data!) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexString
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexString
}
```
let md5 = MD5(data: data!) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5(data: data!)
return md5.hexdigest
}
```
### 参考
- [MD5 加密算法](https://www.cnblogs.com/xiaoyang-123/p/10343280.html)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/79479b71461c)
- [Swift 中的 MD5 加密](https://www.jianshu.com/p/794
let md5 = MD5(data: data!) // cannot find 'MD5' in scope
import CommonCrypto
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5.hash(of: data!)
return String(md5)
}
class Solution {
func hashStr(_ str: String) -> Int {
var hash = 0
for char in str {
hash = (hash << 5) - hash + Int(char.asciiValue!)
}
return hash
}
}
```swift
// Given a string 'text', return its md5 hash equivalent string.
// If 'text' is an empty string, return nil.
// stringToMd5(text: "Hello world") == "3e25960a79dbc69b674cd4ec67a72c62"
func stringToMd5(text: String) -> String? {
guard !text.isEmpty else {
return nil
}
let data = text.data(using: .utf8)
let md5 = MD5.hash(of: data!)
return String(md5)
}
```
### 解题思路
### 代码
```swift
class Solution {
func hashStr(_ str: String) -> Int {
var hash = 0
for char in str {
hash = (hash << 5) - hash + Int(char.asciiValue!)
}
return hash
}
}
```
let md5 = MD5.hash(of: data!) // cannot find 'MD5' in scope
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result: [Int] = []
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
var i = a
while i <= b {
if i % 2 == 0 {
result.append(i)
}
i += 1
}
return result
}
```
// XCTAssertTrue failed
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```swift
// Given two positive integers a and b, return the even digits between a
// and b, in ascending order.
// For example:
// generateIntegers(a: 2, b: 8) == [2, 4, 6, 8]
// generateIntegers(a: 8, b: 2) == [2, 4, 6, 8]
// generateIntegers(a: 10, b: 14) == [] as [Int]
func generateIntegers(a: Int, b: Int) -> [Int] {
var result = [Int]()
for i in a...b {
if i % 2 == 0 {
result.append(i)
}
}
return result
}
```
// Fatal error: Range requires lowerBound <= upperBound