Hacker News new | past | comments | ask | show | jobs | submit login

I challenge myself to do it in bash one liners. I came up with a clever and shockingly simple solution to part2 using expansion and substitution.

  cat 1.txt | sed -E 's/(one)/\11\1/g; s/(two)/\12\1/g; s/(three)/\13\1/g; s/(four)/\14\1/g; s/(five)/\15\1/g; s/(six)/\16\1/g; s/(seven)/\17\1/g; s/(eight)/\18\1/g; s/(nine)/\19\1/g;' | sed -e 's/[^0-9]//g' | awk '{print substr($0,1,1) substr($0,length,1)}' | tr '\n' '+' | sed 's/\(.*\)+/\1\n/' | bc



"I challenge myself to do it with bash one liners."

Is bash required.

For example, this also works in dash, NetBSD sh, pdksh, tcsh, etc.


does it deal with cases like "twone", "nineight" and so on? it doesn't appear so to me because of the leading sed statements would commit the interpretation regardless of what happens next, but perhaps there is something subtle im not seeing.


It uses capture groups and puts them back in the replacement (the \1 ), so a match of "one" is replaced with (thematch)1(thematch). So eightwo would replace the two with two2two and end up like eightwo2two, so then the t is preserved and eight is found in a later step and then you end up with eight8eightwo2two, and can solve that using part1 only looking for numbers.


I see. Thank you for the explanation. I didn't know about that feature of sed.


okay that's very clever


For my own I did the same, but without capture groups. So replaced "one" with "one1one" naively without regex and did that for all numbers.

While it maybe is post-hoc clever, I think most of us ended up there because we tried naively to just replace "one" with "1", which broke on things like twone. So when down that path one had to amend it instead of going somewhere else.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: