Recursive depth first search Integer ArrayList Java - java

What I'm trying to do is essentially look at a set of numbers, and find all subsets of those numbers and eventually print them out. I'm completely stuck on writing the recursion method. The idea is to use a Boolean arraylist as a form of a tree, and traverse through it testing all the different sums for what I'm looking for. The problem is that it's not even going through the tree correctly, so any suggestions would be of great help.
package programmingassignment3;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SubsetSum {
public ArrayList<Integer> set1 = new ArrayList<Integer>(Arrays.asList(1,2,3,4));
int d = 6;
public void test(){
Collections.sort(set1);
for(int i =0;i<set1.size();i++)
if(set1.get(i)>d)
set1.remove(i);
ArrayList<Boolean> set1test = new ArrayList();
recSubSetSum(set1test);
}
public void recSubSetSum(ArrayList<Boolean> subsetList)
{
if(sumOfList(subsetList)>=d)
System.out.println("Output Set(WIP)");
ArrayList<Boolean> leftList = new ArrayList();
ArrayList<Boolean> rightList = new ArrayList();
for(int i =0;i<set1.size();i++)
{
leftList = new ArrayList(subsetList);
rightList = new ArrayList(subsetList);
if(set1.size()>leftList.size())
leftList.add(true);
if(set1.size()>rightList.size())
rightList.add(false);
if(sumOfList(leftList)<d)
{
recSubSetSum(leftList);
if(set1.size()>rightList.size())
rightList.add(false);
}
if(sumOfList(rightList)<d)
recSubSetSum(rightList);
}
}
public int sumOfList(ArrayList<Boolean> subSetList)
{
int sum = 0;
for(int i = 0;i<subSetList.size();i++)
{
if(subSetList.get(i))
sum+=set1.get(i);
}
return sum;
}
}

Related

Initializing 2D ArrayList for for-loop summation (Java)

