user2341013
user2341013

Reputation:

Find factors for a number using hashmap and arraylist

I have the below program where I am checking for factors for each number in an array. I need to use arraylist within a hashmap.

I have the below code -

public class ArrayExcercise {
private static Map<Integer, ArrayList<Integer>> mapOne = new TreeMap<Integer, ArrayList<Integer>>();
private static Map<Integer, ArrayList<Integer>> mapTwo = new TreeMap<Integer, ArrayList<Integer>>();
private static ArrayList<Integer> valuesOne = new ArrayList<Integer>();
private static ArrayList<Integer> valuesTwo = new ArrayList<Integer>();

public static void main(String[] args) {
    int[] randomArrayOne = RandomElementsInAnArray.generateRandomNumber(1,6);       
    System.out.println("The elements in the first array are: "+ Arrays.toString(randomArrayOne));       
    findFactors(randomArrayOne);        
}

static boolean flag = true;

public static boolean findFactors(int[] arrayOne) {         
    for (int i = 0; i < arrayOne.length; i++) {         
        checkFactors(arrayOne[i]);
    }       

    return false;
}

public static synchronized Map<Integer, ArrayList<Integer>> checkFactors(int num) {     
    for (int i = 2; i <= num; i++) {
        if ((num % i == 0)) {               
            valuesOne.add(i);                               
            mapOne.put(num, valuesOne);             
        }
    }       
    return mapOne;
}

}

What I need help here is with adding the elements to the arraylist after finding the factor for the number. If lets say the array(input) has elements - 2,4,6, and I pass each of these numbers as an input to the method findFactors, I want it to display as below -

//I am excluding 1 since 1 is a factor for all numbers.

2 - 2 
4 - 2,4
6 - 2,3,6

Instead I see the output as below -

2 - 2,3,4,6
3 - 2,3,4,6
6 - 2,3,4,6

I understand this is where I am going wrong -

for (int i = 2; i <= num; i++) {
        if ((num % i == 0)) {               
            valuesOne.add(i);                               
            mapOne.put(num, valuesOne);             
        }
    }   

I am appending the values to the arrayList, valuesOne. I have no idea how to fix it. Request someone to please help.

Upvotes: 0

Views: 902

Answers (2)

jlordo
jlordo

Reputation: 37813

Although I would approach this differently, if you simply write

valuesOne = new ArrayList<Integer>();

at the beginning of your checkFactors() method, you will get your desired output, without changing a lot in your current code.

Upvotes: 1

hoaz
hoaz

Reputation: 10163

You need to reinitialize valuesOne ArrayList every time you call checkFactors method.

valuesOne = new ArrayList<Integer>();
for (int i = 2; i <= num; i++) {
    if ((num % i == 0)) {               
        valuesOne.add(i);                               
        mapOne.put(num, valuesOne);             
    }
}       
return mapOne;

Upvotes: 3

Related Questions