Print out the prime numbers less than a given number N. For bonus points your solution should run in N*log(N) time or better. You may assume that N is always a positive integer.
Input sample:
Your program should accept as its first argument a path to a filename. Each line in this file is one test case. Each test case will contain an integer n < 4,294,967,295.
E.g.
10
20
100
Output sample:
For each line of input, print out the prime numbers less than N, in ascending order, comma delimited. (There should not be any spaces between the comma and numbers) E.g.
2,3,5,7
2,3,5,7,11,13,17,19
2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
Here is my solution:
public class problem1 {
public static void main(String [] args) throws Exception
{
File f=new File("C://Users/Rahul/Documents/Projects/r.txt");
FileReader fr=new FileReader(f);
List<Integer> l=new ArrayList<>();
int p;
BufferedReader br = new BufferedReader(fr);
String s;
while( (s= br.readLine()) != null ) {
int a=Integer.parseInt(s);
for(int i=2;i<a;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
l.add(i);
}
String st=l.toString();
st=st.replaceAll("\\[", "").replaceAll("\\]", "").replace(", ", ",");
System.out.print(st);
System.out.println("\t");
}
fr.close();
}
}
My input is :
10
50
And output is :
2,3,5,7
2,3,5,7,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47
But when i submit this solution they are not accepting this solution.
But when i put content in document like this:
10 50
30
I am trying that java program ignore this 50. How to do it ?
Any better solution then this ?
Give me some idea!
To ignore the extra number in your file you can take only the first number of each line.
Your solution is probably not accepted because in your second line you have printed 2,3,5,7 twice (i.e. the primes of the previous line)
See the example below to fix both problems
while( (s= br.readLine()) != null ) {
String [] numbers = s.split(" "); // split the line
int a = Integer.parseInt(numbers[0]); // take only the first one
....
System.out.print(st);
System.out.println("\t");
l.clear(); // clear the list before trying to find primes for the new line
}
"Your program should accept as its first argument a path to a filename"
You have a hardcoded filename in your solution - use args[0] instead.
Othwerwise, your solutions looks OK, although there is some room for improvements regarding the efficiency.
Related
ok so i have two .txt files, one called "input.txt" and another called "output.txt". to create output i have to copy the text from input but replace all spaces between words with #'s and add a new line with the string "#NEW_LINE#" after each line of the original text
for example, if input.txt is this:
the unstoppable marching of time
that is slowly guiding us all towards
an inevitable death
then output.txt should be something like this:
the#unstoppable#marching#of#time
#NEW_LINE#
that#is#slowly#guiding#us#all#towards
#NEW_LINE#
an#inevitable#death
#NEW_LINE#
anyway you get the idea.
now i dont have a problem with this particular task, but then i am also asked to print on the screen a message that shows the total number of lines of text from both files, and another that prints the total number of #'s from output.txt. and while i dont have trouble with counting the lines, their numbers show up correctly but i do have trouble figuring out the #'s... ill explain.
here's part of the code i tried at first: [btw this whole thing takes place on one class, with no other methods apart from main, of course. i thought it would be simpler that way idk 💁♂️💅]
File fsrc=new File("input.txt");
File fdes=new File("output.txt");
int atCount = 0; //number of #'s
int lineCountIN=0; //number of input's lines
int lineCountOUT=0; //number of output's lines
FileReader fr = new FileReader(fsrc);
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(fdes);
String s = null;
while((s=br.readLine())!=null)
{
if ((s.equals(" "))) {
fw.write(s.replace(" ","#"));
atCount++; }
else fw.write(s);
fw.write("\n");
lineCountOUT++;
lineCountIN++;
fw.write("#NEW_LINE#");
fw.write("\n");
lineCountOUT++;
fw.flush();
}
fw.close();
[...]
System.out.println("Total instances of # characters at output.txt: " + atCount);
the message that pops up on the screen will always be: "Total instances of # characters at output.txt: 0".
later i changed the if-else block to a do-while block:
do {
fw.write(s.replace(" ","#"));
atCount++; }
while ((s.equals(" ")));
but then the message does not return the exact number of #'s, in fact the number it shows just happens to be equal to lineCountIN for some reason (for example, for an input.txt file with 3 lines in total, the final message is: "Total instances of # characters at output.txt: 3")
so yeah thats pretty much it lmao i guess im using the atCount thingy wrong?? any help could be appreciated <3
Your approach finding the whitespace was not correct here is the solution, instead of searching in the whole string and count each line, you have to check each character and count it
public static void main(String[] args) {
String s = "the unstoppable marching of time\n" +
"that is slowly guiding us all towards\n" +
"an inevitable death";
int countSpace = 0;
if (s.contains(" ")) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
countSpace++;
}
}
s = s.replace(' ', '#');
}
System.out.println(s);
System.out.println(countSpace);
}
ok so the goal of my program (very basic at this point) is to take in a string of words for example: ("i give you 34 and you give me 50") and what i want is to populate my array with every occurrence of a number in the string. all this gives me back is the last number i give the code ive checked the whole array and all i can ever get back is the last number.
public static void main(String[] args) throws IOException {
BufferedReader read= new BufferedReader(new InputStreamReader(System.in));
String phrase;
int count = 0;
int[] numbers = new int[5];
phrase = read.readLine();
for (int i = 0; i < phrase.length()-1; i++){
if (phrase.substring(i).matches("((-|\\+)?[0-9]+(\\.[0-9]+)?)+")){
numbers[count] = Integer.parseInt(phrase.substring(i));
count++;
System.out.println(numbers[0]);
}
}
}
Some things to point out.
I don't know why you are using a substring method on the input.
You only printed numbers[0]. An array isn't good anyway because you never know how many numbers the input will have.
You are using parseInt, when you group on decimal numbers.
Pattern & Matcher would be recommended over String#matches
Here is the corrected code
List<Double> numbers = new ArrayList<>();
Pattern p = Pattern.compile("([-+]?[0-9]+(?:\\.[0-9]+)?)");
String phrase = "I give you 30, you give me 50. What about 42.1211?";
Matcher m = p.matcher(phrase);
while (m.find()) {
numbers.add(Double.parseDouble(m.group()));
}
System.out.println(numbers); // [30.0, 50.0, 42.1211]
I am looking to manipulate a text file through frequency by letter order. In my program there is a method I'm not sure how to start. I'd like to get an output something like:
Letter / Count
1 A 6 ***
2 B 8 ****
3 C 6 ***
(etc.)
To which 6 names begin with A, 8 with B, and 6 with C.
Then an '*' for every 2 count.
My practice problem is actually using a text file with 90000 names and a different '*' count, but an example code and explanation of why it works would be greatly appreciated for my study.
Here's the beginning of my program, but like I said I'm not sure how to start this method whatsoever.
import javax.swing.JOptionPane;
import java.io.*;
public class P03Census {
String rec;
int ctr = 0;
public static void main(String[] args)throws IOException {
Object result = JOptionPane.showInputDialog(null, "Enter a file name\n(1990 to 2000)\nadd extension",
"Taylor Daggett", JOptionPane.PLAIN_MESSAGE);
String textDoc = (String) result;
File file = new File(textDoc);
System.out.println("-----------------------------------------------------------------------------------------");
System.out.println("File name: " +
file);
if (!textDoc.endsWith(".txt")) {
System.out.println("Usage: This is not a text file!");
System.exit(0);
} else if (!file.exists()) {
System.out.println("File not found!");
System.exit(0);
}
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String rec;
int lines = 0;
int i;
while((rec = br.readLine()) != null){
lines++;
}
System.out.println("Record count:"+lines);
System.out.println("------------------------------------------------------------------------------------------");
}
}
Here's an algorithm that would do what you want, it exploits the fact you can use char variables as int:
First, create an array int[] letterCount = new int[26], which you will use to count the letters.
Then, inside the body of your main while loop, convert the string rec into an array String[] where every element is a name. If, in your input file, the names are always separated by the same char (like whitespace for example), you could use String[] names = rec.split(" ").
Next, run through that names in a for loop, and check the first letter of each name: char firstLetter = names[i].charAt(0). And use it to increase the count of that letter by one, in the array letterCount: letterCount[firstLetter - 'a']++;
At the end of the loop, letterCount should have the right count. Note that if you file contains capital letters, you have to call rec.toLowerCase(), at the start of the body of the loop, otherwise you will get out of bounds error, when trying to call letterCount[firstLetter - 'a'], or if all names start with upper case, then just replace by letterCount[firstLetter - 'A']
Forgive me if this has already been asked, but I am trying to fill an array of user defined size, but I want to make sure any extra input is either dumped or triggers an error to reprompt for input. My assignment requires that all input for an array is done on one line, with spaces separating individual values. The program works fine, and seeing how we are still in the beginning of the class I don't think that we are expected to know how to filter the quantity of inputs on a single line, but it is something that still bugs me.
I have searched for some time now for a solution, but everything thing I find is not quite what I am looking for. I thought doing a while(scannerVariable != "\n") would work, but once I thought about it more I realized that wouldn't do anything for my problem since the new line character is only being encountered once per array regardless of the number of inputs. The snippet with the problem is below:
public static double[] getOperand(String prompt, int size)
{
System.out.print(prompt);
double array[];
array = new double[size];
for(int count = 0; count < size; count++)
{
array[count] = input.nextDouble();
}
return array;
}
All I need is some way of validating the number of inputs or dumping/ignoring extra input, so that there is no trash in the buffer to skip input that follows. The only way I can think of is counting the number of spaces and comparing that against the size of the array -1. I don't think that would be reliable though, and I'm not sure how to extract a whitespace character for the count unless I were to have all the input go into a string and parse it. I can post more code or provide more details if needed. As always, thanks for any help!
This can help you. Function that allows the entry of numbers on a line separated by spaces. Valid numbers are stored in a list of type Double.
public static void entersDouble () {
Scanner input = new Scanner(System.in);
String s;
ArrayList<Double> numbers= new ArrayList<>();
System.out.print("Please enter numbers: ");
s=input.nextLine();
String [] strnum = s.split("\\s+");
int j=0;
while(j<strnum.length){
try {
numbers.add(Double.parseDouble(strnum[j++]));
}
catch(Exception exception) {
}
}
for (Double n : numbers)
System.out.println(n);
}
It seems to me that rather than trying to work out the number of inputs up front you would be better off trying to read them one by one and then taking appropriate action if it's too long or too short.
For example
public static double[] getOperands(String prompt, int size) {
double[] operands = new operands[size];
while (true) {
System.out.println(prompt);
Scanner scanner = new Scanner(System.in);+
int operandCount = 0;
while (scanner.hasNextDouble()) {
double val = scanner.nextDouble();
if (operandCount < size)
operands[operandCount++] = val;
}
if (operandCount == size)
return operands;
else
System.out.println("Enter " + size + " decimals separated by spaces.");
}
}
i want to split the string ...i want spit to happen for just first 5 times then ...rest in 1 string
i tried this
public class FileRead
{
public static void main(String[] args) throws IOException
{
StringBuffer strBuff = new StringBuffer();
String str = null;
File file = new File("D:\\wokies\\5_dataset.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
String [] splitSt =line.split(" ");
System.out.println("split happing");
for (int i = 0 ; i < splitSt.length ; i++)
{
System.out.println(splitSt[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I won't write code for you, but the solution is very simple, one solution is to have a counter, initialize it to 0, increment it on each iteration. When it'll be 5, don't split1.
1 I assume you want to split each time on a new input and not the same one.
java.lang.String.split(String regex, int limit) accepts a limit: How often do you want to split the input?
If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.
So
line.split(" ", 5);
would solve your problem.
You can use split with limit split(regex, limit). Try maybe split(" ", 5), this will create array with max 5 elements and last element will not be split like "a b c d".split(" ", 3) will create ["a", "b", "c d"]
The split method of String can take a second parameter "limit" that "controls the number of times the pattern is applied and therefore affects the length of the resulting array".
Just call line.split(" ", 5);