Wednesday, November 14, 2018

Q13: Coloured Triangles

Question 13:A coloured triangle is created from a row of colours, each of which is red, green or blue. Successive rows, each containing one fewer colour than the last, are generated by considering the two touching colours in the previous row. If these colours are identical, the same colour is used in the new row. If they are different, the missing colour is used in the new row. This is continued until the final row, with only a single colour, is generated.

For example, different possibilities are:

Colour here:            G G        B G        R G        B R
Becomes colour here:     G          R          B          G
With a bigger example:

R R G B R G B B
 R B R G B R B
  G G B R G G
   G R G B G
    B B R R
     B G R
      R B
       G
You will be given the first row of the triangle as a string and its your job to return the final colour which would appear in the bottom row as a string. In the case of the example above, you would the given 'RRGBRGBB' you should return 'G'.

The input string will only contain the uppercase letters 'B', 'G' or 'R' and there will be at least one letter so you do not have to test for invalid input.
If you are only given one colour as the input, return that colour.

3 comments:

  1. def triangle(row):
    output = row
    while len(output) > 1:
    inter_val = ''
    for i in range(len(output)):
    if i+1 != len(output):
    if output[i] == output[i+1]:
    inter_val += output[i]
    else:
    inter_val += list(set('RGB') - set(output[i]+output[i+1]))[0]
    output = inter_val
    return output

    ReplyDelete
  2. def triangle(row):
    color_combinations = {'GG':'G','BG':'R','RG':'B','BR':'G','GR':'B','RR':'R','BB':'B','RB':'G','GB':'R'}
    if len(row)>1:
    row = ''.join([color_combinations[row[i]+row[i+1]] for i in range(len(row)-1)])
    return triangle(row)
    else:
    return row
    print(triangle(input().upper()))

    ReplyDelete
  3. Good Question.

    s = "RRGBRGBB"
    print(" ".join(s))
    while len(s) > 1:
    s = s if len(s) < 2 else "".join(["".join(set("RGB") - set(k) if len(set(k)) > 1 else set(k)) for k in
    ["".join([i, j]) for i, j in zip(s, s[1:])]])
    print(" ".join(s))

    ReplyDelete