DeleteZero's using Java - java

I need to finish this code which involves deleting all the zero's stored in the array. I thought it was complete but it won't compile, it's my last line that is dubios and I'm not getting right. Thank you.
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
for (int i = 0; i < 20; i++) {
rand[i] = (int)(Math.random());
}
System.out.println(array(a));
}
}

Few errors.
This would always insert 0 at rand[i] because you are casting Math.random() to int which will always become zero.
rand[i] = (int)(Math.random());
Change it to sth like this. I have written 10 but you can write any number to define the range.
rand[i] = (int)(Math.random()*10);
This line is also wrong:
System.out.println(array(a));
You need to print the array by looping over it, but more importantly your function array() returns a new array, which should be stored somewhere before printing it.
Here is a possible workaround
rand = array(rand);
for (int i=0; i<rand.length; i++){
System.out.println(rand[i]);
}

The compile time error is due to the fact that, in the main method you have created the array named rand and passing the array named a. from the main method call System.out.print(array(rand))

You can try Java 8's Stream, which turns the whole logic to one line return Arrays.stream(a).filter(n -> n!= 0).toArray();

Little fixed your code:
import java.util.Random; // Import Random
public class DeleteZero {
public static int[] array(int[] a) {
int k = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] !=0)
k++;
}
int[] b = new int[k];
int t = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
b[t] = a[i];
t++;
} else {
System.out.println("Skip at position: [" + i + "] because a[i] == "+a[i]+";"); // Display what removed.
}
}
return b;
}
public static void main (String args[]) {
int[] rand = new int[20];
Random rnd = new Random();
for (int i = 0; i < 20; i++) {
rand[i] = rnd.nextInt(11) + 0; // 11-1 = max, 0 = min
}
int[] a = array(rand);
System.out.println(a); // since it prints something like this: [I#106d69c, we should print all elements manually through a loop.
System.out.println("a.length = " + a.length + ", rand length: " + rand.length);
System.out.print("[");
for (int i = 0; i != a.length; i++) {
String space = ", ";
if (i == a.length-1) //if last not print space
space = "";
System.out.print(a[i]+space); // Print all elements
}
System.out.print("]\n");
}
}
Example of output:
Skip at position: [2] because a[i] == 0;
Skip at position: [8] because a[i] == 0;
Skip at position: [10] because a[i] == 0;
Skip at position: [12] because a[i] == 0;
Skip at position: [16] because a[i] == 0;
[I#106d69c
a.length = 15, rand length: 20
[6, 8, 1, 8, 7, 1, 3, 5, 3, 8, 5, 2, 7, 2, 8]

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

How to make two unequal 2D arrays equal by adding zeroes in null positions in java?

lets say my matrix A has order of 3 x 2 and Matrix B has order of 2 x 4. My resultant Matrix should be in the order of 3 x 4 and it should contain the addition of Matrix A and Matrix B. In order to achieve this I must first make Matrix A and Matrix B equal in size (both should be 3 x 4) by appending the necessary zeroes.
EXAMPLE :-
int[][] a = { {1,0}, {1,1}, {1,0} };
int[][] b = { {1,1,0,1}, {1,1,1,1} };
sumArray(a,b) will return: { {2,1,0,1}, {2,2,1,1}, {1,0,0,0} }
what I tried was. (ans.length means the resultant matrix length)
for(int i =0;i<ans.length;i++)
{
for(int j=0;j<ans[i].length;j++)
{
if(arr1[i][j] == null)
{
arr1[i][j]= 0;
}
if(arr2[i][j] == null)
{
arr2[i][j]= 0;
}
}
}
First you have to find the size of your output array.
int h = a.length>b.length?a.length:b.length;
int w = a[0].length>b[0].length?a[0].length:b[0].length;
int[][] result = new int[h][w];
Then do your assignments.
for(int i = 0; i<result.length; i++){
for(int j = 0; j<result[i].length; j++){
if(i<a.length && j < a[i].length){
result[i][j] += a[i][j];
}
if(i<b.length && j < b[i].length){
result[i][j] += b[i][j];
}
}
}
return result;
Use this code. Just make the dimension identifying part dynamic
import java.util.Arrays;
public class Main
{
public static void main (String[]args)
{
System.out.println ("Hello World");
int m1 = 3, n1 = 1, m2 = 2, n2 = 4; // m1 and n1 are matrix 'x' dimensions and m2 & n2 are natrix 'y' dimensions
int x[][] = {
{1},
{2},
{3}
};
int y[][] = {
{1, 2, 1, 2},
{1, 2, 1, 2}};
int op[][] = new int[m1][n2];
for (int[] row: op)// filling empty matrix with zeroes
Arrays.fill(row, 0);
for (int i = 0; i < m1; i++)
{
for (int j = 0; j < n1; j++)
{
op[i][j] = x[i][j];
}
}
int op2[][] = new int[m1][n2];
for (int[] row: op2)// filling empty matrix with zeroes
Arrays.fill(row, 0);
for (int i = 0; i < m2; i++)
{
for (int j = 0; j < n2; j++)
{
op2[i][j] = y[i][j];
}
}
for(int i=0;i<m1; i++)
{
for(int j=0;j<n2;j++)
{
System.out.print((op[i][j]+op2[i][j])+" ");
}
System.out.println();
}
}
}

How to count 1st duplicates value in array in Java

I have taken array int[] a = {33,33,5,5,9,8,9,9}; In this array so many values are duplicates means 33 comes twice & 5 also comes twice & 9 comes three times.
But I want to count the first value which is duplicate means 33 is first value which comes twice so answer would be 2.
I try:
public class FindFirstDuplicate
{
public static void main(String[] args) {
int c=0;
int[] a = {33,33,5,5,9,8,9,9};
outerloop:
for(int i = 0; i < a.length; i++)
{
for(int j = i+1; j< a.length; j++)
{
if(a[i] == a[j])
{
System.out.println(a[i]); //Duplicate value
c++;
break outerloop;
}
}
}
System.out.print("Count: "+c);
}
}
Output:
33
1
public class HelloWorld{
public static void main(String[] args) {
int[] a = {33,33,5,5,9,8,9,9};
for(int i = 0; i < a.length; i++)
{
int c=1; // we already found one.
// and we initialize this counter inside the loop,
// so that it is reset for each new starting number.
for(int j = i+1; j< a.length; j++) // we're starting from next number (reason we start with c=1)
{
if(a[i] == a[j])
c++;
}
if(c > 0) {
System.out.println("First uplicate value: "+ a[i] + " Count: " + c);
break; // we have to break out of the outer loop,
// so the inner loop can finish counting duplicates
}
}
}
}
Try something like:
int[] numbers = {33, 33, 5, 5, 9, 8, 9, 9};
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i< numbers.length; i++) {
if (!set.add(number[i])) {
System.out.println("first duplicate is " + number[i] + " and index is " + i);
break;
}
}
If the values in the array are non-negative and reasonably small, you can use a BitSet to store whether or not you have seen a value previously:
BitSet bits = new BitSet();
for (int i = 0; i < numbers.length; ++i) {
if (bits.get(numbers[i])) {
System.out.println("first duplicate at " + i + ": " + numbers[i]);
break;
}
bits.set(numbers[i]);
}
You could try this out:
int[] a = {33,33,5,5,9,8,9,9};
Integer[] uniques = new Integer[a.length];
Integer[] counts = new Integer[a.length];
int len = 0;
for(int num : a){
boolean matched = false;
for(int i = 0; i < len; i++){
if(num == uniques[i].intValue()){
matched = true;
counts[i] = new Integer(counts[i]+1);
break;
}
}
if(!matched){
uniques[len] = new Integer(num);
counts[i] = new Integer(1);
len++;
}
}
for(int i = 0; i < len; i++){
if(counts[i].intValue() > 1){
System.out.println("first duplicate is " + uniques[i] + " and number of times it appears " + counts[i]);
break;
}
}
In your code you exit both loops after the first duplicate is found, so any other occurences of the element would be ignored.
Also you start with c = 0. When you get to the second occurence, c will be incremented and be 1, not 2.
To count all elements simply change the loop condition of the outer loop and remove the break:
int c = 1;
int i;
for(i = 0; (c == 1) && (i < a.length); i++)
{
for(int j = i+1; j < a.length; j++)
{
if(a[i] == a[j])
{
c++;
}
}
}
System.out.println(a[i]); //Duplicate value
System.out.print("Count: "+c); // maybe do something else, if c == 1 (no duplicates)???
However SMA's answer describes a more performant way (for arbitrary input arrays) of finding the first duplicate. Once you found the second occurence of the first duplicate, you'd only need to count the number of occurences in the rest of the array to get the final count.

