in reply to Better way of writing "find the missing number(s)"

Hi pritesh_ugrankar.

A hash is usually the best-suited tool for finding out whether elements in one list are in another. Add a key to the hash for each element in the list you are checking, then see if a key exists for each element in the list to be matched.

use strict; use warnings; use feature 'say'; my @x = ( -2, 2, 3, 8, 10 ); my %y = map { $_ => 1 } @x; say "missing: $_" for grep { not exists $y{ $_ } } ( -2 .. 10 );
perl 1186862.pl missing: -1 missing: 0 missing: 1 missing: 4 missing: 5 missing: 6 missing: 7 missing: 9

Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Better way of writing "find the missing number(s)"
by stevieb (Canon) on Apr 03, 2017 at 22:20 UTC

    Hey Nick,

    I had only a few minutes to play with this when it first came up, but I couldn't accomplish what I wanted with the time I had. What I did have was very similar. That said, you've hard-coded your array when doing the grep(), which probably isn't realistic in production, and it's a bit outside of what OP was after. To do it out of order and without hardcoding, an extra sort needs to be put in place. It could be done inline, but this makes it a bit more clear I think:

    use strict; use warnings; use feature 'say'; my @x = ( -2, 3, 2, 10, 15, 8 ); my %y = map { $_ => 1 } @x; @x = sort {$a <=> $b} @x; say "missing: $_" for grep { ! exists $y{$_} } $x[0] .. $x[-1];
Re^2: Better way of writing "find the missing number(s)"
by pritesh_ugrankar (Monk) on Apr 03, 2017 at 18:37 UTC

    Hi,

    Wow. This is going to take some time to understand. But I'll take it one line at a time. :) Thank you very much for sharing your method.

    Thinkpad T430 with Ubuntu 16.04.2 running perl 5.24.1 thanks to plenv!!

      You are welcome. Hint: to understand a statement with map and/or grep, read it from right to left.


      The way forward always starts with a minimal test.