S
S
Spacedandy2016-05-28 22:08:29
Swift
Spacedandy, 2016-05-28 22:08:29

How to find two min values ​​in an array of random numbers?

Can you please tell me how to find two min values ​​in an array of random numbers? The code is written in swift.

var list = [Int] ()
var n: Int = 8
for i in 1...n
{
let list = Int(arc4random_uniform(70))
print (list)
}
func getMin1Min2(numbers:Int...) -> (min1:Int, min2:Int)
{
var min1 = numbers[0]
var min2 = numbers[0]
for number in numbers
{
if number < min1 {min1 = number}
Further attempt to find the 2nd minimum value, but alas . ..

if number > min1
{if number < min2
{min2 = number}
}
}
return (min1, min2)
}
the task should end with a search for two minutes. values ​​in a random array, but alas, I don’t know how to use the created array and the function ...
var value = getMin1Min2 (list)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
ManWithBear, 2016-05-29
@ManWithBear

var min1 = min(arr[0],arr[1])
var min2 = max(arr[0],arr[1])
arr.forEach { (element) in
    if min1 > element {
        min2 = min1
        min1 = element
    } else {
        min2 = min(element,min2)
    }
}

Константин, 2016-05-29
@nicebmw9

Сделай 2 цикла в функции.

  • if number < min2 and number!=min1 {min2=number} . А это второй минимум вторым циклом
  • Didn't find what you were looking for?

    Ask your question

    Ask a Question

    731 491 924 answers to any question