diff options
| author | Dave Jacoby <jacoby.david@gmail.com> | 2021-07-12 10:48:31 -0400 |
|---|---|---|
| committer | Dave Jacoby <jacoby.david@gmail.com> | 2021-07-12 10:48:31 -0400 |
| commit | 34a6514808c066bee4e7f3d7d8bdeb67db056392 (patch) | |
| tree | 05d0e268045ef3d6f971ec0e0c3eb1a48bdb7edd /challenge-113/stuart-little/lua/ch-2.lua | |
| parent | b59f8f4008bb8ec491a9e89f097f04ce54aed4c0 (diff) | |
| parent | 1aa7b6eaba2a58fc1ef0612373e3aed6b61f345d (diff) | |
| download | perlweeklychallenge-club-34a6514808c066bee4e7f3d7d8bdeb67db056392.tar.gz perlweeklychallenge-club-34a6514808c066bee4e7f3d7d8bdeb67db056392.tar.bz2 perlweeklychallenge-club-34a6514808c066bee4e7f3d7d8bdeb67db056392.zip | |
Merge branch 'master' of https://github.com/manwar/perlweeklychallenge-club
Diffstat (limited to 'challenge-113/stuart-little/lua/ch-2.lua')
| -rwxr-xr-x | challenge-113/stuart-little/lua/ch-2.lua | 49 |
1 files changed, 49 insertions, 0 deletions
diff --git a/challenge-113/stuart-little/lua/ch-2.lua b/challenge-113/stuart-little/lua/ch-2.lua new file mode 100755 index 0000000000..6a4f64e368 --- /dev/null +++ b/challenge-113/stuart-little/lua/ch-2.lua @@ -0,0 +1,49 @@ +#!/usr/bin/env lua + +require 'luarocks.loader' +local inspect = require 'inspect' + +sm=0 +for _,v in ipairs(arg) do + if v ~= "." then sm=sm+v end +end +for k,v in ipairs(arg) do + if v ~= "." then arg[k]=("%d"):format(sm-v) end +end + +function oneOver(t) + local count=0 + for k,v in ipairs(t) do + count = count + (v == "." and 1 or -1) + if count == 1 then return k end + end +end + +function strs2t(lst) + if lst[1] == "." then return end + local val=table.remove(lst,1) + local ix=oneOver(lst) + local llst = {table.unpack(lst,1,ix)} + local rlst = {table.unpack(lst,ix+1)} + return {{val},l=strs2t(llst),r=strs2t(rlst)} +end + +print(inspect(strs2t(arg))) + +--[[ +run <script> <tree in preorder form with '.' for empty nodes, entered as space-separated values> + +ref: https://stackoverflow.com/a/2676849/11064961 + +e.g. 1 2 4 . 7 . . . 3 5 . . 6 . . represents the tree + + 1 + / \ + 2 3 + / / \ + 4 5 6 + \ + 7 + +given as an example in the problem formulation at https://perlweeklychallenge.org/blog/perl-weekly-challenge-113/#TASK2 +--]] |
