[英]Reversing an array of ints without any loop
I would like to write a concise code that reverse an array of ints without using any loops . 我想编写一个简洁的代码来反转一个整数数组, 而不使用任何循环 。 By "reversing" I mean the following: [1, 4, 3, 7, 2] -> [2, 7, 3, 4, 1]
. “反向”是指: [1, 4, 3, 7, 2] -> [2, 7, 3, 4, 1]
。 I think that IntStream could be helpful here: it should be possible to "catch" a finite stream and proceed with it like with a stack (LIFO). 我认为IntStream在这里可能会有所帮助:应该有可能“捕获”有限的流并像堆栈(LIFO)一样继续进行。 Unfortunately I can't - could you please help? 不幸的是我不能-您能帮忙吗?
Any loop can be replaced with recursion . 任何循环都可以用递归代替。
Hire is an example. 雇用就是一个例子。
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class RecursionReverseArray {
private static <T> void reverseImpl(T[] arr,int lhsIdx, int rhsIdx) {
if(lhsIdx == rhsIdx)
return;
T tmp = arr[lhsIdx];
arr[lhsIdx] = arr[rhsIdx];
arr[rhsIdx] = tmp;
reverceImpl(arr, ++lhsIdx, --rhsIdx);
}
public static <T> void reverse(T[] arr) {
reverseImpl(arr, 0, arr.length-1);
}
@Test
void test() {
Integer[] actual = {9,8,7,6,5,4,3,2,1};
Integer[] expected = {1,2,3,4,5,6,7,8,9};
reverse(actual);
assertArrayEquals(expected, actual);
}
}
As well as with Java 8+ you can use reverse order stream API . 与Java 8+一样,您可以使用逆序流API 。
If you don't want to use loops, you can use recursions if you want. 如果您不想使用循环,则可以使用递归。 Here is a code written using recursion. 这是使用递归编写的代码。
import java.io.*; 导入java.io. *;
class ReverseArray { 类ReverseArray {
static void rvereseArray(int arr[], int start, int end)
{
int temp;
if (start >= end)
return;
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
rvereseArray(arr, start+1, end-1);
}
static void printArray(int arr[], int size)
{
for (int i=0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main (String[] args) {
int arr[] = {1, 2, 3, 4, 5, 6};
printArray(arr, 6);
rvereseArray(arr, 0, 5);
System.out.println("Reversed array is ");
printArray(arr, 6);
}
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.