in reply to Re: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
in thread LeetCode Problem #1 - Two Sum - Improve and/or discuss.

That's a fair enough comment: any order was specified in the problem spec. I added to @tests:

my @tests = ( [[2,7,11,15], 9, [0,1]], [[2,7,11,15], 9, [1,0]], [[3,2,4], 6, [1,2]], [[3,2,4], 6, [2,1]], [[3,3], 6, [0,1]], [[3,3], 6, [1,0]], );

Modified is_deeply:

for my $test (@tests) { is_deeply sort_arrayref(two_sum($test->[INPUT], $test->[TARGET])), sort_arrayref($test->[EXPECTED]); }

Appended a new subroutine:

sub sort_arrayref { my ($aref) = @_; return [ sort { $a <=> $b } @$aref ]; }

Output now:

1..6 ok 1 ok 2 ok 3 ok 4 ok 5 ok 6

— Ken

Replies are listed 'Best First'.
Re^3: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by LanX (Saint) on Jan 24, 2022 at 02:25 UTC
    not sure why you are duplicating the tests ... (?)

    one sort_arrayref(two_sum(...)) is enough if you only keep tests with already sorted expectations.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

      I'm not following your prosaic description here. Please post whatever parts of the code you'd write differently.

      — Ken

        What LanX is saying is : since you are now sorting the output of twosum as a part of your "is_deeply" compare, you no longer need to duplicate tests , and you can revert to your original set of tests that have the results in increasing-index order.

                        "If you had better tools, you could more effectively demonstrate your total incompetence."

        Hi Ken

        > Please post whatever parts of the code you'd write differently.

        my @tests = ( [[2,7,11,15], 9, [0,1]], [[3,2,4], 6, [1,2]], [[3,3], 6, [0,1]], ); for my $test (@tests) { is_deeply sort_arrayref(two_sum($test->[INPUT], $test->[TARGET])), $test->[EXPECTED]; } sub sort_arrayref { my ($aref) = @_; return [ sort { $a <=> $b } @$aref ]; }

        hope it's clearer now :)

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery