Swift Basic Programming Exercise: Test if the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere
Swift Basic Programming: Exercise-24 with Solution
Write a Swift program to test if the sequence of numbers 1, 2, 3 appears in a given array of integers somewhere.
Pictorial Presentation:
Sample Solution:
Swift Code:
func array012(_ input: [Int]) -> Bool {
for (index, number) in input.enumerated() {
let third_Index = index + 2
let second_Index = index + 1
if second_Index < input.endIndex && number == 1 && input[second_Index] == 2 && input[third_Index] == 3 {
return true
}
}
return false
}
print(array012([0, 1, 1, 2, 3, 1]))
print(array012([0, 1, 1, 2, 4, 1]))
print(array012([1, 1, 2, 0, 1, 2, 3]))
Sample Output:
true false true
Swift Programming Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Swift program to check if one of the first 4 elements in a given array of integers is a 7. The length of the array may be less than 4.
Next: Write a Swift program to create a new string where all the character "a" have been removed except the first and last positions.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/swift-programming-exercises/basic/swift-basic-exercise-24.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics