diff options
| author | 冯昶 <fengchang@novel-supertv.com> | 2022-12-21 09:57:58 +0800 |
|---|---|---|
| committer | 冯昶 <fengchang@novel-supertv.com> | 2022-12-21 09:57:58 +0800 |
| commit | dd2a89a7880a924c4e3df167d71c34b4ed89a3fe (patch) | |
| tree | b208bd6dc97a7b4f025f62c78401dae7a796362c /challenge-195/deadmarshal/lua/ch-2.lua | |
| parent | 7de47c639d3bc4fef60d8df2128c14049f47b1fd (diff) | |
| parent | d05040719c41d928cb4663bac89448f14fd74268 (diff) | |
| download | perlweeklychallenge-club-dd2a89a7880a924c4e3df167d71c34b4ed89a3fe.tar.gz perlweeklychallenge-club-dd2a89a7880a924c4e3df167d71c34b4ed89a3fe.tar.bz2 perlweeklychallenge-club-dd2a89a7880a924c4e3df167d71c34b4ed89a3fe.zip | |
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'challenge-195/deadmarshal/lua/ch-2.lua')
| -rw-r--r-- | challenge-195/deadmarshal/lua/ch-2.lua | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/challenge-195/deadmarshal/lua/ch-2.lua b/challenge-195/deadmarshal/lua/ch-2.lua new file mode 100644 index 0000000000..94a2ee7c4a --- /dev/null +++ b/challenge-195/deadmarshal/lua/ch-2.lua @@ -0,0 +1,38 @@ +#!/usr/bin/env lua +-- luarocks install stdlib +local std = require'std' + +local function is_uniq(t) + for i=1, #t do + for j=i+1, #t do + if t[i] == t[j] then return false end + end + end + return true +end + +local function most_frequent_even(t) + if #std.functional.filter(std.functional.lambda('|e| e % 2 ~= 0'), + std.elems,t) == #t then + return -1 + end + t = std.functional.filter(std.functional.lambda('|e| e % 2 == 0'), + std.elems,t) + local hash = {} + setmetatable(hash,{__index = function(t,k) return 0 end}) + for i=1,#t do hash[t[i]] = hash[t[i]] + 1 end + if is_uniq(std.table.values(hash)) then + return math.min(std.table.unpack(std.table.keys(hash))) + end + local sorted = std.table.okeys(hash) + for i=1,#sorted-1 do + if hash[sorted[i]] == hash[sorted[i+1]] then + return sorted[i] + end + end +end + +print(most_frequent_even({1,1,2,6,2})) +print(most_frequent_even({1,3,5,7})) +print(most_frequent_even({6,4,4,6,1})) + |
