如何从两个数组中交替获取字符?

huangapple go评论78阅读模式
英文:

How do I alternate chars from two arrays?

问题

char[] ch3 = new char[ch1.length + ch2.length];
int count = 0;
int count2 = 0;
for(int i = 0; i < ch3.length; i++){
    if(i < ch1.length) {
        if(i%2 == 0 || count2 == ch2.length) {
            ch3[i] = ch1[count];
            count++;
        }
    }
    if(i < ch2.length) {
        if(i%2 != 0 || count == ch1.length) {
            ch3[i] = ch2[count2];
            count2++;
        }
    }
}
return ch3;
英文:

I need help with figuring out how to combine two char arrays and then have the elements alternate in a new array. The given arrays can be different lengths, for example: char1=[B,D] char2 = [c,R,5] the output should be char3= [B,c,D,r,5]

char[] ch3 = new char[ch1.length + ch2.length];
int count = 0;
int count2 = 0;
for(int i = 0; i &lt; ch3.length; i++){
    if(i &lt; ch1.length) {
        if(i%2 == 0 || count2 == ch2.length) {
            ch3[i] = ch1[count];
            count++;
        }
    }
    if(i &lt;ch2.length) {
        if(i%2 != 0 || count == ch1.length) {
            ch3[i] = ch2[count2];
            count2++;
        }
    }
}
return ch3;

答案1

得分: 1

public static void main(String... args) {
    int[] one = { 1, 2, 3 };
    int[] two = { 44, 55, 66, 77, 88 };
    System.out.println(Arrays.toString(alternate(one, two)));
}

public static int[] alternate(int[] one, int[] two) {
    int[] res = new int[one.length + two.length];

    for (int i = 0, j = 0, k = 0; i < res.length; i++) {
        if (i % 2 == 0) {
            if (j < one.length)
                res[i] = one[j++];
            else
                res[i] = two[k++];
        } else {
            if (k < two.length)
                res[i] = two[k++];
            else
                res[i] = one[j++];
        }
    }

    return res;
}

Output:

[1, 44, 2, 55, 3, 66, 77, 88]
英文:
public static void main(String... args) {
    int[] one = { 1, 2, 3 };
    int[] two = { 44, 55, 66, 77, 88 };
    System.out.println(Arrays.toString(alternate(one, two)));
}

public static int[] alternate(int[] one, int[] two) {
    // result array length is sum of lengths of given arrays.
    int[] res = new int[one.length + two.length];

    // i - result array iterator
    // j - one array iterator
    // k - two array iterarot
    for (int i = 0, j = 0, k = 0; i &lt; res.length; i++) {
        // for even position we put next element from one array
        if (i % 2 == 0)
            // if one array has more elements - add it
            // if no more elements in one array, add next element from two array
            if (j &lt; one.length)
                res[i] = one[j++];
            else
                res[i] = two[k++];
        // for odd position we put next element from two array
        else
            // if two array has more elements - add it
            // if no more elements in two array, add next element from one array
            if (k &lt; two.length)
                res[i] = two[k++];
            else
                res[i] = one[j++];
    }

    return res;
}

Output:

[1, 44, 2, 55, 3, 66, 77, 88]

答案2

得分: 1

public static int[] alternate(int[] a1, int[] a2) {
    int[] a3 = new int[a1.length + a2.length];
    for (int i1 = 0, i2 = 0, i3 = 0; i3 < a3.length; ) {
        if (i1 < a1.length)
            a3[i3++] = a1[i1++];
        if (i2 < a2.length)
            a3[i3++] = a2[i2++];
    }
    return a3;
}

System.out.println(Arrays.toString(alternate(
        new int[] { 1, 2, 3 },
        new int[] { 44, 55, 66, 77, 88 })));
System.out.println(Arrays.toString(alternate(
        new int[] { 44, 55, 66, 77, 88 },
        new int[] { 1, 2, 3 })));

[1, 44, 2, 55, 3, 66, 77, 88]
[44, 1, 55, 2, 66, 3, 77, 88]

public static int[] alternate(int[]... arrays) {
    int[] result = new int[Stream.of(arrays).mapToInt(a -> a.length).sum()];
    int[] ai = new int[arrays.length];
    for (int j = 0; j < result.length; )
        for (int i = 0; i < arrays.length; i++)
            if (ai[i] < arrays[i].length)
                result[j++] = arrays[i][ai[i]++];
    return result;
}

System.out.println(Arrays.toString(alternate(
        new int[] { 1, 2, 3 },
        new int[] { 44, 55, 66, 77, 88 },
        new int[] { 12, 34 },
        new int[] { 5, 6, 7, 8 })));

[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]

