w3resource

Swift Array Programming Exercises: Test if the value 5 appears in a given array of integers exactly 2 times, and no 5's are next to each other

Swift Array Programming: Exercise-35 with Solution

Write a Swift program to test if the value 5 appears in a given array of integers exactly 2 times, and no 5's are next to each other.

Pictorial Presentation:

Swift Array Programming Exercises: Test if the value 5 appears in a given array of integers exactly 2 times, and no 5's are next to each other

Sample Solution:

Swift Code:

func test_5(array_nums: [Int]) -> Bool {
    var ctr = 0
    
    for num in array_nums {
        if num == 5 {
            ctr += 1
        }
    }
    
    for x in 0..<array_nums.count-1 {
        if array_nums[x] == 5 && array_nums[x+1] == 5
        {
            return false
        }
    }
    
    return ctr == 2
}

print(test_5(array_nums: [5, 1, 5, 1, 3]))
print(test_5(array_nums: [5, 1, 5, 5]))
print(test_5(array_nums: [5, 4, 5, 5, 4]))

Sample Output:

true
false
false

Swift Programming Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Swift program to test if a given array of integers contains either 2 even or 2 odd values all next to each other.
Next:Write a Swift program to test if every 3 that appears in a given array of integers is next to another 3.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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/array/swift-array-exercise-35.php