Silver challenge: Dictionaries


#21

// Silver Challenge

var Nevada = [“Clark County”: [1, 2, 3], “Bear County”: [4, 5, 6], “Shark County”: [7, 8, 9]]

for (county, zips) in Nevada {
print("(county) has the following zip codes: (zips)")


#22

For the gold challenge, I tried to eliminate any hardcoded values in the code so it would automatically work with any number of counties. I also didn’t want to have any extra loop counters, just have it automatically detect the various ending points.

var stateZipcodes = ["Calhoun":  ["12345", "23456", "34567", "45678", "56789"],
                     "Fayette":  ["12346", "23457", "34568", "45679", "56780"],
                     "Houghton": ["54321", "65432", "76543", "87654", "98765"]]
var output = "Georgia has the following zip codes: ["
let spaces = String(repeating: " ", count: output.characters.count)
print(output, terminator:"")

let countyArray = Array(stateZipcodes.keys)
for county in countyArray
{
    let countyZipcodes = stateZipcodes[county] ?? []
    for zipcode in countyZipcodes
    {
        print(zipcode, terminator:"")
        if (zipcode != countyZipcodes.last)
        {
            print(", ", terminator:"") // still more zip codes on this line
        }
        else if county != countyArray.last
        {
            print(",")                   // last zip code on this line but not the last line, so use normal line termination
            print(spaces, terminator:"") //  and indent the next line
        }
        else
        {
            print("]") // last zip code in last county, so we're done
        }
    }
}

The only potential issue with this code is that if a county has more or less than 5 zip codes, you won’t get 5 zip codes printed on each line. To fix that you’d have to count the number of zip codes printed and start a new line after every fifth one, not just after each county.


#23

The first solution in this thread is way more elegant than mine. But, this is what I came up with for the Silver Challenge.

//Silver Challenge
//Create arrays of zips
var polkZip = [30306, 30307, 30308, 30309, 30310]
var booneZip = [30311, 30312, 30313, 30314, 30315]
var marshallZip = [30301, 30302, 30303, 30304, 30305]

//Create a dictionary of counties that maps to the zip arrays
var counties = ["Polk": polkZip, "Boone": booneZip, "Marshall": marshallZip]

//Create an array to hold all zips in the dictionary
var zipHolder = [0]

//This is the weird bit.  I have to initialize the array with something and then remove it from the array. If I try to append to the array when it is empty I get errors.
zipHolder.remove(at: 0)

// loop through them to pull out the values for each county
for zips in counties.values {
    // Get a count of the number of zips in the given array
    var countyZipCount = zips.count
    
    //Set a counter so that we can iterate through each array and put the values in each array into the zipHolder array
    var counter = 0
    while counter < countyZipCount {
        zipHolder.append(zips[counter])
        counter += 1
    }
}
// Print out the long list of Zips
print("Iowa has the following zip codes: \(zipHolder)")

I would appreciate any advice on initializing the array before using it. It seems I MUST put a value in the array before appending new values to it. However, if I give the array an initial value and then remove it, all is fine. Hmmmmmm


#24

Read page 82: If you just declare an Array and then try to append you get an error.
The solution is to create an empty array: var zipHolder = [Int] (). Then U don’t need to remove anything. With empty array you do 2 things declare and initialize.


#25

//Silver Challenge
Update Here’s my new solution working as expected. In as few lines as possible.

import Cocoa

var georgia = [“Cobb” : [30064, 30193, 38263, 30060, 34920] , “Fulton” : [37283, 30312, 38943, 30314, 36647 ] , “Gwinnett” : [30028, 36462, 32938, 32389, 31119] ]

var resultArray : [Int] = []
for zipCodes in georgia.values
{
for zip in zipCodes
{
resultArray.append(zip)
}
}
print(“Georgia has the following zip codes :” , resultArray)

//Georgia has the following zip codes : [37283, 30312, 38943, 30314, … ]


#26

Similar solution here:

var ctZips = ["Fairfield": [06464,06614,06615, 06515, 06516],
              "New Haven": [10001, 10111, 10101, 10005, 11003],
              "Litchfield": [07711, 07001, 05523, 08899, 02020]]

var bigZipList = Array<Int>()
for zip in ctZips.values {
    bigZipList += zip
}

print("CT has the following zip codes: \(bigZipList)")

#27

Maybe mine is weird…
import Cocoa
var china = [“hubei”:[101,102,103,104,105],
“shanghai”:[201,201,203,204,205],
“zhejinag”:[301,302,303,304,305],
“hunan”:[401,402,403,404,405]];
let post = Dictionary<String,Double>();
for post in china{
print(post);
}


#28

If you post your code between a pair of 3 back tick marks (```), you will make it easier to read:

var postCodes = [
    "hubei"   : [101,102,103,104,105],
    "shanghai": [201,201,203,204,205],
    "zhejinag": [301,302,303,304,305],
    "hunan"   : [401,402,403,404,405]];

// pretty print...
var maxKeyLen = 0
for (key, _) in postCodes {
    if maxKeyLen < key.count {
        maxKeyLen = key.count
    }
}

for (key, value) in postCodes {
    let padding = String (repeating: " ", count: maxKeyLen - key.count)
    print ("\(key) \(padding): \(value)");
}

should output:

hunan    : [401, 402, 403, 404, 405]
shanghai : [201, 201, 203, 204, 205]
zhejinag : [301, 302, 303, 304, 305]
hubei    : [101, 102, 103, 104, 105]

Become a Competent Programmer


#29

thank you ,I think I have mastered these contents,Thank you very much your reply.

Maybe we can make a friend, My name is 张威,My hometown is in China。

I’m sorry to reply you so late。

we can now send messages by email at any time


#30

Here goes my code:

//Silver Chapter.10
let zipCodesA = [94541, 94542, 94543, 94544, 94545]
let zipCodesB = [94551, 94552, 94553, 94554, 94555]
let zipCodesC = [94561, 94562, 94563, 94564, 94565]
let california = ["Alameda": zipCodesA, "Contra Costa": zipCodesB, "San Francisco": zipCodesC]
        var zipContainer = [Int]()

        for i in zipCodesA {
            zipContainer.append(i)
        }
        for i in zipCodesB {
            zipContainer.append(i)
        }
        for i in zipCodesC {
            zipContainer.append(i)
        }
        print("California has the following zip codes: \(zipContainer)")


//Silver: mo'betta, refactored for/in loop
        for i in california.values {
            for zip in i {
                zipContainer.append(zip)
            }
        }
        print("California has the following zip codes: \(zipContainer)"

#31

Most understandable code solution to the gold challenge that I’ve found yet. Nice work.:+1:t3:


#32

// Silver Challenge that is what i have (
var california = [“San Bruno”:(94066, 94065, 94067, 94061, 94063),
“Pacifica”: (94044, 94042, 94041, 94045, 94048),
“Sunnyvale”: (94085, 94088, 94087, 94089, 94090)]
for city in california {
print("(city.key) zip code is: (city.value) \n")
}