aboutsummaryrefslogtreecommitdiff
path: root/challenge-197/athanasius/raku/ch-2.raku
blob: ef2ad78ec8d7b0c4685469389af6ab57ae796d40 (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
use v6d;

###############################################################################
=begin comment

Perl Weekly Challenge 197
=========================

TASK #2
-------
*Wiggle Sort*

Submitted by: Mohammad S Anwar

You are given a list of integers, @list.

Write a script to perform Wiggle Sort on the given list.


    Wiggle sort would be such as list[0] < list[1] > list[2] < list[3]….


Example 1

  Input: @list = (1,5,1,1,6,4)
  Output: (1,6,1,5,1,4)

Example 2

  Input: @list = (1,3,2,2,3,1)
  Output: (2,3,1,3,1,2)

=end comment
###############################################################################

#--------------------------------------#
# Copyright © 2023 PerlMonk Athanasius #
#--------------------------------------#

#==============================================================================
=begin comment

Interface
---------
1. If no command-line arguments are given, the test suite is run.
2. If the first argument is negative, it must be preceded by "--" to distin-
   guish it from a command-line flag.

Notes
-----
1. 'Wiggle sort' is also known as 'wave sort'.
2. If no solution is possible for a given input, the output is '()', which
   represents the empty list.
3. The solution algorithm is described in [1].
4. The algorithm for determining whether a given input list is wiggle-sortable
   (by counting "medians") is given in [1], corrected in [2].

References
----------
[1] John L., Answer to "How to wiggle sort an array in linear time complex-
    ity?", Computer Science Stack Exchange (8 May, 2020), https://cs.stack
    exchange.com/questions/125372/how-to-wiggle-sort-an-array-in-linear-time-
    complexity

[2] John L, Answer to "How to find wiggle sortable arrays? Did I misunderstand
    John L.s' answer?" Computer Science Stack Exchange (25 April, 2022),
    https://cs.stackexchange.com/questions/150886/how-to-find-wiggle-sortable-
    arrays-did-i-misunderstand-john-l-s-answer

=end comment
#==============================================================================

use Test;

my UInt constant $TEST-FIELDS = 3;

#------------------------------------------------------------------------------
BEGIN
#------------------------------------------------------------------------------
{
    "\nChallenge 197, Task #2: Wiggle Sort (Raku)\n".put;
}

#==============================================================================
multi sub MAIN
(
    #| A list of 1 or more integers

    *@list where { .elems >= 1 && .all ~~ Int:D }
)
#==============================================================================
{
    "Input:  \@list = (%s)\n".printf:              @list  .join: ', ';

    "Output:         (%s)\n" .printf: wiggle-sort( @list ).join: ', ';
}

#==============================================================================
multi sub MAIN()                                           # Run the test suite
#==============================================================================
{
    run-tests();
}

#------------------------------------------------------------------------------
sub wiggle-sort( List:D[Int:D] $list --> List:D[Int:D] )
#------------------------------------------------------------------------------
{
    my Int @list = @$list;
    my Int @sorted;

    if is-wiggle-sortable( @list )
    {
        @list.=sort;

        my UInt $max-i = @list.end;

        for 1 .. $max-i -> UInt $i
        {
            next  if $i %% 2;
            @sorted[ $i ] = @list.pop;
        }

        for 0 .. $max-i -> UInt $j
        {
            next  if $j % 2 == 1;
            @sorted[ $j ] = @list.pop;
        }

        is-wiggle-sorted( @sorted ) or die 'Wiggle sort failed';
    }

    return @sorted;
}

#------------------------------------------------------------------------------
sub is-wiggle-sortable( List:D[Int:D] $list --> Bool:D )
#------------------------------------------------------------------------------
{
    # Count "medians" (see [1] as corrected in [2])

    my Int  @sorted = $list.sort;               # 1. Sort the list
    my UInt $n      = @sorted.elems;            # 2. Find m, the ⌈n/2⌉-th entry
    my UInt $n2     = ($n / 2).ceiling;
    my Int  $m      = @sorted[ $n2 - 1 ];
    my UInt $count  = 0;                        # 3. Count entries equal to m
    $_ == $m && ++$count for @sorted;

    # 4. "The number of medians of A is no more than ⌈n/2⌉. Furthermore, if n
    #     is odd and the number of medians is ⌈n/2⌉, the median must be the
    #     smallest number of A." -- [2], with typo corrected

    return ($count > $n2) ?? False !!
           ($count < $n2) ?? True  !!
           ($n % 2 == 1)  ?? ($m == @sorted[ 0 ]) !! True;
}

#------------------------------------------------------------------------------
sub is-wiggle-sorted( List:D[Int:D] $list --> Bool:D )
#------------------------------------------------------------------------------
{
    for 0 .. $list.end - 1 -> UInt $i
    {
        if $i %% 2
        {
            return False unless $list[ $i ] < $list[ $i + 1 ];
        }
        else
        {
            return False unless $list[ $i ] > $list[ $i + 1 ];
        }
    }

    return True;
}

#------------------------------------------------------------------------------
sub run-tests()
#------------------------------------------------------------------------------
{
    'Running the test suite'.put;

    for test-data.lines -> Str $line
    {
        my Str ($test-name, $input, $expected) =
            $line.split: / \| /, $TEST-FIELDS;

        s/ ^ \s* (.+?) \s* $ /$0/                             # Trim whitespace
            for $test-name, $input, $expected;

        my Int @list   = $input.split( / \, /, :skip-empty ).map: { .Int };
        my Int @sorted = wiggle-sort( @list );
        my Str $got    = @sorted.join: ',';

        ok( is-wiggle-sorted( @sorted ), $test-name ) if $expected;
        is $got, $expected, $test-name;
    }

    done-testing;
}

#------------------------------------------------------------------------------
sub error( Str:D $message )
#------------------------------------------------------------------------------
{
    "ERROR: $message".put;

    USAGE();

    exit 0;
}

#------------------------------------------------------------------------------
sub USAGE()
#------------------------------------------------------------------------------
{
    my Str $usage = $*USAGE;

    $usage ~~ s:g/ ($*PROGRAM-NAME) /raku $0/;

    $usage.put;
}

#------------------------------------------------------------------------------
sub test-data( --> Str:D )
#------------------------------------------------------------------------------
{
    return q:to/END/;
        Example 1   |1,5,1,1,6,4|1,6,1,5,1,4
        Example 2   |1,3,2,2,3,1|2,3,1,3,1,2
        Short       |2,1,1      |1,2,1
        Not sortable|1,2,2      |
        Distinct    |5,4,3,2,1,0|2,5,1,4,0,3
        Single      |42         |42
        Negatives   |-1,-2,-3,-4|-3,-1,-4,-2
        END
}

###############################################################################