Gold solution - rough but it works


#1

Here’s my Gold Challenge solution. Not overly pretty, but it works. :slight_smile:

    //GoldChallenge

//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]

//Define a string intro.
var intro = ("Iowa has the following zip codes: ")

//print it out with a terminator to open the array
print(intro, terminator: " [")

//Set a variable to count the passes through the loop
var passes = 0

for zips in counties.values {
    
    //Increases "passes" to let us know the # of times we've been here.
    passes += 1
    //Set a counter
    var counter = 0
    //Run the loop as long as the counter is less than the number of 
    //zips in the given array.
    while counter < zips.count {
        //If we are on the last zip associated with the last key
        //in the dictionary, change the print terminator.
        if passes == counties.count && (counter + 1) == zips.count {
            print(zips[counter], terminator: "]")
        //Otherwise, print the current zip with a comma at the end
        } else {
            print(zips[counter], terminator: ", ")
        }
        //Increase the counter to get to the next zip
        counter += 1
    }
    //After the last zip in each array, print a new line and a bunch of tabs.
    //This last line of code will run even after the closing bracket of the array,
    //but I don't really care.
    print("", terminator: "\n\t\t\t\t\t\t\t\t\t")
}

Output looks just right.


#2

This does not use the terminator option, rather I do the formatting directly

state[“c1”] = [30306, 30307, 30308, 30309, 30310]

state[“c2”] = [30311, 30312, 30313, 30314, 30315]

state[“c3”] = [30301, 30302, 30303, 30304,30305]

line = “State has the following zip codes: [”
first = true
var entryCount = 0 // number of zips per line counter
for county in keys {
let zips = state[county]!
for i in zips {
if first { // the frst zip is already preceeded by a “[”, the rest preceeded by “,”
first = false
} else {
line += ", "
}
if entryCount >= 5 { // put only 5 zips per line – when 5 have been entered start new line
line += "\n " // insert new line characer to start new line plus space for alignment
entryCount = 0 // reset zips count
}
line += “(i)” // add zip to line
entryCount += 1 // incfement entry count
}
}
line += “]” // all zips printed — append closing square bracket
print(line) // and display it