1 | /*
|
---|
2 | * Rick van der Zwet
|
---|
3 | * 0433373
|
---|
4 | * Scheme programming assigment 1a
|
---|
5 | * Licence: BSD
|
---|
6 | * $Id: exercise1b.cc 375 2007-12-10 23:02:34Z rick $
|
---|
7 | */
|
---|
8 | #include <stdio.h>
|
---|
9 | #include <sysexits.h>
|
---|
10 | #include <iostream>
|
---|
11 | #include <string>
|
---|
12 |
|
---|
13 | using namespace std;
|
---|
14 |
|
---|
15 | /* Make good use of the predifined input of replace string */
|
---|
16 | string
|
---|
17 | sub_atoms (string input, const string rstring)
|
---|
18 | {
|
---|
19 | size_t bi, ri;
|
---|
20 |
|
---|
21 | for (bi = 0; bi < input.length(); bi++) {
|
---|
22 | if (input.at(bi) != ' ') {
|
---|
23 | for (ri = 2; ri < rstring.length(); ri++) {
|
---|
24 | if (input.at(bi) == rstring.at(ri)) {
|
---|
25 | input.replace(bi, 1, rstring, ri + 2, 1);
|
---|
26 | break;
|
---|
27 | }
|
---|
28 | }
|
---|
29 | }
|
---|
30 | }
|
---|
31 | return(input);
|
---|
32 | }
|
---|
33 |
|
---|
34 | string
|
---|
35 | substritute (string input, const string rstring)
|
---|
36 | {
|
---|
37 | size_t cii;
|
---|
38 | int brackets = 1;
|
---|
39 | int start;
|
---|
40 | string output;
|
---|
41 |
|
---|
42 | // Debug: cout << "Input: " << input << endl;
|
---|
43 |
|
---|
44 | /* Find the first bracket */
|
---|
45 | start = input.find('(');
|
---|
46 |
|
---|
47 | /* Cool list has only atoms left start replacing */
|
---|
48 | if (start == -1)
|
---|
49 | return(sub_atoms(input, rstring));
|
---|
50 |
|
---|
51 | start++;
|
---|
52 | /* Find closing bracket */
|
---|
53 | for (cii = start; cii != input.length(); cii++) {
|
---|
54 | if (input.at(cii) == '(')
|
---|
55 | brackets++;
|
---|
56 | else if (input.at(cii) == ')')
|
---|
57 | brackets--;
|
---|
58 |
|
---|
59 | if (brackets == 0)
|
---|
60 | break;
|
---|
61 | }
|
---|
62 |
|
---|
63 | /* ... <start - 1=(> ... <cii=)> ... */
|
---|
64 | // Debug: cout << "Output: " << input.substr(start, cii - start) << endl;
|
---|
65 | // Debug: cout << "start: " << start << " cii: " << cii << endl;
|
---|
66 |
|
---|
67 | /* Call recursive the front, the sub itself and the tail if found */
|
---|
68 | if (start > 1)
|
---|
69 | output += substritute(input.substr(0, start - 1), rstring);
|
---|
70 | output += "(";
|
---|
71 | output += substritute(input.substr(start, cii - start), rstring);
|
---|
72 | output += ")";
|
---|
73 | if (cii <= input.length())
|
---|
74 | output += substritute(input.substr(cii + 1), rstring);
|
---|
75 |
|
---|
76 | return(output);
|
---|
77 | }
|
---|
78 |
|
---|
79 | int
|
---|
80 | main (int argv, char * argc[])
|
---|
81 | {
|
---|
82 | cout << "Expected: ((z (y c) d) z (f y))" << endl;
|
---|
83 | cout << "Actual : ";
|
---|
84 | cout << substritute("((a (b c) d) a (f b))", "((a z) (b y))");
|
---|
85 | cout << endl;
|
---|
86 | return (EX_OK);
|
---|
87 | }
|
---|