Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

152
LINES

< > BotCompany Repo | #640 // Learn to calculate (console)

JavaX source code - run with: x30.jar

1  
!636
2  
!quickmain
3  
!auto-import
4  
5  
import java.math.*; // BigInteger
6  
7  
interface Learner {
8  
  void processInOut(String in, String out);
9  
  String processIn(String in);
10  
}
11  
12  
main {
13  
  psvm {
14  
    print "\nHello. Teach me math."
15  
    LMath learner = new LMath();
16  
    while (true) {
17  
      String in = readLine("\nQ: ");
18  
      in = in.trim();
19  
      
20  
      if (in.equals("restart")) {
21  
        System.out.println("[restart]");
22  
        learner.restart();
23  
        continue;
24  
      }
25  
      
26  
      if (in.length() == 0)
27  
        break;
28  
      
29  
      String guess = learner.processIn(in);
30  
      if (guess != null && guess.length() != 0) {
31  
        System.out.println(in + " => " + guess);
32  
        String ok = readLine("\nOK (y/n)? ");
33  
        ok = ok.toLowerCase().trim();
34  
        boolean yes = ok.startsWith("y") || ok.startsWith("j");
35  
        if (yes) {
36  
          print ":)"
37  
          // OPTIONAL - indicate that guess was OK: learner.processInOut(in, guess);
38  
          continue;
39  
        } else {
40  
          print "Oops."
41  
          // query correcting answer from user
42  
        }
43  
      } else {
44  
        print "I don't know."
45  
      }
46  
      
47  
      String out = readLine(in + " => ");
48  
      out = out.trim();
49  
      learner.processInOut(in, out);
50  
      System.out.println("OK. " + in + " => " + out);
51  
    }
52  
  }
53  
  
54  
  static Scanner system_in = new Scanner(System.in);
55  
  static String readLine(String prompt) {
56  
    System.out.print(prompt);
57  
    return system_in.nextLine();
58  
  }
59  
  
60  
  static BigInteger[] getNumbers(String s) {
61  
    Pattern p = Pattern.compile("-?\\d+");
62  
	  Matcher m = p.matcher(s);
63  
	  List<BigInteger> list = new ArrayList<BigInteger>();
64  
	  while (m.find())
65  
	    list.add(new BigInteger(m.group()));
66  
	  return list.toArray(new BigInteger[list.size()]);
67  
  }
68  
  
69  
  static boolean arraysEqual(BigInteger[] a, BigInteger[] b) {
70  
    if (a.length != b.length) return false;
71  
    for (int i = 0; i < a.length; i++)
72  
      if (!a[i].equals(b[i])) return false;
73  
    return true;
74  
  }
75  
    
76  
  static class LMath implements Learner {
77  
    String allOperations = "+ - * /";
78  
    Set<String> possibleOperations = new TreeSet<String>();
79  
    String outPattern = "";
80  
    
81  
    LMath() {
82  
      restart();
83  
    }
84  
    
85  
    void restart() {
86  
      possibleOperations.addAll(Arrays.asList(allOperations.split(" +")));
87  
    }
88  
    
89  
    public void processInOut(String in, String out) {
90  
      outPattern = out.replaceAll("-?\\d+", "*");
91  
      BigInteger[] inNumbers = getNumbers(in);
92  
      BigInteger[] outNumbers = getNumbers(out);
93  
      try {
94  
        findOperation(inNumbers, outNumbers);
95  
      } catch (Throwable e) {
96  
        e.printStackTrace();
97  
      }
98  
    }
99  
    
100  
    public void findOperation(BigInteger[] in, BigInteger[] out) {
101  
      filterOperations(in, out);
102  
      if (possibleOperations.isEmpty()) {
103  
        System.out.println("TILT");
104  
        restart();
105  
        filterOperations(in, out);
106  
      }
107  
    }
108  
      
109  
    public void filterOperations(BigInteger[] in, BigInteger[] out) {
110  
      for (Iterator<String> i = possibleOperations.iterator(); i.hasNext(); ) {
111  
        String op = i.next();
112  
        BigInteger[] out2 = doOperation(op, in);
113  
        if (out2 == null || !arraysEqual(out, out2))
114  
          i.remove(); // keep only matching operations
115  
      }
116  
    }
117  
    
118  
    public BigInteger[] doOperation(String op, BigInteger[] in) {
119  
      op = op.intern();
120  
      try {
121  
        if (in.length == 2) {
122  
          BigInteger a = in[0], b = in[1], x = null;
123  
          if (op == "+")
124  
            x = a.add(b);
125  
          else if (op == "-")
126  
            x = a.subtract(b);
127  
          else if (op == "*")
128  
            x = a.multiply(b);
129  
          else if (op == "/")
130  
            x = a.divide(b);
131  
          return x != null ? new BigInteger[] {x} : null;
132  
        }
133  
        return null;
134  
      } catch (Throwable e) {
135  
        return null;
136  
      }
137  
    }
138  
    
139  
    public String processIn(String in) {
140  
      if (possibleOperations.isEmpty()) return "";
141  
      String op = possibleOperations.iterator().next();
142  
      
143  
      BigInteger[] inNumbers = getNumbers(in);
144  
      BigInteger[] outNumbers = doOperation(op, inNumbers);
145  
      String s = outPattern;
146  
      if (outNumbers != null)
147  
        for (BigInteger num : outNumbers)
148  
          s = outPattern.replaceFirst("\\*", num.toString());
149  
      return s;
150  
    }
151  
  }
152  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gkwdfizivqfm, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, qbtsjoyahagl, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #640
Snippet name: Learn to calculate (console)
Eternal ID of this version: #640/1
Text MD5: f741b25fe79687d42c048cda01c53f3b
Author: stefan
Category:
Type: JavaX source code
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2015-06-23 23:45:49
Source code size: 4406 bytes / 152 lines
Pitched / IR pitched: No / Yes
Views / Downloads: 698 / 621
Referenced in: [show references]