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

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

Related

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

Matching pairs of array

I have an array with integers, I just have to count the pairs and return that counted value.
static int StockMerchant(int n , int arr[]){
int[] temp = new int[n];
int count = 0;
for(int i =0 ; i<n ; i++){
for(int j= i+1 ; j<n ; j++){
if(arr[i]==arr[j]){
arr[j] = '0';
arr[i] ='0';
count++;
}
}
}
return count;
}
when I try: 1 1 2 2 2: gives output 2
But when I change the input to 1 2 1 2 2: gives output 3
I want the output to be 2 in the second case also. please help.
*Sorry for my bad paint skills.
Hope I was able to point out your mistake:)
Here is my solution :
Its basically sorting the array first and checking if it matches the value increment i position to j+1 and j as i+1
static int StockMerchant(int n, int arr[]) {
Arrays.sort(arr);
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
i = j + 1;
j = i;
count++;
}
}
}
return count;
}
Here i'm assuming all your test inputs contains positive integers, this logic works for the positive values only.
static int StockMerchant(int n , int arr[]){
int starter = n>0 && arr[0] != 0 ? 0 : -1;
int temp = starter;
int count = 0;
Arrays.sort(arr);
for(int i =0 ; i<n ; i++){
if(temp == arr[i]){
temp = starter;
count++;
}else{
temp = arr[i];
}
}
return count;
}

Two-dimentional arrays [duplicate]

This question already has answers here:
Syntax for creating a two-dimensional array in Java
(13 answers)
Closed 3 years ago.
I am working with 2-D arrays and I require help on this topic. My task is to create a 2-D array such that it is n by n (i.e. the number of rows and columns are equal). Fill the array with alternating 0's and 1's
void setup()
{
int n=3;
// code to populate the array
// code to display the output of array in a table format
/* output should be as follows:
The expected result when n=3 should be as the following:
1 0 1
0 1 0
1 0 1
*/
}
Solution:
class test{
public static void main(String[] args) {
int n = 3;
int[][] arr = setup(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(arr[i][j]);
}
System.out.println();
}
}
static int[][] setup(int n){
int[][] arr = new int [n][n];
boolean even = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
arr[i][j] = even ? 1 : 0;
even = !even;
}
}
return arr;
}
}
Output:
0 1 0
1 0 1
0 1 0
This should work.
You can replace the 3 that is given to n with any number you want as the 2D-Array's length.
void setup(){
int n = 3;
int count = 0;
int[][] myArray = new int[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(count % 2 == 0){
myArray[i][j] = 1;
}
else{
myArray[i][j] = 0;
}
System.out.print(myArray[i][j] + " ");
count++;
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
It's not complex, you just have to iterate two loops, that's it. Although you can get the solution on different ways.
public static void main(String[] args) {
int n = 3;
int [][] arr = new int[n][n];
int val = 1;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
arr[i][j] = val;
val = (val == 0) ? 1 : 0;
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
Output:
0 1 0
1 0 1
0 1 0
A simple implementation:
void setup()
{
int n=3;
final int[][] array = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if ((n * i + j) % 2 == 0) {
array[i][j] = 1;
}
}
}
}
Here is how you can approach your logic , create a counter and negate each time after it prints value.
public static void main(String[] args) {
int counter = 0;
int n = 3;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
System.out.print(counter==0?1:0);
counter = ~counter;
}
System.out.println();
}
}
Output
101
010
101
Here is Online source code.

Program which counts minimum of a two dimensional int array

I am trying to create a program, which counts the minimum of each dimension in a two dimensional array. So for ex. if i had an array:
int[][] test = {{1,2,3},{2,3,4},{4,5,6}}
the program would display: [1,2,4] - the minimum of each dimension.
For that I've created a method called minimum, which looks like this
static int[] minimum(int[][] arr) {
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr[i].length; j++) {
int min = arr[i][0];
if(arr[i][j] < min) {
min = arr [i][j];
result [i] = min;
} else{
}
}
}
return result;
}
But when i call out this method in my main, with a sample array
public static void main(String[] args) {
int[][] arr = {{1,2,3,},{3,4,5},{6,6,6}};
System.out.println(Arrays.toString(minimum(arr)));
}
The program displays [0,0,0,]. Do You have any clue where is the problem and how to fix it?
The problem is that if the first element in the array is min, it never gets recorded to the result array. Try:
static int[] minimum(int[][] arr) {
int[] result = new int[arr.length];
for (int i = 0; i < arr.length; i++) {
result[i] = arr[i][0];
for (int j = 1; j < arr[i].length; j++) {
if (arr[i][j] < result[i]) {
result[i] = arr[i][j];
}
}
}
return result;
}
Note that there needs to be at least one element per row in the input matrix for the above function; add a conditional or use Integer.MIN_VALUE to handle empty rows if you wish.
This should work. You reset the min to the first element every time. So you are basically comparing if there is any value smaller than the first one.
static int[] minimum(int[][] arr){
int[] result = new int [arr.length];
for (int i = 0; i < arr.length; i++){
result[i] = Integer.MAX_VALUE;
for(int j = 0; j < arr[i].length; j++){
if(arr[i][j] < result[i]) {
result [i] = arr[i][j];
}
}
}
return result;
}

print highest number to the right in an array

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

Categories