aboutsummaryrefslogtreecommitdiff
path: root/challenge-071/arne-sommer/raku/tll-class-wrong
blob: 019fb1f19ba05473b6ede2ba1f5bc4f3133abaa7 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#! /usr/bin/env raku

subset PosInt of Int where * >= 1;

unit sub MAIN (PosInt $N, :$v, :$verbose = :$v);

class LinkedElement
{
  has $.value;
  has $.next  is rw;

  method print-list
  {
    print self.value;
    if self.next
    {
      print " -> ";
      self.next.print-list;
    }
    else
    {
      print "\n";
    }
  }

  method list-length
  {
    my $length = 1;

    my $current = self.next;

    while ($current)
    {
      $current = $current.next;
      $length++;
    }
    return $length;
  }

  method remove-from-end($from-the-end)
  {
    my $length = self.list-length;

    if $length == 1
    {
       die "[]";
    }
    elsif $from-the-end > $length
    {
      self = self.next;
    }
    else
    {
      my $current = self;

      for 1 .. ($length - $from-the-end -1)
      {
        $current = $current.next;
      }
    
      $current.next = $current.next.next;
    }
  }
}



my $length = (1..50).pick;

my $head;
my $current;

for 1..$length -> $value
{
  my $new = LinkedElement.new(value => $value);

  if $current
  {
    $current.next = $new;
    $current = $current.next;
  }
  else # Initially
  {
    $head = $new;
    $current = $head;
  }
}

$head.print-list;

say "Length: ", $head.list-length if $verbose;

$head.remove-from-end($N);

$head.print-list;