null pointer exception sorting merged array list

I have been trying to figure out how to properly print the return of my method.
When the program prints the return of my method, I am giving a nullPointerException error on line 45(the line where i am trying to print the method).
*I did try to make the return to the method static so it is accessible.
How do I initialize the "answer" variable so that i can print it outside of my method?
Thank you in advance
import javax.swing.JOptionPane;
public class ListSortMerge {
static int[]answer;
public static void main(String[] args) {
int v1 = 0, v2 = 0;
for(int c = 0; c <= 1; c++) {
String values = JOptionPane.showInputDialog("How many values would you like to store in list "+(c+1)+"?");
if (c==0) {
v1 = Integer.parseInt(values);
}
else{
v2 = Integer.parseInt(values);
}
}
int[] numbers1 = new int[v1];
int[] numbers2 = new int[v2];
merge(numbers1,numbers2);
int i;
System.out.println("\nList 1 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v1); i++) {
System.out.println(numbers1[i]);
}
System.out.println("\nList 2 before the sort");
System.out.println("--------------------");
for(i = 0; i < (v2); i++) {
System.out.println(numbers2[i]);
}
System.out.println("\nList after the sort");
System.out.println("--------------------");
for(i = 0; i < (v1+v2); i++) {
System.out.println(answer[i]);
}
}
public static int[] merge(int[] a, int[] b) {
int[] answer = new int[a.length + b.length];
for(int c = 0; c < (a.length); c++)
{
String aVal1 = JOptionPane.showInputDialog("Input list 1 value " +(c+1));
a[c] = Integer.parseInt(aVal1);
}
for ( int c = 0; c < (b.length); c++){
String aVal2 = JOptionPane.showInputDialog("Input list 2 value " +(c + 1));
b[c] = Integer.parseInt(aVal2);
}
int i = 0, j = 0, k = 0;
while (i < a.length && j < b.length)
{
if (a[i] < b[j])
answer[k++] = a[i++];
else
answer[k++] = b[j++];
}
while (i < a.length)
answer[k++] = a[i++];
while (j < b.length)
answer[k++] = b[j++];
return answer;
}
}
You have two different answer variables: one is a local variable in the merge function and another is a static field in the class. You never initialize the second one.

