Browsing reddit the other day, I discovered this thread about a programming puzzle on the Spotify jobs website. Doubt I'm qualified for a job at Spotify, but I like puzzles well enough. Here's my crack at a solution in Perl:
#!/usr/bin/env perl use strict; use warnings; use List::MoreUtils qw/uniq/; use feature qw/state say/; my $friend_id = 1009; my %seen; my @teams; my @reps; while (<>) { chomp; state $count = 0; if($count > 0) { my $pair = make_pair($_); $seen{$pair->[0]}++; $seen{$pair->[1]}++; push @teams, $pair } $count++; } LINE: for my $pair (@teams) { my ($first, $second) = ($pair->[0], $pair->[1]); if($seen{$first} >= 2) { push @reps, $first; next LINE; } elsif($seen{$second} >= 2) { push @reps, $second; next LINE; } else { $second == 1009 ? push @reps, $second : $first == 1009 ? push @reps, $first : push @reps, $first; } } my @result = uniq @reps; say scalar @result; say for @result; sub make_pair { ## Str -> ArrayRef my $s = shift; my @pair = split / /, $s; \@pair; }
Anyone have a better way to do it? I'm sure there's plenty of fat to be trimmed here. :-)
My next move is to write a small program that generates the desired input files so I can do some more thorough testing; just thought it'd be fun to get some feedback from other folks on my perling.
In reply to Perl Solution to Spotify Programming Puzzle by ::rml::
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |