aboutsummaryrefslogtreecommitdiff
path: root/challenge-055/arne-sommer/raku/flip-binary
blob: 8a37bee01e35c558df1874ead139da8d7e6d0b08 (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
#! /usr/bin/env raku

# subset Binary of Int where * ~~ /^<[01]>*$/;
subset Binary where * ~~ /^<[01]>*$/;

unit sub MAIN (Binary $binary, :$verbose);

my $size = $binary.chars;
my %result;

say ": Binary number $binary with length $size" if $verbose;

for ^$size -> $l
{
  for $l .. $size-1 -> $r
  {
    my $new   = flip-binary($binary, $l, $r);
    my $count = count-ones($new);

    %result{$count}.push("L=$l, R=$r -> $new");
    say ": $binary + L:$l R:$r -> $new C:$count" if $verbose;
  }
}

say ": Hash: { %result.raku }" if $verbose;

my $answer = %result.keys.max;

say "The highest number of ones: $answer";

.say for @(%result{$answer});

sub flip-binary (Binary $number is copy, $l, $r)
{
  for $l .. $r -> $index
  {
    $number.substr-rw($index,1) = $number.substr($index,1) eq "1" ?? "0"!! "1";
  }
  return $number;
}

sub count-ones (Binary $number)
{
  return $number.comb.grep( * == "1" ).elems;
}