Day 6: I4G 10 days of Code Challenge.

Photo by Oleg Laptev on Unsplash

Day 6: I4G 10 days of Code Challenge.

Leetcode Problem 1195: On multithreading

Like the last couple of days, this will be an article where I explain the problem from the challenge given and go through my ideas and how I arrived at a solution.

The problem today was rated with a difficulty of medium and honestly, it took me quite some time to understand the question.

The Problem:

Day 6 prob.png

There are four functions whose jobs are to output (or print) various words. printFizz() is to print the word (or string) "fizz"

printBuzz() is to print the word "buzz"

printFizzbuzz() is to print the word "buzz"

printNumber() is to print a number. The problem with this arrangement is that they cannot just automatically write out all these in this order. The challenge asks us to use a particular criteria.

Naturally, we start counting from 1 (because this index is a 1-indexed as described by the problem).

1, 2, 3, 4, 5 ...n. Then we pass each number to various conditions to determine what is eventually outputed (that is "fizz" or "buzz" or "fizzbuzz" or the number).

According to the problem, the conditions are: ⦁ if the number is divisible by 3 but not by 5, print "fizz" ⦁ if the number is divisible by 5 but not by 3, print "buzz" ⦁ if the number is divisible by 3 and by 5, print "fizzbuzz" ⦁ if the number is not divisible by 3 or by 5, print a number

THOUGHT PROCESS

When I had outlined and understood the problem this way👆, it became a lot easier to develop a algorithm for it. My first idea was to implement a similar solution as Day 4 involving events. I planned to set all the events to wait with a python method (wait ()) and only change this method to (set ()) when a particular criterion to perform an event was reached.

This led to a quite complicated code with a lot of loops that executed with a runtime error of "time exceeded".

Day 6 Trial.png

I had to re strategize and work on the entire solution. I came across the threading function called Barrier in python. It helps with synchronizing multithreads. So, a condition is set before each thread is executed. When the thread is executed or not (depending on if the condition is met), it is then paused and moves execution to the next thread.

It is quite similar to the event () function but ensured a much simpler code logic and a smooth execution.

The Solution:

Day 6 soln.png

Ciao!