This question already has answers here:
How to convert a char array back to a string?
(14 answers)
Closed 9 years ago.
i am doing a porter stemmer.....the code gives me output in char array....but i need to convert that into string to proceed with futher work.....in the code i have given 2 words "looking" and "walks"....that is returned as look and walk(but in char array)...the output is printed in stem() function
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package file;
import java.util.Vector;
/**
*
* #author sky
*/
public class stemmer {
public static String line1;
private char[] b;
private int i, /* offset into b */
i_end, /* offset to end of stemmed word */
j, k;
private static final int INC = 50;
/* unit of size whereby b is increased */
public stemmer()
{
//b = new char[INC];
i = 0;
i_end = 0;
}
/**
* Add a character to the word being stemmed. When you are finished
* adding characters, you can call stem(void) to stem the word.
*/
public void add(char ch)
{
System.out.println("in add() function");
if (i == b.length)
{
char[] new_b = new char[i+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
b[i++] = ch;
}
/** Adds wLen characters to the word being stemmed contained in a portion
* of a char[] array. This is like repeated calls of add(char ch), but
* faster.
*/
public void add(char[] w, int wLen)
{ if (i+wLen >= b.length)
{
char[] new_b = new char[i+wLen+INC];
for (int c = 0; c < i; c++)
new_b[c] = b[c];
b = new_b;
}
for (int c = 0; c < wLen; c++)
b[i++] = w[c];
}
public void addstring(String s1)
{
b=new char[s1.length()];
for(int k=0;k<s1.length();k++)
{
b[k] = s1.charAt(k);
System.out.println(b[k]);
}
i=s1.length();
}
/**
* After a word has been stemmed, it can be retrieved by toString(),
* or a reference to the internal buffer can be retrieved by getResultBuffer
* and getResultLength (which is generally more efficient.)
*/
public String toString() { return new String(b,0,i_end); }
/**
* Returns the length of the word resulting from the stemming process.
*/
public int getResultLength() { return i_end; }
/**
* Returns a reference to a character buffer containing the results of
* the stemming process. You also need to consult getResultLength()
* to determine the length of the result.
*/
public char[] getResultBuffer() { return b; }
/* cons(i) is true <=> b[i] is a consonant. */
private final boolean cons(int i)
{ switch (b[i])
{ case 'a': case 'e': case 'i': case 'o': case 'u': return false;
case 'y': return (i==0) ? true : !cons(i-1);
default: return true;
}
}
/* m() measures the number of consonant sequences between 0 and j. if c is
a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
presence,
<c><v> gives 0
<c>vc<v> gives 1
<c>vcvc<v> gives 2
<c>vcvcvc<v> gives 3
....
*/
private final int m()
{ int n = 0;
int i = 0;
while(true)
{ if (i > j) return n;
if (! cons(i)) break; i++;
}
i++;
while(true)
{ while(true)
{ if (i > j) return n;
if (cons(i)) break;
i++;
}
i++;
n++;
while(true)
{ if (i > j) return n;
if (! cons(i)) break;
i++;
}
i++;
}
}
/* vowelinstem() is true <=> 0,...j contains a vowel */
private final boolean vowelinstem()
{ int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
return false;
}
/* doublec(j) is true <=> j,(j-1) contain a double consonant. */
private final boolean doublec(int j)
{ if (j < 1) return false;
if (b[j] != b[j-1]) return false;
return cons(j);
}
/* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
and also if the second c is not w,x or y. this is used when trying to
restore an e at the end of a short word. e.g.
cav(e), lov(e), hop(e), crim(e), but
snow, box, tray.
*/
private final boolean cvc(int i)
{ if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
{ int ch = b[i];
if (ch == 'w' || ch == 'x' || ch == 'y') return false;
}
return true;
}
private final boolean ends(String s)
{
int l = s.length();
int o = k-l+1;
if (o < 0)
return false;
for (int i = 0; i < l; i++)
if (b[o+i] != s.charAt(i))
return false;
j = k-l;
return true;
}
/* setto(s) sets (j+1),...k to the characters in the string s, readjusting
k. */
private final void setto(String s)
{ int l = s.length();
int o = j+1;
for (int i = 0; i < l; i++)
b[o+i] = s.charAt(i);
k = j+l;
}
/* r(s) is used further down. */
private final void r(String s) { if (m() > 0) setto(s); }
/* step1() gets rid of plurals and -ed or -ing. e.g.
caresses -> caress
ponies -> poni
ties -> ti
caress -> caress
cats -> cat
feed -> feed
agreed -> agree
disabled -> disable
matting -> mat
mating -> mate
meeting -> meet
milling -> mill
messing -> mess
meetings -> meet
*/
private final void step1()
{
if (b[k] == 's')
{ if (ends("sses")) k -= 2; else
if (ends("ies")) setto("i"); else
if (b[k-1] != 's') k--;
}
if (ends("eed")) { if (m() > 0) k--; } else
if ((ends("ed") || ends("ing")) && vowelinstem())
{ k = j;
if (ends("at")) setto("ate"); else
if (ends("bl")) setto("ble"); else
if (ends("iz")) setto("ize"); else
if (doublec(k))
{ k--;
{ int ch = b[k];
if (ch == 'l' || ch == 's' || ch == 'z') k++;
}
}
else if (m() == 1 && cvc(k)) setto("e");
}
}
/* step2() turns terminal y to i when there is another vowel in the stem. */
private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; }
/* step3() maps double suffices to single ones. so -ization ( = -ize plus
-ation) maps to -ize etc. note that the string before the suffix must give
m() > 0. */
private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1])
{
case 'a': if (ends("ational")) { r("ate"); break; }
if (ends("tional")) { r("tion"); break; }
break;
case 'c': if (ends("enci")) { r("ence"); break; }
if (ends("anci")) { r("ance"); break; }
break;
case 'e': if (ends("izer")) { r("ize"); break; }
break;
case 'l': if (ends("bli")) { r("ble"); break; }
if (ends("alli")) { r("al"); break; }
if (ends("entli")) { r("ent"); break; }
if (ends("eli")) { r("e"); break; }
if (ends("ousli")) { r("ous"); break; }
break;
case 'o': if (ends("ization")) { r("ize"); break; }
if (ends("ation")) { r("ate"); break; }
if (ends("ator")) { r("ate"); break; }
break;
case 's': if (ends("alism")) { r("al"); break; }
if (ends("iveness")) { r("ive"); break; }
if (ends("fulness")) { r("ful"); break; }
if (ends("ousness")) { r("ous"); break; }
break;
case 't': if (ends("aliti")) { r("al"); break; }
if (ends("iviti")) { r("ive"); break; }
if (ends("biliti")) { r("ble"); break; }
break;
case 'g': if (ends("logi")) { r("log"); break; }
} }
/* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
private final void step4() { switch (b[k])
{
case 'e': if (ends("icate")) { r("ic"); break; }
if (ends("ative")) { r(""); break; }
if (ends("alize")) { r("al"); break; }
break;
case 'i': if (ends("iciti")) { r("ic"); break; }
break;
case 'l': if (ends("ical")) { r("ic"); break; }
if (ends("ful")) { r(""); break; }
break;
case 's': if (ends("ness")) { r(""); break; }
break;
} }
/* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
private final void step5()
{ if (k == 0) return; /* for Bug 1 */ switch (b[k-1])
{ case 'a': if (ends("al")) break; return;
case 'c': if (ends("ance")) break;
if (ends("ence")) break; return;
case 'e': if (ends("er")) break; return;
case 'i': if (ends("ic")) break; return;
case 'l': if (ends("able")) break;
if (ends("ible")) break; return;
case 'n': if (ends("ant")) break;
if (ends("ement")) break;
if (ends("ment")) break;
/* element etc. not stripped before the m */
if (ends("ent")) break; return;
case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
/* j >= 0 fixes Bug 2 */
if (ends("ou")) break; return;
/* takes care of -ous */
case 's': if (ends("ism")) break; return;
case 't': if (ends("ate")) break;
if (ends("iti")) break; return;
case 'u': if (ends("ous")) break; return;
case 'v': if (ends("ive")) break; return;
case 'z': if (ends("ize")) break; return;
default: return;
}
if (m() > 1) k = j;
}
/* step6() removes a final -e if m() > 1. */
private final void step6()
{ j = k;
if (b[k] == 'e')
{ int a = m();
if (a > 1 || a == 1 && !cvc(k-1)) k--;
}
if (b[k] == 'l' && doublec(k) && m() > 1) k--;
}
/** Stem the word placed into the Stemmer buffer through calls to add().
* Returns true if the stemming process resulted in a word different
* from the input. You can retrieve the result with
* getResultLength()/getResultBuffer() or toString().
*/
public void stem()
{
// step1();
// System.out.println("hello in stem");
// step2();
// step3();
// step4();
// step5();
// step6();
//
// i_end = k+1;
// i = 0;
System.out.println(i);
k = i - 1;
if (k > 1)
{
step1();
step2();
step3();
step4();
step5();
step6();
}
for(int c=0;c<=k;c++)
System.out.println(b[c]);
i_end = k+1; i = 0;
}
public static void main(String[] args)
{
stemmer s = new stemmer();
s.addstring("looking");
s.stem();
s.addstring("walks");
s.stem();
//System.out.println("Output " +s.b);
}
}
- Use Character class method toString();
Eg:
class Test
{
public static void main (String[] args) throws java.lang.Exception
{
char c = 'a';
String s = Character.toString(c);
System.out.println(s);
}
}
- Now use this above explained method to convert all the character array items into String.
char[] data = new char[10];
String text = String.valueOf(data);
to convert a char[] to string use this way
String x=new String(char[])
example
char x[]={'a','m'};
String z=new String(x);
System.out.println(z);
output
am
char[] a = new char[10];
for(int i=0;i<10;i++)
{
a[i] = 's';
}
System.out.println(new String(a));
or
System.out.println(String.copyValueOf(a));
Related
I have two classes that do two different things. I am trying to get my FileAccess class to use my encryption class to to encode a set number of phrases in a text file. The first 10 numbers in the file give the program the key value and that should be stored as a int and what comes after the file should be stored as a array of char and those need to be called by the encryption class to code the phrase. I do not know why I can't call my encryption class and I am stumped.
Sorry for being unclear I am trying to design an code that will accept a number of phrases as input and allow the user to encrypt it through the use of an encryption key. This key should be made up of an integer number between-2000000 and +2000000.The encryption algorithm uses the key to shift the letters of the alphabet to the right or left.For example A encoded with a key of 3 would produce D three letters to its right in the alphabet. If the key is so large that the new letter goes past the end of the alphabet, the program should wrap around to a letter near the beginning of the alphabet.
The FileAccess class – This class should read several phrases from a file. The first line of the file should contain an integer indicating the number of phrases in the file. The first 10 characters of each phrase in the file should contain the encryption key to be used in the encryption and decryption process for that phrase. This class should provide a way to access this information by other classes. Finally, this class should have a second method to allow phrases to be saved into a new file. I tried to be as clear as i can now. My problem is I cant call my encode method in my encryption class
Here is the code for the File Access.
public class FileAccess {
public static String[] load(String fileName) throws IOException {
FileReader file = new FileReader(fileName); //open file for reading
BufferedReader input = new BufferedReader(file);
int sizeF = Integer.parseInt(input.readLine()); // variable for the size of the array
String infoInFile[] = new String[sizeF]; // declare and create a string array
for (int i = 0; i < sizeF; i++) { // loop to read the file into the array
infoInFile[i] = input.readLine();
}
input.close();//close the file
return infoInFile;
}
public static int[] key(String finalKey[]) {
int finaloutput[] = new int[5];
String temp;
for (int i = 0; i < finalKey.length; i++) {
temp = finalKey[i].substring(0, 11);
finaloutput[i] = Integer.parseInt(temp);
System.out.println(finaloutput[i]);
}
return finaloutput;
}
public static char[] phrase(String EndOfPhrase[]) {
char letter[] = new char[5];
for (int j = 0; j < EndOfPhrase.length; j++) {
String phrase;
phrase = EndOfPhrase[j].substring(11);
char temp = phrase.charAt(1);
letter = phrase.toCharArray();
System.out.println(letter);
}
return letter;
}
public static void main(String[] args) throws IOException {
String output[]; // call the loader
int[] keyTest;
char[] phraseTest;
String display;
output = FileAccess.load("phrase.txt");
keyTest = key(output);
phraseTest = phrase(output);
for (int i = 0; i < output.length; i++) {
}
}
}
I am not sure if I should have that for loop, but scice the encryption encode method only takes in 1 char at a time and codes I think I need a for loop to keep calling it
HERE IS THE CODE FOR THE encryption code
public class Encryption {
public static boolean isNotALetter(char character) { // returns false if the character is a letter
boolean yorn = false;
return yorn;
}
public static char encode(char letter, int key) { // returns an encrypted character
char encryptedcharacter = 0;
int truevalueofkey = 0;
int valueofletter;
int newvalueofletter;
valueofletter = Encryption.lettertovalue(letter);
truevalueofkey = key % 26;
newvalueofletter = (valueofletter + truevalueofkey)%26;
encryptedcharacter = Encryption.valueToLetter(newvalueofletter);
// add truevalueofkey to key to get
return encryptedcharacter;
}
public static char decode(char letter, int key) { // returns a decrypted character
char decodedcharacter = 0;
int dtruevalueofkey = 0;
int dvalueofletter;
int dnewvalueofletter;
dvalueofletter = Encryption.lettertovalue(letter);
dtruevalueofkey = key % 26;
dnewvalueofletter = (dvalueofletter - dtruevalueofkey)%26;
decodedcharacter = Encryption.valueToLetter(dnewvalueofletter);
return decodedcharacter;
}
public static int lettertovalue(char letter) { // get value of each letter ex A = 1
int value = 0;
// convert to string based on char
switch (letter) {
case 'a': {
value = 1;
break;
}
case 'b': {
value = 2;
break;
}
case 'c': {
value = 3;
break;
}
case 'd': {
value = 4;
break;
}
case 'e': {
value = 5;
break;
}
case 'f': {
value = 6;
break;
}
case 'g': {
value = 7;
break;
}
case 'h': {
value = 8;
break;
}
case 'i': {
value = 9;
break;
}
case 'j': {
value = 10;
break;
}
case 'k': {
value = 11;
break;
}
case 'l': {
value = 12;
break;
}
case 'm': {
value = 13;
break;
}
case 'n': {
value = 14;
break;
}
case 'o': {
value = 15;
break;
}
case 'p': {
value = 16;
break;
}
case 'q': {
value = 17;
break;
}
case 'r': {
value = 18;
break;
}
case 's': {
value = 19;
break;
}
case 't': {
value = 20;
break;
}
case 'u': {
value = 21;
break;
}
case 'v': {
value = 22;
break;
}
case 'w': {
value = 23;
break;
}
case 'x': {
value = 24;
break;
}
case 'y': {
value = 25;
break;
}
case 'z': {
value = 26;
break;
}
}
return value;
}
public static char valueToLetter(int value) {
char letter = 0;
if (value == 1) {
letter = 'a';
}
if (value == 2) {
letter = 'b';
}
if (value == 3) {
letter = 'c';
}
if (value == 4) {
letter = 'd';
}
if (value == 5) {
letter = 'e';
}
if (value == 6) {
letter = 'f';
}
if (value == 7) {
letter = 'g';
}
if (value == 8) {
letter = 'h';
}
if (value == 9) {
letter = 'i';
}
if (value == 10) {
letter = 'j';
}
if (value == 11) {
letter = 'k';
}
if (value == 12) {
letter = 'l';
}
if (value == 13) {
letter = 'm';
}
if (value == 14) {
letter = 'n';
}
if (value == 15) {
letter = 'o';
}
if (value == 16) {
letter = 'p';
}
if (value == 17) {
letter = 'q';
}
if (value == 18) {
letter = 'r';
}
if (value == 19) {
letter = 's';
}
if (value == 20) {
letter = 't';
}
if (value == 21) {
letter = 'u';
}
if (value == 22) {
letter = 'v';
}
if (value == 23) {
letter = 'w';
}
if (value == 24) {
letter = 'x';
}
if (value == 25) {
letter = 'w';
}
if (value == 26) {
letter = 'z';
}
return letter;
}
public static void main(String[] args) {
String yrn = "y";
while (yrn == "y") {
String alsdjkf = JOptionPane.showInputDialog(null, "Enter the letter");
char enchar = alsdjkf.charAt(0);
int keyr = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter the key"));
char newchar = Encryption.decode(enchar, keyr);
JOptionPane.showMessageDialog(null, newchar);
yrn = JOptionPane.showInputDialog(null, "yes or no");
}
}
}
This is what is in the text file:
2
00000000003 The cook worked 12 hours in the darkened kitchen!
00000000025 Did Fred look well? That’s it!
Unfortunately it's quite hard to tell from your question what you are trying to do. I think you want each line to be interpreted as 10 digits and then a phrase to be encoded by the key represented by the digits. Assuming that's correct, I have several suggestions for changes to your code. I recommend you try these and then come back if they don't solve your problem.
FileAccess.load is unnecessary. You can use Files.lines to get all lines in a file in a single statement (use Stream.toArray if you really need it to be in an array).
The massive switch statements to just turn char to int are not needed. You can do math on char values such as letter - 'a' to simplify these.
Use a regular expression rather than decoding each line yourself. "(\\d{10}) (.*)" will read the key and phrase in a single statement.
Once you have the key and phrase you can call your "encryption" code for each line.
And just a warning: if you come back and say "I'm not allowed to use X or Y in my answer" then my comment will be "that would have been useful to know before I put time into trying to help you"!
EDIT: I may have fixed it by making the instance variable static? If so, why does this fix it? This was something my prof glossed over in my intro to OOP class, so I never really learned about it.
so, I'm not sure if I'm using terrible coding practice and just don't realize it, but I'm having a single crippling issue with my program, despite this one issue, everything appears to be running fine.
This program takes strings from an argument file and executes the commands based on the instructions. However, when I issue the command "x = x + 5" I experience a crippling issue.
My class titled Work creates another instance of my other class Read. When it does this, the ArrayList that I define at the top of Read is overwritten with a new instance, and thus, deletes the whole list of variables. I'm unable to find a way to make the initialization execute only once. Where am I going wrong?
Work:
import java.util.*;
public class Work {
static int Precedence(char ch){
switch (ch){
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
return -1;
}
String infixConverter(String infix){
Variable tvar = new Variable(); //consider removing these~
Read reader = new Read();
String pfix = new String("");
Stack<Character> stack = new Stack<>();
for (int i=0; i<infix.length(); ++i) {
char curr = infix.charAt(i);
// if (Character.isLetterOrDigit(curr)||curr==' ') {
if (Character.isDigit(curr)||curr==' ') {
pfix += curr;
}
else if (Character.isLetter(curr)){
// Read reader = new Read();
if (reader.varExists(curr)){
// Variable tvar = new Variable();
int n = reader.getIndex(curr);
tvar = reader.vars.get(n);
pfix += tvar.getValue();
}
else{
//error
}
//implement this below
//check for letter within the string, if the string is
}
else if (curr == '('){
stack.push(curr);
}
else if (curr == ')'){
while (!stack.isEmpty() && stack.peek() != '(') {
pfix += stack.pop();
}
if (!stack.isEmpty() && stack.peek() != '(') {
return "Invalid Expression"; // invalid expression
}
else {
stack.pop();
}
}
else {
while (!stack.isEmpty() && Precedence(curr) <=
Precedence(stack.peek())) {
pfix += stack.pop();
}
stack.push(curr);
}
}
while (!stack.isEmpty()) {
pfix += stack.pop();
}
int sol = postfixEvaluation(pfix);
pfix = Integer.toString(sol);
return pfix;
}
Integer postfixEvaluation(String pfix){
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < pfix.length(); i++){
char curr = pfix.charAt(i);
if(curr == ' '){
continue;
}
else if(Character.isDigit(curr)){
int num = 0;
while(Character.isDigit(curr)){
num = num*10 + (int)(curr-'0');
i++;
if (i==pfix.length()){break;}
curr = pfix.charAt(i);
}
i--;
stack.push(num);
//include variables and be able to insert them into here
}
else{
int val1 = stack.pop();
int val2 = stack.pop();
switch(curr){
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2-val1);
break;
case '/':
stack.push(val2/val1);
break;
case '%':
stack.push(val2%val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
}
Read:
import java.util.*;
public class Read {
ArrayList<Variable> vars = new ArrayList<Variable>();//FIX THIS SHIT AHHHHHHHHH
Variable tempvar = new Variable();
Work eval = new Work();
private int lnNum = 1;
private String arg="";
public void thing() {
String thing,thing2;
if (arg.contains("print")){
String real="";
int i = arg.indexOf('t');
if (i!=4){}//error
thing = arg.substring(0,i);
if (thing!="print"){}//error
thing2 = arg.substring(i+2,arg.length());
real = eval.infixConverter(thing2);
System.out.println(real);
}
else if (arg.contains("read")){
Scanner in = new Scanner(System.in);
int i = arg.indexOf('d');
if (i!=3){}//error
thing = arg.substring(0,i+1);
if (thing!="read"){}//error
thing2 = arg.substring(i+2,arg.length());
char c2 = thing2.charAt(0);
if (thing2.length()>1){}//error
System.out.println("Enter a value for "+thing2+": ");
String vv = in.nextLine();
vv = eval.infixConverter(vv);
int vvv = Integer.parseInt(vv);
tempvar.setValue(c2, vvv);
vars.add(tempvar);
}
else if (arg.contains("=")){
int i = arg.indexOf('=');
int tempval;
thing = arg.substring(0,i-1);
thing2 = arg.substring(i+2,arg.length());
if(thing.length()>1){}//error
thing2=eval.infixConverter(thing2);
char c = thing.charAt(0);
if (vars.contains(thing)){
tempval = Integer.parseInt(thing2);
tempvar.setValue(c,tempval);
int f = vars.indexOf(thing);
}
else if(Character.isLetter(c)){
tempval = Integer.parseInt(thing2);
tempvar.setValue(c,tempval);
vars.add(tempvar);
}
else{
//error
}
}
else{
}
}
boolean varExists(char c){
for (int i = 0; i<vars.size(); i++){
tempvar = vars.get(i);
if (tempvar.getTitle()==c){
return true;
}
}
return false;
}
int getIndex(char c) {
for (int i = 0; i <= vars.size(); i++) {
tempvar = vars.get(i);
if (tempvar.getTitle() == c) {
return i;
}
}
return -1;
}
int inLineNum(){
lnNum++;
return lnNum;
}
void setArg(String c){
arg=c;
}
}
Task is to allocate from bulk of numbers (200k total) Elite and Premium ones. Elite means number is very beautiful and expensive, Premium means more-less beautiful.
My solution works, but it is very slow. To process 200k numbers takes about 40 minutes! Problem is that I have to generate thousands of Regex patterns using masks and then process thousands of numbers through thousands of patterns!
Patterns looks like patternX, patternXY, patternAB, patternABC, patternXAB, patternXABC, patternXYZ, patternXYAB, patternXYAB, for example:
super.patternXYZ = "^\\d+XXYYZZ$|^\\d+ZZXYXY$|^\\d+YXXYYZZ..$";
super.patternXYAB = "^\\d+ABXXYY$|^\\d+ABXYXY$";
Where all the letters are represent mask of numbers: XXYY mathces 4488 or 9933 (X<>=Y) and AABB matches serial sequences like 3344 or 7788 (A+1=B)
Matching occurs by following:
#Override
public Set<String> performCollect() {
for (String number : numbers) {
if (isPatternXMatches(number)) {
result.add(number);
} else if (isPatternXYMatches(number)) {
result.add(number);
}
...
}
return result;
}
Where Regex patterns are being generated for every single match and match performs:
protected boolean isPatternXYZMatches(String number) {
for (int X = 0; X < 10; X++) {
for (int Y = 0; Y < 10; Y++) {
for (int Z = 0; Z < 10; Z++) {
Pattern pattern = Pattern.compile(patternXYZ.replace("X", String.valueOf(X)).replace("Y", String.valueOf(Y)).replace("Z", String.valueOf(Z)));
Matcher matcher = pattern.matcher(number);
if (matcher.find()) {
return true;
}
}
}
}
return false;
}
protected boolean isPatternXYABMatches(String number) {
for (int X = 0; X < 10; X++) {
for (int Y = 0; Y < 10; Y++) {
for (int A = 0, B = 1; B < 10; A++, B++) {
Pattern pattern = Pattern.compile(patternXYAB.replace("A", String.valueOf(A)).replace("B", String.valueOf(B)).replace("X", String.valueOf(X)).replace("Y", String.valueOf(Y)));
Matcher matcher = pattern.matcher(number);
if (matcher.find()) {
return true;
}
}
}
}
return false;
}
Question: Does anyone know or could suggest some better and faster solution?
I replaced Regex with custom matcher and 200k numbers are now processed during 5 seconds instead of 40 minutes!
public Set<String> performCollect() {
for (String number : numbers) {
if (isNumberMatches(number)) {
result.add(number);
}
}
return result;
}
protected boolean isNumberMatches(String number) {
NumberMatcher nm = new NumberMatcher(number, offset);
for (NumberPattern pattern : patterns) {
if (nm.processMatch(pattern)) {
return true;
}
}
return false;
}
...
public class NumberPattern {
private char[] maskChars;
private Integer weight;
public NumberPattern(String mask, Integer weight) {
maskChars = mask.toCharArray();
this.weight = weight;
}
public char[] getMaskChars() {
return maskChars;
}
public void setMaskChars(char[] maskChars) {
this.maskChars = maskChars;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
}
...
public class NumberMatcher {
private char[] numberChars;
private int uniqueChars = 0;
public NumberMatcher(String number, int offset) {
numberChars = number.toCharArray();
List<Character> chars = new ArrayList<>();
for (Character ch : number.substring(offset).toCharArray()) {
if (!chars.contains(ch)) {
uniqueChars++;
chars.add(ch);
}
}
}
public boolean processMatch(NumberPattern pattern) {
if (pattern.getWeight() < uniqueChars) {
return false;
}
Character X = null;
Character Y = null;
Character Z = null;
Character A = null;
Character B = null;
Character C = null;
Character D = null;
final char[] patternChars = pattern.getMaskChars();
int patternIndex = patternChars.length;
int numberIndex = numberChars.length;
while (patternIndex > 0) {
patternIndex--;
numberIndex--;
char numberChar = numberChars[numberIndex];
char patternChar = patternChars[patternIndex];
switch (patternChar) {
case 'A':
if (A == null) {
A = numberChar;
B = (char) (A + 1);
C = (char) (B + 1);
D = (char) (C + 1);
} else if (!A.equals(numberChar)) {
return false;
}
break;
case 'B':
if (B == null) {
B = numberChar;
A = (char) (B - 1);
C = (char) (B + 1);
D = (char) (C + 1);
} else if (!B.equals(numberChar)) {
return false;
}
break;
case 'C':
if (C == null) {
C = numberChar;
B = (char) (C - 1);
A = (char) (B - 1);
D = (char) (C + 1);
} else if (!C.equals(numberChar)) {
return false;
}
break;
case 'D':
if (D == null) {
D = numberChar;
C = (char) (D - 1);
B = (char) (C - 1);
A = (char) (B - 1);
} else if (!D.equals(numberChar)) {
return false;
}
break;
case 'X':
if (X == null) {
X = numberChar;
} else if (!X.equals(numberChar)) {
return false;
}
break;
case 'Y':
if (Y == null) {
Y = numberChar;
} else if (!Y.equals(numberChar)) {
return false;
}
break;
case 'Z':
if (Z == null) {
Z = numberChar;
} else if (!Z.equals(numberChar)) {
return false;
}
break;
case '.':
break;
case '0':
if (numberChar != '0') {
return false;
}
break;
}
}
return true;
}
}
So I was assigned to create an method which takes in a string in infix notation as a parameter and returns a string in postfix notation.
My code seems to work for most examples I throw at it, but a few inputs cause wacky results.
public class Operations<T> {
public int value(char c){
switch(c){
case '(':
case ')':
return 3;
case '*':
case '/':
case '%':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
public String infixToPostfix(String infix){
//Operator stack
myStack<Character> ops = new myStack<Character>();
//Postfix string
String postfix = "";
//Current char being read
char c;
//Marks if paranthesis are being passed in
boolean flag = false;
//Iterate through each character to find operators
for(int i=0; i<infix.length(); i++){
c = infix.charAt(i);
//Add operand to postfix and operator to stack
if(value(c)==0){
postfix+=c;
} else if(ops.isEmpty() || (value(c)>value(ops.getTop()) && c!=')') || c=='(') {
ops.push(c);
} else if(value(c)<value(ops.getTop()) && c!=')') {
if(ops.getTop()=='(' || flag) {
ops.push(c);
flag = true;
} else {
postfix+=ops.pop();
while(!ops.isEmpty() && value(c)<value(ops.getTop())) {
postfix+=ops.pop();
}
ops.push(c);
}
} else if(c==')') {
while(ops.getTop()!='('){
postfix+=ops.pop();
}
ops.pop();
flag = false;
} else {
postfix+=ops.pop();
ops.push(c);
}
}
while(!ops.isEmpty()){
postfix+=ops.pop();
}
return postfix;
}
}
for example, the equation:
- A * B + (C/D*7) – ( (A%C-8) / (H+F-D))
outputs:
ABCD/7+AC8-%HF+D-/-
while the correct answer is:
ABCD/7+AC%8-HF+D-/
What is causing the problem? Thanks
#include <stdio.h>
#include <stdlib.h>
#define ST_PARAMETROV 4 //stevilo vhodnih parametrov
#define VEL_SPOMINA 10000 //velikost spomina +-10000
#define VEL_PROGRAMA 10000 //največja velikost programa
#define DOVOLJENIH_UKAZOV 10000 //največje dovoljeno število ukazov
int main() {
// \0 označuje konec programa
char program[VEL_PROGRAMA] = ",.>,<<,->--->+++.<.<.\0";
int programPointer = 0;
char parametri[ST_PARAMETROV] = {20,30,40,50};
int parametriPointer = 0;
unsigned char spomin[VEL_SPOMINA*2] = {0};
int spominPointer = VEL_SPOMINA;
int stOklepajev;
int stOpravljenihUkazov = 0;
while(program[programPointer] != 0 && DOVOLJENIH_UKAZOV > stOpravljenihUkazov){
switch(program[programPointer]){
case '>':
spominPointer ++;
break;
case '<':
spominPointer --;
break;
case '+':
spomin[spominPointer] ++;
break;
case '-':
spomin[spominPointer] --;
break;
case '.':
printf("%i\n",spomin[spominPointer]);
break;
case ',':
//če je zmanka parametrov zapiše 0
if(parametriPointer > ST_PARAMETROV-1)spomin[spominPointer] = 0;
else spomin[spominPointer] = parametri[parametriPointer++];
break;
case '[':
if(spomin[spominPointer] == 0){
stOklepajev = 1;
while(stOklepajev != 0){
programPointer ++;
if(program[programPointer] == ']'){
stOklepajev--;
}
if(program[programPointer] == '['){
stOklepajev++;
}
}
}
break;
case ']':
if(spomin[spominPointer] != 0){
stOklepajev = 1;
while(stOklepajev != 0){
programPointer--;
if(program[programPointer] == '['){
stOklepajev--;
}
if(program[programPointer] == ']'){
stOklepajev++;
}
}
}
break;
}
programPointer ++;
stOpravljenihUkazov++;
}
return 0;
}
Hi could anybody help me please, I am having some difficulties transforming this code from C language to Java language, could anybody who can do this without any problems and with an ease. I already tried it to transfrom it into Java, but I fail everytime with many errors.
I would really appreciate if someone could just tranform the code into Java and then I will correct the errors myself.
Code itself is a Brainfuck interpreter.
Thanks
Your #defines will probably have to be const char.
Your case switches will have to be converted to
if
else if
else if
...
else
After that it should be fairly simple.
The needful transformations are limited to class and object definitions/initialization and return:
public class Brainfuck
{
final static int
ST_PARAMETROV = 4, //stevilo vhodnih parametrov
VEL_SPOMINA = 10000, //velikost spomina +-10000
VEL_PROGRAMA = 10000, //najve?ja velikost programa
DOVOLJENIH_UKAZOV = 10000; //najve?je dovoljeno ?tevilo ukazov
public static void main(String[] argv)
{
// \0 ozna?uje konec programa
char program[] = new char[VEL_PROGRAMA];
char initialProgram[] = ",.>,<<,->--->+++.<.<.\0".toCharArray();
System.arraycopy(initialProgram, 0, program, 0, initialProgram.length);
int programPointer = 0;
char parametri[] = {20, 30, 40, 50};
int parametriPointer = 0;
char spomin[] = new char[VEL_SPOMINA*2];
int spominPointer = VEL_SPOMINA;
int stOklepajev;
int stOpravljenihUkazov = 0;
while (program[programPointer] != 0
&& DOVOLJENIH_UKAZOV > stOpravljenihUkazov)
{
switch (program[programPointer])
{
case '>':
spominPointer++;
break;
case '<':
spominPointer--;
break;
case '+':
spomin[spominPointer]++;
break;
case '-':
spomin[spominPointer]--;
break;
case '.':
System.out.println((int)spomin[spominPointer]);
break;
case ',':
//?e je zmanka parametrov zapi?e 0
if (parametriPointer > ST_PARAMETROV-1)
spomin[spominPointer] = 0;
else spomin[spominPointer] = parametri[parametriPointer++];
break;
case '[':
if (spomin[spominPointer] == 0)
{
stOklepajev = 1;
while (stOklepajev != 0)
{
programPointer++;
if(program[programPointer] == ']') stOklepajev--;
if(program[programPointer] == '[') stOklepajev++;
}
}
break;
case ']':
if(spomin[spominPointer] != 0)
{
stOklepajev = 1;
while(stOklepajev != 0)
{
programPointer--;
if(program[programPointer] == '[') stOklepajev--;
if(program[programPointer] == ']') stOklepajev++;
}
}
break;
}
programPointer++;
stOpravljenihUkazov++;
}
System.exit(0);
}
}