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

nitpick:

I think

means you have to also allow the reverse order in your tests.

edit

this can be fixed by sorting the result first.

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

  • Comment on Re: LeetCode Problem #1 - Two Sum - Improve and/or discuss.

Replies are listed 'Best First'.
Re^2: LeetCode Problem #1 - Two Sum - Improve and/or discuss.
by kcott (Archbishop) on Jan 24, 2022 at 02:20 UTC

    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

      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