print highest number to the right in an array - java

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]);
}
}
}

Related

why my selection sort program is not working?

public class first {
public static void main(String args[]){
int arr[]={5,4,1,3,2};
for(int i=0; i<arr.length-1;i++){
int smallest=arr[i];
for(int j=i+1; j<arr.length;j++){
if(smallest>arr[j]){
smallest=arr[j];
}
}
//swap
int temp=smallest;
smallest=arr[i];
arr[i]=temp;
}
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
}
i have done this problem by getting the smallest in terms of index number
and the program works properly .
but when i am taking smallest in terms of number present at index number ,
this program did not work.your text
you need to save the smallest number index not the number it self so you know the positions to make the swap
for (int i = 0; i < arr.length - 1; i++) {
int indexOfSmallestNum = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[indexOfSmallestNum] > arr[j]) indexOfSmallestNum = j;
}
int temp = arr[i];
arr[i] = arr[indexOfSmallestNum];
arr[indexOfSmallestNum] = temp;
}

How to make a new array out of only even numbers?

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];
}
}

HackerRank closest number

Given a list of unsorted integers, find the pair of elements that have the smallest absolute difference between them. If there are multiple pairs, find them all.
My reasoning was to compare each: arr[j] - arr[i] with lowest and if it is smaller or equal to that, add that value to the array lowest, but it's not working.
Code:
static int[] closestNumbers(int[] arr) {
int lowest = arr[1] - arr[0];
int lowestArray[] = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (Math.abs(arr[j] - arr[i]) < lowest) {
lowest = Math.abs(arr[j] - arr[i]);
}
}
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] == lowest) {
lowestArray[i] = arr[i];
}
}
return lowestArray;
}
Below is the required code:-
import java.util.*;
class GFG
{
// Returns minimum difference between
// any two pair in arr[0..n-1]
static void printMinDiffPairs(int arr[], int n)
{
if (n <= 1)
return;
// Sort array elements
Arrays.sort(arr);
// Compare differences of adjacent
// pairs to find the minimum difference.
int minDiff = arr[1] - arr[0];
for (int i = 2; i < n; i++)
minDiff = Math.min(minDiff, arr[i] - arr[i-1]);
// Traverse array again and print all pairs
// with difference as minDiff.
for ( int i = 1; i < n; i++)
{
if ((arr[i] - arr[i-1]) == minDiff)
{
System.out.print("(" + arr[i-1] + ", "
+ arr[i] + ")," );
}
}
}
// Driver code
public static void main (String[] args)
{
int arr[] = {5, 3, 2, 4, 1};
int n = arr.length;
printMinDiffPairs(arr, n);
}
}
Does above program handle duplicates?
The cases like {x, x, x} are not handled by above program. For this case, the expected output (x, x), (x, x), (x, x), but above program prints (x, x), (x, x)
The problem is that when you initialize your lowest array like this,
int[] lowest = new int[arr.length];
you are actually initializing it with zeros. Also, whenever you are taking arr[j]-arr[i], it will always be greater than or equal to zero (since your array is sorted in an ascending fashion), leading to incorrect results because the following if statement,
if(Math.abs(arr[j] - arr[i]) <= lowest[l]) {
lowest[l] = Math.abs(arr[j] - arr[i]);
}
will never execute for differences greater than 0.
Initialize the lowest array like so,
for(int i=0;i<lowest.length;i++){
lowest[i] = Integer.MAX_VALUE;
}
Also, your outer loop for the i variable starts with i=1, but it should start with i=0
static int[] closestNumbers(int[] arr) {
int minAbs = Integer.MAX_VALUE;
Arrays.sort(arr);
int[] out = new int[(arr.length) + 3];
int j = 0;
for (int i = 1; i < arr.length; i++) {
minAbs = Math.min(minAbs, Math.abs(arr[i] - arr[i - 1]));
}
for (int i = 1; i < arr.length; i++) {
if(minAbs ==Math.abs(arr[i] - arr[i - 1])) {
out[j++]=arr[i - 1];
out[j++]=arr[i];
}
}
int[] tem= new int[j];
for(int i=0; i<j;i++) {
tem[i]=out[i];
}
return tem;
}

ArrayIndexOutOfBoundExceptions on certain inputs when sorting elements of an array?