How can I split a integer array to n integer array dynamically?

Here I have integer array contains 81 values so that I need to store 9 values per array total I need to get 9 arrays. Eg: array1 from 1 to 9 and array2 from 10 to 18 and array3 from 19 to 27 like that. Can anybody help me how to get this values?
public class demo {
public static void main(String[] args) {
int num = 81;
int numArray = num / 9;
int[] input = new int[num];
for (int i = 0; i < num; i++) {
input[i] = i + 1;
}
for (int j = 0; j < input.length; j++) {
System.out.println(input[j]);
}
}
}
How to get desired result?
You can use System#arraycopy():
int[] first_part = new int[27];
int[] second_part = new int[27];
int[] third_part = new int[27];
System.arraycopy(input, 0, first_part, 0, 27);
System.arraycopy(input, 27, second_part, 0, 27);
...
I've just noticed that you want 9 parts, you can easily put this in a loop and use arraycopy.
public static void main(String[] args) {
int num = 85;
int limit = 5;
int index = 0;
int extra = 0;
int finalArrayIndex = 0;
int[] innerArray = null;
int[] input = new int[num];
boolean isEnd = false;
if (num % limit > 0) {
extra = 1;
}
int[][] finalArray = new int[(num / limit) + extra][limit];
for (int i = 0; i < input.length; i = i + (limit)) {
innerArray = new int[limit];
for (int j = 0; j < limit; j++) {
innerArray[j] = input[index++];
if (index >= input.length) {
isEnd = true;
break;
}
}
finalArray[finalArrayIndex++] = innerArray;
if (isEnd) {
break;
}
}
// just for test
for (int k = 0; k < finalArray.length; k++) {
for (int l = 0; l < finalArray[k].length; l++) {
System.out.println("finalArray[" + k + "]" + "[" + l + "] : "
+ finalArray[k][l]);
}
}
}
This is dynamic solution, you can change value of num and limit variables. I hope this will help you :)
Java Fiddle link : http://ideone.com/jI8IOb
My suggestion is use subList
You can follow these steps.
Store all 81 values in a List (ArrayList)
Then create 9 sub List from that using subList()
You can convert List to array.
List<Integer> fullList=new ArrayList<>();
List<Integer> list1=fullList.subList(0,8); // first 9 elements
Integer[] bar = list1.toArray(new Integer[list1.size()]);

Categories