aboutsummaryrefslogtreecommitdiff
path: root/challenge-051/markus-holzer/raku/ch-2.p6
blob: 2d4bf8049af10150e7cc8b5d683ee7d7370dc7f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use Terminal::ANSIColor;

sub MAIN( Int $from, Int $to, Bool :$show-all = False )
{

	print join ', ', gather for $from..$to -> $n 
	{
		my $is-colorful = is-colorful( $n );
		take colorize( $n, $is-colorful ) 
			if $is-colorful or $show-all;
	}
}

sub colorize( $n, $colorful )
{
	state @colors = <red green yellow blue magenta cyan>;
	my $color     = $colorful ?? @colors.pick !! 'white';
	color( $color ) ~ $n ~ color( 'reset' );
}

sub is-colorful( $n )
{
	my @digits = $n.comb;

	# save some work
	return False 
		if ( @digits.repeated )
		or ( $n > 1 && '1' (elem) @digits );

	my sub product( @n ) { [*] @n };

	not consecutive-combinations( @digits )
		.map({ .&product })
		.repeated
	;
}

sub consecutive-combinations( @n )
{
	my sub keys( @p )   { @p.map: *.key   }
	my sub values( @p ) { @p.map: *.value }

#       Pretty, but adhoc mixins are terribly sloooooow
#	my sub infix:<++>($a, $b)    { $b but ($a + 1 == $b) }; 
#	my sub are-consecutive( @n ) { so [++] @n }; 

#       Too much work
#	my sub are-consecutive( @n ) { 
#		not @n.rotor( 2 => -1 ).first( -> ($a, $b) { $a + 1 != $b }) }

	my sub are-consecutive( @n ) { not ( 1..@n.end ).first({ 
		@n[ $_ ] - @n[ $_ - 1 ] != 1 }) }; 

	@n
		.pairs
		.combinations( 1..* )
		.grep({ .&keys.&are-consecutive })
		.map({ .&values })
	;
}