@SafeVarargs
public static <T> List<T> alternate(Iterable<? extends T>... inputs) {
    List<T> result = new ArrayList<>();
    @SuppressWarnings("unchecked")
    Iterator<? extends T>[] iter = new Iterator[inputs.length];
    for (int i = 0; i < inputs.length; i++)
        iter[i] = inputs[i].iterator();
    for (int prevSize = -1; prevSize < result.size(); ) {
        prevSize = result.size();
        for (int i = 0; i < inputs.length; i++)
            if (iter[i].hasNext())
                result.add(iter[i].next());
    }
    return result;
}

public static <T> List<T> alternate(Collection<? extends Iterable<? extends T>> inputs) {
    @SuppressWarnings("unchecked")
    Iterable<? extends T>[] iterables = inputs.toArray(new Iterable[0]);
    return alternate(iterables);
}

System.out.println(alternate(
        Arrays.asList(1, 2, 3),
        Arrays.asList(44, 55, 66, 77, 88),
        Arrays.asList(12, 34),
        Arrays.asList(5, 6, 7, 8)));
System.out.println(alternate(Arrays.asList(
        Arrays.asList(1, 2, 3),
        Arrays.asList(44, 55, 66, 77, 88),
        Arrays.asList(12, 34),
        Arrays.asList(5, 6, 7, 8))));

[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]
[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]
英文:

Similar solution to answer by oleg.cherednik, but without the need for slow % remainder operator.

public static int[] alternate(int[] a1, int[] a2) {
	int[] a3 = new int[a1.length + a2.length];
	for (int i1 = 0, i2 = 0, i3 = 0; i3 &lt; a3.length; ) {
		if (i1 &lt; a1.length)
			a3[i3++] = a1[i1++];
		if (i2 &lt; a2.length)
			a3[i3++] = a2[i2++];
	}
	return a3;
}

Tests

System.out.println(Arrays.toString(alternate(
		new int[] { 1, 2, 3 },
		new int[] { 44, 55, 66, 77, 88 })));
System.out.println(Arrays.toString(alternate(
		new int[] { 44, 55, 66, 77, 88 },
		new int[] { 1, 2, 3 })));

Output

[1, 44, 2, 55, 3, 66, 77, 88]
[44, 1, 55, 2, 66, 3, 77, 88]

UPDATE

This algorithm can easily be enhanced to merge many arrays:

public static int[] alternate(int[]... arrays) {
	int[] result = new int[Stream.of(arrays).mapToInt(a -&gt; a.length).sum()];
	int[] ai = new int[arrays.length];
	for (int j = 0; j &lt; result.length; )
		for (int i = 0; i &lt; arrays.length; i++)
			if (ai[i] &lt; arrays[i].length)
				result[j++] = arrays[i][ai[i]++];
	return result;
}

Test

System.out.println(Arrays.toString(alternate(
		new int[] { 1, 2, 3 },
		new int[] { 44, 55, 66, 77, 88 },
		new int[] { 12, 34 },
		new int[] { 5, 6, 7, 8 })));

Output

[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]

UPDATE 2

It can also be done for collections:

@SafeVarargs
public static &lt;T&gt; List&lt;T&gt; alternate(Iterable&lt;? extends T&gt;... inputs) {
	List&lt;T&gt; result = new ArrayList&lt;&gt;();
	@SuppressWarnings(&quot;unchecked&quot;)
	Iterator&lt;? extends T&gt;[] iter = new Iterator[inputs.length];
	for (int i = 0; i &lt; inputs.length; i++)
		iter[i] = inputs[i].iterator();
	for (int prevSize = -1; prevSize &lt; result.size(); ) {
		prevSize = result.size();
		for (int i = 0; i &lt; inputs.length; i++)
			if (iter[i].hasNext())
				result.add(iter[i].next());
	}
	return result;
}

public static &lt;T&gt; List&lt;T&gt; alternate(Collection&lt;? extends Iterable&lt;? extends T&gt;&gt; inputs) {
	@SuppressWarnings(&quot;unchecked&quot;)
	Iterable&lt;? extends T&gt;[] iterables = inputs.toArray(new Iterable[0]);
	return alternate(iterables);
}

Tests

System.out.println(alternate(
		Arrays.asList(1, 2, 3),
		Arrays.asList(44, 55, 66, 77, 88),
		Arrays.asList(12, 34),
		Arrays.asList(5, 6, 7, 8)));
System.out.println(alternate(Arrays.asList(
		Arrays.asList(1, 2, 3),
		Arrays.asList(44, 55, 66, 77, 88),
		Arrays.asList(12, 34),
		Arrays.asList(5, 6, 7, 8))));

Output

[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]
[1, 44, 12, 5, 2, 55, 34, 6, 3, 66, 7, 77, 8, 88]

huangapple
  • 本文由 发表于 2020年10月10日 05:48:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64287729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定