-2

I have a text file and a regex that extracts all of the numbers that are written throughout the text. I am able to match and extract the numbers, but I am having trouble trying to identify which extracted numbers are prime.

Could someone help me out? Thanks!

Here is my code:

import java.util.Scanner;//Import Scanner class to read a file in the computer
import java.io.File;//Import File class to read a file in the computer
import java.io.FileNotFoundException;//Import FileNotFoundException class if case file is not found in the computer

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex2 {
    public static void main(String[] args) throws FileNotFoundException {        
        int count = 0;
        //Display each word in INPUT_TEXT
        Scanner INPUT_TEXT = new Scanner(new File("/Users/Matt/Desktop/regex2.csv"));//Create a Scanner Class and File Class to read a file from your computer.

        INPUT_TEXT.useDelimiter(" ");//Divide file into several pieces by a space  
        if (INPUT_TEXT != null) {
            System.out.println(INPUT_TEXT);
        }

        while(INPUT_TEXT.hasNext()) {
            //Read each word
            String TempString = INPUT_TEXT.next();
            //Display all numbers.Eliminate comma, e.g., 1,200 -> 1200
            String temp1 = TempString.replaceAll("[\\,]", "");//Create a String class temp1 that eliminates comma.
            String pattern1 = "[0-9]+";//Create a String class pattern1 that stores the Regular Expression to match numbers.

            Pattern r1 = Pattern.compile(pattern1);//Create Pattern class to compile pattern1.

            Matcher m1 = r1.matcher(temp1);//Match each piece with the Regular Expression

            if (m1.find()) {   
                System.out.print(m1.group() + " ");
                //System.out.println(count);
                count++;
            // if count reaches 5, reset count and print new line
            if (count == 5) {
                count = 0;
                System.out.println();
            }
        }
    }
    INPUT_TEXT.close();//Close your Scanner.
    }
}
V1P3R
  • 176
  • 3
  • 16
  • 2
    You need to write a method to determine whether some input number is prime or not. The only way to determine primality for an integer n is trial division from 1 to \sqrt{n}. – ifly6 Sep 15 '16 at 03:19
  • 3
    @ifly6 but wouldn't it be cool if that could be done with a regexp. – Dawood ibn Kareem Sep 15 '16 at 03:21
  • 2
    You misunderstood [this question](http://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex). This regex doesn't check if string contains a prime number. Code in the question *builds* string of length n (e.g. `***` for n=3) and then checks it with regex. – default locale Sep 15 '16 at 03:21
  • @DavidWallace If only, if only. – ifly6 Sep 15 '16 at 03:23
  • @defaultlocale ahh, I see. Beginner's mistake. This is my first time working with regexp. Just thought I could find a swift way to work this out. – V1P3R Sep 15 '16 at 03:24
  • 1
    @DavidWallace That's thinking small. I want a regex that will determine whether my program terminates. :) – ajb Sep 15 '16 at 03:27
  • 2
    @V1P3R that question isn't really practical, so no wonder you didn't understand it. I'm afraid you'll have to parse a number from string and then run primality test on it. Check out this question: http://stackoverflow.com/questions/2385909/what-would-be-the-fastest-method-to-test-for-primality-in-java – default locale Sep 15 '16 at 03:32
  • @defaultlocale Exactly, so I'm not sure why this question got downvoted. Seems like a pretty logical question for someone who's never worked w/ regexp. But thanks! I will test this out as well. – V1P3R Sep 15 '16 at 03:36
  • @V1P3R It got downvoted due to lack of research effort, mostly because the very first sentence of the accepted answer of the post you linked to *emphasizes* that it's for a string of length *n*. Had you read through the answer to the post you linked to, as well as e.g. the blog post linked in its comments, all of that very clearly explains this as well. "Being new to regexes" doesn't explain why you didn't read the material. – Jason C Sep 15 '16 at 04:10
  • Yeah, `new String(new char[n])` is a tough one to figure out. Editing the link out of your post doesn't hide the fact that you didn't put any real effort in. You shouldn't make edits that completely invalidate existing answers btw. – Jason C Sep 15 '16 at 14:17

3 Answers3

2

You've totally misunderstood the post you linked to. It looks like you have a string that represents a number, and you think you can use a regex to determine whether it's prime. This is totally impossible.

The post showed how to test whether n is prime by creating a string of length n, and matching it against a regex that matches only if the string can be broken down into 2 or more groups of equal length and length >= 2. If it can, then the number can't be prime, because it must be the product of two numbers that are >= 2. This is a very poor way to test for primality. Its only use is to let some people show off their cleverness.

Even if you did create a string of that length, your code wouldn't work, because you're using find(), which will succeed if any substring of your source string matches. This won't work. The trick works only if the matcher is forced to match the entire source string.

ajb
  • 31,309
  • 3
  • 58
  • 84
1

If you're fine with using unary format of a number.

You can refer to this link

Community
  • 1
  • 1
Samuel Kok
  • 585
  • 8
  • 16
0

So yeah, all I had to do was add another "isPrime" method. Although I added each match to an array list, I believe you could have also just parsed the group(0) to Integer and tested each value like that.

Here is my code:

import java.util.Scanner;//Import Scanner class to read a file in the computer
import java.io.File;//Import File class to read a file in the computer
import java.io.FileNotFoundException;//Import FileNotFoundException class if case file is not found in the computer

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*; // Import all java utilities


public class assignmentTwo {
    public static ArrayList<Integer> nums;

    public static void main(String[] args) throws FileNotFoundException{

        int count = 0;


        //Display each word in INPUT_TEXT
        Scanner INPUT_TEXT = new Scanner(new File("/Users/Matt/Desktop/assignment2.csv"));//Create a Scanner Class and File Class to read a file from your computer.


        INPUT_TEXT.useDelimiter(" ");//Divide DemoData.txt into several pieces by a space

        // test to see if file was received
        if (INPUT_TEXT != null) {

            System.out.println(INPUT_TEXT);

        }


        while(INPUT_TEXT.hasNext()){


            //Read each word
            String TempString = INPUT_TEXT.next();

            //Display all numbers.Eliminate comma, e.g., 1,200 -> 1200
            String temp1 = TempString.replaceAll("[\\,]", "");//Create a String class temp1 that eliminates comma.
            String pattern1 = "[0-9]+";//Create a String class pattern1 that stores the Regular Expression to match numbers.
            Pattern r1 = Pattern.compile(pattern1);//Create Pattern class to compile pattern1.
            Matcher m1 = r1.matcher(temp1);//Match each piece with the Regular Expression


            // array variable
            nums = new ArrayList<Integer>();

            // find values that match
            if (m1.find( )) {

            // parse array values from string to integers
            int parsedNum = Integer.parseInt(m1.group());
            nums.add(parsedNum);


            //If a number is matched, print the number.
            System.out.print(m1.group() + " ");

            // increment counter when number validation is reached
            count++;


            // if count reaches 5, reset count and print new line
            if (count == 5) {

            count = 0;

            System.out.println();



    }

    // run isPrime method
     isPrime();

}

    }

        INPUT_TEXT.close();//Close your Scanner.

    }

    // isPrime method to test which #s are prime
    public static int isPrime(){

        // finds size of array
        for(int s = 0; s < nums.size(); s++){

            // primeNum is true by default
            boolean primeNum = true;

            /* if a value from the array is divisible by any # <= array value
                then that value is not prime */
            for (int divisor = 2; divisor <= nums.get(s) / 2; divisor++) {
                if (nums.get(s) % divisor == 0) {

                    primeNum = false;

                }

            }
                // if value is prime, print out current value 
                if (primeNum) {

                    //System.out.println();
                    System.out.print(nums.get(s) + " ");

                    // return array list values
                    return nums.get(s);

                }

        }

        // exit status
        return 0;
    }    
}
V1P3R
  • 176
  • 3
  • 16