[VicPiMakers Projects] Progress on the Coding Challenge

David Reid goldilocks at mac.com
Thu Oct 22 05:24:12 EDT 2020


Hello VicPiMakers Gang :)

I’m joining remotely from Thailand where a much-appreciated job has taken me these days .. but it’s a +14 hour time change from Victoria, so I haven’t managed to make any of the online meetings yet. I’m meant to be here until July, so hopefully I’ll get a chance to join in online at some point coming up.

Craig and Deid were kind enough to send me the last Coding Challenge though, and I’ve been enjoying some of the 2 week quarantine time here puzzling away on this fun task :) THANKS !!

So .. earlier on in the emails, someone said this seemed like a good opportunity to learn a new programming language. Lately I've had it in the back of my mind to check out ‘Swift' as I’ve got mostly Mac’s running at home (aside from tinkering with the Raspberry Pi and also a couple of Ubuntu VMs) .. so it seemed like a great opportunity.

I’m not finished quite yet but quarantine is coming to an end in a couple of days, so here’s my progress so far .. I’m done #7 .. stuck on #8 .. it did occur to me that there’s one number missing from the sequence which I think should be 118 .. not sure if the discussion has floated to the top as to whether this omission is a typo or not, but I think that including the number might make the sort process a lot easier .. just haven’t got to it yet :)

As for my first bits of learning Swift, the language seems mostly sensible, coming from a hobbyist level of C.
- Swift includes what seems a bare minimum of formatting requirements .. just some very C-like use of brackets, braces and parentheses.
- Indentation doesn’t seem to matter
- no line terminators are required
- Casting variables, calling functions etc. seem to be pretty sensible.
- The defining of the return type of a function is a little interesting with a “func name(arguments) -> returnType" format.
- The defining of variables is interesting .. ‘let’ = constants, ‘var’ = variables, and variables are automatically typed by the compiler, or if you like, you can cast them upon initialization.
- I had to dig around a bit to find the ‘ceil(float)’ function which is a sort of dedicated rounding process to force the .41 to round up. There’s also a corresponding ‘floor(float)’ function which always rounds down .. handy :)
- Within Xcode, I really enjoyed the fact that you can sort of type a something, anything, then add a dot, and a list of possibilities will present itself .. very nice for learning :) I’ll drop in a screenshot here. The red warning is only because I haven’t made up my mind yet in this case as to what function I actually need .. it goes away when warranted after you complete the function and arguments.


One puzzle .. when I was working on output #6, The for loop in Swift seems very stripped down vs C, and the only problem I found was when I wanted it to iterate from high to low during the ‘bit adding process’ .. apparently that’s uncommon in Swift. I was able to get the job done by building an array of ’loopValue’ seeds and iterating through that array to give me the 1 and 0 in the right order. I might not have found the right way to do this .. someone correct me if you can find a better way :)

I’ll paste my swift code in here, as well as attach my Swift Playground file which anyone can open, provided you have Xcode on your Mac. These Playgrounds are pretty slick .. they have 2 columns, one for code, where I’ve done all of this, then another on the right where they explain the number of times through a loop, variables get written out etc. there’s also a command-line output you can pop up at the bottom. The cool thing is when you edit the file, Xcode more or less updates the right column in real-time and you don’t have to manually compile and run your code .. seems pretty cool.

Anyhow, cheers to all .. 32C here and (even though I can’t get out to enjoy it until Saturday morning) some sunshine made its way through the rainy-season weather we’ve had here this last couple of weeks.

Dave



import UIKit

// here are the inputs
var inputInts = [72,111,63,85,61,56,118,121,61,69,63,61]

// working on Output #1
var sum = 0
for number in inputInts {
    sum += number
}

print("Output #1 - Sum of inputs is: \(sum)")

// working on Output #2
var average :Float = 0.0
average = Float(sum) / Float(inputInts.count)
var averageInt :Int = Int(average)
// ceil is like rounding but forced up
var averageRemainder = Int(ceil(Float(inputInts.count) * (average - Float(averageInt))))

print("Output #2 - Average of inputs is: \(averageInt), \(averageRemainder)")