My task is to write a function that rearranges an array so that the odd numbers occur in the beginning of the array, from greatest to least, and the even numbers from least to greatest at the end. We are not allowed to use any other libraries except for the standard input and output streams.
The output works when the numbers are:
{-15, 450, 6, -9, 54}
But if I changed the elements to:
{-55, 45, 6, 11, 54}
There is an exception error. Here is my code:
public class ary1 {
public static void sort(int A[], int n) {
int tmp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (A[0] % 2 == 0) //even
{
if (A[i] < A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
} else {
if (A[i] > A[j]) {
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
}
}
public static void showAray(int A[], int n) {
for (int i = 0; i < n; i++) {
System.out.println(A[i]);
}
}
public static void main(String args[]) {
int array1[] = {-55, 45, 6, 11, 54};
int odd = 0;
int even = 0;
for (int i = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int[] array2 = new int[even];
int[] array3 = new int[odd];
for (int i = 0, j = 0, k = 0; i < array1.length; i++) {
if (array1[i] % 2 == 0) {
array2[j++] = array1[i];
} else {
array3[k++] = array1[i];
}
}
System.out.println("Original array:\n");
showAray(array1, array1.length);
sort(array2, even);
sort(array3, odd);
for (int i = 1; i < array1.length; i++) {
if (i < odd) {
array1[i] = array3[i];
} else {
array1[i] = array2[(i + 1) - even];
}
}
System.out.println("\nAfter sorting:\n");
showAray(array1, array1.length);
}
}
I know there is a logical error here, but I can't figure out what exactly. Is there any way to change the logic to work with all integers? Thanks.
array1[i] = array2[(i + 1) - even];
EDIT - Here is the stacktrace.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at ary.main(arytest.java:67)
Java Result: 1
Change this
array1[i] = array2[(i + 1) - even];
to
array1[i] = array2[i - odd];
I guess this is what you want

create an array and a function allowing deletion zeros rom the array

i have a code that create an array of 7 integers than the system have a function that check where array[i] == 0 will place zeros at the most right of the array and at the end the system display the original array and the compressed array like this
original array:
0 5 0 12 0 0 4
compressed array :
5 12 4 0 0 0 0
can anyone help me ??
this is the code
package question3;
import java.util.Scanner;
public class ArrayWithCompression {
static int[] array = new int[7];
static Scanner sc = new Scanner(System.in);
public static void main(String[] args){
System.out.println("enter numbers");
for(int i = 0 ; i< array.length; i++){
array[i] = sc.nextInt();
}
System.out.println(compression(array));
}
public static int[] compression(int[] newarray){
for(int i = 0; i< array.length; i++ ){
if(array[i] == 0){
array[i] = i++;
}
array[i] = newarray[i];
}
return newarray;
}
}
You are close to the right answer. I suggest you step through your code in your debugger to see what you are doing.
Since it is hard to give you a hint without giving you the answer...
public static int[] compression(int[] array){
int j = 0;
// iterate over all the numbers in the array.
for (int i : array)
// if the number is not 0 add it back into the array
if (i != 0)
// add it back only counting non-0 for the index
array[j++] = i;
// fill the rest of the array with zero.
Arrays.fill(array, j, array.length, 0);
}
you can try this code in your compression method:
public static int[] compression(int[] newarray){
int []arr= new int[newarray.length];
int j=0;
for(int i = 0; i< newarray.length; i++ ){
if(newarray[i] != 0){
arr[j++] = newarray[i];
}
}
return arr;
}
without using other array :
public static int[] compression(int[] newarray){
for(int i = 0; i< newarray.length; i++ ){
if(newarray[i] != 0){
continue;
}else
{
for(int j = i; j< newarray.length; j++)
{
if(newarray[j] != 0)
{
newarray[i]=newarray[j];
newarray[j]= 0;
break;
}
}
}
}
return newarray;
}
and you can change your main method (printing array ) :
array= compression(array);
for(int i = 0 ; i< array.length; i++){
System.out.println(array[i]);
}
You can try it out like:
for (int i = 0; i < arr.length - i; i++) {// loop decreases as after each loop a zero if found is put at last
for (int j = 0; j < arr.length - 1; j++) { // this loop puts first 0 in last by swapping each nos.
if (arr[j] == 0) {
arr[j] = arr[j + 1];
arr[j + 1] = 0;
}
}
}
return arr;
and in main function:
array = compression(array);
for (int i : array) {
System.out.println(i);
}

Categories