ArrayList = Finding Composite or Prime Numbers - java

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 );

Related

How to fill in the gaps in each array element?

If I have an array like this
int[] array = {2,4,6,8,11};
how to print the gaps between each array element?
Gaps = 3 5 7 9 10
This is my program but the output is always 5 it doesn't print the other gaps is there any method rather than hash set? thank you
`
import java.util.HashSet;
import java.util.Set;
public class test {
public static void main(String[] args) {
int[] array = {2,4,6,8,11};
Set<Integer> set = new HashSet<>();
for(int m : array) {
if( set.add(m));
}//for
for(int i = 1 ; i < set.size() ;i++) {
if(!set.contains(i)) {System.out.println("Gaps = " + set.size()); }
}
}
}
`
In the following solution, I've fixed the logic errors you have made. There are other efficient ways to solve this problem.
import java.util.HashSet;
import java.util.Set;
public class test {
public static void main(String[] args) {
int[] array = {2,4,6,8,11};
Set<Integer> set = new HashSet<>();
for(int m : array) {
if( set.add(m));
}//for
for(int i = 1 ; i < (2* set.size()) + 1 ;i++) {
if(!set.contains(i)) {System.out.println(i); }
}
}
}

How do i print values instead of memory location in java? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I am trying to solve a popular problem on leetcode called two sum on my ide(intellij). I am expecting it to print index of values inside the array but its printing a memory address. I did some searching and found that i need to override to string(), i did the override and its still printing the memory address. what am i doing wrong? If anyone can help me out, i would appreciate it. Thank you. :)
import java.util.HashMap;
import java.util.Map;
public class Main {
#Override
public String toString() {
return super.toString();
}
public static void main(String[] args) {
int arr[]={2,7,11,15};
int target= 9;
int result[]=(find(arr,target));
System.out.println(result);
}
public static int[] find(int[] arr,int target){
Map<Integer,Integer> hm =new HashMap<>();
for(int i=0;i<arr.length;i++){
int num= target- arr[i];
if(hm.containsKey(num)){
return new int[]{hm.get(num),i};
}
hm.put(arr[i],i);
}
return new int[]{-1, -1};
}
}
So there are two ways you can do this. First of all, the output that you are getting is basically hash values. What you want to do is print out the elements in that array. The first way to do it is to iterate through your array and simply print out the values like so:
for(int j=0;j<result.length;j++){
System.out.println(result[j]);
}
The other way you could do this would be if you just used The Array class and its toString() method.
System.out.println(Arrays.toString(yourArray));
Both methods should work.
Your problem – which has been already answered – set aside, if you'd want to set up an environment in a single file, this might work OK for a Main.java file:
import java.util.*;
// import javafx.util.*;
class Solution {
public static final int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
HashMap<Integer, Integer> map = new HashMap<>();
for (int index = 0; index < nums.length; index++) {
if (map.get(target - nums[index]) != null) {
indices[1] = index;
indices[0] = map.get(target - nums[index]);
return indices;
}
map.put(nums[index], index);
}
return indices;
}
}
class Main {
public static void main(String[]args) {
Solution s = new Solution();
int arr[] = {2,7,11,15};
int target = 9;
System.out.println(s.twoSum(arr, target)[0]);
System.out.println(s.twoSum(arr, target)[1]);
}
}
Prints:
0
1

function.Function as parameter in print method