I am trying to sum N pairs of ints--an Nx2 ArrayList--and return the N summations as an ArrayList. While I understand it is not necessary to set up a class to accomplish this, I would like to do so as practice for future projects.
import java.util.ArrayList;
public class SumsInLoop {
public SumsInLoop(int numberOfPairs, ArrayList<ArrayList<Integer>> numbersList) {}
public ArrayList<Integer> getSums(int numberOfPairs, ArrayList<ArrayList<Integer>> numbersList) {
ArrayList<Integer> pairsOfSums = new ArrayList<Integer>();
for (ArrayList<Integer> Pair : numbersList) {
int x = Pair.get(0);
int y = Pair.get(1);
int sum = x + y;
pairsOfSums.add(sum);
}
System.out.println(pairsOfSums);
return pairsOfSums;
}
The data that I am given is a random assortment of N pairs (numbersOfPairs) of integers, e.g. 612673 108695. I would like to add these pairs of integers to a 2D ArrayList (numbersList) that will be called by getSums.
However, I am having difficulties initializing numbersList. My main function is as follows:
public static void main(String[] args) {
int myNumberOfPairs = 13;
ArrayList[][] myNumbersList = new ArrayList[13][2];
myNumbersList[0][0] = new ArrayList<>();
myNumbersList[0][0].add(612673);
myNumbersList[0][1].add(108695);
myNumbersList[1][0] = new ArrayList<>();
myNumbersList[1][0].add(756875);
myNumbersList[1][1].add(496058);
SumsInLoop mySum = new SumsInLoop(myNumberOfPairs,myNumbersList);
mySum.getSums(myNumberOfPairs, myNumbersList);
The last two lines of code throw errors, asking me to change myNumbersList to type ArrayList<List<Integer>> which throws even more errors, even after changing all 2D ArrayLists to type ArrayList<List<Integer>>.
So, my two questions are as follows:
How can I initialize an NxM ArrayList and populate it correctly?
Is there a faster way of accomplishing this task while still using a class method?
P.S. I'm used to coding in Python and am self-teaching myself Java, so any other information or resources you can provide me with are much appreciated.
You may want to simplify your input by using 2D array of int : int[][] myNumbersList = new int[13][2];
The expected output in that case is a 1D array of int[13] that can be obtained as follows (demonstrated with 2 pairs. See mcve ) :
public class SumsInLoop {
//pairsOfInts should be an [n][2] array
private static int[] sumOfPairs(int[][] pairsOfInts) {
int[] sums = new int[pairsOfInts.length];
for(int pairIndex = 0; pairIndex < pairsOfInts.length; pairIndex++) {
sums[pairIndex]= pairsOfInts[pairIndex][0]+pairsOfInts[pairIndex][1];
}
return sums;
}
public static void main(String[] args) {
int numberOfPairs = 2;
int[][] pairsOfInts = new int[numberOfPairs][2];
pairsOfInts[0] = new int[] {612673,108695 };
pairsOfInts[1] = new int[] {756875,496058 };
int[] sumOfPairs = sumOfPairs(pairsOfInts);
System.out.println(Arrays.toString(sumOfPairs));
}
}
If you want a solution implemented with List you can make use of javafx Pair (or make your own pair class.
The input can be defined as List<Pair<Integer,Integer>> pairsOfInts = new ArrayList<>();
The out put can be an array as above, or a List<Integer>:
import java.util.ArrayList;
import java.util.List;
import javafx.util.Pair;
public class SumsInLoop {
private static List<Integer> sumOfPairs(List<Pair<Integer, Integer>> pairsOfInts) {
List<Integer> sums = new ArrayList<>();
for(Pair<Integer,Integer> pair : pairsOfInts) {
sums.add(pair.getKey()+ pair.getValue());
}
return sums;
}
public static void main(String[] args) {
List<Pair<Integer,Integer>> pairsOfInts = new ArrayList<>();
pairsOfInts.add (new Pair<>(612673,108695 ));
pairsOfInts.add (new Pair<>(756875,496058));
List<Integer> sumOfPairs = sumOfPairs(pairsOfInts);
System.out.println(sumOfPairs);
}
}
The (compile) exception you are getting is due to the fact that you expect a ArrayList<ArrayList<Integer>>, but pass an ArrayList[][]. (which is not the same in Java)
In your case you'd need (in the main method):
ArrayList<ArrayList<Integer>> myNumbersList = new ArrayList</* when java > 6 ;)*/>(13);
this only sets the capacity of the (parent) list (..and the underlying/internal backing array)
to initialize the child lists, you'd not come around looping (somehow...even not in python :):
for (int i = 0; i < 13; i++) {
myNumbersList.add(new ArrayList<Integer>(2));
}
Depends on what means "correctly" ...but I assume with "random data", ideally you would again inner loop:
java.util.Random rnd = new Random(/*seed default current timestamp*/);
//...
for (int i = 0; i < 13; i++) {
ArrayList<Integer> innerList = new ArrayList<>(2);
for (int j = 0; j < 2; j++) {
innerList.add(rnd.netxInt(/*bound default Integer.MAX_VALUE*/) /*+/-/% offset*/);
}
myNumberList.add(innerList);
}
Sorry I am not aware of one (faster way), but much depends on the "input format".
Since you already know the amount of values in a pair, an ArrayList is unnecessary. You can create your own, simpler implementation of a pair.
class Pair {
public final int left;
public final int right;
public Pair(int left, int right){
this.left = left;
this.right = right;
}
}
You can then access the values by creating a pair object and accessing its fields.
Pair p = new Pair(10, 7);
System.out.println(p.left); // 10
System.out.println(p.right); // 7
You can then more easily redefine your getSums method.
public static List<Integer> getSums(List<Pair> pairs){
List<Integer> pairsOfSums = new ArrayList<>();
for(Pair pair : pairs){
int sum = pair.left + pair.right;
pairsOfSums.add(sum);
}
return pairsOfSums;
}
Please also notice the function can be static and you don't need to pass the number of pairs. The for-each loop will cycle through all of them regardless.
Initializing the array is then easier than the method you have described in the question.
List<Pair> pairs = new ArrayList<>();
pairs.add(new Pair(7, 10));
pairs.add(new Pair(18, 3));
pairs.add(new Pair(-6, 0));
pairs.add(new Pair(4, 2));
System.out.println(SumsInLoop.getSums(pairs));

ArrayList = Finding Composite or Prime Numbers

I am working on an "ArrayListFunHouse" program which mainly involves factors.
There are two methods: a method for finding the factors of each number besides the number itself and one, as well as another method for finding which factors are composite and/or prime, and removing all prime numbers from the array.
Here is the main program:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class ArrayListFunHouse
{
public static ArrayList<Integer> getListOfFactors(int number)
{
int i=0;
ArrayList<Integer> factors = new ArrayList<Integer>();
for(i=2;i<=number-1;i++){
if(number%i==0)
factors.add(i);
}
Collections.sort(factors);
return factors;
}
public static void keepOnlyCompositeNumbers( List<Integer> nums)
{
/*
//GET HELP FOR THIS PART
*/
}
}
note that I left the finding composite numbers method empty, because I honestly have no idea what to do there. Trying other solutions from the internet don't work.
Here is the runner:
import java.util.Scanner;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class ArrayListFunHouseRunner
{
public static void main( String args[] )
{
System.out.println(ArrayListFunHouse.getListOfFactors(9));
System.out.println(ArrayListFunHouse.getListOfFactors(23));
System.out.println(ArrayListFunHouse.getListOfFactors(50));
System.out.println(ArrayListFunHouse.getListOfFactors(100));
System.out.println(ArrayListFunHouse.getListOfFactors(762));
Integer[] nums = {2,6,8,9,10,12,13,15,17,24,55,66,78,77,79};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(nums) );
System.out.println( list );
ArrayListFunHouse.keepOnlyCompositeNumbers( list );
System.out.println( list );
}
}
This part of the runner:
Integer[] nums = {2,6,8,9,10,12,13,15,17,24,55,66,78,77,79};
List<Integer> list = new ArrayList<Integer>( Arrays.asList(nums) );
System.out.println( list );
ArrayListFunHouse.keepOnlyCompositeNumbers( list );
System.out.println( list );
relies on the composite number method, which is supposed to remove prime numbers from the array, as I have already said.
I have already figured out everything related to the first method. It is just the second method I am stuck on.
I would suggest making your method a predicate rather than altering the list that is passed in. That way you can use it in many different ways (with examples below).
So:
public static boolean isComposite(int number) {
for (int i = 2; i < number; i++) {
if (number % i == 0)
return true;
}
return false;
}
Then you can easily remove composites from your list with:
list.removeIf(ArrayListFunHouse::isComposite);
Note that removeIf was added in Java 8 but there's easy ways to achieve the same effect in previous versions.
A slightly more elegant way if you are familiar with Java 8 streams might be to return a stream from your factor finder then use that in the composite checker:
public static IntStream getFactors(int number) {
return IntStream.range(2, number).filter(n -> number % n == 0);
}
public static boolean isComposite(int number) {
return getFactors(number).findAny().isPresent();
}
Then finding composite factors becomes:
List<Integer> compositeFactors = getFactors(number)
.filter(ArrayListFunHouse::isComposite)
.collect(Collectors.toList());
There's really no reason to sort the collection as it is already sorted as it is constructed.
Try this for the method keepOnlyCompositeNumbers.
public static ArrayList<Integer> keepOnlyCompositeNumbers( List<Integer> nums)
{
List<Integer> compositeList=new ArrayList<Integer>();
for(Integer num:nums){
int count=0;
for(int i=2;i<num;i++){
if(num%i==0){
count++;
}
}
if(count!=0){
compositeList.add(num);
}
}
return (ArrayList<Integer>) compositeList;
}
}
Try this to print those composite numbers.
System.out.println( list );
List<Integer> compositeList1=new ArrayList<Integer>();
compositeList1= ArrayListFunHouse.keepOnlyCompositeNumbers( list );
System.out.println( compositeList1 );

Why am I unable to add nodes to my adjacency list?

It says that I must initialize the adjbut it doesn't work. I know something is majorly wrong. I also tried using an ArrayList inside an ArrayList and that didn't work either. What's wrong you reckon?
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AdjacencyList {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter nodes below like (u,v):");
//Create List
ArrayList<Integer>[] adj;
for (int i=0; i<2; i++) {
String nodes = in.nextLine();
String[] data = nodes.split(",");
String u = data[0];
String v = data[1];
int inNode = Integer.parseInt(u);
int outNode =Integer.parseInt(v);
adj[inNode] = new ArrayList<Integer>();
adj[inNode].add(outNode);
System.out.println("Added to list");
}
//print nodes and then their corresponding list
System.out.println(adj[1]);
}
}
Assuming that you really want an array of ArrayLists, you should initialize it like this:
ArrayList<Integer>[] adj = (ArrayList<Integer>[]) new ArrayList[SIZE];

