95 lines
2.1 KiB
Lua
95 lines
2.1 KiB
Lua
require "llib"
|
|
|
|
local inp = llib.io.readfile("7.input")
|
|
|
|
local lines = {}
|
|
for s in inp:gmatch("[^\r\n]+") do
|
|
table.insert(lines, s)
|
|
end
|
|
|
|
local function index(t,c)
|
|
for i=1,#t do
|
|
if t[i] == c then return i end
|
|
end
|
|
return -1
|
|
end
|
|
|
|
local function get_type(card)
|
|
local matching = {}
|
|
local matching_count = {}
|
|
for i=1,string.len(card) do
|
|
local char = string.sub(card,i,i)
|
|
if index(matching,char) == -1 then
|
|
table.insert(matching,char)
|
|
table.insert(matching_count,1)
|
|
else
|
|
local ind = index(matching,char)
|
|
matching_count[ind] = matching_count[ind] + 1
|
|
end
|
|
end
|
|
|
|
if #matching == 1 then
|
|
return 7
|
|
elseif #matching == 2 then
|
|
--4 of a kind or full house
|
|
if matching_count[1] > 1 and matching_count[2] > 1 then
|
|
return 5
|
|
end
|
|
return 6
|
|
elseif #matching == 3 then
|
|
--3 of a kind or two pair
|
|
if matching_count[1] == 3 or matching_count[2] == 3 or matching_count[3] == 3 then
|
|
return 4
|
|
end
|
|
return 3
|
|
elseif #matching == 4 then
|
|
return 2
|
|
end
|
|
|
|
return 1
|
|
end
|
|
|
|
local card_value = {"2","3","4","5","6","7","8","9","T","J","Q","K","A"};
|
|
|
|
local function is_better_card(A,B)
|
|
for i = 1,string.len(A) do
|
|
local v1 = index(card_value,string.sub(A,i,i))
|
|
local v2 = index(card_value,string.sub(B,i,i))
|
|
if v1 > v2 then return true
|
|
elseif v2 > v1 then return false end
|
|
end
|
|
end
|
|
|
|
local hands_btype = {}
|
|
for i=1,#lines do
|
|
local hand = string.sub(lines[i],1,5)
|
|
local bet = string.sub(lines[i],6)
|
|
local type = get_type(hand)
|
|
if hands_btype[type] == nil then
|
|
hands_btype[type] = {{hand=hand,bet=bet}}
|
|
else
|
|
for i=1,#hands_btype[type] do
|
|
local op_card = hands_btype[type][i].hand
|
|
if is_better_card(op_card, hand) then
|
|
table.insert(hands_btype[type], i, {hand=hand,bet=bet})
|
|
break
|
|
end
|
|
if i == #hands_btype[type] then
|
|
table.insert(hands_btype[type], {hand=hand,bet=bet})
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
local rank = 1
|
|
local total = 0
|
|
for f=1,15 do
|
|
if hands_btype[f] ~= nil then
|
|
for i=1,#hands_btype[f] do
|
|
total = total + (rank * hands_btype[f][i].bet)
|
|
rank = rank + 1
|
|
end
|
|
end
|
|
end
|
|
print(total)
|