Thursday, December 28, 2017

Working Out Algorithms

Knowing common algorithms is a major advantage for developers. Algorithms are powerful tools in our belts. If there is a complex or difficult to solve problem, knowing a proven algorithm that will solve it would immensely speed up the development cycle. Do I know many algorithms? Not many. Sadly.
But in my binary watchface I needed an algorithm for determining which squares need to be lit. I could do it by 'brute force' using a ton of ifs etc. But I wanted something more elegant (Although I hadn't really bothered to make the rect objects themselves very elegant - they're all hardcoded, not created programmatically).
I was hoping I could use bitwise checks, like:
if (2 & hr2 > 0) ...
if (4 & hr2 > 0) ...
If I had been more familiar with bitwise operations I would have never entertained the idea. I didn't work. I hit the internet but didn't find much. So I had to work out my own.
I need to get my binary valued squares to equal that column's time (Or battery) value. So I decided to create a variable to hold the sum. Then I started with the largest value. If adding that goes over the column's value, do nothing. Otherwise, add it and light up that square. Then move on to the next lesser value (From 8 to 4 to 2 to 1).
That was it. So much easier than I thought it would be. Thus is the beauty of algorithms.

No comments:

Post a Comment

From Shotcut to Kdenlive

So I've been using Shotcut for a while now, for my YouTube videos... and music videos. I love the application. Slicing clips, doing fade...