SpringN
SpringN

Reputation: 954

Find smallest number in dictionary Swift

Im trying to find the smallest number that is also false in my dictionary. I'm also using the new Swift Language. How can I make this work?

var firstRow = [1: false, 2: false, 3: false, 4: false, 5: false, 6: false]




  for (number, bool) in firstRow {

            if bool == false {

              //  NSLog("\(number)")


                for i = number; i > 0; i-- {
                    if number <= smallest {

                        smallest = number

                        NSLog("\(smallest)")
                    }

                }
               // NSLog("\(bool, number)")
            }
      }

Upvotes: 1

Views: 3222

Answers (4)

Umair Ali
Umair Ali

Reputation: 836

You can use the built-in min(by: ) method to fetch the minimum value using key or value in dictionary.

let minmum = firstrow.min { a, b in
    return a.value < b.value
 }
 // use minimum object to print key and value 
 print(minimum.key)
 print(minimum.value)

Upvotes: 1

Anton Strogonoff
Anton Strogonoff

Reputation: 34102

There seems to be a built-in filter() method on arrays in Swift, so I'd go with something like:

let falseNumbers: Int[] = firstRow.keys.filter { firstRow[$0] == false }
let smallestFalseNumber: Int = sort(falseNumbers)[0]

The above assumes there is at least one false value in firstRow dictionary. To ensure that:

if find(firstRow.values, false) {
    // The above code
}

Upvotes: 0

fqdn
fqdn

Reputation: 2843

If you're doing this strictly in Swift, I'd go with ASKASK while adding the the change:

let firstRow = [1: true, 2: false, 3: true]

var smallest = Int.max

for (number, bool) in firstRow {
    if bool == false && number < smallest {
        smallest = number
    }
}

There's no guarantee about the order in which your key-value pairs will be enumerated in your Dictionary, so given this example the fact that your keys are Integers that are displayed in ascending order does not help us, you will still need to check every pair in the Dictionary.

You might benefit from using an Array of Tuples here, especially if you know beforehand that the associated integers will be added to your collection in increasing order - or even if you don't, then you could at least sort the array by the first value in each tuple and thereby break out of the for loop when appropriate; for example:

let firstRow = [(1, true), (2, false), (3: true)]
var smallest: Int!  // given that it might be possible _none_ of them are 'false'
for (number, bool) in firstRow {
    if bool == false {
        smallest = number
        break
    }
}

Upvotes: 0

ASKASK
ASKASK

Reputation: 667

Here you go:

var smallest = 10000000000
for (number, bool) in firstRow {

        if bool == false && number < smallest{
             smallest = number

        }
}
println("\(smallest)")

Upvotes: 2

Related Questions