make a two random array and find the match number in swift

To generate two random arrays in Swift, we can use the following code:

main.swift
let firstArray = (0..<10).map { _ in Int.random(in: 0...100) }
let secondArray = (0..<10).map { _ in Int.random(in: 0...100) }
127 chars
3 lines

This code generates two arrays of length 10 with elements randomly chosen from 0 to 100.

To find the matching numbers in the two arrays, we can use a simple loop and an array intersection operation like this:

main.swift
var matches: [Int] = []

for number in firstArray {
    if secondArray.contains(number) && !matches.contains(number) {
        matches.append(number)
    }
}

print(matches)
174 chars
10 lines

Here, we loop through the elements of the first array, check if they exist in the second array, and add them to a matches array if they do. We also check that the number is not already in the matches array to avoid duplicates.

The matches array will contain all the numbers that are present in both arrays.

gistlibby LogSnag