问题描述
我的任务是想出一种编码字符串的方法.除其他事项外,我需要按给定数字移动每个字母,但转换后的字母必须是一个字母(循环移位).
I have been tasked with coming up with a way of encoding a string. Among other things, I need to shift each letter by a given number but the transformed letter must be a letter (circular shift).
到目前为止,我得到了以下代码:
I have got the following code so far:
def play_pass(str, n)
letters = ('a'..'z').to_a
str.chars.map {|x| letters.include?(x.downcase) ? (x.ord + n).chr : x}.join
end
这适用于大多数字母
我的问题是,如果我试图将 y
移动 2 个位置,我应该得到 a
而是得到字符 [
My problem is that if I am trying to shift y
by 2 places, I should get a
but instead I get the character [
我哪里出错了?
推荐答案
试试这个:
def play_pass(str, n)
letters = ('a'..'z').to_a
str.chars.map {|x| letters.include?(x.downcase) ?
letters[letters.find_index(x.down_case) + n - letters.size] : x}.join
end
p play_pass("abcdefghijklmnopqrstuvwxyz", 2)
输出
"cdefghijklmnopqrstuvwxyzab"
[Finished in 0.3s]
工作原理
letters
是 a
到 z
的字符数组,就像 OP 在他的代码中那样.我们遍历 str
中的所有字符,并在 letters
数组中找到它的索引.然后我们将 n
添加到该索引以获取移位的字符.为了避免从数组中脱落,我们减去 letters.size
(在本例中为 26
),以便我们对 letters
的查找使用0
和 25
之间的值.
letters
is an array of chars a
to z
just the way OP has in his code.We iterate over all chars in str
, and find its index in letters
array. Then we add n
to that index to get the shifted character. To avoid falling off the array, we subtract letters.size
(in this case 26
), so that the our lookup into letters
is done using value between 0
and 25
.
例如:在OP指出的场景中,如果要移位的字符是y
,那么,在letters
的索引上加2就会得到移位index 26
(24
是 letters
数组中 y
的索引,2
是数字我们在测试用例中移动的字符) - 为了使 letters
表现得像循环数组,并且不会遇到索引超出限制类型的异常,我们从 letters.size
中减去 letters.size
code>26 移位索引.因此,我们得到索引0
,它代表我们感兴趣的字符a
.
For example: In the scenario that OP pointed out, if the character to be shifted was y
, then, adding 2 to its index in letters
will give us shifted index 26
(24
is index of y
in letters
array, 2
is number characters we are shifting in the test case) - To make letters
behave like circular array, and not encounter index out of bound type of exception, we subtract letters.size
from 26
shifted index. Thus, we get index 0
, which represents char a
which is what we are interested in.
另一个例子是 a
的情况 - 这里的移位索引将是 0 + 2 = 2
.当我们从中减去 letters.size
时,我们得到 -24
.Ruby 允许负索引,其中数组元素的查找是从反向完成的,它将解析为正确的元素.索引-1
与索引(size-1)
相同,类似地,-size
的索引值等于索引0代码>.
Another example is case of a
- Here the shifted index will be 0 + 2 = 2
. When we subtract letters.size
from it, we get -24
. Ruby allows negative indexes wherein lookup of array element is done from reverse, and it will resolve to correct element. Index -1
is same as Index (size-1)
, similarly, index value of -size
is equal to index 0
.
这篇关于旋转字符串中的字母,使每个字母移动到另一个字母 n 位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!