Creating a New Reverse Java Array - java

CodingBat > Java > Array-1 > reverse3:
Given an array of ints length 3, return a new array with the elements in reverse order, so {1, 2, 3} becomes {3, 2, 1}.
public int[] reverse3(int[] nums) {
int[] values = new int[3];
for (int i = 0; i <= nums.length - 1; i++) {
for (int j = nums.length-1; j >= 0; j--) {
values[i] = nums[j];
}
}
return values;
}
I can't get this to work properly, usually the last int in the array, becomes every single int in the new array

You don't want a two-level loop. Just have one loop:
for(int i = 0, j = nums.length - 1; i < nums.length; i++,j--) {
values[i] = nums[j];
}
or, alternately, just don't track j sepearately, and do this:
for(int i = 0; i < nums.length; i++) {
values[i] = nums[nums.length - 1 - i];
}

Unless this is a homework, why not just use Apache ArrayUtils'
ArrayUtils.reverse(nums)
Never re-invent the wheel :)

The length of the input int[] is fixed at 3? Then it doesn't get any simpler than this.
public int[] reverse3(int[] nums) {
return new int[] { nums[2], nums[1], nums[0] };
}
See also:
CodingBat/Java/Array-1/reverse3
Note that Array-1 is "Basic array problems -- no loops." You can use a loop if you want, but it's designed NOT to be solved using loops.

Firstly, while creating new array give it size of old array.
Next, when you're reversing an array, you don't need two loops, just one:
int length = oldArray.length
for(int i = 0; i < length; i++)
{
newArray[length-i-1] = oldArray[i]
}

You only want a single loop, but with indices going both ways:
public int[] reverse(int[] nums) {
int[] back = new int[nums.length];
int i,j;
for (i=0,j=nums.length-1 ; i<nums.length ; i++,j--)
back[i] = nums[j];
return back;
}

public int[] reverse3(int[] nums) {
int rotate[]={nums[2],nums[1],nums[0]};
return rotate;
}

This code gives correct output:-
public int[] reverse3(int[] nums) {
int[] myArray=new int[3];
myArray[0]=nums[2];
myArray[1]=nums[1];
myArray[2]=nums[0];
return myArray;
}

I got this with Python.. So you can get the idea behind it
def reverse3(nums):
num = []
for i in range(len(nums)):
num.append(nums[len(nums) - i - 1])
return num

In your code, for each value of i, you are setting target array elements at i to value in "nums" at j. That is how you end up with same value for all the elements at the end of all iterations.
First of all, very bad logic to have two loops for a simple swap algorithm such as :
public static void reverse(int[] b) {
int left = 0; // index of leftmost element
int right = b.length-1; // index of rightmost element
while (left < right) {
// exchange the left and right elements
int temp = b[left];
b[left] = b[right];
b[right] = temp;
// move the bounds toward the center
left++;
right--;
}
}//endmethod reverse
or simplified:
for (int left=0, int right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
Why go through all this pain, why dont you trust Java's built-in APIs and do something like
public static Object[] reverse(Object[] array)
{
List<Object> list = Arrays.asList(array);
Collections.reverse(list);
return list.toArray();
}

public int[] reverse3(int[] nums) {
int[] values = new int[nums.length];
for(int i=0; i<nums.length; i++) {
values[nums.length - (i + 1)]=nums[i];
}
return values;
}

Related

How to return an array with the indexes of a certain int from another array

I'm a beginner Java student and I have been trying to write a method that lists all indexes of a certain int within an array. What I've done so far is store the value of that int at its corresponding index within another array but the best I can do is set the values of all other indexes that are not equal to the original int to -1.
I think I need to store the value i within the array and delete all the -1s but I don't know how to do this. By the way, these values are -1 because all my arrays in this program contain ints that are between 0-100. What would I do if possible ints within this array could be any number?
Also surely there is an easier or more efficient way of doing this.
public static int[] maxValueIndex(int[] arr, int targetValue, int x) {
int[] maxValue = new int[x];
for (int i = 0; i < arr.length; i++) {
if (arr[i] == targetValue) {
maxValue[i] = arr[i];
} else {
maxValue[i] = -1;
}
}
return maxValue;
}
If I understood your query correctly then you want an array with all the indices i such that arr[i]==targetValue. We can achieve this efficiently using any dynamic data structure. Like, use an ArrayList and keep adding all the desired indices one by one then convert the List to an array and return it.
Something like this:
List<Integer> index = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == targetValue)
index.add( i );
}
int[] maxValue = index.stream().mapToInt(Integer::intValue).toArray();
return maxValue;
If it is required to use arrays only to resolve this task, it may take two passes to create a compacted array containing only valid indexes:
Find the number of matches, and then create and fill a compact array
public static int[] getTargetIndexes(int targetValue, int ... arr) {
int n = arr.length;
int targetCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == targetValue) {
targetCount++;
}
}
int[] indexes = new int[targetCount];
for (int i = 0, j = 0; j <targetCount && i < n; i++) {
if (arr[i] == targetValue) {
indexes[j++] = i;
}
}
return indexes;
}
Create an array of the same length, fill it and then compact by using Arrays.copyOf:
public static int[] getTargetIndexes(int targetValue, int ... arr) {
int n = arr.length;
int[] indexes = new int[n];
int targetCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == targetValue) {
indexes[i] = i;
targetCount++;
} else {
indexes[i] = -1;
}
}
for (int i = 0, j = 0; j < targetCount && i < n; i++) {
if (indexes[i] > -1) {
indexes[j++] = i;
}
}
return Arrays.copyOf(indexes, targetCount); // truncate bad indexes
}
Also, the signature of the method uses vararg to pass the input array as a sequence of int -- the vararg argument int ... arr should be the last one then.
If Stream API can be used, the task may be resolved conveniently in a declarative way:
public static int[] getTargetIndexes(int targetValue, int ... arr) {
return IntStream.range(0, arr.length) // get stream of indexes
.filter(i -> arr[i] == targetValue) // keep only matching indexes
.toArray(); // build output array
}

