How do I make this code shorter by using arrays

code.org lesson 13 introduction to arrays answers
processing arrays
traversing arrays
array java
developing algorithms using arrays
write statements to declare the array and assign the values to the corresponding positions.
processing add to array
string array processing

How do I make this code shorter by using Arrays? This is part of a larger code where I simulated the lottery. this specific portion is where the user numbers are generated and I cant seem to figure out how to make this into an Array.

public static void compypick()
{
    boolean done;
    Random  randomgen = new Random();
    winn0 = randomgen.nextInt(53) + 1;

    done = false;
    while (!done)
    {
        winn1 = randomgen.nextInt(53) + 1;
        if (winn1 != winn0)
            done = true;
    }
    done = false;
    while (!done)
    {
        winn2 = randomgen.nextInt(53) + 1;
        if ((winn2 != winn1) && (winn2 != winn0))
            done = true;
    }
    done = false;
    while (!done)
    {
        winn3 = randomgen.nextInt(53) + 1;
        if ((winn3 != winn2) && (winn3 != winn1) && (winn3 != winn0))
            done = true;
    }
    done = false;
    while (!done)
    {
        winn4 = randomgen.nextInt(53) + 1;
        if ((winn4 != winn3) && (winn4 != winn2) && (winn4 != winn1) && (winn4 != winn0))
            done = true;
    }
    done = false;
    while (!done)
    {
        winn5 = randomgen.nextInt(53) + 1;
        if ((winn5 != winn4) && (winn5 != winn3) && (winn5 != winn2) && (winn5 != winn1) && (winn5 != winn0))
            done = true;
    }
    System.out.printf ("Winning numbers: %d %d %d %d %d %d\n", winn0, winn1, winn2, winn3, winn4, winn5);
}

If they need to be unique you can use a Set:

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

Or java 8+ you can use the ints() method to get a Stream and collect it to a Set:

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

Or:

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

Sample output:

48 3 41 25 11 31  

Microsoft Visual Basic 2017 for Windows, Web, and Database , Does this make my code shorter? Arrays can shorten and simplify your code, allowing you to create loops that deal efficiently with any number of elements. Before we dive into the code examples, below is a brief overview of SAS Array statements and Do Group processing. ARRAY STATEMENTS Arrays are temporary groupings of SAS variables that have the same data type and are arranged in a particular order. Array statements allow you to do more with less code and only exist for the duration of the data step.

A simple solution using just arrays would be this:

public static boolean contains(int[] array, int x) {
    for (int i : array) {
        if (i == x) return true;
    }
    return false;
}

public static void main(String[] args) {

    Random randomgen = new Random();
    int[] winningNumbers = new int[6];

    for (int i = 0; i < 6; i++) {
        int winn = randomgen.nextInt(53) + 1;
        while(contains(winningNumbers, winn)){
            winn = randomgen.nextInt(53) + 1;
        }
        winningNumbers[i] = winn;
    }

    System.out.printf("Winning numbers: ");
    for (int i: winningNumbers) {
        System.out.printf("%d ", i);
    }
    System.out.println();
}

Microsoft Visual Basic 2015 for Windows, Web, Windows Store, and , Does this make my code shorter? Arrays can shorten and simplify your code, allowing you to create loops that deal efficiently with any number of elements. the​  In this tutorial we will see how to use bash arrays and perform fundamental operations on them. After following this tutorial you should be able to understand how bash arrays work and how to perform the basic operations on them. Create an array The first thing to do is to distinguish between bash indexed array and bash associative array. The

Here's a solution in reducing your current code to some good extent:

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);

If you want to persist the unique winning numbers after printing then you could do:

int[] res = random.ints(6, 1, 53) // IntStream
                  .distinct() // IntStream of distinct values
                  .toArray();

System.out.printf ("Winning numbers: %d %d %d %d %d %d\n", 
                res[0], res[1], res[2], res[3], res[4], res[5]);
