如何在方程式中使用多个整数(Ruby)

时间:2018-07-20 15:19:35

标签: ruby binary

我编写了一个从二进制到整数的转换工具,但是它对数字的大小有限制。因此,我尝试为二进制代码编写公式。我想出了一个方程式,因此我尝试将其放入代码中。一切正常,除了将方程式应用于每个数字。这是我想出的方程式:

d代表整数
z代表任何(和每个)数字

d = z[2^(z-1)]

这是我到目前为止编写的代码:

answer = gets.chomp
n = answer.reverse # reverses the answer
y1 = answer.size # the amount of digits in the answer
x1 = answer
z = (1..y1).each { |z| puts z } # every number between 1 and number of digits
w = (1..1).each.to_a * y1.to_i #in case I need to multiply the entire array
s = x1 # [z] - 1 # any given digit minus one
v = 2 ** s.to_i # exponent
u = z.zip(w).map{|x, y| x * y} # an array: [1, 2, 3]
print u
t = u.to_i # Tried converting to integer
puts x1[t]

但是当我用数字1011运行该错误时,会出现此错误:

[1, 2, 3, 4]
undefined method `to_i' for [1, 2, 3, 4]:Array
Did you mean?  to_s
               to_a
               to_h
(repl):16:in `<main>'

我觉得我已经尝试了所有方法,但是如果您以某种方式找到将方程式应用于每个数字的方法,或者您想出了一个简单的方程式,请告诉我。

1 个答案:

答案 0 :(得分:1)

这将返回一个数组u = z.zip(w).map{|x, y| x * y},因此您正在尝试将数组转换为整数。如果需要,可以执行以下操作:

array = [1,0,1]     #your binary in array form
s = array.join('')  #transform it into string
s.to_i(2)           #this return the integer and result (2) represents base

Check this link

更好的是:array.join('').to_i(2)

相关问题