How to List value are possible String combination in java?

i have one arrayList
List value = new ArrayList();
this arraylist are value is = {a,b,c,d}
i have required combination to string using this arraylist
Required Output: abcd,bcd,acd,abd,abc,cd,bd,bc,ad,ac,ab,a,b,c,d,null
If it's possible? then please send me code....
It's my code but not perfectly work
import java.util.ArrayList;
import java.util.List;
public class PossibleCombination {
public static void main(String[] args) {
List segList = new ArrayList();
for(int i=65;i<70;i++){
segList.add((char)i);
}
int segSize = segList.size();
int[][] a = new int[segSize][2];
int i;
for(i=0; i<= segSize-1; i++)
{
a[i][0] = 0;
a[i][1] = 1;
}
boolean b1 = true;
int t =0;
while(b1)
{
StringBuffer stb = new StringBuffer();
for(i=0;i<segSize; i++)
{
if(a[i][0]==0)
stb.append(segList.get(i));
}
System.out.println(stb);
if(t>=a.length){
t=0;
}
int Pos=t;
while(a[Pos][0]>=a[Pos][1])
{
if(Pos<segSize-1)
Pos++;
else
break;
}
a[Pos][0]++;
Pos--;
while(Pos>=0)
{
if(a[Pos][0]>0)
{
a[Pos][0]--;
break;
}
Pos--;
}
t++;
if(a[segSize-1][0]> a[segSize-1][1]){
b1 = false;
}
}
}
}
Yes, It is definitely possible. However, it will of course require exponential time.
I will leave the actual implementation to you, but here are some hints.
The easiest way to do this is recursively, but that will take a lot of stack space very quickly.
Another way to do this is via some kind of breath-first expanding of the resulting list. This can be done iteratively with a FIFO queue.
List<String[]> value = new ArrayList<String[]>();
String[] item = {"a","b","c"};
value.add(item);

