如何使用另一个数组中的某些特定值将数组填充到其长度?

时间:2018-04-24 16:06:38

标签: java arrays

我有一个功能 int[ ] fill(int[ ] arr, int k, int n)返回长度为n的数组,值包含重复的第一个k元素。

我的代码是:

class Repeat_block {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int k = 3;
    int n = 10;
    int arr[] = { 1, 2, 3, 5, 9, 12, -2, -1 };
    System.out.println(Arrays.toString(fill(arr, k, n)));

}

public static int[] fill(int[] arr, int k, int n) {
    int arr2[] = new int[n];
    if (k == 0 || n <= 0) {
        return null;
    }

    for (int i = 0; i < n; i++) {
        if (i <k) {
            arr2[i] = arr[i];

        }

    }

    return arr2;

}

}

该函数应返回1,2,3,1,2,3,1,2,3,1   但它返回1,2,3,0,0,0,0,0,0,0。我尝试了很多想法   但无法弄清楚得到正确的逻辑。任何人都有一些最好的想法。

5 个答案:

答案 0 :(得分:1)

一旦i == k,您需要将其重置为0.因此您需要使用两个循环变量。

for (int i = 0, j = 0; i < n; i++, j++) {
     if (j == k) {
        j = 0;
     }
     arr2[i] = arr[j];
}

答案 1 :(得分:1)

将for-loop替换为:

for (int i = 0; i < n; i++) {           
  arr2[i] = arr[i % k]
}

答案 2 :(得分:0)

试试这个。

public static int[] fill(int[] arr, int k, int n) {
    if (k == 0 || n <= 0) {
        return null;
    }

    int[] ret = new int[n];
    int counter = 0;
    int value = 1;
    while (counter < n) {
        if (value > k) value = 1;
        ret[counter] = value;
        value++;
        counter++;
    }
    return ret;

}

答案 3 :(得分:0)

我认为使用流很容易,我相信它可以更容易地完成,但这是我的不良尝试:

import java.util.*;
import java.lang.*;
import java.util.stream.Collectors;

class Main
{
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int k = 3;
        int n = 10;
        int arr[] = { 1, 2, 3, 5, 9, 12, -2, -1 };
        fill(arr, k, n);
    }

    public static void fill(int[] arr, int k, int n) {
        String elementsToCopy = Arrays.stream(arr)
                .limit(k)
                .mapToObj(String::valueOf)
                .reduce((a,b) -> a.concat(",").concat(b))
                .get();

        List<String> resultInList = Collections.nCopies(n, elementsToCopy);
        resultInList
                .stream()
                .collect(Collectors.toList());

        System.out.println(resultInList
                .toString()
                .replace(" ", "")
                .replace("[", "")
                .substring(0, n+n-1));
    }
}

答案 4 :(得分:0)

只是为了练习,我在Python3中完成了这个:

def fill(arr,k,n):
    c = math.ceil(n/k)
    return (arr[0:k]*c)[0:n]