按 J 中的长度对字符串中的单词进行排序

Sorting words in a string by their length in J

我有以下字符串: s=:'when can we dance' 我可以用这个找到每个单词的长度: # each ;:s 我可以按 ascending/descending order:(/:~) # each ;:s 对长度进行排序,这会给我盒装输出。 但是我如何打印这些文字呢?

您已经在使用 /:~,即 Reflex of dyadic Sort Up/:~ y 等同于 y /: y。这是一个方便的快捷方式,但在这种情况下,您跳过的是您正在寻找的解决方案。 /:(没有 Reflex)根据会导致排序 y 的排列排列其 x。那个“会导致排序 y 的排列”顺便说一下 monadic /: (Grade Up) 是为了.

   ]w=:;:'when can we dance'
+----+---+--+-----+
|when|can|we|dance|
+----+---+--+-----+
   /: w
1 3 2 0
   (/: w) { w
+---+-----+--+----+
|can|dance|we|when|
+---+-----+--+----+
   w /: w
+---+-----+--+----+
|can|dance|we|when|
+---+-----+--+----+

因此,要按其他内容对 w 进行排序,例如其项目的长度,只需提供其他内容作为 Sort Up 的 y:

   w /: # each w
+--+---+----+-----+
|we|can|when|dance|
+--+---+----+-----+
   (/: # each) w     NB. a hook
+--+---+----+-----+
|we|can|when|dance|
+--+---+----+-----+

;: 给你字符串中的 J 个单词,这可能不是你想要的:

   ;: 'when can''t we dance'
|open quote
|       ;:'when can''t we dance'

其中一个 ;. Cut family or stdlib's splitstring or regexes 可能会有所帮助。

   13 : ';: ''when can we dance'''  NB. 13 : can be a mnemonic
(<;._1 ' when can we dance')"_

   <;._1 ' ','when can''t we dance'
+----+-----+--+-----+
|when|can't|we|dance|
+----+-----+--+-----+
   ' ' splitstring 'when can''t we dance'
+----+-----+--+-----+
|when|can't|we|dance|
+----+-----+--+-----+

   s=:'when can''t   we dance'  NB. excess space
   <;._1 ' ',s  NB. empty boxes in result
+----+-----+++--+-----+
|when|can't|||we|dance|
+----+-----+++--+-----+
   require 'regex'
   '[\w'']+' rxall s
+----+-----+--+-----+
|when|can't|we|dance|
+----+-----+--+-----+

要将这些单词列表恢复为字符串,

   w
+----+---+--+-----+
|when|can|we|dance|
+----+---+--+-----+
   ;: inv w
when can we dance
   ' ' joinstring w
when can we dance

Julian 在上面的回答中很好地解释了处理撇号的方法,但如果您忽略它们的存在,我会使用 &.(下)和 ;:(单词)装箱后按长度排序,然后拆箱。

   s=:'when can we dance' 
   (/:  # each)  &. ;: s
we can when dance

(/: # each) 是根据每个长度对它们进行排序的钩子,&.;: 将它们装箱,然后在最后拆箱以提供结果。