From d24bdea94e208042810202f4c7ac404ae820779e Mon Sep 17 00:00:00 2001 From: Abigail Date: Fri, 12 Feb 2021 20:20:13 +0100 Subject: Lua solution for week 4, part 2 --- challenge-004/abigail/README.md | 2 ++ challenge-004/abigail/lua/ch-2.lua | 51 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 challenge-004/abigail/lua/ch-2.lua diff --git a/challenge-004/abigail/README.md b/challenge-004/abigail/README.md index be970d21a6..b26977cfc3 100644 --- a/challenge-004/abigail/README.md +++ b/challenge-004/abigail/README.md @@ -47,4 +47,6 @@ The sets of letters are read from standard input. ### Solutions * [GNU AWK](awk/ch-2.gawk) * [Bash](bash/ch-2.sh) +* [C](c/ch-2.c) +* [Lua](lua/ch-2.lua) * [Perl](perl/ch-2.pl) diff --git a/challenge-004/abigail/lua/ch-2.lua b/challenge-004/abigail/lua/ch-2.lua new file mode 100644 index 0000000000..c1214ac67d --- /dev/null +++ b/challenge-004/abigail/lua/ch-2.lua @@ -0,0 +1,51 @@ +#!/opt/local/bin/lua + +-- +-- See ../README.md +-- + +-- +-- Run as: lua ch-2.lua -f FILE < input-file +-- + +-- +-- Parse option, and exit if incorrect +-- + +local filename = "" +if #arg == 2 and arg [1] == "-f" +then filename = arg [2] +end + +if file == "" +then io . stderr : write ("Requires a '-f FILE' option\n") + os . exit (1) + end + +-- +-- Given a file name, and a set of letters, print +-- the words from the file which can be made with the letters. +-- +function extract_words (filename, letters) + for word in io . lines (filename) do + copy = word : gsub ("\n", "") : lower () + for i = 1, letters : len () do + -- + -- Remove each of the characters of 'letters' from + -- 'copy', after lowercasing, and only once. + -- + copy = copy : gsub (letters : sub (i, i) : lower (), "", 1) + end + -- + -- If we end up with the empty string, we have a winner. + -- + if (copy : len () == 0) + then + print (word) + end + end +end + +for line in io . lines () do + extract_words (filename, line : gsub ("\n", "")) +end -- cgit