I have this code which is to check in the two arrays and print out the values that dont exist in the other array. I think the way i did it is not the most efficient way to do it hence can anyone offer a better OOP way to write this code in Java?
Thanks
public class Calculate {
static int [] x = {1,2,4,6,7};
static int [] y = {2,3,4,6,7};
static boolean xflag = true;
static boolean yflag = true;
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<x.length; i++)
{
for (int b=0; b<y.length; b++)
{
if(x[i]!= y[b])
{
xflag= false;
}
else
{
xflag = true;
break;
}
}
if(xflag==false)
{
System.out.println(x[i] +" does not exist in array 2");
}
}
for(int i = 0; i<x.length; i++)
{
for (int b=0; b<y.length; b++)
{
if(y[i]!= x[b])
{
yflag= false;
}
else
{
yflag = true;
break;
}
}
if(yflag==false)
{
System.out.println(y[i] +" does not exist in array1");
}
}
}
}
Using Collection class removeAll method
String original[] = { "1","2","3","4","6"};
String testStr[] = { "1","2","3","5","7" };
List origList = new ArrayList(Arrays.asList(original));
List testList = new ArrayList(Arrays.asList(testStr));
System.out.println(origList.removeAll(testList));
System.out.println(origList);
you can use java collection framework, Many function are there,
here is simple example check it.
public static void main(String a[]){
List<String> sl = new ArrayList<String>();
sl.add("apple");
sl.add("java");
sl.add("c++");
sl.add("unix");
sl.add("orange");
sl.add("airtel");
List<String> tl = new ArrayList<String>();
tl.add("job");
tl.add("oracle");
tl.add("jungle");
tl.add("cricket");
boolean isCommon = Collections.disjoint(sl,tl);
System.out.println("Does not found any common elements? "+isCommon);
tl.add("java");
isCommon = Collections.disjoint(sl,tl);
System.out.println("Does not found any common elements? "+isCommon);
}
You may use Apache's CollectionUtils for this purpose if you want an abstraction from the implementation logic.E.g:
public static void main(String[] args) {
List<Integer> list1=Arrays.asList(1,2,4,6,7);
List<Integer> list2=Arrays.asList(2,3,4,6,7);
System.out.println(CollectionUtils.disjunction(list1,list2));
}
You can code this way
List<Integer> array1 = Arrays.asList(1,2,4,6,7);
List<Integer> array2 = Arrays.asList(2,3,4,6,7);
List<Integer> disjointArray = new ArrayList<Integer>();
for (Integer value : array1) {
if (!array2.contains(value)) {
disjointArray.add(value);
}
}
And then you can print disjointArray or do whatever manipulation you want.
Here a running example using Javas Collection classes:
public class Disjunction {
public static void main(String args[]) throws UnsupportedEncodingException {
//Some data preparation
List<Integer> list1=Arrays.asList(1,2,4);
List<Integer> list2=Arrays.asList(5,2,8);
//Here calculating data1-data2 and data2-data1, collect all list items
//that are in data1 or in data2 but not in both.
List<Integer> data1 = new ArrayList<>(list1);
data1.removeAll(list2);
List<Integer> data2 = new ArrayList<>(list2);
data2.removeAll(list1);
//Merging both results. data1 contains now exclusive or of list1 and list2
data1.addAll(data2);
System.out.println("exclusive or is " + data1);
}
}
It prints out
exclusive or is [1, 4, 5, 8]
Try the following program that checks two arrays for numbers they both have and numbers they don't have:
package test;
import java.util.ArrayList;
public class ArrayDifferentiater {
public static void main(String[] args) {
int[] ori = { 1, 5, 4, 8, 6, 65, 16, 6, 575, 64, 561, 57, 57 };
int[] che = { 1, 4, 8, 6 };
sort(ori, che);
}
public static void sort(int[] a, int[] b) {
/**
* 'foundNum' contains the numbers which exists in both array.
* 'notFoundNum' contains the numbers which exists in only first array.
*/
ArrayList<Integer> foundNum = new ArrayList<>();
ArrayList<Integer> notFoundNum = new ArrayList<>();
// First for loop starts
for (int i = 0; i < a.length; i++) {
// Second for loop starts
for (int j = 0; j < b.length; j++) {
/**
* Check if array 1 contains value of array 2.
* If contains than add it to "foundNum" arraylist.
*/
if (a[i] == b[j]) {
foundNum.add(a[i]);
// Remove the number which exists in both arrays from "notFoundNum" arraylist.
if (notFoundNum.contains(a[i])) {
for (int k = 0; k < notFoundNum.size(); k++) {
if (notFoundNum.get(k) == a[i]) {
notFoundNum.remove(k);
}
}
}
break;
} // First if block ends
/**
* Checks if a not found number does not exists in 'notFoundNum' arraylist (to reduce redundancy)
* then adds a not found number to 'notFoundNum' arraylist
* */
if (!notFoundNum.contains(a[i]))
notFoundNum.add(a[i]);
} // Second for loop ends
} // First for loop ends
System.out.println("Found Numbers : " + foundNum);
System.out.println("Not Found Numbers : " + notFoundNum);
}
}
Here is the output for the above program:
Found Numbers : [1, 4, 8, 6, 6]
Not Found Numbers : [5, 65, 16, 575, 64, 561, 57]
Related
I've started learning java some time ago. I'm reading through the Java Foundations book and doing exercises from the book to practice.
Just come across this one "Modify the java program so that it works for the numbers in the range between -25 and 25." and I wonder if you have any different solutions to it or is it really that simple? :)
Here's the original code:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 15;
final int MULTIPLE = 10;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = index * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
And here's my solution to it:
public class BasicArray
{
public static void main(String[] args)
{
final int LIMIT = 51;
final int MULTIPLE = 1;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++)
list[index] = (index - 25) * MULTIPLE;
list[5] = 999; // change one array value
// Print the array values
for(int value : list)
System.out.println(value + "");
}
}
Yes, basically it's really simple exercise.
Regarding to your solution we actually don't need MULTIPLE in code.
public class BasicArray {
public static void main(String[] args) {
final int LIMIT = 51;
int[] list = new int[LIMIT];
// Initialize the array values
for(int index = 0; index < LIMIT; index++) {
list[index] = (index - 25);
}
list[5] = 999; // change one array value
// Print the array values
for(int value : list) {
System.out.println(value + "");
}
}
}
If you are ready for a bit of advanced java, you can try following:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(System.out::println);
}
}
Or this if you need to replace one value:
public class BasicArray {
public static void main(String[] args) {
IntStream.rangeClosed(-25, 25)
.forEach(i -> {
if (i == -20) { // change one array value
System.out.println(999);
} else {
System.out.println(i);
}
});
}
}
I have a TreeMap in which I have keys and all its values and a target value.Below is my approach. It's basically to find a subset. But here i need the keys of the values which sum to the target. I have done a recursion approach. Here I want to end the recursion if I get any one subset. Is there any optimal way to solve this? Note :- The values will be much bigger and I will have hundreds of data.
import java.util.*;
public class SubsetFromATree {
public static void main(String[] args) {
TreeMap<Integer,Integer> tm = new TreeMap<Integer,Integer>() ;
tm.put(0, 3);
tm.put(1, 4);
tm.put(2, 5);
tm.put(3, 6);
// for(int i =0;i<20;i++) {
// tm.put(i, i+1);
// }
ArrayList<Integer> ans = new ArrayList<>();
ArrayList<Integer> out = new ArrayList<>();
StringBuffer s = new StringBuffer("0");
subset(tm,10,out,tm.size(),s,ans);
System.out.println(ans);
}
private static void subset(TreeMap<Integer, Integer> tm, int tsum, ArrayList<Integer> out, int size, StringBuffer val,
ArrayList<Integer> ans) {
// TODO Auto-generated method stub
if(tsum == 0) {
val.append("1");
for(int i = 0;i<out.size();i++) {
ans.add(out.get(i));
}
return;
}
if(size == 0 || val.equals("1")) {
return;
}
//Not including
subset(tm,tsum,out,size-1,val,ans);
ArrayList<Integer> output = new ArrayList<>(out);
output.add(tm.get(size-1));
subset(tm,tsum-tm.get(size-1),output,size-1,val,ans);
return;
}
}
I am new to this programming world. I tried to print length of the array without using predefined functions.
But when i run my code i am getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
can someone please help me to find out the bug
Here is my code.
public class Arraylen {
public static void main(String[] args) {
int[] ary = {1, 3, 4, 5, 68, 9};
int len;
for(len = 1; ary[len] != '\0'; len++) {
System.out.println(len);
}
}
}
What is wrong with using ary.length? .length is a property and not a function. You would not be coding ary.length(), let alone that "function" doesn't even exist.
public class StackOverflow {
public static void main(String args[]) {
int[] ary = {1, 3, 4, 5, 68, 9};
System.out.println(ary.length);
}
}
Result:
6
Just use an enhanced for loop:
public class Arraylen
{
public static void main(String[] args)
{
int[] ary = {1,3,4,5,68,9};
int len = 0;
for(int number : ary)
{
len++;
}
System.out.println(len);
}
}
This iterates over every item in the array, without you having to worry that the index will go over the array size.
You could also use a while loop with a try-catch block to find the length.
Something like this:
boolean lengthFound = false;
int length = 0;
while (!lengthFound) {
try {
// This line throws an Exception when length is equal to the length of the array
int notImportant = array[length] + 2;
length++;
}
// This prevents the exception from breaking anything and gets you out of the
// loop
catch (ArrayOutOfBoundsException ex) {
lengthFound = true;
}
}
// At this point array.length == length
I am trying to construct a program that would take an array of int({1,2,3} and a length value and calculate all possible combinations of this array.
For example:
int[] arr= new char[] {0,1};
int[] tes = new int[3];
possiblecomb(2, arr,tes,0);
This will output:
00
10
01
11
But i keep getting a Stack overflow error when i try to call the possiblecomb in the for loop
import java.util.Arrays;
public class Program {
public static void main(String[] args) {
// Create an arr to work with
int[] test = new int[] {0,1};
int[] tes = new int[3];
// Find all possible combinations of this arr in the string size of 3
possiblecomb(3, test,tes,0);
}
public static void possiblecomb(int maxLength, int[] nums, int[] curr,int end) {
// If the current array has reached it's maximum length
if(end == maxLength) {
System.out.println(Arrays.toString(curr));
// Else add each number from the numbs to new array and process these new arrays again
} else {
for(int i = 0; i < nums.length; i++) {
int[] oldCurr = curr.clone();
curr[end]= nums[i];
possiblecomb(maxLength,nums,curr,end++);
curr = oldCurr.clone();
}
}
}
}
Try moving your recursive call outside of the for.
You are using the for in order to copy contents.
Your end variable will eventually increment above max lenght, and your (==) comparison won't be a stopper.
Take the example where num.Length = 2 and end is 2 :
You will call your function once with end = 3 which will stop and print inside the recursive call, and next, when i == 1 your end will be 4 and the recursive call won't break.
If you want to avoid the infinite recurssion with your current code in order to better debug with output, put the break condition
if (end>=maxLength)
As #MichaelCMS said you never stop the recursion, hence a stack overflow.
If you don't mind using Lists instead of arrays this is a solution:
import java.util.*;
public class Program {
private static List<List<Integer>> combinations(List<Integer> list, int maxLength) {
return combinations(list, maxLength, new ArrayList(), new ArrayList());
}
private static List<List<Integer>> combinations(List<Integer> list, int length, List<Integer> current, List<List<Integer>> result) {
if (length == 0) {
List<List<Integer>> newResult = new ArrayList<>(result);
newResult.add(current);
return newResult;
}
List<List<List<Integer>>> res3 = new ArrayList<>();
for (Integer i : list) {
List<Integer> newCurrent = new ArrayList<>(current);
newCurrent.add(i);
res3.add(combinations(list, length - 1, newCurrent, result));
}
List<List<Integer>> res2 = new ArrayList<>();
for (List<List<Integer>> lst : res3) {
res2.addAll(lst);
}
return res2;
}
public static void printCombinations(List<Integer> list, int maxLength) {
List<List<Integer>> combs = combinations(list, maxLength);
for (List<Integer> lst : combs) {
String line = "";
for (Integer i : lst) {
line += i;
}
System.out.println(line);
}
}
public static void main(String[] args) {
List<Integer> l = Arrays.asList(0, 1);
printCombinations(l, 2);
}
}
That gives you:
00
01
10
11
I'm playing with array and iterator. I don't want to use collections. Just simple iterator and methods defined by myself.
I have set of students in array (size of array is equal to the number of students) and they are in chronogical order (by student index (ID) number - 123456, 162475 in constructor etc.). So I want to create new array which is bigger than previous one (by one element) and add new student, but with saving the chronogical order. I have method that create bigger array and overwrite the reference to the old one, but I don't know how to add element in specific place using iterator. Using for() with it's array[i+1]=array[i] would be easy, but I don't know how to do it with iterator.
that's a part of my code:
public class GrupaStud {
public static void main(String[] args) {
Student [] s = new Student[5];
s[0]=new Student("Katarzyna", "Gryzipiórko", 123456, 5);
s[1]=new Student("Bartosz", "Polański", 162475, 4);
s[2]=new Student("Heniek", "Zając", 175642, 3);
s[3]=new Student("Konstanty", "Mołotow", 432156, 2);
s[4]=new Student("Bogdan", "Cichowlaz", 666555, 2.5);
ArrayIterator itab = new ArrayIterator(s);
s = biggerArray(s);
itab = new ArrayIterator(s);
Student nowy =new Student("Małgorzata", "Kopytko", 165642, 4);
for (itab.first(); !itab.isDone(); itab.next()) {
Student st = (Student) itab.current();
//in my mind that if need to check if index number of current element is bigger than
//int index above (165642) , but exactly here I don't know, how to add Student nowy
//to the array with moving rest of elements
if (st.nrIndex >nowy.nrIndex)
}
}
public static Student[] biggerArray(Student[] s)
{
Student[] newArray = new Student[6];
for (int i=0; i<s.length; i++)
newArray[i] = s[i];
return newArray;
}
}
I would add the existing values to your new array as you traverse with the iterator, rather than initializing all the values in biggerArray. There isn't an easy way to insert into the middle of an array like that (which is why you would normally use an ArrayList for this sort of thing).
Something like:
itab = new ArrayIterator(s);
Student[] newArray = new Student[6];
int newIndex = 0;
Student nowy =new Student("Małgorzata", "Kopytko", 165642, 4);
for (itab.first(); !itab.isDone(); itab.next()) {
Student st = (Student) itab.current();
if (st.nrIndex > nowy.nrIndex) { //Not sure about the meaning of this condition, make sure you only add the new student once!
newArray[newIndex] = nowy;
newIndex++;
}
newArray[newIndex] = st;
newIndex++;
}
It's also interesting to take a look at how ArrayList inplements this. It uses System.arraycopy, with which you could take a similar approach to what you are doing, and have:
s = biggerArray(s);
itab = new ArrayIterator(s);
int index = 0;
Student nowy =new Student("Małgorzata", "Kopytko", 165642, 4);
for (itab.first(); !itab.isDone(); itab.next()) {
Student st = (Student) itab.current();
if (st.nrIndex >nowy.nrIndex) {
System.arraycopy(s, index, s, index + 1, 5 - index);
s[index] = nowy;
break;
}
index++;
}
You should consider using an ArrayList instead which handles insertion better. Otherwise, you will need to shift all of the elements over in the array. ArrayList also automatically expand for you, so they are good when size is uncertain.
ArrayList<Student> students = new ArrayList<Student>();
students.add(student1);
students.add(student2);
students.add(student3);
int insertionIndex = 1;
students.add(insertionIndex, student4);
This does as specified. It accepts the original array and a to-insert-into array, which must be exactly one greater in length (well, at least one greater). Since it is generified to work with all (non-primitive) types, it cannot create the array itself.
The function:
public static final <O> O[] getNewArrayWithInserted(int insertIdx, O toInsert, O[] orig_arr, O[] arr_toInsInto) {
int idx = -1;
try {
for(O o : orig_arr) {
idx++; //First iteration: was -1, now 0
if(idx < insertIdx) {
arr_toInsInto[idx] = o;
continue;
}
if(idx == insertIdx) {
arr_toInsInto[idx++] = toInsert;
}
arr_toInsInto[idx] = o;
}
} catch(ArrayIndexOutOfBoundsException abx) {
throw new ArrayIndexOutOfBoundsException("idx=" + idx + ", insertIdx=" + insertIdx + ", orig_arr.length=" + orig_arr.length + ", arr_toInsInto.length=" + arr_toInsInto.length + ", original error:" + abx);
}
return arr_toInsInto;
}
Which is called with (index to insert-at, followed by the value to insert):
Integer[] intArr2 = ManualArrayInsertWItrIntoNewArray.<Integer>getNewArrayWithInserted(3, 4, intArr, new Integer[intArr.length + 1]);
Full example:
import java.util.Arrays;
/**
<P>{#code java ManualArrayInsertWItrIntoNewArray}</P>
**/
public class ManualArrayInsertWItrIntoNewArray {
public static final void main(String[] ignored) {
//You don't have to prefix it with ManualArrayInsertWItr in this static main,
//but it's normally called this way.
Integer[] intArr = new Integer[] {1, 2, 3, 5, 6, 7, 8, 9};
Integer[] intArr2 = ManualArrayInsertWItrntoNewArray.<Integer>getNewArrayWithInserted(3, 4,
intArr, new Integer[intArr.length + 1]);
System.out.println("Original: " + Arrays.toString(intArr));
System.out.println("New with insert: " + Arrays.toString(intArr2));
}
public static final <O> O[] getNewArrayWithInserted(int insertIdx, O toInsert, O[] orig_arr, O[] arr_toInsInto) {
int idx = -1;
try {
for(O o : orig_arr) {
idx++; //First iteration: was -1, now 0
if(idx < insertIdx) {
arr_toInsInto[idx] = o;
continue;
}
if(idx == insertIdx) {
arr_toInsInto[idx++] = toInsert;
}
arr_toInsInto[idx] = o;
}
} catch(ArrayIndexOutOfBoundsException abx) {
throw new ArrayIndexOutOfBoundsException("idx=" + idx + ", insertIdx=" + insertIdx + ", orig_arr.length=" + orig_arr.length + ", arr_toInsInto.length=" + arr_toInsInto.length + ", original error:" + abx);
}
return arr_toInsInto;
}
}
Output:
[C:\java_code\]java ManualArrayInsertWItrIntoNewArray
Original: [1, 2, 3, 5, 6, 7, 8, 9]
New with insert: [1, 2, 3, 4, 5, 6, 7, 8, 9]