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.
Related
i dont kow ehy my programs dont run.
i am trying to reverse my array through user defined function.
i can give an input but cannot find out the answer.
import java.util.*;
public class reverseanarray{
public static int reversea(int array[]){
int swap;
int j=array.length;
for(int i=0;i<array.length/2;i++){
swap=array[i];
array[i]=array[j];
array[j]=swap;
j--;
}
return j;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
//System.out.println();
//int a = sc.nextInt();
System.out.println("please input the length");
int y=sc.nextInt();//INPUT OF LENGTH OF ARRAY
int arr[]=new int[y];
//INPUT ARRAY
for(int r=0;r<arr.length;r++){
System.out.println("please input the "+r+" index value");
arr[r]=sc.nextInt();
}
System.out.println(reversea(arr));
for(int i=0;i<y;i++){
System.out.println(arr[i]);
}
}
}
The code is giving you an ArrayIndexOutOfBoundsException, as you are trying to address an array index which is beyond array limits. The reason for this is, that arrays are 0-indexed, so an array of length 10 has indexes 0-9. Your code does not take this into account when defining field j.
The only change you need to make is change that line:
int j = array.length;
into this one:
int j = array.length - 1;
You could also do some more refactoring and rewrite method as:
public static int[] reversea(int array[]) {
int swap;
for (int i = 0, j = array.length-1; i < j; i++, j--) {
swap = array[i];
array[i] = array[j];
array[j] = swap;
}
return array;
}
Instead of returning useless value of j after reversing, the refactored method returns the array in reversed order.
PS: Please use CamelCase for your class names.
The logic is in method "reverseArray(int[] array)"
import java.util.Arrays;
public class ArrayReverse {
public static void main(String[] args) {
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
System.out.println("original array :: " + array + " : " + Arrays.toString(array));
reverseArray(array);
System.out.println("reversed array :: " + array + " : " + Arrays.toString(array));
}
public static void reverseArray(int[] array) {
// We will iterate on the half of the array length
// If the array size is an even number (e.g.: {1 ,2 ,3 ,4} we will iterate on
// the half of the array size (e.g.: 2 numbers)
// If the array size is an odd number (e.g.: {1 ,2 ,3 ,4 ,5} we will iterate on
// the half of the array size minus 1 (e.g.: 2 numbers)
for (int i = 0; i < array.length / 2; i++) {
// We add the value of the number at index i in array (let's say its value is x)
// to the value of the number at index (length of array-i-1) of the array (let's
// say value y)
array[i] = array[i] + array[array.length - 1 - i];
// Now the value of array[i] is x+y
// We retrieve the value of the number at index (length of array-i-1) from the
// number at index i in array
array[array.length - 1 - i] = array[i] - array[array.length - 1 - i];
// Now the value of array[length of array-i-1] is (x+y)-y=x
// And finally, we retrieve the value of the number at index (length of
// array-i-1) from number at index i in array
array[i] = array[i] - array[array.length - 1 - i];
// Now the value of array[i] is (x+y)-x=y
// We have swapped x and y values in the array
}
}
}
This can seem a bit complicated but this method only use addition and substraction, no complicated algorithm.
Furthermore, there is no variable instance created except variable "i" as a counter on array index.
And, finally, no new array is created. The reversed array is the original array instance simply reversed.
I need to create an array, compare each pair of this array, and then find and print the largest element of each pair. I have created an array like below, but it's printing me only the two largest of the whole array!
public class Main {
public static void main(String[] args) {
int[] arr = {1, -5, 2, 6, 10, 7};
int a = arr[0];
int b = arr[1];
for (int i = 0; i<arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (a > b || b > a) {
a = arr[i];
b = arr[j];
}
}
}
System.out.println(a);
System.out.println(b);
}
}
In the example below, I have 3 pairs (6 elements) and I want to get maximum of each pair as an example:
Input: {1, -5, 2, 6, 10, 7}
Output: 1, 6, 10
I appreciate any help you can provide.
Your program does not print the two largest numbers. It prints the two last numbers of the array. If you add a 200 in the mid of the array, it will still print 10 and 7.
Also, the System.out.println()-lines are outside any loop, so they will run only once.
If you want to get the higher number out of the first and second, the third and fourth, fifth and sixth element and so on (due to the expected output, I assume this is what you want to get), then the for-loop will fail like this. On each run of the loop, it will check if a > b or b > a. If that's the case, a gets the value of arr[i] and b the value of arr[j]. On the last run, i will be the second last value and j the last value of the array, so you will always get the last two elements. Unless you compare two times the same value in the array, then a and b will get the same value and nothing will change anymore from there.
If you want to compare the pairs like I described, then maybe you should instead try something like this:
for(int i = 0; i < arr.length; i+=2)
{
if(!(i == arr.length-1)) // in case there is no i+1 index anymore
{
if(arr[i]>arr[i+1])
{
System.out.println(arr[i]);
}
else if(arr[i+1]>arr[i])
{
System.out.println(arr[i+1]);
}
}
}
I came across a Hackerearth coding problem where you have to perform the following tasks over an integer array-
Search for a particular number in the array and replace it's occurrences with 1
Move all the 1s to the first part of the array, maintaining the original order of the array
For example- if we have an integer array {22,1,34,22,16,22,35,1}, here we search for the number "22" (let us assume it is present in the array), replace it with 1 and move all those 1s (including the 1s already present) to the first part of the array and the resultant array should look like {1,1,1,1,1,1,34,16,35} -maintaining the original order of the array, preferably in Java.
I actually have coded a solution and it works fine but is not optimal, can anyone help me find an optimal solution (w.r.t. time-space complexity)?
Below is my solution-
public static void main(String[] args) {
int[] n = rearr(new int[] {22,1,34,22,16,22,1,34,1}, 22);
for(int i=0; i<n.length; i++) {
System.out.print(n[i]+" ");
}
}
static int[] rearr(int[] a, int x) {
int[] temp = new int[a.length];
int j=0, c=0, k=0;
//search and replace
for(int i=0; i<a.length; i++) {
if(a[i] == x) {
a[i] = 1;
}
}
//shift all 1s to first part of array or shift all non-1s to last part of the array
for(int i=0; i<a.length; i++) {
if(a[i] != 1) {
temp[j] = a[i];
j++;
}
if(a[i] == 1) {
c++;
}
}
j=0;
for(int i=0; i<a.length && c>0; i++, c--) {
a[i] = 1;
j++;
}
for(int i=j ;i<a.length; i++) {
a[i] = temp[k];
k++;
}
return a;
}
This can be done in linear time and space complexity, by returning a completely new list instead of modifying the original list.
static int[] rearr(int[] a, int x) {
// allocate the array we'll return
int[] b = new int[a.length];
int fillvalue = 1;
// iterate backwards through the list, and transplant every value OTHER than
// (x or 1) to the last open index in b, which we track with b_idx
int b_idx = b.length - 1;
for (int i = a.length - 1; i >= 0; i--) {
if (a[i] != x && a[i] != fillvalue)) {
b[b_idx] = a[i];
b_idx--;
}
}
// once we've gone through and done that, fill what remains of b with ones
// which are either original or are replacements, we don't care
for (int i = b_idx; i >= 0; i--) {
b[i] = fillvalue;
}
return b;
}
This is linear space complexity because it requires additional space equal to the size of the given list. It's linear time complexity because, in the worst case, it iterates over the size of the list exactly twice.
As a bonus, if we decide we want to leave the original 1s where they were, we can do that without any trouble at all, by simply modifying the if condition. Same if we decide we want to change the fill value to something else.
Doing this with constant space complexity would require O(n^2) list complexity, as it would require swapping elements in a to their proper positions. The easiest way to do that would probably be to do replacements on a first run through the list, and then do something like bubblesort to move all the 1s to the front.
This can be done in a single iteration through the array. We can use 2 pointer approach here where we will use on pointer to iterate through the array and other one to point to the index of 1 in the array.
The code is below:
public static void main(String[] args) {
// input array
int[] arr = { 22, 1, 34, 22, 16, 22, 35, 1, 20, 33, 136 };
// element to be replaced
int x = 22;
int j = -1;
for (int i = arr.length - 1; i >= 0; i--) {
if (arr[i] == 1 || arr[i] == x) {
if (j == -1) {
j = i;
}
// incase arr[i]==x
arr[i] = 1;
} else {
if (j != -1) {
arr[j] = arr[i];
arr[i] = 1;
j--;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
Here we initialise j=-1 since we consider there are no 1's present in the array.
Then we start iterating the array from the end towards the starting of the array as we have to push all the 1's to the starting of the array. Now when we reach to 1 or x (particular number in your case), we check if this is first occurrence of the x or 1, if yes then we initialise the j with this index and change arr[i] = 1 because this could be equal to x then we need to make it 1. If the arr[i] is not 1 or x it means its a number which we need to push at back of the array. We check if we have position of 1 or j=-1. If j=-1 it means this number is already pushed back at end of array else we swap the number at i and j, and decrement j by 1.
At the end of the array we will have the array sorted in a fashion which is required.
Time Complexity: Since we are only iterating the array one, hence the time complexity is O(n).
Space Complexity: Since there are no extra space being used or constant space being used hence the space complexity is O(1)
So, I am trying to create 2 randomly generated arrays,(a, and b, each with 10 unique whole numbers from 0 to 20), and then creating 2 arrays with the info of the last two. One containing the numbers that appear in both a and b, and another with the numbers that are unique to a and to b. The arrays must be listed in a "a -> [1, 2, 3,...]" format. At the moment I only know how to generate the 2 arrays, and am currently at the Intersection part. The problem is, that I can create a array with the correct list of numbers, but it will have the same length of the other two, and the spaces where it shouldn't have anything, it will be filled with 0s when its supposed to create a smaller array with only the right numbers.
package tps.tp1.pack2Arrays;
public class P02ArraysExtractUniqsAndReps {
public static void main(String[] args) {
int nbr = 10;
int min = 0;
int max = 20;
generateArray(nbr, min, max);
System.out.println();
}
public static int[] generateArray(int nbr, int min, int max) {
int[] a = new int[nbr];
int[] b = new int[nbr];
int[] s = new int[nbr];
s[0] = 0;
for (int i = 0; i < a.length; i++) {
a[i] = (int) (Math.random() * (max - min));
b[i] = (int) (Math.random() * (max - min));
for (int j = 0; j < i; j++) {
if (a[i] == a[j]) {
i--;
}
if (b[i] == b[j]) {
i--;
}
}
}
System.out.println("a - > " + Arrays.toString(a));
System.out.println("b - > " + Arrays.toString(b));
for (int k = 0; k < a.length; k++) {
for (int l = 0; l < b.length; l++) {
if (a[k] == b[l]) {
s[l] = b[l];
}else {
}
}
}
System.out.println("(a ∪ (b/(a ∩ b)) - > " + Arrays.toString(s));
return null;
}
public static boolean hasValue(int[] array, int value) {
for (int i = 0; i < array.length; i++) {
if (array[i] == value) {
return true;
}
}
return false;
}
}
Is there any way to create the array without the incorrect 0s? (I say incorrect because it is possible to have 0 in both a and b).
Any help/clarification is appreciated.
First, allocate an array large enough to hold the intersection. It needs to be no bigger that the smaller of the source arrays.
When you add a value to the intersection array, always add it starting at the beginning of the array. Use a counter to update the next position. This also allows the value 0 to be a valid value.
Then when finished. use Array.copyOf() to copy only the first part of the array to itself, thus removing the empty (unfilled 0 value) spaces. This works as follow assuming count is the index you have been using to add to the array: Assume count = 3
int[] inter = {1,2,3,0,0,0,0};
inter = Arrays.copyOf(inter, count);
System.out.println(Arrays.toString(inter);
prints
[1,2,3]
Here is an approach using a List
int[] b = {4,3,1,2,5,0,2};
int [] a = {3,5,2,3,7,8,2,0,9,10};
Add one of the arrays to the list.
List<Integer> list = new ArrayList<>();
for(int i : a) {
list.add(i);
}
Allocate the intersection array with count used as the next location. It doesn't matter which array's length you use.
int count = 0;
int [] intersection = new int[a.length];
Now simply iterate thru the other array.
if the list contains the value, add it to the intersection array.
then remove it from the list and increment count. NOTE - The removed value must be converted to an Integer object, otherwise, if a simple int value, it would be interpreted as an index and the value at that index would be removed and not the actual value itself (or an Exception might be thrown).
once finished the intersection array will have the values and probably unseen zeroes at the end.
for(int i = 0; i < b.length; i++) {
int val = b[i];
if (list.contains(val)) {
intersection[count++] = val;
list.remove(Integer.valueOf(val));
}
}
To shorten the array, use the copy method mentioned above.
intersection = Arrays.copyOf(intersection, count);
System.out.println(Arrays.toString(intersection));
prints
[3, 2, 5, 0, 2]
Note that it does not matter which array is which. If you reverse the arrays for a and b above, the same intersection will result, albeit in a different order.
The first thing I notice is that you are declaring your intersection array at the top of the method.
int[] s = new int[nbr];
You are declaring the same amount of space for the array regardless of the amount you actually use.
Method Arrays.toString(int []) will print any uninitialized slots in the array as "0"
There are several different approaches you can take here:
You can delay initializing the array until you have determined the size of the set you are dealing with.
You can transfer your content into another well sized array after figuring out your result set.
You could forego using Array.toString, and build the string up yourself.
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.