-2

试图在 ruby​​ 中转换这个要点,这是我的代码:

$char_map = ('!.' + '0123456789' + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz').scan(/./)
$int_map  = Hash.new
$char_map.each_with_index {|v,k| $int_map[v] = k }
$cutoff = ($char_map.count) - 11

# Converts an integer to its text-encoded form.
def to_chars(value)

  if value < $cutoff
    return $char_map[value]
  end
  value -= $cutoff
  out = []
  while value != 0
    value, rem = value.divmod($char_map.count)
    out.push($char_map[rem])
  end
  # handle when value == cutoff
  if !out
    out.push($char_map[value])
  end
  out.push($char_map[$cutoff + out.count - 1])
  out.reverse!
  return out.join('')

end


# Converts characters from the provided string back into their integer
# representation, and returns both the desired integer as well as the number
# of bytes consumed from the character string (this function can accept a
# string that is the result of a concatenation of results from to_chars() ).
def to_val(chars)

  chars = chars.scan(/./)
  first = $int_map[chars[0]]
  if first < $cutoff
    return first, 1
  end
  first -= $cutoff - 1
  dec = []
  for ch in chars[1..1+first] do
    dec.push($int_map[ch])
  end
  value = dec.pop() + $cutoff
  m = $char_map.count

  while dec != []
    value += m * dec.pop()
    m *= $char_map.count
  end
  return value, first + 1

end

# Converts a sequence of integers into a string that represents those
# integers.
def from_sequence(lst)
  lst.map! {|int| to_chars(int)}
  return lst.join('')
end
# Converts a string that rappresents a sequence of integers back into a 
# a list of integers
def from_string(str)
  out = []
  i = 0
  while i < str.length
      this, used = to_val(str[i, str.length - i])
    out.push(this)
    i += used
  end
  return out
end

p to_chars(123456789)
p to_val(to_chars(123456789))
p from_string(from_sequence([123456789,4688]))

(对不起全局变量等......仅用于测试,当作品适合自己的班级时)

错误在最后一行,而不是打印回[123456789, 4688]数组打印[7901231212, 4688]

为什么?错误在哪里?

4

1 回答 1

2

您将编码文本长度存储在最后一个字符中(反转时,它成为第一个字符),因此在您的to_var方法中,first将编码文本长度存储在first -= $cutoff - 1. 但是,通过迭代chars[1..1+first],您实际上访问了first + 1字符。您应该在此处使用独占范围:chars[1...1+first]chars[1..first]

此外,ruby 将空数组视为true值,只有falsenil被视为false。因此,在您的to_chars方法中,条件if !out将永远不会满足,因为您已将数组分配给out. 你应该if out.empty?在这里使用。

不知道是否还有其他错误。

于 2013-06-18T11:55:02.030 回答