Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.Arrays;
import java.util.Random;

public class Main {
    /**Random object wich can be used inside the others methods as Shuffle.*/
    protected static Random rand = new Random();

    /**Split an array of any type, by selecting randomly a number of elements to be part of the second array and the rest the first array.
     *<p>
     *If the third parameter is big enough to store the return, it will be stored there; otherwise a new array will be created.
     *@param array The array that will get the extraction.
     *@param number The number of elements that will be extracted..
     *@param type The class of the copy to be returned.
     *@return An array of 2 arrays, where the first one has the original array with the extraction and the second one the elements that were extracted 
     */
    @SuppressWarnings("unchecked")
    public static <T> T[][] extractFrom(T[] array, int number, T[][] type) {
        shuffle(array);
        return divideAt(array, array.length - number, type);
    }

    /**Shuffle an array
     *@param array The array to be shuffled
     */
    public static <T> void shuffle(T[] array) {
        int i, j;
        T obj;
        for (i = 0; i < array.length; i++) {
            j = rand.nextInt(array.length);
            obj = array[i];
            array[i] = array[j];
            array[j] = obj;
        }
    }

    /**Split an array of any type at a position given by the second parameter.
     *<p>
     *If the third parameter is big enough to store the return, it will be stored there; otherwise a new array will be created.
     *@param array The array that will be splitted.
     *@param pos The position where the array will be splitted.
     *@param type The class of the copy to be returned.
     *@return An array of 2 arrays, where the first one has the element from 0 to pos and the second one has the elements from pos to array.length 
     */
    @SuppressWarnings("unchecked")
    public static <T> T[][] divideAt(T[] array, int pos, T[][] type) {
        Object[][] ret = { Arrays.copyOfRange(array, 0, pos), Arrays.copyOfRange(array, pos, array.length) };
        return Arrays.asList(ret).toArray(type);
    }
}