DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 115

Challenge, My solutions

TASK #1 › String Chain


You are given an array of strings.

Write a script to find out if the given strings can be chained to form a circle. Print 1 if found otherwise 0.

A string $S can be put before another string $T in circle if the last character of $S is same as first character of $T.

My solution

I thought this was straight and even submitted a pull request last night. My logic was to get a sorted order of the first letter and last letter of each word. If they matched, we had a solution. And it worked for the two examples. However, I realised a few minute later that it didn't cover the cases where we had two different circles (for example ab bc ca ij jk ki).

This had me thinking today (sorry boss!) about what the best way of finding a solution that didn't involve a recursive sub-routine. I failed.

So I now have a solution that works, but I'm not overly happy with it, but I believe it works. It will be interesting to see how other Team PWC members tackle the task.

I have a recursive subroutine _reduce_list that takes two parameters, the words used and the words remaining. The first call puts the first word in the list in the used value. It doesn't really matter what word we used first, as we need to make a circle.

For each call, I find possible words we can add to the list (where there first letter is the same as the last letter of the last word), and recursively call the subroutine. If there is no solution, I return 0. If we have found a possible solution, we need to do one final check that the first letter of the first word is the same as the last letter of the last word to complete the circle.


$ ./ abc dea cd 

$ ./ ade cbd fgh
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Largest Multiple


You are given a list of positive integers (0-9), single digit.

Write a script to find the largest multiple of 2 that can be formed from the list.

My solution

Hopefully this is as straight forward as I think it is. After checking all inputs are a single digit, I sort the numbers in decreasing order in an array called @numbers. I then find the position (index) of the last even number. If it is not already in the last position, I move that digit to the end.

I also display a message if no even digits can be found.


$ ./ 1 0 2 6

$ ./ 1 4 2 8

$ ./ 4 1 7 6
Enter fullscreen mode Exit fullscreen mode

Top comments (0)