// working on Output #3
var arrayOfEvens = [Int]()
for number in inputInts {
    if ((Int(number / 2) * 2) == number) {
        arrayOfEvens.append(number)
    }
}

print("Output #3 - Even numbers: \(arrayOfEvens)")

// working on Output #4
var largest = 0
var largestPosition = 0
for n in 0..<inputInts.count {
    if (inputInts[n] > largest) {
        largest = inputInts[n]
        largestPosition = n
    }
}
// print("largest is \(largest) at position \(largestPosition)")
var smallest = largest
var smallestPosition = 0
for n in 0..<inputInts.count {
    if (inputInts[n] < largest) {
        smallest = inputInts[n]
        smallestPosition = n
    }
}

print("Output #4 - Smallest is \(smallest) in position \(smallestPosition)")

// working on Output #5
var repeats = [Int]()
var repeatsTotalCount = 0
var alreadyFoundThese = [Int]()

for lookingFor in inputInts {
    if (alreadyFoundThese.contains(lookingFor)) {
        // nothing to do if we've already found it once
    } else {
        var count = 0
        for thisPosition in inputInts {
            if (thisPosition == lookingFor) {
                count += 1
            }
        }
        if (count > 1) {
            for _ in 0..<count {
                repeats.append(lookingFor)
                repeatsTotalCount += 1
            }
        }
        alreadyFoundThese.append(lookingFor)
    }
}

print("Output #5 - Number of repeats: \(repeatsTotalCount) consisting of: \(repeats)")

// working on Output #6
// Ok the idea of laying down the two input numbers as a line of bits, end to end, then treating the pile of bits as another format by grouping them in a differen way is very cool .. but I had to google this one like crazy !!
inputInts[0]
let firstInt = Int8(inputInts[0])
let secondInt = Int8(inputInts[1])

let loopValues = [1,0]

func load16(incomingArray: [UInt8]) -> UInt16{
    var u: UInt16 = 0
    for index in loopValues {
        u = u << 8
        print (u)
        u = u | UInt16(incomingArray[index])
        print (u)
    }
    return u
}

var intsToCombine = [UInt8(inputInts[1]),UInt8(inputInts[0])]
var resultInt16 = load16(incomingArray: intsToCombine)

print("Output #6 - New number is: \(resultInt16)")

// working on Output #7
var sortArray = inputInts
var neededToSwapStuff = 1
var totalSortActions = 0
while (neededToSwapStuff > 0) {
    neededToSwapStuff = 0
    for number in 0..<(sortArray.count-1) {
        if (sortArray[number] > sortArray[number+1]){
            neededToSwapStuff += 1
            totalSortActions += 1
            let numberBeingMoved = sortArray[number]
            sortArray[number] = sortArray[number+1]
            sortArray[number+1] = numberBeingMoved
        }
    }
}

print("Output #7 - Input 'ints' were sorted to \(sortArray) in: \(totalSortActions) actions")

// working on Output #8
// the 11th value (118) was missing from the sorted sring in the coding_challenge1 file .. made this very interesting

// still stuck here .. thinking the 11th value was omitted and should be in the set for full comprehension as 118 corresponds to the lower case 'v' in ascii.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://vicpimakers.ca/pipermail/projects_vicpimakers.ca/attachments/20201022/7acf2977/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Screen Shot 2020-10-22 at 4.04.57 PM.png
Type: image/png
Size: 168368 bytes
Desc: not available
URL: <http://vicpimakers.ca/pipermail/projects_vicpimakers.ca/attachments/20201022/7acf2977/attachment.png>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://vicpimakers.ca/pipermail/projects_vicpimakers.ca/attachments/20201022/7acf2977/attachment-0001.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ViPiChallenge1.playground.zip
Type: application/zip
Size: 19327 bytes
Desc: not available
URL: <http://vicpimakers.ca/pipermail/projects_vicpimakers.ca/attachments/20201022/7acf2977/attachment.zip>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://vicpimakers.ca/pipermail/projects_vicpimakers.ca/attachments/20201022/7acf2977/attachment-0002.htm>


More information about the Projects mailing list