Coloured Triangle

A colored triangle is created from a row of colors ( B , G , or R ).

Successive rows, each containing one fewer color than the last, are generated by considering the two touching colors in the previous row. If these colors are identical, the same color is used in the new row; if they are different, the missing color is used in the new row.

This is continued until the final row with only a single color is generated, as illustrated below.

1
2
3
4
5
6
R R G B R G
 R B R G B
  G G B R
   G R G
    B B
     B 

What will be the last color with this 1000 color row?


Note: Want to try a much harder version of this problem? Check it out on CodeWars .

B G R

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

3 solutions

Antoine Crbs
Nov 16, 2018

Simple Python Solution :

1
2
3
def triangle(s):
    while len(s) > 1: s= ''.join(({'R', 'G', 'B'} - {a, b}).pop() if a != b else a for a, b in zip(s, s[1:]))
    return s

output: 'R'

java solution:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class ColoredTriangle {

    //replace lastRow value with first row.
    static String lastRow="RRGBRG";
    public static void main(String[] args) {
        StringBuilder nextRow = new StringBuilder();
        while(lastRow.length() > 1) {
            for(int i = 0; i < lastRow.length() - 1; i++) {
                nextRow.append(color(lastRow.charAt(i), lastRow.charAt(i+1)));

            }
            lastRow = nextRow.toString();
            nextRow = new StringBuilder();
        }
        System.out.println("lastRow is " + lastRow);
    }

    public static char color(char first, char second) {
        //if same - return the color. else, return the missing one.
        return first == second ? first : "RGB".replace(first, ' ').replace(second, ' ').trim().charAt(0);
    }

}

Python solution similar to @Antoine Crbs, but without zip:

1
2
3
4
5
colors = {'R', 'G', 'B'}
row = list(input())
while len(row) != 1:
    row = [(colors-{row[i], row[i+1]}).pop() if row[i] != row[i+1] else row[i] for i in range(len(row)-1)]
print(row[0]) 

2 pending reports

Vote up reports you agree with

×

Problem Loading...

Note Loading...

Set Loading...