// still have access to "res" later on for further processing...

Arrays \ Processing.org, Arrays can make the task of programming much easier. The code on the left demonstrates using separate variables. The shorten() function decreases an array by one element by removing the last element and returns the shortened array:. sort() method is a java.util.Arrays class method.. Syntax: public static void sort(int[] arr, int from_Index, int to_Index) arr - the array to be sorted from_Index - the index of the first element, inclusive, to be sorted to_Index - the index of the last element, exclusive, to be sorted This method doesn't return any value.

Arrays are fine for this job, but I think sets are a better choice, as you want unique numbers. You should also use a for loop. You are basically repeating some operation five times.

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);

Introduction to Arrays, Students then watch a short video introducing arrays and a subset of the operations Create arrays and access information stored within them using an index. Note that the code uses defined constants for the width and height, instead of using directly their numerical values. This gives the code a better readability, and allows changes in the code to be made easily in one place. Arrays as parameters At some point, we may need to pass an array to a function as a parameter.

Since the domain set has only 53 elements, you can chose this approach:

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);
    }
}

6.2. Traversing Arrays with For Loops, Note that the variable i (short for index) is often used in loops as the loop counter The following code demonstrates a loop that changes the values in an array. on line 14 to make sure that the loop doesn't go beyond the length of the array,  So, what are the uses of arrays created from the Python array module? The array.array type is just a thin wrapper on C arrays which provides space-efficient storage of basic C-style data types. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory than normal lists.

6.1. Array Creation and Access, Use the Active Code window below to create 4 parallel arrays and intialize them using initialization lists that represent the data below. Remember that the order of​  For example, to declare a 10-element array called balance of type double, use this statement − double balance[10]; Here balance is a variable array which is sufficient to hold up to 10 double numbers. Initializing Arrays. You can initialize an array in C either one by one or using a single statement as follows −

How can I make this code shorter ?, Using arrays and loops means fewer chances for bugs / typos to creep in, means the code is readable and easily extensible. [ I will NOT respond  MATLAB is an abbreviation for "matrix laboratory." While other programming languages mostly work with numbers one at a time, MATLAB® is designed to operate primarily on whole matrices and arrays. All MATLAB variables are multidimensional arrays, no matter what type of data. A matrix is a two-dimensional array often used for linear algebra.

C++: Methods of code shortening in competitive programming , What is Competitive Programming and How to Prepare for It? What Are The Best Resources For Competitive Programming? How to begin with Competitive  How to Merge Two Arrays in Java. Merging two arrays in Java is similar to concatenate or combine two arrays in a single array object. We have to merge two arrays such that the array elements maintain their original order in the newly merged array. The elements of the first array precede the elements of the second array in the newly merged array.

Comments
  • So, you want to pick the six numbers out of set [1-53]?
  • be very careful with random.ints(0, 54).boxed().collect(Collectors.toSet()); as random.ints(0, 54) returns an infinite stream and currently there is no short-circuiting operation to consume the stream. consider using limit or simply use the 3 arg version of random.ints where the first argument is the size of the stream.
  • @Aomine Yes I just realized I forgot that. Thanks for pointing that out
  • Also, both your solutions are correct in the sense that the values in the accumulating set will have "unique" values but they're incorrect in "assuming" that the accumulating set will always have 6 "unique" values. you'll need to call distinct before limit for the Java-8 solution. now that we've used distinct you might even consider collecting to a List instead of a Set.
  • The same comment under the @Aomine answer could be applied here.
  • This is a good answer for these inputs, but consider picking 9999 out of 10000 elements, or even more. I mean distinct() would pay price in the time performance.
  • @zlakad since when can you have around "9999" winning numbers? do you want the company to go bankrupt? ^_^. the generated numbers will always be a small amount so no need to worry about performance.
  • I'm just thinking theoretically - some similar problem. Of course, my example is not good enough, since we can pick just one missing element, and print the rest, but 50_000 from set of 100_000?