Skip to content

Commit 2754bec

Browse files
FridaTveitsjwarner-bp
authored andcommitted
grep: add exercise (exercism#1429)
* grep: WIP add exercise * grep: implement exercise * grep: add to config.json * grep: update config.json and add hints * grep: Add .keep file * grep: improve reference solution * grep: Make sure settings.gradle is in alphabetical order
1 parent 36f2472 commit 2754bec

9 files changed

Lines changed: 697 additions & 0 deletions

File tree

‎config.json‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -638,6 +638,20 @@
638638
"unlocked_by": "rotational-cipher",
639639
"uuid": "d36ce010-210f-4e9a-9d6c-cb933e0a59af"
640640
},
641+
{
642+
"core": false,
643+
"difficulty": 5,
644+
"slug": "grep",
645+
"topics": [
646+
"pattern_matching",
647+
"strings",
648+
"files",
649+
"filtering",
650+
"searching"
651+
],
652+
"unlocked_by": "robot-name",
653+
"uuid": "9c15ddab-7b52-43d4-b38c-0bf635b363c3"
654+
},
641655
{
642656
"core": false,
643657
"difficulty": 6,

‎exercises/grep/.meta/hints.md‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
Since this exercise has difficulty 5 it doesn't come with any starter implementation.
2+
This is so that you get to practice creating classes and methods which is an important part of programming in Java.
3+
It does mean that when you first try to run the tests, they won't compile.
4+
They will give you an error similar to:
5+
```
6+
path-to-exercism-dir\exercism\java\name-of-exercise\src\test\java\ExerciseClassNameTest.java:14: error: cannot find symbol
7+
ExerciseClassName exerciseClassName = new ExerciseClassName();
8+
^
9+
symbol: class ExerciseClassName
10+
location: class ExerciseClassNameTest
11+
```
12+
This error occurs because the test refers to a class that hasn't been created yet (`ExerciseClassName`).
13+
To resolve the error you need to add a file matching the class name in the error to the `src/main/java` directory.
14+
For example, for the error above you would add a file called `ExerciseClassName.java`.
15+
16+
When you try to run the tests again you will get slightly different errors.
17+
You might get an error similar to:
18+
```
19+
constructor ExerciseClassName in class ExerciseClassName cannot be applied to given types;
20+
ExerciseClassName exerciseClassName = new ExerciseClassName("some argument");
21+
^
22+
required: no arguments
23+
found: String
24+
reason: actual and formal argument lists differ in length
25+
```
26+
This error means that you need to add a [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html) to your new class.
27+
If you don't add a constructor, Java will add a default one for you.
28+
This default constructor takes no arguments.
29+
So if the tests expect your class to have a constructor which takes arguments, then you need to create this constructor yourself.
30+
In the example above you could add:
31+
```
32+
ExerciseClassName(String input) {
33+
34+
}
35+
```
36+
That should make the error go away, though you might need to add some more code to your constructor to make the test pass!
37+
38+
You might also get an error similar to:
39+
```
40+
error: cannot find symbol
41+
assertEquals(expectedOutput, exerciseClassName.someMethod());
42+
^
43+
symbol: method someMethod()
44+
location: variable exerciseClassName of type ExerciseClassName
45+
```
46+
This error means that you need to add a method called `someMethod` to your new class.
47+
In the example above you would add:
48+
```
49+
String someMethod() {
50+
return "";
51+
}
52+
```
53+
Make sure the return type matches what the test is expecting.
54+
You can find out which return type it should have by looking at the type of object it's being compared to in the tests.
55+
Or you could set your method to return some random type (e.g. `void`), and run the tests again.
56+
The new error should tell you which type it's expecting.
57+
58+
After having resolved these errors you should be ready to start making the tests pass!
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import java.io.IOException;
2+
import java.nio.charset.Charset;
3+
import java.nio.file.Files;
4+
import java.nio.file.Paths;
5+
import java.util.Collections;
6+
import java.util.List;
7+
import java.util.stream.Collectors;
8+
import java.util.stream.IntStream;
9+
10+
class GrepTool {
11+
12+
String grep(String pattern, List<String> flags, List<String> files) {
13+
boolean shouldAddFilenameToEachLine = files.size() > 1;
14+
return files
15+
.stream()
16+
.map(file -> grepFile(pattern, flags, file, shouldAddFilenameToEachLine))
17+
.filter(line -> !line.isEmpty())
18+
.collect(Collectors.joining("\n"));
19+
}
20+
21+
private String grepFile(String pattern, List<String> flags, String filename, boolean shouldAddFilenameToEachLine) {
22+
List<String> lines = readFile(filename);
23+
24+
String matchingLines = IntStream.range(0, lines.size())
25+
.filter(lineIndex -> lineMatchesPattern(lines.get(lineIndex), pattern, flags))
26+
.mapToObj(lineIndex -> {
27+
String lineWithFlagsApplied = applyFlagsToLine(lines.get(lineIndex), flags, lineIndex + 1);
28+
return shouldAddFilenameToEachLine ? filename + ":" + lineWithFlagsApplied : lineWithFlagsApplied;
29+
})
30+
.collect(Collectors.joining("\n"));
31+
32+
boolean shouldPrintFilenameInsteadOfMatchingLines = flags.contains("-l");
33+
return shouldPrintFilenameInsteadOfMatchingLines && !matchingLines.isEmpty() ? filename : matchingLines;
34+
}
35+
36+
private boolean lineMatchesPattern(String line, String pattern, List<String> flags) {
37+
boolean isCaseInsensitive = flags.contains("-i");
38+
String lineToCompare = isCaseInsensitive ? line.toLowerCase() : line;
39+
String patternToCompare = isCaseInsensitive ? pattern.toLowerCase() : pattern;
40+
41+
boolean shouldMatchEntireLine = flags.contains("-x");
42+
boolean matchesPattern = shouldMatchEntireLine
43+
? lineToCompare.equals(patternToCompare)
44+
: lineToCompare.contains(patternToCompare);
45+
46+
boolean shouldInvertMatch = flags.contains("-v");
47+
//noinspection SimplifiableConditionalExpression
48+
return shouldInvertMatch ? !matchesPattern : matchesPattern;
49+
}
50+
51+
52+
private String applyFlagsToLine(String line, List<String> flags, int lineNumber) {
53+
boolean shouldAddLineNumber = flags.contains("-n");
54+
return shouldAddLineNumber ? lineNumber + ":" + line : line;
55+
}
56+
57+
private List<String> readFile(String filename) {
58+
try {
59+
return Files.readAllLines(Paths.get(filename), Charset.forName("UTF-8"));
60+
} catch (IOException e) {
61+
return Collections.emptyList();
62+
}
63+
}
64+
65+
}

‎exercises/grep/.meta/version‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
1.1.0

‎exercises/grep/README.md‎

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# Grep
2+
3+
Search a file for lines matching a regular expression pattern. Return the line
4+
number and contents of each matching line.
5+
6+
The Unix [`grep`](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html) command can be used to search for lines in one or more files
7+
that match a user-provided search query (known as the *pattern*).
8+
9+
The `grep` command takes three arguments:
10+
11+
1. The pattern used to match lines in a file.
12+
2. Zero or more flags to customize the matching behavior.
13+
3. One or more files in which to search for matching lines.
14+
15+
Your task is to implement the `grep` function, which should read the contents
16+
of the specified files, find the lines that match the specified pattern
17+
and then output those lines as a single string. Note that the lines should
18+
be output in the order in which they were found, with the first matching line
19+
in the first file being output first.
20+
21+
As an example, suppose there is a file named "input.txt" with the following contents:
22+
23+
```text
24+
hello
25+
world
26+
hello again
27+
```
28+
29+
If we were to call `grep "hello" input.txt`, the returned string should be:
30+
31+
```text
32+
hello
33+
hello again
34+
```
35+
36+
### Flags
37+
38+
As said earlier, the `grep` command should also support the following flags:
39+
40+
- `-n` Print the line numbers of each matching line.
41+
- `-l` Print only the names of files that contain at least one matching line.
42+
- `-i` Match line using a case-insensitive comparison.
43+
- `-v` Invert the program -- collect all lines that fail to match the pattern.
44+
- `-x` Only match entire lines, instead of lines that contain a match.
45+
46+
If we run `grep -n "hello" input.txt`, the `-n` flag will require the matching
47+
lines to be prefixed with its line number:
48+
49+
```text
50+
1:hello
51+
3:hello again
52+
```
53+
54+
And if we run `grep -i "HELLO" input.txt`, we'll do a case-insensitive match,
55+
and the output will be:
56+
57+
```text
58+
hello
59+
hello again
60+
```
61+
62+
The `grep` command should support multiple flags at once.
63+
64+
For example, running `grep -l -v "hello" file1.txt file2.txt` should
65+
print the names of files that do not contain the string "hello".
66+
67+
# Java Tips
68+
69+
Since this exercise has difficulty 5 it doesn't come with any starter implementation.
70+
This is so that you get to practice creating classes and methods which is an important part of programming in Java.
71+
It does mean that when you first try to run the tests, they won't compile.
72+
They will give you an error similar to:
73+
```
74+
path-to-exercism-dir\exercism\java\name-of-exercise\src\test\java\ExerciseClassNameTest.java:14: error: cannot find symbol
75+
ExerciseClassName exerciseClassName = new ExerciseClassName();
76+
^
77+
symbol: class ExerciseClassName
78+
location: class ExerciseClassNameTest
79+
```
80+
This error occurs because the test refers to a class that hasn't been created yet (`ExerciseClassName`).
81+
To resolve the error you need to add a file matching the class name in the error to the `src/main/java` directory.
82+
For example, for the error above you would add a file called `ExerciseClassName.java`.
83+
84+
When you try to run the tests again you will get slightly different errors.
85+
You might get an error similar to:
86+
```
87+
constructor ExerciseClassName in class ExerciseClassName cannot be applied to given types;
88+
ExerciseClassName exerciseClassName = new ExerciseClassName("some argument");
89+
^
90+
required: no arguments
91+
found: String
92+
reason: actual and formal argument lists differ in length
93+
```
94+
This error means that you need to add a [constructor](https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html) to your new class.
95+
If you don't add a constructor, Java will add a default one for you.
96+
This default constructor takes no arguments.
97+
So if the tests expect your class to have a constructor which takes arguments, then you need to create this constructor yourself.
98+
In the example above you could add:
99+
```
100+
ExerciseClassName(String input) {
101+
102+
}
103+
```
104+
That should make the error go away, though you might need to add some more code to your constructor to make the test pass!
105+
106+
You might also get an error similar to:
107+
```
108+
error: cannot find symbol
109+
assertEquals(expectedOutput, exerciseClassName.someMethod());
110+
^
111+
symbol: method someMethod()
112+
location: variable exerciseClassName of type ExerciseClassName
113+
```
114+
This error means that you need to add a method called `someMethod` to your new class.
115+
In the example above you would add:
116+
```
117+
String someMethod() {
118+
return "";
119+
}
120+
```
121+
Make sure the return type matches what the test is expecting.
122+
You can find out which return type it should have by looking at the type of object it's being compared to in the tests.
123+
Or you could set your method to return some random type (e.g. `void`), and run the tests again.
124+
The new error should tell you which type it's expecting.
125+
126+
After having resolved these errors you should be ready to start making the tests pass!
127+
128+
129+
# Running the tests
130+
131+
You can run all the tests for an exercise by entering
132+
133+
```sh
134+
$ gradle test
135+
```
136+
137+
in your terminal.
138+
139+
## Source
140+
141+
Conversation with Nate Foster. [http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf](http://www.cs.cornell.edu/Courses/cs3110/2014sp/hw/0/ps0.pdf)
142+
143+
## Submitting Incomplete Solutions
144+
145+
It's possible to submit an incomplete solution so you can see how others have completed the exercise.

‎exercises/grep/build.gradle‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
apply plugin: "java"
2+
apply plugin: "eclipse"
3+
apply plugin: "idea"
4+
5+
repositories {
6+
mavenCentral()
7+
}
8+
9+
dependencies {
10+
testCompile "junit:junit:4.12"
11+
}
12+
13+
test {
14+
testLogging {
15+
exceptionFormat = 'full'
16+
events = ["passed", "failed", "skipped"]
17+
}
18+
}

‎exercises/grep/src/main/java/.keep‎

Whitespace-only changes.

0 commit comments

Comments
 (0)