Comparing elements in a circular array(java) - java

i am trying to formulate a for loop that will take an array, for instance of 5 elements, and will allow me to treat a[0] as if it is after a[4], and a[4] as if it was before a[0].
I cannot change the array, and it stores a thread in each element, so i would rather make it as simple as possible to not corrupt the contents of the thread(threads are synchornized and using reentrantlock - so the question is only about array).
I want to make this simple for loop:
for (int i = 0; i < ARRAYSIZE; i++)
to allow me to treat it as if it was a cyclic array. I thought of using the mudolo operation to achieve that, but that doesn't work either. here's what i tried:
for (int i = i+1 % n; i < ARRAYSIZE; i++)
but that doesn't work as well. What I am trying to do is basically check if array[i] is larger than array[i+1] or array[i-1].
would appreciate your assistance.

Use the modulo operator on the loop variable i by the size of the array:
public static void main(String [] args) {
int [] arr = {1, 5, 4, 3, 3, 4, 3, 1};
int ARRAYSIZE = arr.length;
for (int i = 0; i < ARRAYSIZE; i++) {
int index = i % ARRAYSIZE;
int indexUpper = (i + 1) % ARRAYSIZE;
//access array using index
if (arr[index] == arr[indexUpper]) {
System.out.format("Elements %d and %d are equals.\n", index, indexUpper);
}
}
}
Note how for the upper value you want to cycle through, you need to do (i + 1) % ARRAYSIZE to ensure you get the next element. To get the element two places over, add 2 instead, or whatever modifier you choose.
This test shows how elements 7 and 0 are equal because it is cyclical.
Output:
Elements 3 and 4 are equals.
Elements 7 and 0 are equals.

Related

How to fill in only the even indexes of an ArrayList?

So I was trying to produce an arraylist where the even indexes were all filled. Something like this [1, -, 1, -, 1, -........]. But it's giving me an index out of bounds error. Why is that?
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<>(10);
for (int i=0; i<11; i+=2) {
a.add(i, new Integer(1234));
}
}
}
Remember indices always start with 0.
You've created an arraylist with size 10, which means you should iterate through index 9, not 10.
Your for loop should be:
for (int i = 0; i < 10; i += 2)
Arrays use zero based indexing meaning you can reference a[0] through a[9]. so your constraint in the for loop
Should be i < 10. I’ll edit this answer and give more detail when I get home.
First, you loop constraint is off, for an array (and ArrayList) of size 10, indices are 0 through 9, means you need to check for i < 10.
Second, the parameter of ArrayList constructor (10 in this case) is the capacity, but not size - it's still empty, no actual elements in there. So you need to add zeroes (or nulls) in the loop too:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
a.add(1234);
} else {
a.add(0); // or a.add(null)
}
}

Creating a program that increments Arrays

An integer array stores values 3,2,3,4,5. I am trying to create a program that increments these values by 2 and then saves the result into the same array using a for loop. I tried but something is wrong with my code, here:
public class ArrayClass {
int a[] = {2, 3, 3, 4, 5};
}
public class ArrayObject {
public static void main(String[] Ella) {
int a[] = new int[5];
int i;
for (i = 2; i < a.length; i = i + 2) {
a[i] = i + 2;
System.out.println(a[i]);
}
}
}
This should work:
for (i = 0; i < a.length; i++) {
a[i] += 2;
System.out.println(a[i]);
}
You see, when increasing every single value of an array, the index has to be 0 and max the array's length. By adding one to i, the indexing of the array increases by one, which means the next number will be increased by two. what you did was add two to the "i" variable which means that only 3 of the varialbes would have been changed.
Please make below change to your code.It will work.
for (i = 0; i < a.length; i++) {
a[i] = a[i] + 2;
System.out.println(a[i]);
}
The error is that when you do i = i + 2, you are just incrementing the position index, not the actual value in that position.
you need to do:
a[i] = a[i]+2;
Let me explain what a[i] is:
|3|2|3|4|5|
1 2 3 4 5
The first row are the values. The second row is the index. "Index" means the position number of each of positions in the array.
Another problem is that, when you initialise i, it need to be i=0. That is because i array indices (plural of index) always start from 0. That means that a[0] is the first position in the array That would be number 3 from your data set.

sort an array, so that first and last element will form a "pair"

