如何通过使用数组使这段代码更短

时间:2018-12-01 20:50:13

标签: java

如何使用npm install @angular/http来简化此代码?这是我在其中模拟彩票的较大代码的一部分。该特定部分是生成用户编号的地方,我似乎无法弄清楚如何将其变成Arrays

Array

5 个答案:

答案 0 :(得分:1)

如果它们需要唯一,则可以使用Set

Set<Integer> set = new HashSet<>();
while(set.size() < 6) {
    set.add(randomgen.nextInt(53) + 1);
}

或者Java 8+,您可以使用ints()方法来获取Stream并将其收集到Set

Random random = new Random();
Set<Integer> set = random.ints(0, 54)                          
                         .distinct().limit(6)
                         .boxed().collect(Collectors.toSet()); 

或者:

Set<Integer> set = random.ints(6, 1, 53).distinct().boxed().collect(Collectors.toSet());

示例输出:

48 3 41 25 11 31  

答案 1 :(得分:1)

仅使用数组的简单解决方案是:

id

答案 2 :(得分:1)

这是一个在很大程度上减少当前代码的解决方案:

local currentTouchPosition = vec2(touch.x,touch.y)

if (touch.state == BEGAN) then  end

if (touch.state == MOVING) then
    if  ((imagePosition.x - imageSize.x/2) < currentTouchPosition.x and
        (imagePosition.x  + imageSize.x/2) > currentTouchPosition.x and
        (imagePosition.y  - imageSize.y/2) < currentTouchPosition.y and
        (imagePosition.y  + imageSize.y/2) > currentTouchPosition.y)    then

        imagePosition = currentTouchPosition
    end
end       

if (touch.state == ENDED) then  end

如果要在打印后保留唯一的中奖号码,则可以执行以下操作:

String result = random.ints(6, 1, 54) // IntStream
                .distinct() // IntStream of distinct values
                .mapToObj(Integer::toString) // Stream<String>
                .collect(joining(" ", "Winning numbers: ", "")); // String
System.out.println(result);

答案 3 :(得分:0)

数组很适合这项工作,但是我认为集合是更好的选择,因为您想要唯一数字。您还应该使用for循环。您基本上是重复执行五次操作。

Set<Integer> winningNumbers = new HashSet<>();
for (int i = 0 ; i < 5 ; i++) {
    while (true)
    {
        int number = randomgen.nextInt(53) + 1;
        if (winningNumbers.add(number)) { // "add" returns false if the element already exists in the set
            break;
        }
    }
}
// printing the numbers:
System.out.println("Winning numbers: " + winningNumbers);

答案 4 :(得分:0)

由于域集只有53个元素,因此您可以选择以下方法:

public static void main(String[] args) {

        //populate 'box'
        //(you can do it only once in the static block)
        List<Integer> balls = new ArrayList<>();
        for (int i = 1; i <= 53 ; i++) {
            balls.add(i);
        }

        //shuffle the balls in the box
        Collections.shuffle(balls);

        //pick the first six elements
        List<Integer> userBalls = balls.subList(0, 6);

        //optionally you can sort the user balls
        userBalls.sort(Integer::compareTo);

        //print
        System.out.println(userBalls);
    }
}