restructured + input for 2
This commit is contained in:
56
src/Problem2.java
Normal file
56
src/Problem2.java
Normal file
@@ -0,0 +1,56 @@
|
||||
package src;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Problem2 {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String filePath = "inputs/inputProblem2.txt";
|
||||
|
||||
try {
|
||||
String input = readFileAsString(filePath);
|
||||
List<Long> numbers = parseRanges(input);
|
||||
|
||||
for (Long num : numbers) {
|
||||
System.out.println(num);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static String readFileAsString(String filePath) throws IOException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
sb.append(line.trim()); // remove extra spaces/newlines
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static List<Long> parseRanges(String input) {
|
||||
List<Long> result = new ArrayList<>();
|
||||
String[] ranges = input.split(",");
|
||||
|
||||
for (String range : ranges) {
|
||||
String[] parts = range.split("-");
|
||||
if (parts.length != 2) {
|
||||
throw new IllegalArgumentException("Invalid range: " + range);
|
||||
}
|
||||
long start = Long.parseLong(parts[0]);
|
||||
long end = Long.parseLong(parts[1]);
|
||||
result.add(start);
|
||||
result.add(end);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user