incompatible conversion from int[] to int

class Solution {
public int removeDuplicates(int[] nums) {
int [] arr = new int[nums.length];
for(int i=0; i<nums.length; i++){
if(nums[i] != nums[i+1]){
arr[i] = nums[i];
}
}
return arr;
}
}
this is my code and I am having error ::
incompatible conversion from int[] to int.
Your return statement is returning the int array, but your declared return type is an int primitive. You should return the int array instead:
public int[] removeDuplicates(int[] nums)
The above solutions are right but i noticed another problem in your solution. Let's say that the array has 10 numbers.
You start from i = 0; and you continue until the i < array.legth. But in your comparison you compare num[i] and num [i+1]. So when i = 9 that is the last index of the array, the comparison will be if num[9] == num[10],so you will have a runtime error, because there is not index 10.
one think you can do is this:
class Solution {
public int[] removeDuplicates(int[] nums) {
int [] arr = new int[nums.length];
for(int i=0; i<nums.length-1; i++){
if(nums[i] != nums[i+1]){
arr[i] = nums[i];
}
}
return arr;
}
You got to change the array.length to array.length-1.
And if you still stuck that's an existed soltion for youe problem.
remove dublicates
Already said the return type must be int[] too.
public int[] removeDuplicates(int[] nums) {
if (nums.length == 0) {
return nums;
}
int[] arr = nums.clone();
int j = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[j]) {
++j;
arr[j] = arr[i];
}
}
return Arrays.copy(arr, j + 1);
}
The removal of consecutive duplicates must be done a bit different. Above a not so elegant solution. Not tested.

Two Sum LeetCode Java Questions

