Java -如何在每次迭代中分割数组并有效地传递给函数?

时间:2021-08-10 21:16:13

I have an array that holds some values and a function that takes in two arrays. What I want to do is split the array so that the last element is not in the array so I have two arrays, one that has all the original elements except the last and one that has just one element - the last. After I pass this into a function, I want to use the original array but this time put the second last element into a seperate array and so on. I want to do this five times. The following will explain it better:

我有一个包含一些值的数组和一个包含两个数组的函数。我要做的是分割数组,这样最后一个元素就不在数组中了,所以我有两个数组,一个有所有的原始元素,除了最后一个元素,另一个只有一个元素——最后一个元素。在我将它传递给一个函数之后,我想使用原始数组,但是这次将第二个最后的元素放入一个分开的数组中,以此类推。我想这样做五次。下面将更好地解释它:

int[] val = {25,50,66,75,100,1000,5000,10000,25000};

for (int i=0; i<5; i++){

//Need to split the array and then pass it to the function here
}

public void evaluate(int[] train, int[] test){

....
}

So for example in the first iteration I want to remove/split 25000 from the array and put it into another array and then pass the two arrays throught the function:

例如,在第一次迭代中,我想从数组中删除/拆分25000并将其放入另一个数组中,然后通过函数传递两个数组:

first array now has {25,50,66,75,100,1000,5000,10000} and second array now has {25000}

第一个阵列现在有{25,50,66,75,100,1000,5000,10000}第二个阵列现在有{25000}

On next iteration I want to now split/remove 10000 (25000 is now back in the array):

在下一次迭代中,我想现在拆分/删除10000(25000现在回到数组中):

so first array now has {25,50,66,75,100,1000,5000,25000} and second array now has {10000}

第一个数组现在有{25,50,66,75,100,1000,5000,25000}第二个数组现在有{10000}

So basically it is going from the bottom and working its way up, but only 5 times.

基本上它从底部向上移动,但是只有5次。

6 个解决方案

#1


1  

Create the two arrays up front, and swap one element into your test array after each iteration. This will be faster than allocating new arrays all the time.

预先创建两个数组,并在每次迭代之后将一个元素交换到测试数组中。这将比一直分配新的数组要快。

int[] val = {25,50,66,75,100,1000,5000,10000,25000};

// create the destination arrays:
int[] train = new int[val.length-1];
int[] test = new int[1];

// initialize the arrays:
test[0] = val[val.length-1];
for (int i = 0; i < val.length-1; ++i)
{
    train[i] = val[i];
}

int timesToIterate = 5;

for (int iteration = 0; iteration < timesToIterate; ++iteration)
{
    evaluate(train, test);

    int i = train.length-1-iteration;
    if (i >= 0) // don't swap if this is the last element in the array
    {
        int tmp = test[0];
        test[0] = train[i];
        train[i] = tmp;
    }
}

With your example data, the arrays passed into the evaluate function are:

通过示例数据,传递到evaluate函数的数组为:

{25 50 66 75 100 1000 5000 10000 } {25000}
{25 50 66 75 100 1000 5000 25000 } {10000}
{25 50 66 75 100 1000 10000 25000 } {5000}
{25 50 66 75 100 5000 10000 25000 } {1000}
{25 50 66 75 1000 5000 10000 25000 } {100}

#2


1  

I dunno what you are trying to do in the end but this seems to be a perfect fit for a functional programing language. Anyway we can do it in java and moreover with arrays :

我不知道你最后想做什么,但这似乎是一个完美的功能编程语言。无论如何,我们可以用java和数组来做:

In you for loop that's going from 1 to 5 included you might put something like :

在你的for循环中,它从1到5包含你可能会这样写:

for (int i=1; i<=5; i++){
  int[] train = new int[val.length-i];
  System.arraycopy( val, 0, train, 0, train.length-1 );
  int test = new int[1];
  test[0] = val[val.length-i];
  evaluate(train,test);
}

#3


1  

The algorithm I would use is:

我使用的算法是:

  1. Take the original array, A, and create a new A' with 1 less element and a single-element array, call it B.
  2. 取原始数组A,创建一个新的A',少1个元素和一个单元素数组,称为B。
  3. Populate A' with n-1 elements, populate B with 1 element.
  4. 用n-1元素填充A,用1个元素填充B。
  5. Then, when you've completed processing A' and B, swap the appropriate element in A' with B[0].
  6. 然后,当你完成处理A和B时,用B[0]交换A中的适当元素。

The single copy is O(n) and each of the 5 iterations has a constant time operation to do the swap. Memory is also O(n).

单拷贝是O(n),每5个迭代都有一个常数时间操作来执行交换。记忆是O(n)。

#4


1  

