diff options
| author | Mohammad Sajid Anwar <Mohammad.Anwar@yahoo.com> | 2024-05-28 10:40:04 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2024-05-28 10:40:04 +0100 |
| commit | 9d9ab993cf4822e4c5210eae0552cec775c48ef5 (patch) | |
| tree | 6b55e2cfa652535ce8246a9874bb87ce01ac5245 /challenge-271/deadmarshal/lua/ch-2.lua | |
| parent | e6ae176ee1951c5871249e0e0c4f1a6f6e5d95af (diff) | |
| parent | a41401173d5365ab6bd76f07bbcd81c3198301a4 (diff) | |
| download | perlweeklychallenge-club-9d9ab993cf4822e4c5210eae0552cec775c48ef5.tar.gz perlweeklychallenge-club-9d9ab993cf4822e4c5210eae0552cec775c48ef5.tar.bz2 perlweeklychallenge-club-9d9ab993cf4822e4c5210eae0552cec775c48ef5.zip | |
Merge pull request #10173 from deadmarshal/TWC271
TWC271
Diffstat (limited to 'challenge-271/deadmarshal/lua/ch-2.lua')
| -rw-r--r-- | challenge-271/deadmarshal/lua/ch-2.lua | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/challenge-271/deadmarshal/lua/ch-2.lua b/challenge-271/deadmarshal/lua/ch-2.lua new file mode 100644 index 0000000000..ee051c1084 --- /dev/null +++ b/challenge-271/deadmarshal/lua/ch-2.lua @@ -0,0 +1,32 @@ +#!/usr/bin/env lua + +local function decimal_to_binary(n) + assert(type(n) == 'number','n must be a number!') + local bin = "" + while n > 0 do + bin = (n % 2) .. bin + n = n // 2 + end + return bin +end + +local function pop_count(n) + assert(type(n) == 'number','n must be a number!') + local bin, count = decimal_to_binary(n),0 + for pos=1,#bin do + if bin:sub(pos,pos) == "1" then count = count + 1 end + end + return count +end + +local function sort_by_one_bits(t) + assert(type(t) == 'table','t must be a table!') + table.sort(t,function(a,b) + local pa,pb = pop_count(a),pop_count(b) + return pa == pb and a < b or pa < pb end) + return t +end + +print(table.unpack(sort_by_one_bits{0,1,2,3,4,5,6,7,8})) +print(table.unpack(sort_by_one_bits{1024,512,256,128,64})) + |
