gpt4 book ai didi

Ruby - App Academy 关于 While 循环中条件的练习

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:28 26 4
gpt4 key购买 nike

我正在完成 App Academy's practice problems对于第一个编码挑战,并对为 #8 nearby az 提供的解决方案有疑问:

# Write a method that takes a string in and returns true if the letter
# "z" appears within three letters **after** an "a". You may assume
# that the string contains only lowercase letters.
#
# Difficulty: medium.

def nearby_az(string)
idx1 = 0
while idx1 < string.length
if string[idx1] != "a"
idx1 += 1
next
end

idx2 = idx1 + 1
while (idx2 < string.length) && (idx2 <= idx1 + 3)
if string[idx2] == "z"
return true
end

idx2 += 1
end

idx1 += 1
end

return false
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts("\nTests for #nearby_az")
puts("===============================================")
puts('nearby_az("baz") == true: ' + (nearby_az('baz') == true).to_s)
puts('nearby_az("abz") == true: ' + (nearby_az('abz') == true).to_s)
puts('nearby_az("abcz") == true: ' + (nearby_az('abcz') == true).to_s)
puts('nearby_az("a") == false: ' + (nearby_az('a') == false).to_s)
puts('nearby_az("z") == false: ' + (nearby_az('z') == false).to_s)
puts('nearby_az("za") == false: ' + (nearby_az('za') == false).to_s)
puts("===============================================")

在第二个 while 循环中:

 while (idx2 < string.length) && (idx2 <= idx1 + 3)

为什么条件是(idx2 < string.length)必要的?我在没有它的情况下测试了代码并得到了相同的结果。

感谢您的协助。

最佳答案

why is the condition (idx2 < string.length) necessary?

这不是必需的。当 idx2 超出字符串的边界时,它可以防止循环的无意义迭代。

寻址超出字符串长度的字符将返回 nil。 nil永远不会等于 'z' .所以我们不妨在到达终点时就停下来。这就是检查的目的,优化。

在其他情况下,越界访问通常是一种严重的违规行为,会导致各种问题(通常是崩溃)。因此,始终这样做是有意义的。

关于Ruby - App Academy 关于 While 循环中条件的练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com