perl logo Perl logo (Thanks to Olaf Alders)

The weekly challenge 356 - Task 1: Kolakoski Sequence

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-356/#TASK1
 3 #
 4 # Task 1: Kolakoski Sequence
 5 # ==========================
 6 #
 7 # You are given an integer, $int > 3.
 8 #
 9 # Write a script to generate the Kolakoski Sequence of given length $int and
10 # return the count of 1 in the generated sequence. Please follow the wikipedia
11 # page for more informations.
12 #
13 ## Example 1
14 ## Input: $int = 4
15 ## Output: 2
16 ##
17 ## (1)(22)(11)(2) => 1221
18 #
19 ## Example 2
20 ## Input: $int = 5
21 ## Output: 3
22 ##
23 ## (1)(22)(11)(2)(1) => 12211
24 #
25 ## Example 3
26 ## Input: $int = 6
27 ## Output: 3
28 ##
29 ## (1)(22)(11)(2)(1)(22) => 122112
30 #
31 ## Example 4
32 ## Input: $int = 7
33 ## Output: 4
34 ##
35 ## (1)(22)(11)(2)(1)(22)(1) => 1221121
36 #
37 ## Example 5
38 ## Input: $int = 8
39 ## Output: 4
40 ##
41 ## (1)(22)(11)(2)(1)(22)(1)(22) => 12211212
42 #
43 ############################################################
44 ##
45 ## discussion
46 ##
47 ############################################################
48 #
49 # Just implement the algorithm from
50 # https://en.wikipedia.org/wiki/Kolakoski_sequence#Algorithms
51 # and print the result.
52 #
53 use v5.36;
54 
55 kolakoski_sequence(4);
56 kolakoski_sequence(5);
57 kolakoski_sequence(6);
58 kolakoski_sequence(7);
59 kolakoski_sequence(8);
60 
61 sub kolakoski_sequence($int) {
62     say "Input: $int";
63     my @sequence = ();
64     my $next = 1;
65     my $how_many = 1;
66     my $ones_found = 0;
67     foreach my $i (1..$int) {
68         if($sequence[$i]) {
69             $how_many = $sequence[$i];
70             push @sequence, $next;
71             push @sequence, $next if $how_many == 2;
72         } else {
73             $how_many = $i;
74             push @sequence, $next;
75             push @sequence, $next if $how_many == 2;
76         }
77         $ones_found++ if $next == 1;
78         $next = $next == 1 ? 2 : 1;
79     }
80     say "Output: $ones_found";
81 }