I am trying to check whether an element of array has a successor.in other words, make the Ascending sublist to 0 and the rest to 1. the first element of the inputArray should be ignored
if yes then the both element should be 0 if not then 1. For example: for the input
int[] arr = {1,8,1,9,10};
the output should be [1,1,1,0,0]
another example: for the input int[] arr = {1,2,3,9,100}; should the output be: [1,0,0,1,1]
This is my try, but it does not work as expected. Where am i making failur?
public class HelloWorld {
public static void main(String[] args) {
int[] arr = { 1, 8, 1, 9, 10 };
int[] listOutput;
for (int i = 1; i<arr.length - 1; i++) {
if (arr[i] - arr[i + 1] == -1) {
arr[i] = 0;
arr[i + 1] = 0;
} else {
arr[i] = 1;
}
}
System.out.println("Hello World");
for (int i = 0; i<arr.length; i++) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
int[] arr = { 1, 8, 1, 9, 10 };
// assume arr.length >= 2
boolean asc = arr[1] - arr[0] == 1;
for (int i = 1; i < arr.length - 1; i++) {
if (arr[i + 1] - arr[i] == 1) {
arr[i] = 0;
asc = true;
} else {
if (asc) {
asc = false;
arr[i] = 0;
}
else {
arr[i] = 1;
}
}
}
arr[arr.length - 1] = asc ? 0 : 1;
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
This will replace each ascending (by 1) sublist of size greater than 1 with 0s, and will replace each remaining element with 1 (besides the first element which remains unchanged).
You're looping the array from 1 instead of from 0.
Related
Basically, I am trying to make an entirely new array of a new length that contains only the even ints in an array of integers.
However, I am getting an index out of bounds error. Can you help me find what I did wrong?
import java.util.Arrays;
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[i] += arr[i];
}
}
return result;
}
}
You should use a new variable to keep track of the current result index (let's say, j):
public static int[] evens(int[] arr) {
int length = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
// Access result with `j` and update its value
result[j++] = arr[i];
}
}
return result;
}
Also, you can you streams:
int[] array = {1, 3, 4, 5, 6};
int[] even = IntStream.of(array).filter(item -> item%2 == 0).toArray();
System.out.println(Arrays.toString(even));
You need a new index variable for the result array and your assignment is also wrong as instead of assigning you are adding the even number to the result array element.
int j = 0;
int[] result = new int[length];
// add even ints to new array
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0)
{
result[j++] = arr[i];
}
}
Problem is you are using i for the result array AND the original array. You should only increment the result array inside of the IF (when you find an even number) otherwise, you go out of bounds due to i (the original arr) being a larger size than the result array.
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
//add even ints to new array
int resultCount = 0;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[resultCount] += arr[i];
resultCount++;
}
}
return result;
}
Simply when you want to assign a value to result[] you do it with the index in the array arr, 0, 1 and 5. You just have to declare an auxiliary int aux = 0; variable before second loop and increment according to arr[i] % 2 == 0 so true
result[i] += arr[i];
a
int aux = 0;
result[aux++] += arr[i];
Complete code
public class findevens {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[]{4,8,19,3,5,6})));
}
public static int[] evens(int[] arr) {
//create new array by determining length
//of even number ints
int length = 0;
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0) {
length++;
}
}
int[] result = new int[length];
int aux = 0;
//add even ints to new array
for (int i = 0; i < arr.length; i++){
if (arr[i] % 2 == 0) {
result[aux++] += arr[i];
}
}
return result;
}
}
Since you don't really know how long the resultant array will be you can copy them to the front of the current array. Then use the final location as the count of values.
int[] input = {1,2,3,4,5,6,7,8,9};
int k = 0;
for(int i = 0; i < input.length; i++) {
if (input[i] % 2 == 0) {
input[k++] = input[i];
}
}
int[] evens = Arrays.copyOf(input, k);
System.out.println(Arrays.toString(evens));
Prints
[2, 4, 6, 8]
A simple way is to filter even numbers using the Stream API and return the result as an array.
Arrays.stream(arr)
.filter(n -> n % 2 == 0)
.toArray();
Demo:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(Arrays.toString(evens(new int[] { 4, 8, 19, 3, 5, 6 })));
}
static int[] evens(int[] arr) {
return Arrays.stream(arr).filter(n -> n % 2 == 0).toArray();
}
}
Output:
[4, 8, 6]
What went wrong with your code:
result.length is 3 and therefore in result[], the maximum index you can access is 2 (i.e. result.length -1) whereas your second loop counter goes up to 5 (i.e. arr.length - 1) and you are using the same counter to access elements in result[] resulting in ArrayIndexOutOfBoundsException.
If you want to do it in your own way, you need to use a separate counter for result[] e.g.
int[] result = new int[length];
//add even ints to new array
for (int i = 0, j = 0; i < arr.length; i++)
{
if (arr[i] % 2 == 0) {
result[j++] = arr[i];
}
}
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I have two sorted arrays. I need to connect both of them into one new sorted array:
int[] arr1 = {1,2,3,6,8};
int[] arr2 = {4,5,9,12,208,234};
printArr(allSort(arr2,arr1));
}
public static int[] allSort(int[] arr, int[] arr3) {
int[] newArr = new int[arr.length + arr3.length];
int j = 0;
int k = 0;
for (int i = 0; i < newArr.length - 1; i++) {
if(j == arr3.length){
newArr[i] = arr[k];
k++;
}
if(k == arr.length){
newArr[i] = arr3[j];
j++;
}
if(arr[k] > arr3[j]){
newArr[i] = arr3[j];
j++;
} else if (arr[k] < arr3[j]) {
newArr[i] = arr[k];
k++;
}
}
return newArr;
}
I tried to build an array that has a length equal to the length of the both arrays summed together and then run a loop on it.
However, this code returns the error: AArrayIndexOutOfBoundsException: 5.
Just add continue in both the if condition like this,
if(j == arr3.length){
newArr[i] = arr[k];
k++;
continue;
}
if(k == arr.length){
newArr[i] = arr3[j];
j++;
continue;
}
So here anyway the other loop is completed thats why we are iterating and adding all the values so it doesn't need to check all other conditions so we can skip it.
Also,
for (int i = 0; **i < newArr.length**; i++)
Since you are checking "<".
The ArrayIndexOutOfBoundsException() is an Exception and what it basically means is that at some point you're trying to access a element of an array with an illegal index. Refer to the ArrayIndexOutOfBoundsException Documentation for more informations.
after looking to your code at some point here are the index's values:
.
In the loop you're calling arr[k] with k = 5 in if(arr[k] > arr3[j]) as arr is an Array of length 5 and thus has a maximum index of 4 and that is why you're getting an out of bounds exception.
Your main problem is control when first array finished.
I made some adjusts on your code and now it's working.
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3, 6, 8 };
int[] arr2 = { 4, 5, 9, 12, 208, 234 };
int[] newArr = allSort(arr1, arr2);
for (int i = 0; i <= newArr.length - 1; i++) {
System.out.println(" " + newArr[i]);
}
}
public static int[] allSort(int[] arr1, int[] arr2) {
int j = 0;
int k = 0;
boolean endArr1 = false;
int[] newArr = new int[arr1.length + arr2.length];
for (int i = 0; i <= newArr.length - 1; i++) {
if (arr1[k] < arr2[j] && !endArr1) {
System.out.println("k: " + k + " " + arr1.length);
newArr[i] = arr1[k];
if(k < arr1.length-1)
k++;
else
endArr1 = true;
} else if (arr2[j] < arr1[k] || endArr1) {
System.out.println("j: " + j + " " + arr2.length);
newArr[i] = arr2[j];
if(j < arr2.length-1)
j++;
}
}
return newArr;
}
I need to return an index of the element where the sum of the elements on the left is equal to the sum of the elements on the right. e.g for the array [-3, 8, 3, 1, 1, 3], the return value is index 2 since the sum of the elements to the left of the first 3 ([-3, 8]) is the same as the sum of elements to its right ([1, 1, 3]).
So I started by doing a liner-search function to find the intended index,
then after that i attempted to split the array left and right of the selected index but had no success doing so
I haven't had much success getting it to work
//linear-search portion,x is the index selected to be split point
public static int findindex(int arr[], int x) {
//if array is null
if (arr == null) {
return -1;
}
//find array length
int len = arr.length;
int i = 0;
//traverse the array
while (i < len) {
//if the i-th element is is x then return the index
if (arr[i] == x) {
return i;
} else {
i = i + 1;
}
}
//splint array portion,returns index if not possible
int leftsum = 0;
//treverse array elements
for (int i = 0; i < x; i++) {
//adds current elements to left
leftsum += arr[i];
//find sum of remader the array elements to rightsum
int rightsum = 0;
for (int j = i + 1; j < x; J++)
rightsum += arr[j];
//split pint index
if (leftsum == rightsum)
return i + 1;
}
//if not possible return
return -1;
}
// driver code
public static void main(String[] args) {
int[] array1 = { -3, 8, 3, 1, 1, 3 };
System.out.println(findindex(array1));
}
You can use the below code for solve the problem
static void Main(string[] args)
{
int[] array1 = {-3, 8, 3, 1, 1, 3}; // { -3, 8, 3, 1, 1, 3, 6, 1, 19 };
int indexPosition = GetIndex(array1);
if (indexPosition != -1)
{
Console.WriteLine(indexPosition);
}
}
static int GetIndex(int[] param)
{
if (param.Length < 0) return -1;
int leftSum = 0, rightSum = 0; int rightIndex = param.Length - 1;
for (int i = 0; i < param.Length; i++)
{
if (i < rightIndex)
{
if (leftSum > rightSum)
{
rightSum += param[rightIndex];
rightIndex -= 1;
}
else
{
if (i < rightIndex)
{
leftSum += param[i];
}
}
}
else
{
rightSum += param[rightIndex]; // if you are looking for only index position you can comment this line,
//variable rightSum and leftSum will give you the sum of left and right side of the array
rightIndex -= 1;
break;
}
}
return rightIndex;
}
Hope this helps .
Your code has two problems. One is that the variable i is defined two times in the same method. Another problem is that you only provide one input parameter and not two. I don't even know what parameter x should be and therefore also removed it from my improved version. I also removed the while loop as I don't understand what you tried to do there. Anyways here is my version of the code:
public static int findindex(int arr[]) {
if (arr == null) {
return -1;
}
int len = arr.length;
int leftsum = 0;
for(int i = 0; i < len; i++)
{
leftsum += arr[i];
int rightsum = 0;
for(int j = i+2; j < len; j++)
rightsum += arr[j];
if(leftsum == rightsum)
return i+1;
}
return -1;
}
public static void main(String[] args) {
int[] array1 = {-3, 8, 3, 1, 1, 3};
System.out.println(findindex(array1));
}
When I removed everything unneccessary from your code the only bug was that you should have initialized j with i+2, because you don't want to include the element at the index itself and only the right side, if I understood the requirements of your code correctly.
I need to use recursion that takes in array of integers and has the even integers appear before the odd integers i.e an array of [1,2,3,4,5] should look like [2,4,1,3,5]. Please note that the integers do not need to be in any specific order just even before odd. Here is what I have so far, any help would be appreciated!
public class EBOMain {
static int[] Array = { 1, 2, 3, 4, 5, 6};
static int n;
public static void main(String[] args) {
System.out.print("Array before sort: " );
for (int i = 0; i < Array.length; i++)
System.out.print(Array[i] +" ");
n = Array.length;
rearrange(Array, n);
System.out.print("\nArray after sort: " );
for (int i = 0; i < Array.length; i++)
System.out.print(Array[i] +" ");
}
public static void rearrange(int []Array,int n){
if (n==0)
return;
else if(Array[n-1]%2==0) {
for(int i=0;i<n-1;i++) {
if(Array[i]%2!=0) {
int temp = Array[i];
Array[i]= Array[n-1];
Array[n-1] = temp;
rearrange(Array,n-1);
}
}
}
else
rearrange(Array,n-1);
}
}
You forgot to initialize n with the length of the array in the first call to rearrange. See this corrected code. Make sure you use Java code conventions; I renamed the Arrayvariable to array.
public class EBOMain {
static int[] array = { 1, 2, 3, 4, 5, 6 };
public static void main(String[] args) {
System.out.print("array before sort: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
rearrange(array, array.length); // <-- Change is here
System.out.print("\narray after sort: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void rearrange(int[] array, int n) {
if (n == 0) {
return;
} else if (array[n - 1] % 2 == 0) {
for (int i = 0; i < n - 1; i++) {
if (array[i] % 2 != 0) {
int temp = array[i];
array[i] = array[n - 1];
array[n - 1] = temp;
rearrange(array, n - 1);
}
}
} else {
rearrange(array, n - 1);
}
}
}
Output:
array before sort: 1 2 3 4 5 6
array after sort: 6 2 4 1 3 5
I would like to have an optimized java program to print the highest digits to the right of an array.
For eg: a[]={3,6,7,2,4,1}
output should be 7,4,1.
I wrote a program like below
class Rightlargest{
public static void main(String args[]){
int a[]={1,3,2,4,5,2};
int c[]=new int[20];
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]<a[j]){
a[i]=a[j];
}
}
c[i]=a[i];
}
for(int i=0;i<c.length;i++)
{
if(c[i]!=c[i+1])
System.out.println(c[i]);
}
}
}
Even though I got the correct output, its throwing array out of bounds exception along with it.
Please advise.
When i equals of a.length-1, j takes value a.length and that is the problem.
The array has length of 5 elements. It means the last element has index of 4
Fix for : ArrayIndexOutOfBoundsException
i < c.length -1
for (int i = 0; i < c.length -1; i++) { // c.length -1
if (c[i] != c[i + 1])
System.out.println(c[i]);
}
This will not exceed the array index out of bounds. Your loop was executing 1 index more than array length.
As array length->20 and array index starts from 0, Your loop was iterating (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20) making last index to be checked as 21 which was out of array bounds.
Working code with fix:
public class RightLargest {
public static void main(String args[]) {
int a[] = { 1, 3, 2, 4, 5, 2 };
int c[] = new int[20];
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
a[i] = a[j];
}
}
c[i] = a[i];
}
for (int i = 0; i < c.length -1; i++) {
if (c[i] != c[i + 1])
System.out.println(c[i]);
}
}
}