在Forth中对字符串数组进行排序

时间:2018-03-28 11:51:00

标签: sorting forth gforth

我使用CREATE创建了一个字符串数组:

create mystringarray s" This" , s" is" , s" a", s" list" ,

我想按升序排序。我在网上找到了汇编语言的一些教程,但我想在Forth中完成。什么是最佳实践方法?

2 个答案:

答案 0 :(得分:7)

您需要首先确保您的数据表示准确无误。

Forth中的文字字符串是使用单词s"获得的,所以你会写,例如:

s" This"  ok

输入后,如果您执行.s,则会看到两个值:

.s <2> 7791776 4  ok

这是指向实际字符串(字符数组)的指针,以及字符串中字符数的计数。 Forth中的某些单词理解这个字符串表示。 type就是其中之一。如果您现在输入type,则会在显示屏上输入字符串:

type This ok

现在你知道你需要两个单元格来表示由s"获得的字符串。您的create需要考虑到这一点,并使用2,字来存储每个条目2个单元格,而不是只存储一个单元格的,

create myStringArray
    s" This" 2,
    s" is" 2,
    s" an" 2,
    s" array" 2,
    s" of" 2,
    s" strings" 2,

这是字符串的地址/计数对数组。如果要访问其中一个,可以按如下方式进行:

: myString ( u1 -- caddr u1 )  \ given the index, get the string address/count
    \ fetch 2 cells from myStringArray + (sizeof 2 cells)*index
    myStringArray swap 2 cells * + 2@ ;

打破这一点,你需要取数组变量myStringArray的基础,并为你想要的字符串地址/计数添加正确的偏移量。该偏移量是索引(在数据堆栈上)的数组条目(2个单元格)的大小。因此,表达式myStringArray swap 2 cells * +。接下来是2@,它检索该位置的双字(地址和计数)。

投入使用......

3 myString type array ok
0 myString type This ok

等...

现在您已经了解了索引数组的基础知识,那么排序的“最佳实践”将遵循为您要排序的数组类型选择排序算法的常规最佳实践。在这种情况下,冒泡排序可能适用于非常小的字符串数组。 You would use the compare word to compare two strings.例如:

s" This" 0 myString compare .s <1> 0  ok

结果为0,表示字符串相等。

答案 1 :(得分:4)

对数组进行排序的最佳实践方法是使用一些现有的库。如果现有的图书馆不适合您的需求,或者您的主要目的是学习 - 那么实现自己的库是有意义的。

使用库

例如,来自The Forth Foundation Library(Cell array module)的FFL可用于对任何项目的数组进行排序。

代码示例

include ffl/car.fs
include ffl/str.fs

0 car-new value arr  \ new array in the heap

\ shortcut to keep -- add string into our 'arr' array
: k ( a1 u1 -- ) str-new dup arr car-push str-set ;

\ set compare method
:noname ( a1 a2 -- n ) >r str-get r> str-get compare ; arr car-compare!

\ dump strings from the array
: dump-arr ( -- ) arr car-length@ 0 ?do i arr car-get str-get type cr loop ;

\ populate the array
s" This" k s" is" k s" a" k s" list" k

\ test sorting
dump-arr cr
arr car-sort 
dump-arr cr

输出

This
is
a
list

This
a
is
list

使用裸Forth

如果您只需要学习的Forth解决方案,请查看bubble sort sample

字符串数组应仅包含字符串地址。琴弦本身应保存在其他地方。在这种情况下使用计数字符串格式很有用 - 因此,我们对字符串文字使用c"字。为了保持字符串本身,我们将初始化代码放入定义(在这种情况下为:noname) - 它将字符串保留在字典空间中。

冒号排序从数字的变体改编为字符串的变体,只需替换比较项的单词。请注意,2@字会返回顶部最低地址的值。

代码示例

\ some helper words
: bounds ( addr1 u1 -- addr1 addr2 ) over + swap ;
: lt-cstring ( a1 a2 -- flag ) >r count r> count compare -1 = ;

\ create an array of counted strings
:noname ( -- addr cnt )
  here
    c" This" , c" is" , c" a" , c" list" ,
  here over - >cells
; execute constant cnt constant arr

\ dump strings from the array  
: dump-arr ( -- ) cnt 0 ?do i cells arr + @ count type cr loop ;

\ bubble sort
: sort-arr ( -- )
  cnt 2 u< if exit then
  cnt 1 do true
    arr cnt i - cells bounds do
      i 2@ ( a2 a1 ) lt-cstring if i 2@ swap i 2! false and then
    cell +loop
    if leave then
  loop
;

\ test sorting
dump-arr cr
sort-arr
dump-arr cr

\ the output is the same as before
相关问题