I am attempting a Java mock interview on LeetCode. I have the following problem:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
I was attempting to implement a recursive solution. However, I am receiving errors upon trying to run my code.
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] sumnums = nums.clone();
//int[2] sol = {0,1};
int[] sol = new int[]{0,1};
sol = new int[2];
int j=sumnums.length;
int t=target;
for(int i=0;i<sumnums.length;i++){
if ((sumnums[i]+sumnums[j])==t){
sol[0]=i;
sol[1]=j;
//return sol;
}
}
j=j-1;
twoSum(sumnums,t);
return sol;
}
}
Error(s):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Solution.twoSum(Solution.java:12)
at __DriverSolution__.__helper__(__Driver__.java:8)
at __Driver__.main(__Driver__.java:54)
It appears to me the error may have to do with the following line of code:
if ((sumnums[i]+sumnums[j])==t){
Therefore, I am wondering if this is a syntax related error. I am attempting to check to see if two numbers add up to a different number.
Since this is a naive attempt at a recursive solution, I am happy to take any other criticism. But I am mostly concerned with getting my attempt at this problem to work and run with all testcases.
Thanks.
METHOD 1. Naive approach: Use two for loops
The naive approach is to just use two nested for loops and check if the sum of any two elements in the array is equal to the given target.
Time complexity: O(n^2)
// Time complexity: O(n^2)
private static int[] findTwoSum_BruteForce(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
METHOD 2. Use a HashMap (Most efficient)
You can use a HashMap to solve the problem in O(n) time complexity. Here are the steps:
Initialize an empty HashMap.
Iterate over the elements of the array.
For every element in the array -
If the element exists in the Map, then check if it’s the complement (target - element) also exists in the Map or not. If the complement exists then return the indices of the current element and the complement.
Otherwise, put the element in the Map, and move to the next iteration.
Time complexity: O(n)
// Time complexity: O(n)
private static int[] findTwoSum(int[] nums, int target) {
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (numMap.containsKey(complement)) {
return new int[] { numMap.get(complement), i };
} else {
numMap.put(nums[i], i);
}
}
return new int[] {};
}
METHOD 3. Use Sorting along with the two-pointer sliding window approach
There is another approach which works when you need to return the numbers instead of their indexes. Here is how it works:
Sort the array.
Initialize two variables, one pointing to the beginning of the array (left) and another pointing to the end of the array (right).
Loop until left < right, and for each iteration
if arr[left] + arr[right] == target, then return the indices.
if arr[left] + arr[right] < target, increment the left index.
else, decrement the right index.
This approach is called the two-pointer sliding window approach. It is a very common pattern for solving array related problems.
Time complexity: O(n*log(n))
// Time complexity: O(n*log(n))
private static int[] findTwoSum_Sorting(int[] nums, int target) {
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
while(left < right) {
if(nums[left] + nums[right] == target) {
return new int[] {nums[left], nums[right]};
} else if (nums[left] + nums[right] < target) {
left++;
} else {
right--;
}
}
return new int[] {};
}
Why not use a HashMap? Here is how it will work. We will iterate through the array and check if the target - nums[i] exists in the map. If not, we will store Key, Value as the number and its index respectively i.e K = nums[i], V = i
Here is how it will work:
Consider nums = [2, 7, 11, 15], target = 9
We will start iterating the array
First comes 2. Here we will check ( 9 - 2 ) i.e 7 does not exist in the hashmap, so we will store 2 as key and its index 0 as its value
Then, comes 7. Here we will check ( 9 - 7 ) i.e 2 which exists in the map and so we will return the index of 2 and index of 7 i.e returning [ 0, 1 ]
public int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++)
{
if(map.containsKey(target - nums[i]))
{
return new int[] {map.get(target-nums[i]),i};
}
else
map.put(nums[i],i);
}
return new int[] {-1,-1};
}
As you mentioned
First comes 2. Here we will check ( 9 - 2 ) i.e 7 does not exist in the hashmap
actually 7 does exist in the HashMap right
nums = [2, 7, 11, 15], target = 9
public static int[] twoSum(int[] nums, int target) {
int[] sumnums = nums.clone();
//int[2] sol = {0,1};
int[] sol = new int[]{0,1};
sol = new int[2];
int j=sumnums.length; // Every recursion j will be initialized as sumnums.length instead of J-1
int t=target;
for(int i=0;i<sumnums.length;i++){
// if ((sumnums[i]+sumnums[j])==t){
// Remember that Java arrays start at index 0, so this value(sumnums[j]) is not exist in the array.
if ((sumnums[i]+sumnums[j-1])==t){
sol[0]=i;
sol[1]=j;
return sol;
}
}
j=j-1;
twoSum(sumnums,t);
return sol;
}
One of the many possible solutions:
public class TwoSumIndex {
public static void main(String... args) {
int[] arr = {2, 7, 11, 15, 9, 0, 2, 7};
System.out.println(findTwoSums(arr, 9));
}
private static List<List<Integer>> findTwoSums(int[] arr, int target) {
Set<Integer> theSet = Arrays.stream(arr).mapToObj(Integer::valueOf).collect(Collectors.toSet());
List<Integer> arrList = Arrays.stream(arr).mapToObj(Integer::valueOf).collect(Collectors.toList());
List<Pair<Integer, Integer>> theList = new ArrayList<>();
List<Integer> added = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
int a = target - arr[i];
if (theSet.contains(a) && added.indexOf(i) < 0) { // avoid duplicates;
Integer theOther = arrList.indexOf(a);
theList.add(new Pair(i, theOther));
added.add(i);
added.add(theOther);
}
}
return theList.stream().map(pair -> new ArrayList<>(Arrays.asList(pair.getKey(), pair.getValue())))
.collect(Collectors.toList());
}
}
There are several things you need to know:
duplicates in the input array are allowed;
un-ordered array in the input is allowed;
no index pair duplicate in the output;
time complexity is theoretically O(N^2) but actually will be much lower since theSet.contains(a) O(logN) will filter out all failed indexes and then do the index duplicate O(N) checking, so the actual time complexity should be O(NlogN);
The output for the demo:
[[0, 1], [4, 5], [6, 1], [7, 0]]
I use the simpler approch
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices= new int[2];
int len=nums.length;
for(int i=0; i<len; i++){
for(int j=i+1; j<len;j++){
if((nums[i]+nums[j])==target){
indices[0] = i;
indices[1] = j;
return indices;
}
}
}
return null;
}
}
Complete code for beginners
//Predefined values
import java.util.Arrays;
public class TwoSum {
public static void main(String args[]) {
Solution solution = new Solution();
int target = 9;
int num[] = {2, 7, 11, 15};
num = solution.twoSum(num, target);
System.out.println(Arrays.toString(num));
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int result[] = new int[2];
int sum;
for (int i = 0; i + 1 < nums.length; i++) {
// adding the alternate numbers
sum = nums[i] + nums[i + 1];
if (sum == target) {
result[0] = i;
result[1] = i + 1;
return result;
}
}
return null;
}
}
************************************************************************
//User-defined
import java.util.Arrays;
import java.util.Scanner;
/**
*
* #author shelc
*/
public class TwoSum {
public static void main(String[] args) {
Solution solution = new Solution();
Scanner scanner = new Scanner(System.in);
int n;
System.out.print("Enter the number of elements : ");
n = scanner.nextInt();
int array[] = new int[10];
System.out.println("Enter the array elemets : ");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
int target;
System.out.println("Enter the target : ");
target = scanner.nextInt();
int nums[] = solution.twoSum(array, target);
System.out.println(Arrays.toString(nums));
}
}
class Solution {
public int[] twoSum(int nums[], int target) {
int result[] = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if ((nums[i] + nums[j]) == target) {
result[0] = i;
result[1] = j;
return result;
}
}
}
return null;
}
}
public static int[] twoSum(int[] nums, int target) {
int[] arr = new int[2];
int arrIndex =0;
for(int i =0; i<nums.length; i++){
for(int j = 0;j<nums.length-1;j++){
if( i!=j) {// don't check to itself
if (nums[i] + nums[j] == target) {
arr[arrIndex] = i;
arr[arrIndex + 1] = j;
break;
}
}
}
}
Arrays.sort(arr);
return arr;
}

