summaryrefslogtreecommitdiff
path: root/chapter22/docs/examples
diff options
context:
space:
mode:
Diffstat (limited to 'chapter22/docs/examples')
-rw-r--r--chapter22/docs/examples/BubbleSort.smp54
-rw-r--r--chapter22/docs/examples/bubble.dat2
2 files changed, 50 insertions, 6 deletions
diff --git a/chapter22/docs/examples/BubbleSort.smp b/chapter22/docs/examples/BubbleSort.smp
index 025bb5a2..70f45717 100644
--- a/chapter22/docs/examples/BubbleSort.smp
+++ b/chapter22/docs/examples/BubbleSort.smp
@@ -25,6 +25,13 @@ val require = { Scan s, u8 c ->
usage();
};
+val peek = { Scan s, u8 c ->
+ skip(s);
+ if( s.buf[s.x] != c ) return false;
+ s.x++;
+ return true;
+};
+
val number = { Scan s ->
skip(s);
i32 n = 0;
@@ -37,10 +44,45 @@ val number = { Scan s ->
// Read from stdin a line of the form "[ 4, 3, 2, 1]" and print it sorted.
val main = { ->
Scan !s = new Scan{ buf = sys.io.stdin(); };
- while( s.x < s.buf# ) {
- require(s,'[');
- int n = number(s);
- sys.libc._exit(n);
- };
- return 0;
+ require(s,'[');
+ // Array of parsed results
+ int[] !ns = new int[16];
+ i32 num = 0;
+ // Parse a list of numbers
+ if( !peek(s,']') ) { // Handle the empty list
+ // Parse "123, " until a something else
+ while( s.x < s.buf# ) {
+ int n = number(s);
+ i32 q=n;
+ ns[num++] = n;
+ if( !peek(s,',') )
+ break;
+ };
+ require(s,']'); // Close the list
+ }
+
+ // Print a list of numbers
+ sys.io.p("[ ");
+ u8[] !buf = new u8[20];
+ for( int i=0; i<num; i++ ) {
+ int x = ns[i];
+ if( !x ) { sys.io.p("0, "); continue; }
+
+ u32 log=0, q=x;
+ while( q>0 )
+ { q/=10; log++; }
+ i32 raw=log;
+ sys.libc._exit(raw);
+ // for( int j=0, a=x; j<log; j++ ) {
+ // q = x/10;
+ // buf[log-j] = '0'+(x-q*10);
+ // x = q;
+ // }
+ // int raw = buf;
+ // sys.libc.write(1,raw,log);
+ // sys.io.p(", ");
+ }
+ sys.io.p("]");
+
+ return num;
};
diff --git a/chapter22/docs/examples/bubble.dat b/chapter22/docs/examples/bubble.dat
new file mode 100644
index 00000000..6cffd25c
--- /dev/null
+++ b/chapter22/docs/examples/bubble.dat
@@ -0,0 +1,2 @@
+ [ 99, 4,3, 1]
+ \ No newline at end of file