The easiest thing to do would be to switch from using arrays to using a List<Integer>. You can then use the subList method to construct arrays that are subsequences of the original array.

最简单的方法是从使用数组切换到使用列表 。然后,您可以使用子列表方法来构造作为原始数组子序列的数组。

If you insist on using arrays, you have two options:

如果你坚持使用数组,你有两个选择:

  1. Add arguments to represent the start and end index of the applicable range for each array argument. You then need to rewrite your logic to go from start through end-1 (instead of 0 through array.length - 1).
  2. 添加参数表示每个数组参数适用范围的起始和结束索引。然后需要重写逻辑,从开始到结束(而不是从0到数组)。长度- 1)。
  3. Allocate new arrays and copy the data into them. This won't work if you intend to modify the array elements and in any case is a lot of extra work.
  4. 分配新的数组并将数据复制到其中。如果您打算修改数组元素,这将不起作用,而且在任何情况下都需要做大量额外的工作。

Here's some code to show how to use a List<Integer>:

下面的代码演示了如何使用列表 :

// autobox each value as an Integer:
List<Integer> vals = Arrays.asList(
    new Integer[] {25,50,66,75,100,1000,5000,10000,25000});
final int len = vals.length();

for (int i=0; i<5; i++){
    evaluate(vals.subList(0, i), vals.subList(i, len));
}

public void evaluate(List<Integer> train, List<Integer> test){

....
}

#5


1  

check out the Arrays API you can do it with the Arrays.copyOf(..) method.

查看数组API,您可以使用Arrays.copyOf(.. .)方法来实现它。

newArray = Arrays.copyOf(oldArray, oldArray.length-1)

Perhaps this code can help you you.

也许这段代码可以帮助您。

    int[] val = { 25, 50, 66, 75, 100, 1000, 5000, 10000, 25000 };
    int[] firstArray = new int[val.length-1];
    int[] SecondArray = new int[1];     
    //iterates the whole array set to 5 if needed
    for (int n = 0; n < val.length; n++) {
        SecondArray[0] = val[val.length-n-1];
        for(int x = 0, firstArrayCounter= 0; x < val.length; x++){
            if(val[x]!=SecondArray[0]){                 
                firstArray[firstArrayCounter] = val[x];
                firstArrayCounter++;
            }       
        }
        //prints what is in the arrays                      
        for (int i = 0; i < firstArray.length; i++)
            System.out.print(firstArray[i] + " ");
        System.out.println("\n"+SecondArray[0]);
    }

Good luck!

好运!

#6


1  

You can use ArrayUtils of Apache commons, code example is like as follows:

可以使用Apache commons的ArrayUtils,代码示例如下:

    private static int[] val = { 25, 50, 66, 75, 100, 1000, 5000, 10000, 25000 };
    private static int[] test = {};

    public static void evaluate(int[] train, int[] test) {
        for (int i = 0; i < train.length; i++) {
            System.out.print(train[i] + ",");
        }
        System.out.println("");
        for (int i = 0; i < test.length; i++) {
            System.out.print(test[i] + ",");

        }
        System.out.println("");
        System.out.println("-----");
    }

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            if (!ArrayUtils.isEmpty(test))
                ArrayUtils.remove(test, 0);
            evaluate(ArrayUtils.remove(val, val.length - 1 - i), ArrayUtils.add(test, val[val.length - 1 - i]));
        }
    }

#1


1  

Create the two arrays up front, and swap one element into your test array after each iteration. This will be faster than allocating new arrays all the time.

预先创建两个数组,并在每次迭代之后将一个元素交换到测试数组中。这将比一直分配新的数组要快。

int[] val = {25,50,66,75,100,1000,5000,10000,25000};

// create the destination arrays:
int[] train = new int[val.length-1];
int[] test = new int[1];

// initialize the arrays:
test[0] = val[val.length-1];
for (int i = 0; i < val.length-1; ++i)
{
    train[i] = val[i];
}

int timesToIterate = 5;

for (int iteration = 0; iteration < timesToIterate; ++iteration)
{
    evaluate(train, test);

    int i = train.length-1-iteration;
    if (i >= 0) // don't swap if this is the last element in the array
    {
        int tmp = test[0];
        test[0] = train[i];
        train[i] = tmp;
    }
}

With your example data, the arrays passed into the evaluate function are:

通过示例数据,传递到evaluate函数的数组为:

{25 50 66 75 100 1000 5000 10000 } {25000}
{25 50 66 75 100 1000 5000 25000 } {10000}
{25 50 66 75 100 1000 10000 25000 } {5000}
{25 50 66 75 100 5000 10000 25000 } {1000}
{25 50 66 75 1000 5000 10000 25000 } {100}

#2


1  

