4 ms·
Hot take: The optimal solution is the most obvious one for people who are more used to UNIX commands than programming languages, because the primitives in UNIX
by rakoo 3y ago
Hot take: The optimal solution is the most obvious one for people who are more used to UNIX commands than programming languages, because the primitives in UNIX are more powerful (they give you a beautiful solution if you can make your problem fit in them; if not, the shell becomes atrocious).
Here's my reasoning for the problem: we have 2 files, one for each day, and we want to see who came both days on different pages. That's a job for join, with some sort|uniq in the middle.
- for each page, we want unique CustomerId -> PageId "mappings", but in UNIX land that's just 2 columns on the same row:
cat dayX | awk '{print $3 $2}' | sort | uniq
- now I have two lists, I join them
join day1_uniq day2_uniq
this gives me, for each customer, its id, then all its pages, on the same line. Customers who came only on one day are not in the output.
- now I want to see if there are at least 2 pages and those 2 pages are different. There's no easy UNIX way to do this because it's all on a single line, so we'll use awk to build a hashmap. We don't need to build a map of all pages, we only need to see if there are at least 2 different pages
cat both_days | awk '{for (i = 1; i < NF; i++) {pages[$i] = 1; if (length(pages) == 2) {print; next}} }'
(Note: length() is not posix but gawk)
Result: a list of all customers having visited at least 2 different pages on both days. Everything is dominated by the initial sort. I haven't ran this, it's a rough draft.