Working with really big numbers

please have a look at the following code
import java.util.ArrayList;
import java.util.List;
public class Big
{
static int primeNumber = 2;
public static void main(String[]args)
{
int numberDevident = 147;
int left=0;
int result=0;
List numbers = new ArrayList();
while(true)
{
result = numberDevident/primeNumber;
left = numberDevident%primeNumber;
if(left!=0)
{
primeNumber++;
}
else
{
numbers.add(primeNumber);
numberDevident = result;
System.out.println(primeNumber);
}
}
}
}
This code find the prime factors of a given number (Variable "numberDevident" in the code"). But, there is a case, that is, the given number is 600851475143
It is no way matching to int, long or double. How can I solve this using this much of a big number? Please help
Here I am doing the same with BigInteger
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
public class Problem3
{
static BigInteger primeNumber = new BigInteger("2");
static BigInteger zero = new BigInteger("0");
static BigInteger add = new BigInteger("1");
public static void main(String[]args)
{
BigInteger numberDevident = new BigInteger("147");
BigInteger left= new BigInteger("0");;
BigInteger result=new BigInteger("0");;
List numbers = new ArrayList();
while(true)
{
result = numberDevident.divide(primeNumber);
left = numberDevident.remainder(primeNumber);
if(left!=zero)
{
primeNumber.add(add);
}
else
{
numbers.add(primeNumber);
numberDevident = result;
System.out.println(primeNumber.toString());
}
}
}
}
still no good, it is not displaying anything. Please help.
You might want to take a look at BigInteger.

Categories