Commit 9aedb724 authored by Frédéric Bapst's avatar Frédéric Bapst
Browse files

add s04, s05, s07

parent f4563298
package s04;
@SuppressWarnings("serial")
public class ExprException extends Exception {
public ExprException() {
super();
}
public ExprException(String msg) {
super(msg);
}
}
package s04;
import java.util.HashMap;
public class ExprInterpreter {
private static ExprSymbolStream lexer;
// TODO - A COMPLETER (ex. 3)
public static int evaluate(String e) throws ExprException {
lexer = new ExprSymbolStream(e);
int res = parseExpr();
// test if nothing follows the expression...
if (lexer.crtSymbol().length() > 0)
throw new ExprException("bad suffix");
return res;
}
private static int parseExpr() throws ExprException {
int res = 0;
// TODO - A COMPLETER
return res;
}
private static int parseTerm() throws ExprException {
int res = 0;
// TODO - A COMPLETER
return res;
}
private static int parseFact() throws ExprException {
int res = 0;
// TODO - A COMPLETER
return res;
}
private static int applyFct(String fctName, int arg) throws ExprException {
return 0; // TODO - A COMPLETER
}
}
package s04;
import java.util.ArrayList;
public class ExprInterpreterTest {
static class TestData{
final String expr;
final int val; // expression correct value
TestData(int v, String e) {
expr=e; val=v;
}
}
//============================================================
static ArrayList<TestData> corpusWithoutVars=new ArrayList<TestData>();
static ArrayList<TestData> corpusWithVars =new ArrayList<TestData>();
static {
corpusWithoutVars.add(new TestData(1, "1" ));
corpusWithoutVars.add(new TestData(2, "(2)" ));
corpusWithoutVars.add(new TestData(24, "3+21" ));
corpusWithoutVars.add(new TestData(7, "2*2+3" ));
corpusWithoutVars.add(new TestData(7, " 2 * 2+ 3" ));
corpusWithoutVars.add(new TestData(7, "2 *2+ 3 " ));
corpusWithoutVars.add(new TestData(7, "3 +2*2" ));
corpusWithoutVars.add(new TestData(4, "abs(0-sqr(2))"));
corpusWithoutVars.add(new TestData(4, "abs(0+sqr(2))"));
corpusWithoutVars.add(new TestData(2, "(sqrt (4))" ));
corpusWithoutVars.add(new TestData(12, "2+2+2+2+2+2"));
corpusWithoutVars.add(new TestData(2, "((abs(sqr(2)-cube(2)))-(sqrt(4)))"));
corpusWithoutVars.add(new TestData(14, "2*(4+3)"));
corpusWithoutVars.add(new TestData(-18, "3*(4-sqr(4))/2"));
corpusWithVars.add(new TestData(0, "(4-1)abc -abc"));
corpusWithVars.add(new TestData(8, "(2)v +v +v +v"));
corpusWithVars.add(new TestData(3, "(3+ (4-1)v) -v"));
corpusWithVars.add(new TestData(29, "3*(4-1)abc + (2)*abc + (4+abc)xy + xy"));
};
static String[] wrongExpressions = {
" ",
"2+",
"3+*2",
"3a*2",
"((1+234)*5))",
"(((1+234)*5)",
"abso(0-5)",
"a bs(0-2)",
"2 2+3",
"sqrt(0-4)",
"3-aaa",
"(3+1)aaa -aab"
};
// ------------------------------------------------------------
public static void generateException(String msg) {
try { Thread.sleep(300); }
catch (InterruptedException ex) { }
throw new RuntimeException(msg);
}
// ------------------------------------------------------------
public static int testExpr(String expr) throws ExprException {
System.out.print("'"+ expr + "'");
int res = ExprInterpreter.evaluate(expr);
System.out.println(" gives result : " + res);
return res;
}
// ------------------------------------------------------------
public static void testCorrectExpr() {
for (TestData td:corpusWithoutVars) {
try {
int res = testExpr(td.expr);
if (res != td.val) {
generateException("'" + td.expr + "' returns " + res
+ " but the correct result is: " + td.val);
}
}
catch (ExprException e) {
e.printStackTrace();
generateException("'" + td.expr + "' is wrong due to " + e);
}
}
}
// ------------------------------------------------------------
public static void testExprWithVars() {
System.out.println();
for (TestData td:corpusWithVars) {
try {
int res = testExpr(td.expr);
if (res != td.val) {
generateException("'" + td.expr + "' returns " + res
+ " but the correct result is: " + td.val);
}
}
catch (ExprException e) {
e.printStackTrace();
generateException("'" + td.expr + "' is wrong due to " + e);
}
}
}
// ------------------------------------------------------------
public static void testWrongExpr() {
String expr;
boolean exprIsAccepted;
int i;
System.out.println();
for (i = 0; i < wrongExpressions.length; i++) {
exprIsAccepted = true;
expr = wrongExpressions[i];
try {
testExpr(expr);
} catch (Exception e) {
System.out.println(" rejected due to " + e);
exprIsAccepted = false;
}
if (exprIsAccepted) {
generateException("'" + expr +
"' is accepted, but it should be refused ");
}
}
}
//------------------------------------------------------------
public static void main(String[] args) {
testCorrectExpr();
testWrongExpr();
testExprWithVars();
System.out.println("\nTest passed successfully !");
}
}
package s04;
public class ExprSymbolStream {
private String crtToken = "";
private String whole;
private int nextCharIndex=0; // index of the char following crtToken
// ------------------------------------------------------------
public ExprSymbolStream(String s) {
whole = s;
goToNextSymbol();
}
// ------------------------------------------------------------
public String crtSymbol() { // returns "" if the end is reached
return crtToken;
}
// ------------------------------------------------------------
private boolean noMoreChars() {
return nextCharIndex>=whole.length();
}
// ------------------------------------------------------------
private void trimSpaces() {
if (noMoreChars()) return;
char c = whole.charAt(nextCharIndex);
while (Character.isWhitespace(c)) {
nextCharIndex++;
if (noMoreChars()) return;
c = whole.charAt(nextCharIndex);
}
return;
}
// ------------------------------------------------------------
public void goToNextSymbol() {
crtToken = "";
trimSpaces();
if (noMoreChars()) return;
char c = whole.charAt(nextCharIndex);
// .....
// TODO - A COMPLETER...
// Selon que le prochain caractre est :
// - une lettre :
// grouper les lettres conscutives
// - un chiffre :
// grouper les chiffres conscutifs
// - autre chose :
// prendre juste ce caractre
}
// ------------------------------------------------------------
public boolean isNumber() {
if (crtToken.length()==0)return false;
for(int j=0; j<crtToken.length(); j++)
if (! Character.isDigit(crtToken.charAt(j)))
return false;
return true;
}
// ------------------------------------------------------------
public boolean isIdent() {
if (crtToken.length()==0)return false;
for(int j=0; j<crtToken.length(); j++)
if (! Character.isLetter(crtToken.charAt(j)))
return false;
return true;
}
// ------------------------------------------------------------
public boolean isOpeningParenth() {return crtToken.equals("(");}
public boolean isClosingParenth() {return crtToken.equals(")");}
public boolean isPlus() {return crtToken.equals("+");}
public boolean isMinus() {return crtToken.equals("-");}
public boolean isStar() {return crtToken.equals("*");}
public boolean isSlash() {return crtToken.equals("/");}
// ------------------------------------------------------------
public int intFromSymbol(){ // returns 0 if crtSymbol is not a number
if (! isNumber())
return 0;
return Integer.parseInt(crtToken);
}
}
package s04;
import java.util.ArrayList;
public class ExprSymbolStreamTest {
static class TestData{
final String expr;
final int size; // number of tokens
TestData(int s, String e) {
expr=e; size=s;
}
}
//============================================================
static ArrayList<TestData> corpus=new ArrayList<TestData>();
static {
corpus.add(new TestData(1, "7" ));
corpus.add(new TestData(3, "(2)" ));
corpus.add(new TestData(3, "3+21" ));
corpus.add(new TestData(5, "2*2+3" ));
corpus.add(new TestData(5, " 2 * 2+ 3" ));
corpus.add(new TestData(5, "2 *2+ 3 " ));
corpus.add(new TestData(8, "((abs(sqr(2)"));
corpus.add(new TestData(7, "(sqrt (4)))" ));
corpus.add(new TestData(6, "aa55bb cc 4 4"));
corpus.add(new TestData(11, "2+2+2+2+2+2"));
};
//------------------------------------------------------------
public static void testLexicalAnalyzer(String expr, int expectedSize) {
System.out.println("--------------------");
System.out.println("Symbol stream for : '" + expr + "'");
ExprSymbolStream s = new ExprSymbolStream(expr);
System.out.print(" gives : ");
int n=0;
String whole="";
String t=s.crtSymbol();
while (!t.equals("")) {
n++;
whole+=t;
System.out.print(" " + t);
s.goToNextSymbol();
t=s.crtSymbol();
}
System.out.println();
if (n!=expectedSize)
generateException("bad number of symbols");
if (!whole.equals(withoutSpaces(expr)))
generateException("bad sequence of symbols");
}
// ------------------------------------------------------------
public static void generateException(String msg) {
try { Thread.sleep(300); }
catch (InterruptedException ex) { }
throw new RuntimeException(msg);
}
// ------------------------------------------------------------
static String withoutSpaces(String s) {
String res="";
for(int i=0; i<s.length(); i++) {
char c=s.charAt(i);
if(c != ' ') res += c;
}
return res;
}
// ------------------------------------------------------------
public static void main(String[] args) {
for (TestData e:corpus) {
testLexicalAnalyzer(e.expr, e.size);
}
System.out.println("\nTest passed successfully !");
}
}
<?include("list-dir.php");?>
package s05;
/* The capacity can't be negative. It's
forbidden to remove when empty, or to add
when full. The collection cannot be empty
(resp. full) after adding (resp. removing)
*/
public class BoundedIntStack {
private int[] buf;
private int top = -1;
/*@ ... TODO ... @*/
public BoundedIntStack(int capacity) {
// assert TODO
buf = new int[capacity];
// assert TODO
}
/*@ ... TODO ... @*/
public int pop() {
// assert TODO
return buf[top--];
// assert TODO
}
public void push(int x) {
// assert TODO
buf[++top] = x;
// assert TODO
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top >= buf.length-1;
}
}
\ No newline at end of file
<?include("list-dir.php");?>
package s07;
public class PostCorrespondenceProblem {
//==================================================
static class Domino {
final String up, down;
Domino(String u, String d) {
up=u; down=d;
}
}
//==================================================
static boolean solved(Domino[] t, int maxSteps) {
return solved(t, maxSteps, "", "");
}
static boolean solved (Domino[] t, int k, String a, String b) {
// TODO A COMPLETER...
return false;
}
public static void main(String[] args) {
Domino[] t1= {
new Domino("100","1"),
new Domino("0","100"),
new Domino("1","00"),
};
Domino[] t2= {
new Domino("10","0"),
new Domino("0","001"),
new Domino("001","1"),
};
Domino[] t3= {
new Domino("1","111"),
new Domino("10111","10"),
new Domino("10","0"),
};
Domino[] t4= {
new Domino("10","101"),
new Domino("011","11"),
new Domino("101","011"),
};
System.out.println(solved(t1, 50));
System.out.println(solved(t2, 50));
System.out.println(solved(t3, 50));
System.out.println(solved(t4, 50));
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment