#Lua Programming# Chap10. Comprehensive Example(종합 예제)

--1. The Eight-Queen Problem--
--[[---------------------------------------------
설명 : 체스판에 있는 8개의 여왕말을 서로 공격할 수 없는 위치로 배치한다.
한 행
--]]---------------------------------------------

--2. 가장 많이 나오는 단어 찾기(단어가 나오는 횟수를 반환)--
--[[------------------------------------------
<설명>
텍스트를 읽어서 단어마다 나온 횟수를 센다.
단어 리스트를 빈도가 높은 순으로 정렬한다.
정렬한 리스트에서 n번째까지의 원소를 출력한다.
프로그램 정지 누를시 그 결과를 반환한다.
--]]------------------------------------------
local function CallAllWords()
  local function allwords()
    local auxwords = function()
      for line in io.lines() do
        for word in string.gmatch(line,"%w+") do
          coroutine.yield(word)
        end
      end
    end
    return coroutine.wrap(auxwords)
  end
 
  local counter = {}
  for w in allwords() do
    counter[w] = (counter[w] or 0) + 1
  end
 
  local words = {}
  for w in pairs(counter) do
    words[#words + 1] = w
  end
 
  table.sort(words, function(w1, w2)
    return counter[w1] > counter[w2] or
      counter[w1] == counter[w2] and w1 < w2
  end)
 
  for i = 1, (tonumber(arg[1]) or 10) do
    print(words[i], counter[words[i]])
  end
end
CallAllWords()

#Lua Programming# Chap10. Comprehensive Example(종합 예제) #Lua Programming# Chap10. Comprehensive Example(종합 예제) Reviewed by kukanuc on 4월 16, 2019 Rating: 5

댓글 없음:

Powered by Blogger.