功能需要帮助 [英] help needed with function

查看:64
本文介绍了功能需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我正在尝试完成以下功能:


/ *测试是否所有球选择匹配以相同顺序绘制的所有球


该函数有两个参数:

一组绘制的球

一个数组选定的球。


功能代码将一个阵列中的每个球与另一个阵列中相同位置的球进行比较。


函数返回:

如果数组包含相同顺序的相同数字,则为true

否则为false。

* /


我写的代码是

展开 | 选择 | 换行 | 行号

解决方案

最好的事情就是在循环中使用一个变量。然后在循环完成后返回变量。所以逻辑就像这样流动。首先将变量设置为false。如果匹配,则循环遍历数组设置变量为true。如果drawnBalls中的所有元素都等于selectBalls中的所有元素。然后变量将保持为真。如果任何元素不匹配,则设置为false,并将for index设置为最后一个值。这是因为如果一个元素drawnBalls不等于selectBalls那么数组是相同的并且你返回false。类似于以下内容。

展开 | 选择 | Wrap | 行号


虽然这个想法是正确的,但代码肯定可以优化。不需要变量。如果存在不匹配,则返回false。如果循环结束并且你仍然在函数中,这意味着所有值都匹配,所以在那一点返回true。


感谢您的回复,


我正在尝试修改我的代码以考虑这两个建议并提出:

展开 | 选择 | Wrap | 行号

Hi guys,

I''m trying to complete a function that does the following:

/* Tests if all balls selected match all balls drawn in the same order

The function takes two arguments:
an array of drawn balls
an array of selected balls.

The function code compares each ball in one array with the ball at the same position in the other array.

The function returns:
true if the arrays contain the same numbers in the same order
false otherwise.
*/

The code I have written is

Expand|Select|Wrap|Line Numbers

解决方案

The best thing to due is use a variable in the loop. Then after the loop is done then return the variable. So the logic flows like this. First set the variable to false. Then loop through array setting variable to true if you have a match. If all elements in drawnBalls equall all elements in selectBalls. Then the variable will remain true. if any element doesn''t match then set to false and break out of the for setting index to last value. This is due to the fact that if one element drawnBalls is not equal to selectBalls then the arrays are the same and you return false. Something like the following.

Expand|Select|Wrap|Line Numbers


Although the idea is correct, the code could definitely be optimised. There''s no need for a variable. If there is a non-match, just return false. If the loop ends and you''re still in the function, that means that all values match, so return true at that point.


Thanks for the reply both,

I''m trying to amend my code to take into account both suggestions and have come up with:

Expand|Select|Wrap|Line Numbers


这篇关于功能需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