Code Abbey -- Reverse String (in place)

Oforth examples. Feel free to post your own code.

Code Abbey -- Reverse String (in place)

Postby sotolf » 10 Sep 2015 09:09

For this one they wanted to reverse a string, which would be a very short program,
but, the complication is that they want us to do it in place, so it gets a bit tricky, but with string buffers, very possible.
I can't help feeling that my solution is inelegant though, there is probably something obvious that I'm missing, or at least some way of making it
a bit nicer, but at least it works

Code: Select all
: getLn { System.Console askln }                                               
: charExch(sbuf, x, y) { sbuf at(x)   sbuf at(y)
                                  x sbuf put   y sbuf put }
: prepStrBuf { StringBuffer new swap << }
: revStr(sbuf) { |f l| 1 ->f sbuf size ->l
                      while(f l <) [ f l sbuf charExch 
                                        f 1 + ->f   l 1 - ->l ] sbuf }

getLn prepStrBuf revStr . printcr
sotolf
 
Posts: 55
Joined: 30 Jul 2015 15:53

Re: Code Abbey -- Reverse String (in place)

Postby Franck » 10 Sep 2015 17:10

Hi,

1) If you want to create a string buffer from a string, you can use #asStringBuffer

2) For the solution, you can use a loop instead of while :

Code: Select all
: revStr(sbuf)
{
|i s|
   sbuf size dup ->s 2 / loop: i [ i s i - 1 + sbuf charExch ] sbuf
}
Franck
 
Posts: 159
Joined: 29 Oct 2014 19:01

Re: Code Abbey -- Reverse String (in place)

Postby sotolf » 11 Sep 2015 07:03

Franck wrote:Hi,

1) If you want to create a string buffer from a string, you can use #asStringBuffer


Ah, I'm quite sure I did try that :p but since I didn't manage to do it with it, I probably didn't ;)

2) For the solution, you can use a loop instead of while :

Code: Select all
: revStr(sbuf)
{
|i s|
   sbuf size dup ->s 2 / loop: i [ i s i - 1 + sbuf charExch ] sbuf
}


The loop looks cleaner yes, it's a much better choice here.

Seems like the easier of the Code Abbey challenges are coming to an end, and there are just a couple left before they are going to be a bit more interesting.
sotolf
 
Posts: 55
Joined: 30 Jul 2015 15:53


Return to Oforth examples

Who is online

Users browsing this forum: No registered users and 1 guest

cron