I have an array of objects which I want to sort by indices in the following order. I will always have an array size to the power of 2.
Example array size: 8. Indices: [0][1] [2][3] [4][5] [6][7]
After sort: [0][7] [1][6] [2][5] [3][4]
So basically alternating between first and last element which was not sorted yet.
I already thought of a way of doing it, and I can get the "pairs" but they are in the wrong order (and I think it would not work with any other to the power of 2 array?).
Here I'm using an int array and their indices as values to make it simpler for myself.
int[] array = new int[]{0,1,2,3,4,5,6,7};
int[] sortedArray = new int[8];
for(int i = 0; i < array.length; i+=2){
sortedArray[i] = array[i];
}
for(int i = 1; i < array.length; i+=2){
sortedArray[i] = array[array.length - i];
}
Output: [0][7] [2][5] [4][3] [6][1]
You can do this with a single loop. Consider the following algorithm:
int[] array = new int[]{0,1,2,3,4,5,6,7};
int[] sortedArray = new int[8];
for(int i = 0; i < array.length; i+=2){
sortedArray[i] = array[i/2];
sortedArray[i + 1] = array[array.length - i/2 - 1];
}
System.out.println(Arrays.toString(sortedArray)); // prints [0, 7, 1, 6, 2, 5, 3, 4]
This creates the final array by setting two values at a time:
every even index of the result array is mapped with the first values of the initial array
every odd index of the result array is mapped with the last values of the initial array
Here's a recursive approach to it, and improvements exist.
Motivation: Work your way through the array until you're left with only two values to compare. Once you're done, simply print them. Otherwise, print the value and continue slicing the array. We use two index locations to help us walk through the array, as each one governs its end of the array. We cease recursion when the difference between our start and end index is 1.
Steps to guard against silly things, like a zero-length array, I leave as an exercise for the reader.
public static void arrangeArray(int[] array) {
arrangeArray(array, 0, array.length - 1);
}
private static void arrangeArray(int[] array, int startIndex, int endIndex) {
System.out.printf("[%d][%d]\t", array[startIndex], array[endIndex]);
if(endIndex - startIndex > 1) {
arrangeArray(array, startIndex + 1, endIndex - 1);
}
}
You can extend a List and then Override the way this List works with indices so 0 remains 0 but 1 becomes physically a 2 in your internal array.
If you implement this object correctly, Collections.sort() won't see the difference. Then you can add your methods to get the internal Array for whatever you have to do.
The advantage of this approach is performance. You don't have to scramble the list yourself in a secondary step.
class swap
{
public static void main(String args[])
{
int arr[]={0,1,2,3,4,5,6,7};
int sorted[]=new int[8];
int end=7;
int i=1,j;
for(int k=0;k<8;k++)
{
sorted[k]=arr[k];
}
for(j=1;j<8;j=j+2)
{
sorted[j]=arr[end];
end--;
}
for(j=2;j<8;j=j+2)
{
sorted[j]=arr[i];
i++;
}
for(int k=0;k<8;k++)
System.out.println(sorted[k]);
}
}

Java Recursion on an ArrayList

