How to modify this program to print just three lines and intent to 2nd and 3rd start with space. My if-statement doesn't seem work
package com.TnationChallange;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
for (String part : getParts("screen space to display information", 7, 3)) {
System.out.println(part);
}
}
private static List<String> getParts(String string, int partitionSize, int maxLine) {
List<String> parts = new ArrayList<String>();
int len = string.length();
for (int i = 0; i < len; i += partitionSize) {
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
maxLine++;
if (maxLine == 3) {
break;
}
}
return parts;
}
}
The third parameter you pass to the getParts method is 3 and because you call maxLine++ before if (maxLine == 3) that condition will never be true.
You should use something like this:
....
maxLines--;
if(maxLines == 0){
....
}
.....
You need a different variable to count the lines.
package com.TnationChallange;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
for (String part : getParts("screen space to display information", 7, 3)) {
System.out.println(part);
}
}
private static List<String> getParts(String string, int partitionSize, int maxLine) {
List<String> parts = new ArrayList<String>();
int len = string.length();
int count = 0;
for (int i = 0; i < len; i += partitionSize) {
parts.add(string.substring(i, Math.min(len, i + partitionSize)));
count++;
if (maxLine == count) {
break;
}
}
return parts;
}
}
This is assuming you want to limit your result by maxLine.
Related
I have done a filter interface that filters out all the strings that have more than 3 letters without any particular pattern. How do i now define a abstract class Filter with a public method filter that calls the method acept that can be implemented in different ways? All of this using Template method pattern?
public class WordFilter extends Filter{
public boolean accept(String obj){
return(((String) obj).length() <= 3);
}
}
import java.util.Arrays;
public class RunHere {
public static void main(String[] args) {
String[] theArray = { "oig3", "jt3jjt3", "wee", "02ri", "Adam", "lel", "32", "k" };
System.out.println(Arrays.toString(theArray));
WordFilter filt = new WordFilter();
String[] resultat = filter(theArray, filt);
System.out.println(Arrays.toString(resultat));
}
public static String[] filter(String[] a, Filter f){
String x;
int count = 0;
int pos = 0;
for (int i = 0; i < a.length; i++) {
x = a[i];
if (x.length() < 4) {
count++;
}
}
System.out.println("Count is :" + count);
String[] filtered = new String[count];
for (int i = 0; i < a.length; i++) {
if (f.accept(a[i])) {
filtered[pos] = a[i];
pos++;
}
}
return filtered;
}
}
public abstract class Filter {
abstract boolean accept(String x);
}
The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses.
But in the problem that you have given, i see that there is only one step( finding Strings of size n). i.e there is no step before or after finding string of size n.
If Something was there(multiple tasks), i would have done it like below. Which would implement the Template pattern.
public abstract class Filter {
abstract boolean accept(String x);
void BeforeStep() {
// Do something
}
void AfterStep() {
// do something
}
}
public static String[] filter(String[] a, Filter f) {
String x;
int count = 0;
int pos = 0;
**f.BeforeStep();**
for (int i = 0; i < a.length; i++) {
x = a[i];
if (x.length() < 4) {
count++;
}
}
System.out.println("Count is :" + count);
String[] filtered = new String[count];
for (int i = 0; i < a.length; i++) {
if (f.accept(a[i])) {
filtered[pos] = a[i];
pos++;
}
}
f.AfterStep();
return filtered;
}
I have an array called myArray that contains words separated by a space and trimmed from a PDF from the first page to the last page. I wrote a simple print array method that iterates through and prints each element one by one and it looks great!
Immediately after I have it go through another for loop for the length of the array and checks if (myArray[i].equals("(19)")) {//print something} When printing the array to the console it is clear that the value (19) exists in the array.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessRead;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray;
static String[] events = {"400", "800", "1500",
"3000", "5000", "10000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
printArray(myArray);
//System.out.println();
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
if (!currentEvent.equals("")) {
if (myArray[i].charAt(0) == '(' && (myArray[i].charAt(myArray[i].length() - 1) == ')')) {
String formatedRunners = "";
//It is possible to see some numbers such as (19)) or (19)
if (containsCharacter(myArray[i], ')') == 2) {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 2);
} else {
formatedRunners = myArray[i].substring(1, myArray[i].length() - 1);
}
int numberOfRunners = Integer.parseInt(formatedRunners);
int distance = Integer.parseInt(currentEvent);
sum += numberOfRunners * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static void readFile() {
Scanner c = new Scanner(System.in);
System.out.println("Enter a file path: ");
String filePath = c.nextLine();
file = new File(filePath);
}
public static void parsePDF(File file) throws IOException {
textStripper = new PDFTextStripper();
pdDoc = PDDocument.load(file);
//Parse PDF
textStripper.setStartPage(1);
//textStripper.setEndPage();
//Parsed String
parsedText = textStripper.getText(pdDoc);
}
public static boolean contains(String s) {
for (int i = 0; i < events.length; i++) {
if (s.equals(events[i])) {
return true;
}
}
return false;
}
public static void printArray(String[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
if (myArray[i].equals("")) {
//Use some filler to avoid crashes when checking characters
myArray[i] = "NULL";
}
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
public static int containsCharacter(String str, char c) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == c) {
count++;
}
}
return count;
}
}
Here is what I want:
Parsing and trimming etc. (OK)
Iterating over myArray (in the main method) and detecting events (OK)
If an event occurred then the next value must be (Any number) like (19)
(NOK)
The number from step 3. will be used to compute another number
Reset the current event to repeat the process over and
over again.
It seems like that it is reading each event correctly but only picks up (19)) instead of (19).
There are several problems in you code (No Exceptionhandling, everything static, small bugs etc.) but I will focus on the major issue. (I removed the code which I did not change)
public class Main {
static File file;
static PDFTextStripper textStripper;
static PDDocument pdDoc;
static COSDocument cosDoc;
static String parsedText;
static int sum = 0;
static String[] myArray = {"Seeded", "3000", "random", 25, "(44)", "1500", "random", "(13)"};
static String[] events = {"400", "800", "1500", "3000", "5000", "10000", "200.000"};
public static void main(String[] args) {
//Read the PDF file into instance variable file
readFile();
try {
parsePDF(file);
} catch (IOException e) {
e.printStackTrace();
}
myArray = parsedText.split(" ");
removeWhiteSpace(myArray);
String currentEvent = "";
for (int i = 0; i < myArray.length; i++) {
if (contains(myArray[i])) {
currentEvent = myArray[i];
}
else if (!currentEvent.isEmpty()) {
Integer value = extractNumber(myArray[i]);
if (!myArray[i].isEmpty() && value!=null) {
int distance = Integer.parseInt(currentEvent);
sum += value.intValue() * distance;
//reset currentEvent
currentEvent = "";
}
}
}
//Print total distance in meters
System.out.println(sum + " meters");
//Convert meters to miles using the following equation: meters / 1609.344
System.out.println( Math.round((sum / 1609.344)) + " miles");
}
public static Integer extractNumber(String toCheck) {
Pattern r = Pattern.compile("^.*?\\([^\\d]*(\\d+)[^\\d]*\\).*$");
Matcher m = r.matcher(toCheck);
if(m.find()) {
return Integer.valueOf(m.group(1));
}
return null;
}
public static void removeWhiteSpace(String[] a) {
for (int i = 0; i < myArray.length; i++) {
//Trim off all extra whitespace
myArray[i] = myArray[i].trim();
}
}
The result is
151500 meters
94 miles
Simply not printing the same output as the line above and I can't figure out why this is happening, I've noticed that it's printing the last N numbers from the end backwards, whatever i input into the parameter it prints that amount a second time.
Here's the main
public class main {
public static void main(String args[]) {
ScalesSolution s1 = new ScalesSolution(11);
s1.println();
ScalesSolution s2 = new ScalesSolution(s1.GetSol());
s2.println();
}
}
Heres the ScalesSolution Class
import java.util.ArrayList;
import java.util.Random;
public class ScalesSolution {
private String scasol;
public void print() {
System.out.print(scasol);
}
// Display the string with a new line
public void println() {
print();
System.out.println();
}
public String GetSol()
{
return scasol;
}
}
Heres the randomOther Class
import java.util.*;
import java.io.*;
public class randomOther {
// Shared random object
static private Random rand;
// Create a uniformly distributed random integer between aa and bb inclusive
static public int UI(int aa, int bb) {
int a = Math.min(aa, bb);
int b = Math.max(aa, bb);
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
int d = b - a + 1;
int x = rand.nextInt(d) + a;
return (x);
}
// Create a uniformly distributed random double between a and b inclusive
static public double UR(double a, double b) {
if (rand == null) {
rand = new Random();
rand.setSeed(System.nanoTime());
}
return ((b - a) * rand.nextDouble() + a);
}
static public ArrayList<Double> ReadNumberFile(String filename) {
ArrayList<Double> res = new ArrayList<Double>();
Reader r;
try {
r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.parseNumbers();
stok.nextToken();
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_NUMBER) {
res.add(stok.nval);
}
stok.nextToken();
}
} catch (Exception E) {
System.out.println("+++ReadFile: " + E.getMessage());
}
return (res);
}
}
Here is the issue the Output:
00101001010101101011001011010101101001011010001011010010101101001001011010010
01011010010
I believe that both outputs should be the same and I see that there is a problem here, not sure why they aren't
I see that the way your are using System.out.print inside your RandomBinaryString(int n) is causing confusion. It is printing and appending to the String s. Try to avoid that. Replacing the System.out.print(s += '0'); and System.out.print(s += '1'); with s += '0'; and s += '1';in the RandomBinaryString will fix your output.
Use the snippet below in your code:
private static String RandomBinaryString(int n) {
String s = new String();
// Code goes here
// Create a random binary string of just ones and zeros of length n
for (int i = 0; i < n; i++) {
int y = randomOther.UI(0, 1);
if (y == 0) {
s += '0';// this line here was changed
} else {
s += '1';// and this line here was changed too
}
}
return (s);
}
Hope this helps!
I use the following components in my code:
A byte array, each bit representing whether the correspondent number is prime(0) or not(1)
A recursion of Filtering.filter()
I want to ascertain whether these parts make it more efficient or actually slow it down. Any other advices also appreciated.
Code:
import java.lang.Math;
import java.util.*;
class Container{
public final byte[] binary_array;
private final int bit_length;
public Container(int nominal_bit_length){
int byte_length = (int)Math.ceil(nominal_bit_length / 8.0);
this.binary_array = new byte[byte_length];
this.bit_length = 8 * byte_length;
}
private String toBinaryString(int index){//convert into a binary string the byte value on which the bit number refered by the index exists
int byte_index = index / 8;
//System.out.println(index);
String str = Integer.toBinaryString(this.binary_array[byte_index]);
String formatted = ("00000000" + str).substring(str.length());
return formatted;
}
public char get(int index){
String str = this.toBinaryString(index);
return str.charAt(index % 8);//
}
public char set(int index, char value){
StringBuilder str = new StringBuilder(this.toBinaryString(index));
char temp = str.charAt(index % 8);//
str.setCharAt(index % 8, value);//
int byte_index = index / 8;
this.binary_array[byte_index] = (byte)Integer.parseUnsignedInt(str.toString(), 2);
return temp;
}
public int length(){
return this.bit_length;
}
public static Container preset(){
Container c = new Container(8);
c.set(1-1, '1');
c.set(4-1, '1');
c.set(6-1, '1');
c.set(8-1, '1');
return c;
}
}
class Screener{
private static void filterMultiplesOf(int num, Container container){
if (num == 1){
return;
}
int i = 2;
while ((i * num - 1) < container.length()){
container.set(i * num - 1, '1');
i++;
}
}
public static void filter(Container c){
int num = c.length();
if (num <= 8){
c = Container.preset();
} else{
Container base = new Container((int)Math.floor(Math.sqrt(num)));
filter(base);
for (int i = 0; i < base.length(); i++){
if (base.get(i) == '0'){
filterMultiplesOf(i+1, c);
}
}
}
}
}
public class Prime2{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
Container c = new Container(num);
Screener.filter(c);
for (int i = 1; i < c.length(); i++){
if (c.get(i) == '0'){
System.out.print((i + 1) + " ");
}
}
}
}
Edit at 12-03-2014:
What about this segment code?
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class PrimeGenerator {
public static Set<Integer> prime(int num){
if (num <= 2){
Set<Integer> foo = new HashSet<>();
foo.add(2);
return foo;
}
IntStream stream = IntStream.rangeClosed(1, num);
Set<Integer> base = prime((int)Math.ceil(Math.sqrt(num)));
IntStream multiples = base.stream().flatMapToInt((factor) -> (IntStream.rangeClosed(2, (int)Math.floorDiv(num, factor)).map(n -> n * factor)));
Set<Integer> primeset = stream.collect(HashSet::new, HashSet::add, HashSet::addAll);
Set<Integer> nonprimeset = multiples.collect(HashSet::new, HashSet::add, HashSet::addAll);
primeset.removeAll(nonprimeset);
primeset.remove(1);
return primeset;
}
public static void main(String[] args) {
// TODO code application logic here
prime(100000).stream().map(num -> num + " ").forEach(System.out::print);
}
}
as well as this:
import java.lang.Math;
import java.util.*;
/**
* Variation of BitSet which does NOT interpret the highest bit synonymous with
* its length.
*
* #author casper.bang#gmail.com
*/
class FixedBitSet extends BitSet{
int fixedLength;
public FixedBitSet(int fixedLength){
super(fixedLength);
this.fixedLength = fixedLength;
}
#Override
public int length() {
return fixedLength;
}
}
class Screener{
private static FixedBitSet preset;
static{
preset = new FixedBitSet(4);
preset.set(1-1, true);
preset.set(4-1, true);
}
private static void filterMultiplesOf(int num, FixedBitSet bitset){
//System.out.println("--------");
if (num == 1){
return;
}
int i = 2;
while ((i * num - 1) < bitset.length()){
bitset.set(i * num - 1, true);
i++;
}
}
public static void filter(FixedBitSet bitset){
//System.out.println("--------");
int num = bitset.length();
if (num <= 4){
//System.out.println("--------");
bitset = preset;
} else{
FixedBitSet base = new FixedBitSet((int)Math.floor(Math.sqrt(num)));
filter(base);
for (int i = 0; i < base.length(); i++){
if(!base.get(i)){
filterMultiplesOf(i + 1, bitset);
}
}
}
}
}
public class Prime3{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
int num = reader.nextInt();
FixedBitSet bs = new FixedBitSet(num);
// System.out.println(bs.length());
Screener.filter(bs);
for (int i = 1; i < bs.length(); i++){
if(!bs.get(i)){
System.out.print((i + 1) + " ");
}
}
}
}
Your "efficient" usage of a byte array is immaterial to the bad performance of your code, which uses string building to implement getting and setting.
Instead write code which uses low-level bit-manipulation operators (such as ~, &, and |) to implement get and set.
If you're not up to that, then consider using BitSet, a JDK-provided class which serves the same purpose.
If you want to learn how it's done, then simply open BitSet's source code.
I started to learn java yesterday and I wrote the followind program which should print pairs of equal numbers, but when I run it I get
Exception in thread "main" java.lang.NullPointerException
at _aaaa.main(_aaaa.java:26)
Here is my program:
import java.util.*;
class pair {
int first, second;
pair() {
first = second = 0;
}
public void make_pair(int a, int b)
{
first = a;
second = b;
}
}
public class aaaa {
public static void main(String[] idontneedthis)
{
Scanner input = new Scanner(System.in);
int N = input.nextInt(), i, lg = 0;
int[] A = new int[5010];
pair[] B = new pair[5010];
for (N <<= 1, i = 1; i <= N; ++i)
{
int var = input.nextInt();
if (A[var] > 0)
{
B[++lg].make_pair(A[var], var);
A[var] = 0;
}
else
{
A[var] = i;
}
}
if (lg == 0) System.out.print("-1");
for (i = 1; i <= lg; ++i)
{
System.out.print(B[i].first + " " + B[i].second + "\n");
}
}
}
Please tell me what is wrong or why do I get this error. I mention that if I cut the line 26 ( B[++lg].make_pair(A[var], var); ) it will write -1.
Thank you!
You need to initialise the pairs in your array:
if (A[var] > 0) {
B[++lg] = new pair(); //here
B[lg].make_pair(A[var], var);
A[var] = 0;
}
This line:
pair[] B = new pair[5010];
creates an array of 5010 pairs but until you initialise them, they are all null.
Also note that since 5010 and N are not related, you could get an ArrayIndexOutOfBoundException depending on N.
This is how I would write it. The less said the better ;)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Pair {
final int first, second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
#Override
public String toString() {
return first + " " + second;
}
}
public class Main {
public static void main(String... ignored) {
Scanner input = new Scanner(System.in);
int numOfPairs = input.nextInt();
List<Pair> pairs = new ArrayList<Pair>();
for(int i = 0; i < numOfPairs;i++) {
int first = input.nextInt();
int second = input.nextInt();
pairs.add(new Pair(first, second));
}
for (Pair pair : pairs)
System.out.println(pair);
}
}
pair[] B = new pair[5010];
Only allocates the space for 5010 B elements. You need to instantiate each element in that array.
for(int i = 0; i <B.length;i++)
{
B[i] = new pair();
}
Style things:
Class names start with upper case letters: AAAA not aaaa.
also star imports are bad:
import java.util.*;
replace with:
import java.util.Scanner;