I'm trying to compare two int arrays, where array 1 is the standard (1...n) and array 2 is random numbers within the range of (1...n). The numbers that are missing from array 2 need to be printed out. So far, I've managed the following, but I can't seem to figure out how to use the boolean array to my benefit.
import java.util.Scanner;
public class findLeaves {
private boolean[] id;
private String[] surface;
private int[] head;
public boolean[] inputId() {
System.out.println("Input number of IDs");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
id = new boolean[n];
return this.id;
}
public int[] inputHead() {
System.out.println("Input each head value.");
head = new int[id.length];
for (int i = 0; i < id.length; i++){
Scanner scan = new Scanner(System.in);
head[i] = scan.nextInt();
}
return this.head;
}
public boolean Leaves() {
for (int i = 0; i < head.length; i++);
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print(j + ",");
}
return true;
}
public static void main(String[] args) {
findLeaves x = new findLeaves();
x.inputId();
x.inputHead();
x.Leaves();
}
}
Currently, Leaves() is just printing out:
0,1,2,3,4,5,6,7,8,
Does anyone know of a way that this can be accomplished? I'm relatively new to Java, and haven't been able to find anything googling or here that solves my problem. Thanks in advance!
Edit:
When I update Leaves to be:
public boolean Leaves() {
for (int i = 0; i < head.length; i++) id[head[i]] = true;
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print(j + ",");
}
return true;
}
I get an error of:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at findLeaves.Leaves(findLeaves.java:28)
at findLeaves.main(findLeaves.java:39)
First of all, you have termination point here for (int i = 0; i < head.length; i++);, so you'll not even run this loop.
This is a shorter way to find missing value from original array in random:
import java.util.Arrays;
public class Main {
private int[] original = new int[] {1, 3, 5, 7, 9}; // original array
private int[] random = new int[] {1, 2, 3, 4, 5, 6}; // missing value from original array will be printed
public static void main(String[] args) {
Main m = new Main();
Arrays.sort(m.original); // sort is required for binarySearch()
for (int i : m.random) {
if (Arrays.binarySearch(m.original, i) < 0)
System.out.println(i);
}
}
}
With Java 8+:
import java.util.stream.IntStream;
public class Main {
private int[] original = new int[] {1, 3, 5, 7, 9};
private int[] random = new int[] {1, 2, 3, 4, 5, 6};
public static void main(String[] args) {
Main m = new Main();
for (int i : m.random) {
if (IntStream.of(m.original).noneMatch(value -> value == i))
System.out.println(i);
}
}
}
Without any libraries:
public class Main {
private int[] original = new int[] {1, 3, 5, 7, 9};
private int[] random = new int[] {1, 2, 3, 4, 5, 6};
public static void main(String[] args) {
Main m = new Main();
for (int i : m.random) {
if (!contains(m.original, i))
System.out.println(i);
}
}
public static boolean contains(int[] array, int value) {
for (int i : array)
if (i == value)
return true;
return false;
}
}
Output:
2
4
6
change this code
public boolean Leaves() {
for (int i = 0; i < head.length; i++) id[head[i] -1] = true;
for (int j = 0; j < id.length; j++) {
if (!id[j]) System.out.print((j +1)+ ",");
}
return true;
}
Related
I have found out the duplicate numbers in the array "a" but could not store the duplicate ones in another array "b". Any help much appreciated!
Here is my code:
public static void main(String[] args) {
int[] a = {1,2,3,3,5,6,1,7,7};
int[] b={};
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[j]);
}
}
}
Because the length of result is not know, I would like to use a ArrayList instead of an array :
int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7};
List<Integer> b = new ArrayList<>();
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] == a[j] && !b.contains(a[j])) {
b.add(a[j]);
System.out.println(a[j]);
}
}
}
System.out.println(b);//result : [1, 3, 7]
You can try finding duplicates in an array using collections framework too:
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
public class MyClass {
public static void main(String args[]) {
int[] a = {1,2,3,3,5,6,1,7,7};
Set<Integer> set=new HashSet<Integer>();
List<Integer> list=new ArrayList<Integer>();
for(int i:a) {
if(!set.add(i)) {
list.add(i);
}
}
int[] b=new int[list.size()];
for (int i=0;i<list.size();i++) {
b[i] =list.get(i);
}
}
}
Here I have used the fact that sets do not allow duplicate and if set.add returns false, that means that element is already available in the set
We cannot change the size of Array once it is initialized. Here we do not know how many duplicates item will be in the Array.
EDIT -- This might be a better solution, my earlier solution was throwing ArrayIndexOutOfBoundException as indicated by #YCF_L --
import java.util.Arrays;
public class T {
public static void main(String[] args) {
//int[] a = {1, 2, 3, 3, 5, 6, 1, 7, 7}; //Set-1, provided by #YCF_L
int[] a = {1,1,3,3,5,6,1,7,7}; //Set-2, provided by OP
int[] b = {};
for (int i=0, k=0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
if(a[i] == a[j]){
System.out.println(a[j]);
k = k+1;
int[] p = new int[k];
for(int x=0; x < b.length; x++) {
p[x] = b[x];
}
p[k-1] = a[i];
b = p;
}
}
}
System.out.println(Arrays.toString(b));
System.out.println(Arrays.toString(removeDuplicates(b)));
}
public static int[] removeDuplicates(int[] a) {
boolean[] bArr = new boolean[1000];
int j = 0;
for (int i = 0; i < a.length; i++) {
if (!bArr[a[i]]) {
bArr[a[i]] = true;
j++;
}
}
int[] b = new int[j];
int c = 0;
for (int i = 0; i < bArr.length; i++) {
if (bArr[i]) {
b[c++] = i;
}
}
return b;
}
}
Output with Set-1 :
[1, 3, 7]
[1, 3, 7]
Output with Set-2 :
[1, 1, 1, 3, 7]
[1, 3, 7]
My program is supposed to take a provided array and create a new array where each element is the sum of the previous elements in original array. For example element one in new array is element one in original array. Element two in new array is sum of element one an element two in original array. Element three in new array is sum of elements one, two and three in original array. I wrote this but I know it is incomplete. Please guide.
public class PrefixSum
{
public static void main(String[] args)
{
int[] array = new int[]{0,5,1,-3,2,0,4};
int[] newArray = new int[7];
int x = 0;
for(int i = 0; i < array.length; i++)
{
x = array[i];
x = x + i;
}
newArray[0] = 0;
System.out.println(" " + newArray[x]);
}
}
You can use a variable runningTotal to keep count of the running total like so:
import java.util.Arrays;
class Main {
public static void main(String[] args) {
int[] originalArray = new int[]{0,5,1,-3,2,0,4};
int[] sumArray = new int[originalArray.length];
int runningTotal = 0;
for(int i = 0; i < originalArray.length; i++){
runningTotal += originalArray[i];
sumArray[i] = runningTotal;
}
System.out.println("The originalArray is: " + Arrays.toString(originalArray));
System.out.println("The sumArray is: " + Arrays.toString(sumArray));
}
}
Output:
The originalArray is: [0, 5, 1, -3, 2, 0, 4]
The sumArray is: [0, 5, 6, 3, 5, 5, 9]
Try it here!
You may Debug this code in order to understand the changes.
public static void main(String[] args)
{
int[] array = new int[]{0,5,1,-3,2,0,4};
int[] newArray = new int[7];
int x = 0;
for(int i = 0; i < array.length; i++)
{
x += array[i];
newArray[i] = x;
}
}
public static void main(String[] args)
{
int[] array = new int[]{0,5,1,-3,2,0,4};
int[] newArray = new int[7];
int sum = 0;
for(int i = 0; i < array.length; i++)
{
sum += array[i];
newArray[i]= sum;
System.out.println(" " +newArray[i]);
}
}
List<Integer> sums = new ArrayList<>();
Stream.of(0, 5, 1, -3, 2, 0, 4).reduce((left, right) -> {
sums.add(left + right);
return left + right;
});
Printing sums after running yields :
[0, 5, 6, 3, 5, 5, 9]
Try it here.
I trying to write recursive function in Java.
The function needs to count for me all the diffrents values in array.
i.e
{{1,1,1,1},{4,4,4,4},{3,3,1,1}}
The recursive function returns 3 (1,4,3)
This is the function that i need to write:
int numOfColors(int[][] map)
What I have been tried:
public static int numOfColors(int[][] arr) {
int i=0;
int j=0;
int colors=0;
int contains = arr[i][j];
if (arr== null) {
return 0;
} else if (arr[i][j] != 0&& arr[i][j]!=contains) {
colors ++;
}
return numOfColors(arr) + 1;
}
Exception in thread "main" java.lang.StackOverflowError
How can i fix it?
Thanks!
Below is one way of finding count of unique values using recursion and without using any Set or List -
package test;
public class Main {
public static void main(String[] args) {
int[][] arr = { { 4, 2, 2, 1, 4 }, { 4, 4, 3, 1, 4 }, { 1, 1, 4, 2, 1 }, { 1, 4, 0, 2, 2 }, { 4, 1, 4, 1, 1 } };
System.out.println(numOfColors(arr));
}
public static int numOfColors(int[][] arr) {
int unique = 0;
if (arr.length == 0) {
return unique;
} else {
int[] subArr = arr[arr.length - 1];
outerLoop: for (int i = 0; i < subArr.length; i++) {
int j = i + 1;
for (; j < subArr.length; j++) {
if (subArr[i] == subArr[j]) {
break;
}
}
if (j == subArr.length) {
int k = 0;
for (; k < arr.length - 1; k++) {
for (int l = 0; l < arr[k].length; l++) {
if (subArr[i] == arr[k][l]) {
continue outerLoop;
}
}
}
if (k == arr.length - 1) {
unique++;
}
}
}
int[][] dest = new int[arr.length - 1][];
System.arraycopy(arr, 0, dest, 0, arr.length - 1);
unique += numOfColors(dest);
return unique;
}
}
}
Output
5
Note that this problem can be solved without recursion easily. Also, above code can be make easy using Set
I think you should store unique values in Set and build final result base on it size. Here is one from many solutions:
package com.company;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
int[][] map = new int[][] {{1,1,1,1},{4,4,4,4},{3,3,1,1}};
System.out.println(numOfColors(map));
}
public static int numOfColors(int[][] map) {
HashSet<Integer> result = new HashSet<Integer>();
numOfColorsImpl(map, 0, result);
return result.size();
}
private static void numOfColorsImpl(int[][] map, int rowIndex, Set<Integer> result) {
if (rowIndex == map.length)
return;
for (int value : map[rowIndex]) {
result.add(value);
}
numOfColorsImpl(map, rowIndex + 1, result);
}
}
You could use a recursive helper function that removes duplicates.
import java.util.*;
public class Main {
public static void main(String[] strg) {
int[][] arr = {{1, 1, 1, 1}, {4, 4, 4, 4}, {3, 3, 1, 1}};
numOfColors(arr);
}
static int numOfColors(int[][] map) {
ArrayList<Integer> intlist = new ArrayList<Integer>();
for (int o = 0; o < map.length; o++) {
for (int n = 0; n < map[o].length; n++) {
intlist.add(map[o][n]);
}
}
intlist = removeDuplicates(intlist, 0);
System.out.println(intlist.size()+" " +intlist);
return intlist.size();
}
static ArrayList<Integer> removeDuplicates(ArrayList<Integer> list, int counter) {
if (list == null) {
throw new NullPointerException();
}
if (counter < list.size()) {
if (list.contains(list.get(counter))) {
if (list.lastIndexOf(list.get(counter)) != counter) {
list.remove(list.lastIndexOf(list.get(counter)));
counter--;
}
}
removeDuplicates(list, ++counter);
}
return list;
}
}
Output
3 [1, 4, 3]
Online demo
I don't think recursion is necessary in this case, so I will explain the way I would go about it. I will refer to arr as array A. First, you create a hash set of numbers that you have seen already, which we will call hash set B. Then, you can loop through array A, processing each element. Check if hash set B contains that element. If it does, continue, if not, add that value to hash set B. After the loop, return the length of hash set B, or the entire set if you want to see what the unique values are.
For example:
import java.util.HashSet;
public class Class {
public static void main(String[] args){
int[][] A = {{1, 1, 1, 1}, {4, 4, 4, 4}, {3, 3, 1, 1}};
System.out.println("Number of different values: " + countUniqueVals(A));
}
public static int countUniqueVals(int[][] A){
HashSet<Integer> B = new HashSet<Integer>();
for (int row = 0; row < A.length; row++)
for (int col = 0; col < A[row].length; col++)
B.add(A[row][col]);
return B.size();
}
}
This question already has answers here:
Printing distinct integers in an array
(8 answers)
Closed 8 years ago.
A program in Java that should count the no. of occurrence and display the most repeated first no. followed by others. for eg. input: 223331544 output: 32415
class Example {
public static void main(String a[]) {
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
for (int i = 0; i < arr.length; i++) {
boolean isDistinct = false;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
isDistinct = true;
break;
}
}
if (!isDistinct) {
System.out.print(arr[i] + " ");
}
}
}
}
The following code will print out distinct numbers:
import java.util.*;
public class Example {
public static void main(String[] args) {
Integer[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> s = new HashSet<Integer>(Arrays.asList(arr));
System.out.println(s);
}
}
But this is not the answer. The requirement is to remove all the numbers that appear more than once. To do that, make a Map that containts the number as key and occurrence as value. While put the numbers into the Map, if the number is already exists, +1 the occurrence. So the code is like the following:
import java.util.*;
public class Test {
public static void main(String[] args) {
int[] arr = { 5, 2, 7, 2, 4, 7, 8, 2, 3 };
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int i : arr) {
if (m.get(i) == null)
m.put(i, 1);
else
m.put(i, m.get(i) + 1);
}
for (Map.Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() == 1)
System.out.print(e.getKey() + " ");
}
}
}
Try this solution for your problem.
import java.util.*;
class Hello
{
public static void main(String[] args)
{
int[] arr = {5, 2, 7, 2, 4, 7, 8, 2, 3};
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < arr.length; i++){
set.add(arr[i]);
}
//now if you will iterate through this set, it will contain only unique values.
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
I thinkd Set already can help u do this, advanced Link.http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
You can try in this way
public static void main(String a[]) {
int[] arr = {1,2,2,3,4,5,5};
for (int i = 0; i < arr.length; i++) {
boolean isDistinct = false;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j] && i!=j) {
isDistinct = true;
break;
}
}
if (!isDistinct) {
System.out.print(arr[i] + " ");
}
}
}
Out put:
1 3 4
Use set
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class NonDuplicateElement{
public static void main(String []args){
int[] arr = {5,2,7,2,4,7,8,2,3};
Set<Integer>set = new HashSet<Integer>();
Set<Integer>remset = new HashSet<Integer>();
for(int i=0;i<arr.length;i++)
{
if(set.contains(arr[i]))
{
remset.add(arr[i]);
}
else
{
set.add(arr[i]);
}
}
Iterator<Integer> iter = remset.iterator();
while(iter.hasNext())
{
Integer element = iter.next();
if(set.contains(element))
{
set.remove(element);
}
}
iter = set.iterator();
while(iter.hasNext())
{
System.out.println(iter.next()+ "\t");
}
}
}
Output : 3 4 5 8
I am trying to create method that creates new array only from the even numbers from another array. However, I do not understand why I have the right length (only with the number of the even numbers) of my output array, but I have 0s instead of the actual numbers.
I know that the problem is simple, but right now I am stuck with it.
import java.util.*;
public class test{
public static int [] myMethod(int []arr){
int [] temp;
int howManyEven = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2==0){
howManyEven++;
}
}
temp = new int [howManyEven];
int evenNum = 0;
for(int i=0;i<temp.length;i++){
boolean even = false;
for(int j=0;j<arr.length;j++){
if(arr[j]%2==0){
even = true;
evenNum = arr[j];
}
}
if(!even){
temp[i]=evenNum;
}
}
return temp;
}
public static void main (String[]args){
int [] myArray = {5,5,8,9,7,4,4,2,3};
System.out.println(Arrays.toString(myMethod(myArray)));
}
}
In the second part of your myMethod, where there is nested for loop, your outer loop should iterate over arr. It can be simplified to below
temp = new int [howManyEven];
int j = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]%2 == 0) {
temp[j++] = arr[i];
}
}
Better you can use java collections and finish the work in single loop
public static Integer[] myMethod(int []arr){ //notice the return type is Integer[] instead of int[]
List<Integer> evens = new ArrayList<Integer>();
for(int a : arr) {
if(a%2 == 0) {
evens.add(a);
}
}
return evens.toArray(new Integer[evens.size()]);
}
Look again at this:
if(!even){
temp[i]=evenNum;
}
I think you will notice yourself what's wrong.
Instead of processing the information twice for even numbers, you can create a List of integers which are 'even' and return that, or convert into primitive int[] and return that.
public static int[] myMethod(int[] arr) {
List<Integer> even = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
if(arr[i]%2==0){
even.add(arr[i]);
}
}
int []result = new int[even.toArray().length];
Iterator it = even.iterator();
int count=0;
while(it.hasNext()){
result[count++]=(int)it.next();
}
return result;
}
public static void main(String[] args) {
int[] myArray = {5, 5, 8, 9, 7, 4, 4, 2, 3};
System.out.println(Arrays.toString(myMethod(myArray)));
}
output
run:
[8, 4, 4, 2]
BUILD SUCCESSFUL (total time: 0 seconds)
The easiest way would be myMethod should create a temparory list which collects the even numbers from the input array and then convert it to an output array containing only the even elements which should be returned to the caller
Working Example
public static void main(String... str) {
// results array has only even numbers
Integer[] results = myMethod(new int[]{5, 5, 8, 9, 7, 4, 4, 2, 3});
for(int i=0;i<results.length;i++)
System.out.println(results[i]); // print each even number
}
static Integer[] myMethod(int[] inputArray) {
List<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < inputArray.length; i++) {
if (inputArray[i] % 2 == 0) {
temp.add(inputArray[i]);
}
}
return temp.toArray(new Integer[5]);
}
Hope this code clarifies you well.