I have an ArrayList of int.
The main program - calls a method to get a list of the sum of all (n member) combination of the members of the list. Where n can be anywhere between 2 - 6. E.g. Original List is {1,2,3,4,5}; Then the output should be {6, 7, 8, 8, 9, 10, 9, 10, 11, 12} where n = 3;
I am looking for the optimum way to do this. Right now, the way I have written the program (which is working) is without recursion. I have methods for all numbers i.e.
MyMethod2 -- gives me all the sum of 2 member combinations of MyArrayList
MyMethod3 -- gives me all the sum of 3 member combinations of MyArrayList
MyMethod4 -- gives me all the sum of 4 member combinations of MyArrayList
......
So, you can see that there is a lot of duplicate set of codes.
Also the way the program has currently been written (e.g. My Method3):
MyMethod3
ArrayList<Integer> sum = new ArrayList<Integer>();
for (i = 0; i < MyArrayList.size(); i++){
for (j = i + 1; j < MyArrayList.size(); j++){
for (k = j + 1; k < MyArrayList.size(); k++){
int total = MyArrayList.get(i) + MyArrayList.get(j) + MyArrayList.get(k);
sum.add(total);
}
}
}
return sum;
The MyMethod for n = 6, can become pretty long. Also "n" can change in the future.
Is there a better way to do this using recursion to minimize duplicate code, and using the number n as a variablefor the method call. Is there a standard package in Java that can help with recursion.
Adding the Code based on #Maertin suggestion - which worked for me
ArrayList<Integer> myArray = new ArrayList<Integer>();
myArray.add(5);
myArray.add(6);
myArray.add(4);
myArray.add(2);
myArray.add(1);
ArrayList<Integer> finalSumArray = combineTwoArrayList(3, myArray, myArray);
public static ArrayList<Integer> combineTwoArrayList(int n, ArrayList<Integer> origArray, ArrayList<Integer> finalSumArray) {
if (n == 1) return finalSumArray;
ArrayList<Integer> finalSumArray = new ArrayList<Integer>();
for (int i = 0; i < sumArray.size() - 1; i++){
for (int j = i + 1; j < origArray.size(); j++){
finalSumArray.add(sumArray.get(i) + origArray.get(j));
}
}
--n;
return combineTwoArrayList(n, origArray, finalSumArray);
}
You are correct in wanting to do this via recursion, because now, instead of having three separate methods, you could have one method with a parameter n for n-member combinations.
public int nCombinationSum( int n, int i, ArrayList<Integer> arr, ArrayList<Integer> sumArr) {
/* Gets n-combination sums and puts into sumArr
Input: n consecutive element combination, current index i in arr, and output ArrayList
Output: Gets n consecutive element combinations in arr from index i to index (i + n) and puts into sumArr
*/
//**BASE CASE**
//if index out of arr bounds
if( i + n > arr.size() )
return 0;
//**RECURSIVE CASE**
else {
//sum of values in arr from i to (i + n)
int currComboSum = 0;
for( int j = 0; j < n; j++ )
currComboSum += arr.get(j);
//adding sum to next element in resultant array
sumArr.add( currComboSum );
return nCombinationSum( n, i + 1, arr, sumArr );
}
}
USAGE
In your main method, you can call nCombinationSum and provide it with the kind of combination (n), starting index (in your case, 0), and arrayList (arr), and the arrayList you want to append the sums in (sumArr).
This also has the potential added benefit of allowing you to add any n-combination sum starting from a certain index. If you would like, you could add an end index as well, but this is fairly extended as it is.
EDIT: Please edit your question to reflect that you want the result to be an arrayList of sums, rather than the total sum. It is not clear right now.
Basically, what you want to do with recursion, in general, is to set a base case and a recursive case.
Your base case would be if your index is out of bounds, because you're going to call all elements from index i to i + n.
For the recursive case, use the algorithm below to account for each element in arr, then just keep returning the function with the next index value, and the function will continue running until it is out of bounds.
Algorithm
Getting sum of n-combination elements
Appending that sum into resultant array sumArr
Feel free to refer to the code above for reference.
You can use recursion. Basically, you should have only two for loops. (which is the code for two member combinations). When you compute 'total', pass each 'total' value to an ArrayList MyArrayList2. Now for MyMethod3, you use the elements of MyArrayList2 and the original ArrayList and find new 'total' values again and pass that to MyArrayList3. For MyMethod4, you use the elements of MyArrayList3 and the original ArrayList and find new 'total' values again and pass that to MyArrayList4.... ....

Java: Array Index Out of Bounds Exception

System.out.print("Enter an integer: ");
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int lArray = x - 2;
int[] newArray = new int[lArray];
System.out.println("Let's display all possible integers...");
for (int i = 0; i <= newArray.length; i++) {
newArray[i] = i + 2;
System.out.print(newArray[i] + " ");
}
I've just started Java recently, but I sure that if I coded similarly in another language, I would face the same problem. This is an excerpt from an application where it lists all the prime numbers up until the user's input.
The reason why x-2 is used as the definition of lArray is because the length of the array will be all the integers from 2 until the number {2, 3, 4, 5... x}.
I noticed that for the line
for (int i = 0; i <= newArray.length; i++) {
if I change i <= newArray to i < newArray, the code works without error. However, the user's input, x, is left out which is a problem if x is prime.
You should use < and not <= in:
for (int i = 0; i <= newArray.length; i++)
^^
If foo any array, valid index of foo are [0,foo.length-1]
Using foo.length as an index will cause ArrayIndexOutofBoundsException.
And also lArray which contains number of natural numbers <=x but excluding only one number 1, its value should be x-1 and not x-2.
Change the array length to (x - 1) instead, and go with the < condition, which you've already found is necessary to avoid the out-of-bounds exception.
The reason you need an array that is 1 element larger than what you're currently using is because there are (n - 1) candidates that must be considered between 2 and n , not (n - 2).
For example, there are two candidates less than or equal to three (2 and 3), both of which, coincidentally, happen to be prime.
for (int i = 0; i <= newArray.length; i++) //should be <, not <=
for (int i = 0; i < newArray.length; i++)
You need to use:
int lArray = x - 1;
And change your condition to use < instead of <=.
In Java as in C/C++, arrays are ZERO based. So your array of N values will go from index 0 to N-1.
Taking your example: {2, 3, 4, 5... x}.
You will need N-1 values to store all positive numbers but 1 in an integer array. So, if N equals to 4, your array will be:
newArray[0] = 2;
newArray[1] = 3;
newArray[2] = 4;
Hence, array lenght must be 3 (N-1).

Categories