请在红宝石中使用我的“洗牌”代码(please help with my “shuffle” code in ruby)

编程入门 行业动态 更新时间:2024-10-10 19:16:35
请在红宝石中使用我的“洗牌”代码(please help with my “shuffle” code in ruby)

这是个问题

洗牌。 现在你已经完成了新的排序算法,相反呢? 编写一个采用数组并返回完全混洗版本的shuffle方法。 一如既往,你会想测试它,但测试这个更棘手:你如何测试以确保你获得完美的洗牌? 你甚至会说一个完美的洗牌会是什么? 现在测试它。

这是我的代码答案:

def shuffle arr x = arr.length while x != 0 new_arr = [] rand_arr = (rand(x)) x-- new_arr.push rand_arr arr.pop rand_arr end new_arr end puts (shuffle ([1,2,3]))

我的错误是什么? 为什么这个代码不工作?

this is the question

Shuffle. Now that you’ve finished your new sorting algorithm, how about the opposite? Write a shuffle method that takes an array and returns a totally shuffled version. As always, you’ll want to test it, but testing this one is trickier: How can you test to make sure you are getting a perfect shuffle? What would you even say a perfect shuffle would be? Now test for it.

This is my code answer:

def shuffle arr x = arr.length while x != 0 new_arr = [] rand_arr = (rand(x)) x-- new_arr.push rand_arr arr.pop rand_arr end new_arr end puts (shuffle ([1,2,3]))

What are my mistakes? Why doesn't this code work?

最满意答案

除了其他的小错误外,你似乎还不知道弹出和推送正在做什么(从数组末尾开始或添加一些项目)。

你可能正在尝试写下类似的东西。

def shuffle arr x = arr.length new_arr = [] while x != 0 randpos = rand(x) x = x-1 item = arr[randpos] new_arr.push item arr[randpos] = arr[x] arr.pop end new_arr end puts (shuffle ([1,2,3]))

Beside minor other errors you seems not to understand what pop and push are doing (taking or adding some items from the end of the array).

You are probably trying to write something like below.

def shuffle arr x = arr.length new_arr = [] while x != 0 randpos = rand(x) x = x-1 item = arr[randpos] new_arr.push item arr[randpos] = arr[x] arr.pop end new_arr end puts (shuffle ([1,2,3]))

更多推荐

本文发布于:2023-04-29 10:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1335621.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:请在   红宝石   代码   ruby   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!