Coding Games Chuck Norris Lua实现

字符串转Chuck Norris code

规则:

把字符串转ASCII码

ASCII码转7bit 二进制,

二进制转Chuck Norris

ps:代码写的不好,欢迎大佬批评指正

 

-- Auto-generated code below aims at helping you parse
-- the standard input according to the problem statement.

MESSAGE = io.read()

-- Write an action using print()
-- To debug: io.stderr:write("Debug message\n")
function int2bit(num)
  --创建一个长度为7的表,用来存7个bit位
  --初始化为 0000000
  local bit = {}
  for i = 1,7 do
    bit[i] = "0"
  end
  local index = 1

  function convert(x)
    --用除2的方式计算二进制
    a = math.floor(x/2)
    b = x%2
    bit[index] = tostring(b)
    index = index + 1
    if a ~= 1 and a ~= 0 then
      return a
    else
      bit[index] = tostring(a)
      return 0
    end
  end
  while num ~= 0 do
    num = convert(num)
  end
  --翻转一下,才是正确的二进制bit
  local _Bit = {}
  for i = #bit,1,-1 do
    _Bit[#_Bit+1] = bit[i]
  end
  return _Bit
end

function str2bit_s(str)
  --将字符串ACSII码转成bit串
  local _bit_str = ""
  for i = 1,#str do
    local bit_T
    bit_T = int2bit(string.byte(str,i))
    for i = 1,#bit_T do
      _bit_str = _bit_str..tostring(bit_T[i])
    end
  end
  -- print(_bit_str)
  return _bit_str
end

function cut_str(str)
  --bit串0和1之间插入一个字母"a",分割子串用
  local t = {}
  for i = 1, #str do
    local s = string.sub(str,i,i)
    local s_next = i < #str and string.sub(str,i+1,i+1) or "a"
    t[#t+1] = s
    if tonumber(s) ~= tonumber(s_next) then
      t[#t+1] = "a"
    end
  end
  local _str = ""
  for i = 1, #t do
    _str = _str..tostring(t[i])
  end
  _last_str = ""
  local function setChuckNorris(str)
  --根据子串内容和长度拼成新的要求串
    local s = ""
      if string.sub(str,1,1) == "1" then
          s = " 0 "
      else
          s = " 00 "
      end
      for i = 1,string.len(str) do
          s = s.."0"
      end
      _last_str = _last_str..s
  end
  --string.gmatch %d+ 会把不相邻的数字分割成单独的子串

  for word in string.gmatch(_str, "%d+") do
   	setChuckNorris(word)
  end
  --因为拼串方法,串首多出一个空格,所以返回从2到串尾
  return string.sub(_last_str,2,-1)
end

str = MESSAGE

ChuckNorris_str = cut_str(str2bit_s(str))
print(ChuckNorris_str)

原创内容,转载请注明出处

点赞
  1. 1163848899说道:

    博客还真是个好东西!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Are you human? Click the Apple...