The Challenge:
Two words can be 'chained' if the last character of the first word is the same as the first character of the second word.
Given a list of words, determine if there is a way to 'chain' all the words in a circle.
Example:
1 | Input: { "eggs" , "karat" , "apple" , "snack" , "tuna" } |
2 | Output: True |
Print statements are not part of your character count. Your code should explicitly state if the array of words are chained or not.
Shortest and most valid answer within a week gets the solution.
If you ask in Discord or on the Website for a solution you are disqualified
I'll update the question with my implementation within due time.
Inspired by this post
Please do not moderate this Question as it doesn't break any rules
My solution.
please check to see if it passes through your testcases or not.
EDIT: Found a bug when in an odd number of elements, n-1 elements form a chain but the last one is something like "wow" where if it is flipped, it would still count as chain. This has been fixed now.
01 | local words = { "apple" , "estonia" , "wow" } |
02 |
03 | local function isChained () |
04 | local copy = { } ; |
05 |
06 | for i, word in pairs (words) do |
07 | copy [ i ] = word:reverse(); |
08 | end |
09 |
10 | table.sort(copy); |
11 | table.sort(words); |
12 |
13 | for i = 1 , #words do |
14 | if (words [ i ] :sub( 1 , 1 ) ~ = copy [ i ] :sub( 1 , 1 ) or copy [ i ] = = words [ i ] :reverse()) then |
15 | return false ; |
Can't be bothered to optimize it or make it shorter
01 | --words = {"eggs", "karat", "apple", "no", "snack", "tuna"} |
02 | words = { "monkey" , "moan" , "neh" , "neat" , "hort" , "team" , "gah" } |
03 | --words = {"eggs", "sea", "apple"} |
04 | --words = {"apple", "earth", "roda"} |
05 |
06 | function intable(table, value) |
07 | for i, v in pairs (table) do |
08 | if type (v) = = "table" and type (value) = = "table" then |
09 | for i 2 , v 2 in pairs (v) do |
10 | if value [ i 2 ] ~ = v 2 then return false end |
11 | end |
12 | for i 2 , v 2 in pairs (value) do |
13 | if v [ i 2 ] ~ = v 2 then return false end |
14 | end |
15 |