I dunno what you are trying to do in the end but this seems to be a perfect fit for a functional programing language. Anyway we can do it in java and moreover with arrays :

我不知道你最后想做什么,但这似乎是一个完美的功能编程语言。无论如何,我们可以用java和数组来做:

In you for loop that's going from 1 to 5 included you might put something like :

在你的for循环中,它从1到5包含你可能会这样写:

for (int i=1; i<=5; i++){
  int[] train = new int[val.length-i];
  System.arraycopy( val, 0, train, 0, train.length-1 );
  int test = new int[1];
  test[0] = val[val.length-i];
  evaluate(train,test);
}

#3


1  

The algorithm I would use is:

我使用的算法是:

  1. Take the original array, A, and create a new A' with 1 less element and a single-element array, call it B.
  2. 取原始数组A,创建一个新的A',少1个元素和一个单元素数组,称为B。
  3. Populate A' with n-1 elements, populate B with 1 element.
  4. 用n-1元素填充A,用1个元素填充B。
  5. Then, when you've completed processing A' and B, swap the appropriate element in A' with B[0].
  6. 然后,当你完成处理A和B时,用B[0]交换A中的适当元素。

The single copy is O(n) and each of the 5 iterations has a constant time operation to do the swap. Memory is also O(n).

单拷贝是O(n),每5个迭代都有一个常数时间操作来执行交换。记忆是O(n)。

#4


1  

The easiest thing to do would be to switch from using arrays to using a List<Integer>. You can then use the subList method to construct arrays that are subsequences of the original array.

最简单的方法是从使用数组切换到使用列表 。然后,您可以使用子列表方法来构造作为原始数组子序列的数组。

If you insist on using arrays, you have two options:

如果你坚持使用数组,你有两个选择:

  1. Add arguments to represent the start and end index of the applicable range for each array argument. You then need to rewrite your logic to go from start through end-1 (instead of 0 through array.length - 1).
  2. 添加参数表示每个数组参数适用范围的起始和结束索引。然后需要重写逻辑,从开始到结束(而不是从0到数组)。长度- 1)。
  3. Allocate new arrays and copy the data into them. This won't work if you intend to modify the array elements and in any case is a lot of extra work.
  4. 分配新的数组并将数据复制到其中。如果您打算修改数组元素,这将不起作用,而且在任何情况下都需要做大量额外的工作。

Here's some code to show how to use a List<Integer>:

下面的代码演示了如何使用列表 :

// autobox each value as an Integer:
List<Integer> vals = Arrays.asList(
    new Integer[] {25,50,66,75,100,1000,5000,10000,25000});
final int len = vals.length();

for (int i=0; i<5; i++){
    evaluate(vals.subList(0, i), vals.subList(i, len));
}

public void evaluate(List<Integer> train, List<Integer> test){

....
}

#5


1  

check out the Arrays API you can do it with the Arrays.copyOf(..) method.

查看数组API,您可以使用Arrays.copyOf(.. .)方法来实现它。

newArray = Arrays.copyOf(oldArray, oldArray.length-1)

Perhaps this code can help you you.

也许这段代码可以帮助您。

    int[] val = { 25, 50, 66, 75, 100, 1000, 5000, 10000, 25000 };
    int[] firstArray = new int[val.length-1];
    int[] SecondArray = new int[1];     
    //iterates the whole array set to 5 if needed
    for (int n = 0; n < val.length; n++) {
        SecondArray[0] = val[val.length-n-1];
        for(int x = 0, firstArrayCounter= 0; x < val.length; x++){
            if(val[x]!=SecondArray[0]){                 
                firstArray[firstArrayCounter] = val[x];
                firstArrayCounter++;
            }       
        }
        //prints what is in the arrays                      
        for (int i = 0; i < firstArray.length; i++)
            System.out.print(firstArray[i] + " ");
        System.out.println("\n"+SecondArray[0]);
    }

Good luck!

好运!

#6


1  

You can use ArrayUtils of Apache commons, code example is like as follows:

可以使用Apache commons的ArrayUtils,代码示例如下:

    private static int[] val = { 25, 50, 66, 75, 100, 1000, 5000, 10000, 25000 };
    private static int[] test = {};

    public static void evaluate(int[] train, int[] test) {
        for (int i = 0; i < train.length; i++) {
            System.out.print(train[i] + ",");
        }
        System.out.println("");
        for (int i = 0; i < test.length; i++) {
            System.out.print(test[i] + ",");

        }
        System.out.println("");
        System.out.println("-----");
    }

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            if (!ArrayUtils.isEmpty(test))
                ArrayUtils.remove(test, 0);
            evaluate(ArrayUtils.remove(val, val.length - 1 - i), ArrayUtils.add(test, val[val.length - 1 - i]));
        }
    }