2

为了玩Stretch the word,我定义了以下词,以尝试通过与此答案相同的方法解决问题:

USING: kernel math sequences sequences.repeating ;
IN: stretch-words

! "bonobo" -> { "b" "bo" "bon" "bono" "bonob" "bonobo" }
: ascend-string ( string -- ascending-seqs )
    dup length 1 + iota [ 0 swap pick subseq ] map
    [ "" = not ] filter nip ;

! expected: "bonobo" -> "bonoobbooo"
! actual:   "bonobo" -> "bbbooonnnooobbbooo"
: stretch-word ( string -- stretched ) 
    dup ascend-string swap zip
    [ 
      dup first swap last 
      [ = ] curry [ dup ] dip count 
      repeat 
    ] map last ;

stretch-word应该按照它在字符串中出现的次数重复字符串中的字符。但是,我的实现是重复它获得的 1string 的所有实例。

我觉得这在 Factor 中很容易实现,但我不太明白。我如何让它做我想要的?

4

2 回答 2

2

嗯......不是一个伟大的高尔夫球,但它的工作......

首先,我做了一个小改动,ascend-string以便将字符串留在堆栈中:

: ascend-string ( string -- string ascending-seqs )
    dup length 1 + iota [ 0 swap pick subseq ] map
    [ "" = not ] filter ;

所以stretch-word可以这样工作:

: stretch-word ( string -- stretched ) 
    ascend-string zip         ! just zip them in the same order
    [ 
      first2 over             ! first2 is the only golf I could make :/
      [ = ] curry count       ! same thing
      swap <array> >string    ! make an array of char size count and make it a string
    ] map concat ;            ! so you have to join the pieces

编辑:我认为问题在于使用重复来完成这项工作。

于 2016-04-24T03:19:12.107 回答
1
: ascend-string ( string -- seqs )
    "" [ suffix ] { } accumulate*-as  ;
: counts ( string -- counts )
    dup ascend-string [ indices length ] { } 2map-as ;
: stretch-word ( string -- stretched )
    [ counts ] keep [ <string> ] { } 2map-as concat ;
"bonobo" stretch-word print
bonoobbooo

indices length也可以是[ = ] with count

于 2016-06-04T12:42:16.657 回答