There are other options to reverse an input numbers on an array? [duplicate]

I am trying to reverse an int array in Java.
This method does not reverse the array.
for(int i = 0; i < validData.length; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
What is wrong with it?
To reverse an int array, you swap items up until you reach the midpoint, like this:
for(int i = 0; i < validData.length / 2; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
The way you are doing it, you swap each element twice, so the result is the same as the initial list.
With Commons.Lang, you could simply use
ArrayUtils.reverse(int[] array)
Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.
Collections.reverse(Arrays.asList(yourArray));
java.util.Collections.reverse() can reverse java.util.Lists and java.util.Arrays.asList() returns a list that wraps the the specific array you pass to it, therefore yourArray is reversed after the invocation of Collections.reverse().
The cost is just the creation of one List-object and no additional libraries are required.
A similar solution has been presented in the answer of Tarik and their commentors, but I think this answer would be more concise and more easily parsable.
public class ArrayHandle {
public static Object[] reverse(Object[] arr) {
List<Object> list = Arrays.asList(arr);
Collections.reverse(list);
return list.toArray();
}
}
I think it's a little bit easier to follow the logic of the algorithm if you declare explicit variables to keep track of the indices that you're swapping at each iteration of the loop.
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
I also think it's more readable to do this in a while loop.
public static void reverse(int[] data) {
int left = 0;
int right = data.length - 1;
while( left < right ) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
// move the left and right index pointers in toward the center
left++;
right--;
}
}
Use a stream to reverse
There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array:
int[] a = {8, 6, 7, 5, 3, 0, 9};
int[] b = IntStream.rangeClosed(1, a.length).map(i -> a[a.length-i]).toArray();
Guava
Using the Google Guava library:
Collections.reverse(Ints.asList(array));
In case of Java 8 we can also use IntStream to reverse the array of integers as:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]
for(int i=validData.length-1; i>=0; i--){
System.out.println(validData[i]);
}
Simple for loop!
for (int start = 0, end = array.length - 1; start <= end; start++, end--) {
int aux = array[start];
array[start]=array[end];
array[end]=aux;
}
If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.
public static void reverseArray4(int[] array) {
int len = array.length;
for (int i = 0; i < len/2; i++) {
array[i] = array[i] ^ array[len - i - 1];
array[len - i - 1] = array[i] ^ array[len - i - 1];
array[i] = array[i] ^ array[len - i - 1];
}
}
This will help you
int a[] = {1,2,3,4,5};
for (int k = 0; k < a.length/2; k++) {
int temp = a[k];
a[k] = a[a.length-(1+k)];
a[a.length-(1+k)] = temp;
}
This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.
I hope you glean something from it.
#Test
public void reverseTest(){
Integer[] ints = { 1, 2, 3, 4 };
Integer[] reversedInts = reverse(ints);
assert ints[0].equals(reversedInts[3]);
assert ints[1].equals(reversedInts[2]);
assert ints[2].equals(reversedInts[1]);
assert ints[3].equals(reversedInts[0]);
reverseInPlace(reversedInts);
assert ints[0].equals(reversedInts[0]);
}
#SuppressWarnings("unchecked")
private static <T> T[] reverse(T[] array) {
if (array == null) {
return (T[]) new ArrayList<T>().toArray();
}
List<T> copyOfArray = Arrays.asList(Arrays.copyOf(array, array.length));
Collections.reverse(copyOfArray);
return copyOfArray.toArray(array);
}
private static <T> T[] reverseInPlace(T[] array) {
if(array == null) {
// didn't want two unchecked suppressions
return reverse(array);
}
Collections.reverse(Arrays.asList(array));
return array;
}
Your program will work for only length = 0, 1.
You can try :
int i = 0, j = validData.length-1 ;
while(i < j)
{
swap(validData, i++, j--); // code for swap not shown, but easy enough
}
There are two ways to have a solution for the problem:
1. Reverse an array in space.
Step 1. Swap the elements at the start and the end index.
Step 2. Increment the start index decrement the end index.
Step 3. Iterate Step 1 and Step 2 till start index < end index
For this, the time complexity will be O(n) and the space complexity will be O(1)
Sample code for reversing an array in space is like:
public static int[] reverseAnArrayInSpace(int[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
while(startIndex < endIndex) {
int temp = array[endIndex];
array[endIndex] = array[startIndex];
array[startIndex] = temp;
startIndex++;
endIndex--;
}
return array;
}
2. Reverse an array using an auxiliary array.
Step 1. Create a new array of size equal to the given array.
Step 2. Insert elements to the new array starting from the start index, from the
given array starting from end index.
For this, the time complexity will be O(n) and the space complexity will be O(n)
Sample code for reversing an array with auxiliary array is like:
public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
int[] reversedArray = new int[array.length];
for(int index = 0; index < array.length; index++) {
reversedArray[index] = array[array.length - index -1];
}
return reversedArray;
}
Also, we can use the Collections API from Java to do this.
The Collections API internally uses the same reverse in space approach.
Sample code for using the Collections API is like:
public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
List<Integer> arrayList = Arrays.asList(array);
Collections.reverse(arrayList);
return arrayList.toArray(array);
}
There are some great answers above, but this is how I did it:
public static int[] test(int[] arr) {
int[] output = arr.clone();
for (int i = arr.length - 1; i > -1; i--) {
output[i] = arr[arr.length - i - 1];
}
return output;
}
It is most efficient to simply iterate the array backwards.
I'm not sure if Aaron's solution does this vi this call Collections.reverse(list); Does anyone know?
public void getDSCSort(int[] data){
for (int left = 0, right = data.length - 1; left < right; left++, right--){
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
Solution with o(n) time complexity and o(1) space complexity.
void reverse(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
public void display(){
String x[]=new String [5];
for(int i = 4 ; i > = 0 ; i-- ){//runs backwards
//i is the nums running backwards therefore its printing from
//highest element to the lowest(ie the back of the array to the front) as i decrements
System.out.println(x[i]);
}
}
Wouldn't doing it this way be much more unlikely for mistakes?
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] temp = new int[intArray.length];
for(int i = intArray.length - 1; i > -1; i --){
temp[intArray.length - i -1] = intArray[i];
}
intArray = temp;
Using the XOR solution to avoid the temp variable your code should look like
for(int i = 0; i < validData.length; i++){
validData[i] = validData[i] ^ validData[validData.length - i - 1];
validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
validData[i] = validData[i] ^ validData[validData.length - i - 1];
}
See this link for a better explanation:
http://betterexplained.com/articles/swap-two-variables-using-xor/
2 ways to reverse an Array .
Using For loop and swap the elements till the mid point with time complexity of O(n/2).
private static void reverseArray() {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
for (int i = 0; i < array.length / 2; i++) {
int temp = array[i];
int index = array.length - i - 1;
array[i] = array[index];
array[index] = temp;
}
System.out.println(Arrays.toString(array));
}
Using built in function (Collections.reverse())
private static void reverseArrayUsingBuiltInFun() {
int[] array = new int[] { 1, 2, 3, 4, 5, 6 };
Collections.reverse(Ints.asList(array));
System.out.println(Arrays.toString(array));
}
Output : [6, 5, 4, 3, 2, 1]
public static void main(String args[]) {
int [] arr = {10, 20, 30, 40, 50};
reverse(arr, arr.length);
}
private static void reverse(int[] arr, int length) {
for(int i=length;i>0;i--) {
System.out.println(arr[i-1]);
}
}
below is the complete program to run in your machine.
public class ReverseArray {
public static void main(String[] args) {
int arr[] = new int[] { 10,20,30,50,70 };
System.out.println("reversing an array:");
for(int i = 0; i < arr.length / 2; i++){
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
For programs on matrix using arrays this will be the good source.Go through the link.
private static int[] reverse(int[] array){
int[] reversedArray = new int[array.length];
for(int i = 0; i < array.length; i++){
reversedArray[i] = array[array.length - i - 1];
}
return reversedArray;
}
Here is a simple implementation, to reverse array of any type, plus full/partial support.
import java.util.logging.Logger;
public final class ArrayReverser {
private static final Logger LOGGER = Logger.getLogger(ArrayReverser.class.getName());
private ArrayReverser () {
}
public static <T> void reverse(T[] seed) {
reverse(seed, 0, seed.length);
}
public static <T> void reverse(T[] seed, int startIndexInclusive, int endIndexExclusive) {
if (seed == null || seed.length == 0) {
LOGGER.warning("Nothing to rotate");
}
int start = startIndexInclusive < 0 ? 0 : startIndexInclusive;
int end = Math.min(seed.length, endIndexExclusive) - 1;
while (start < end) {
swap(seed, start, end);
start++;
end--;
}
}
private static <T> void swap(T[] seed, int start, int end) {
T temp = seed[start];
seed[start] = seed[end];
seed[end] = temp;
}
}
Here is the corresponding Unit Test
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
public class ArrayReverserTest {
private Integer[] seed;
#Before
public void doBeforeEachTestCase() {
this.seed = new Integer[]{1,2,3,4,5,6,7,8};
}
#Test
public void wholeArrayReverse() {
ArrayReverser.<Integer>reverse(seed);
assertThat(seed[0], is(8));
}
#Test
public void partialArrayReverse() {
ArrayReverser.<Integer>reverse(seed, 1, 5);
assertThat(seed[1], is(5));
}
}
Here is what I've come up with:
// solution 1 - boiler plated
Integer[] original = {100, 200, 300, 400};
Integer[] reverse = new Integer[original.length];
int lastIdx = original.length -1;
int startIdx = 0;
for (int endIdx = lastIdx; endIdx >= 0; endIdx--, startIdx++)
reverse[startIdx] = original[endIdx];
System.out.printf("reverse form: %s", Arrays.toString(reverse));
// solution 2 - abstracted
// convert to list then use Collections static reverse()
List<Integer> l = Arrays.asList(original);
Collections.reverse(l);
System.out.printf("reverse form: %s", l);
static int[] reverseArray(int[] a) {
int ret[] = new int[a.length];
for(int i=0, j=a.length-1; i<a.length && j>=0; i++, j--)
ret[i] = a[j];
return ret;
}
public static int[] reverse(int[] array) {
int j = array.length-1;
// swap the values at the left and right indices //////
for(int i=0; i<=j; i++)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
j--;
}
return array;
}
public static void main(String []args){
int[] data = {1,2,3,4,5,6,7,8,9};
reverse(data);
}

Recursion - Combination with in array with no repetition in Java

So I know how to get the size of a combination - factorial of the size of the array (in my case) over the size of the subset of that array wanted. The issue I'm having is getting the combinations. I've read through most of the questions so far here on stackoverflow and have come up with nothing. I think the issue I'm finding is that I want to add together the elements in the combitorial subsets created. All together this should be done recursively
So to clarify:
int[] array = {1,2,3,4,5};
the subset would be the size of say 2 and combinations would be
{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}
from this data I want to see if the subset say... equals 6, then the answers would be:
{1,5} and {2,4} leaving me with an array of {1,5,2,4}
so far I have this:
public static int[] subset(int[] array, int n, int sum){
// n = size of subsets
// sum = what the sum of the ints in the subsets should be
int count = 0; // used to count values in array later
int[] temp = new temp[array.length]; // will be array returned
if(array.length < n){
return false;
}
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < n; j++) {
int[] subset = new int[n];
System.arraycopy(array, 1, temp, 0, array.length - 1); // should be array moved forward to get new combinations
**// unable to figure how how to compute subsets of the size using recursion so far have something along these lines**
subset[i] = array[i];
subset[i+1] = array[i+1];
for (int k = 0; k < n; k++ ) {
count += subset[k];
}
**end of what I had **
if (j == n && count == sum) {
temp[i] = array[i];
temp[i+1] = array[i+1];
}
}
} subset(temp, n, goal);
return temp;
}
How should I go about computing the possible combinations of subsets available?
I hope you will love me. Only thing you have to do is to merge results in one array, but it checks all possibilities (try to run the program and look at output) :) :
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5};
int n = 2;
subset(array, n, 6, 0, new int[n], 0);
}
public static int[] subset(int[] array, int n, int sum, int count, int[] subarray, int pos) {
subarray[count] = array[pos];
count++;
//If I have enough numbers in my subarray, I can check, if it is equal to my sum
if (count == n) {
//If it is equal, I found subarray I was looking for
if (addArrayInt(subarray) == sum) {
return subarray;
} else {
return null;
}
}
for (int i = pos + 1; i < array.length; i++) {
int[] res = subset(array, n, sum, count, subarray.clone(), i);
if (res != null) {
//Good result returned, so I print it, here you should merge it
System.out.println(Arrays.toString(res));
}
}
if ((count == 1) && (pos < array.length - 1)) {
subset(array, n, sum, 0, new int[n], pos + 1);
}
//Here you should return your merged result, if you find any or null, if you do not
return null;
}
public static int addArrayInt(int[] array) {
int res = 0;
for (int i = 0; i < array.length; i++) {
res += array[i];
}
return res;
}
You should think about how this problem would be done with loops.
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] + array[j] == sum) {
//Add the values to the array
}
}
}
Simply convert this to a recursive code.
The best way I can think to do this would be to have each recursive call run on a subset of the original array. Note that you don't need to create a new array to do this as you are doing in your code example. Just have a reference in each call to the new index in the array. So your constructor might look like this:
public static int[] subset(int[] array, int ind, int sum)
where array is the array, ind is the new starting index and sum is the sum you are trying to find

Categories

Resources