I dont have any clue how to approach the problem i am facing. We have to print out an array using function.Function as a parameter and using lambas to print out 1. the even and 2. the odd numbers.
final class Main
{
private Main() {}
public static void main(String[] argv)
{
// Fill the array with integer values and print out only
// values of even indices
DataStructure ds = new DataStructure();
ds.printEven();
// Even
ds.print(..);
}
// Odd
ds.print(...);
}
// end of main class
import java.util.Arrays;
import java.util.function.Function;
class DataStructure
{
// Create an array
private final static int SIZE = 15;
private int[] arrayOfInts = new int[SIZE];
int getSize()
{
return SIZE;
}
int[] getInts()
{
return arrayOfInts;
}
DataStructure()
{
// fill the array with ascending integer values
for (int i = 0; i < SIZE; i++)
{
arrayOfInts[i] = i;
}
}
private DataStructureIterator getIterator(IteratorStrategy strategy)
{
return strategy.getIterator(this);
}
void print(IteratorStrategy strategy)
{
DataStructureIterator iterator = getIterator(strategy);
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
}
void printEven()
{
// Print out values of even indices of the array
DataStructureIterator iterator =
getIterator(newEvenIteratorStrategy());
while (iterator.hasNext())
{
System.out.print(iterator.next() + " ");
}
System.out.println();
}
//this method is still missing - we have to use the given parameters
void print(java.util.function.Function <Integer,Boolean> iterator)
{
}
}
The expected output is for isEven 0 2 4 6 8 10 12 14
and for isOdd 1 3 5 7 9 11 13
The rest of the given class shouldn't be important atleast i think so.
I am searching for solutions or just a hint for hours but I dont find anything useful. Your help is much appreciated and sorry for my english
If you need anything let me know. Btw I am new to stackoverflow so I hope I did everything right
Not sure that I understood what you really wanted but maybe you should have
a look at this link: https://www.boraji.com/java-8-javautilfunctionfunction-example.
It explains how to use the Function interface and gives an example with even and odds number...
In your case, Function<Integer, boolean> means that you are going to receive an Integer as input and that you must return a boolean (I suppose true if even and false if odd).
Hope it helps! ;)

Checking if a word is equal to a specific word in an ArrayList

I'm trying to create a method which will search through an ArrayList containing several words searching for a specific String. Where if the String is not equal to any words in the ArrayList it will add the word to the list, and if the word already exists in the list, it will count how many times the word occurs and then add one more, which will represent the last String input.
This is what I've got so far in my code:
public void leggTilOrd(String ord) {
if (Ord.contains(ord)) {
teller++;
}
if (!Ord.contains(ord)) {
Ord.add(ord);
}
System.out.println(teller);
}
Obviously this will only add one more number in the counter (teller), so what I'm trying to achieve it to add 1 on top of all the occurrences of that specific String in the list and this is where I'm stuck.
Edit: I should also mention that Ord is an ArrayList I've created earlier in the code.
Here's the full code:
import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class Ordliste {
private ArrayList<String> Ord = new ArrayList<String>();
private int teller = 0;
public void lesBok (String filnavn) throws Exception{
Scanner fil = new Scanner(new File(filnavn));
while(fil.hasNextLine()){
Ord.add(fil.next());
} fil.close();
}
public void leggTilOrd(String ord){
if(Ord.contains(ord)){
teller++;
} if (!Ord.contains(ord)){
Ord.add(ord);
} System.out.println(teller);
}
}
Instead of doing this , you can keep track of the strings in your list using a Set
Set<String> set = new HashSet<String>();
public void leggTilOrd(String ord) {
if (set.contains(ord) != null) {
teller++;
} else {
Ord.add(ord);
set.add(ord);
}
System.out.println(teller);
}
Are you tied to using an ArrayList? I'd recommend using a Map<String, Integer> instead and store the number of occurrences of a specific string as value in the map:
if (map.get(ord) != null) {
map.put(ord, map.get(ord) + 1);
}
else {
map.put(ord, 1);
}
Still not sure exactly what you are trying to accomplish, do you increment teller each time you add a different word?
This is a simple way to do what I believe you are attempting, and should get you going in the right direction.
import java.util.Arrays;
import java.util.List;
public class test
{
static int teller = 0;
static List<String> words = Arrays.asList("dog", "cat", "dog");
public static void main(String[] args)
{
System.out.println(teller);
addAndCount("dog");
System.out.println(teller);
teller = 0;
addAndCount("cat");
System.out.println(teller);
teller = 0;
addAndCount("fish");
System.out.println(teller);
}
public static void addAndCount(String newWord)
{
teller += 1 + Math.toIntExact(
words.stream().filter(string -> newWord.equals(string)).count());
words.add(newWord);
}
}

Recursive depth first search Integer ArrayList 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;
}
}

Categories