让我们建立一个楼梯


19

对于初学者,我们没有足够(半)轻松的挑战。越来越多的简单方法已经被采用。因此,我试图提出一些初学者可能可以实现的目标,但这并不是重复的。

输入:

用您的OS换行符(即\r\n)分隔的单个字符串,
或包含多个字符串的数组。

输出- 楼梯

删除所有非字母和非数字符号。所以剩下的就是[A-Za-z0-9]。然后“建楼梯”;基本上按长度排序,顶部最小,底部最大。

挑战规则:

  1. 当两个字符串的长度相等时,我们将它们彼此合并为一个大字符串(顺序无关紧要,因此可以是从第一到最后或从最后到第一,无论您喜欢哪两个)。
  2. 当合并的字符串再次具有相等的长度时,上述规则可以堆叠(请参见测试案例2)。

通用规则:

  • 输入为STDIN,仅包含ASCII字符。输出为STDOUT。
  • 输出的大小写必须与输入的大小写相同。
  • 每个提交必须是能够编译和运行的完整程序,而不仅仅是方法/功能。编辑:我是新手,所以即使我自己更喜欢完整的程序,也许从现在开始使用默认值确实更好。对不起,每个人都已经发布了完整程序。随时进行编辑,下次我将尽量不更改挑战中的帖子。
  • 这是,因此最短的答案以字节为单位。我可能会接受一年后最短的答案。
    不要让代码高尔夫球的答案阻止您发布像C#之类的高尔夫非代码高尔夫球语言!尝试提出所有编程语言的最短答案。
  • 随意使用比该问题更新的语言。

测试用例:

输入1:

This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do

输出1:

Okthatwilldo
Thisisasampletext
Blablablasomemoretext
Thewoodmaybeofexcellentquality
thatyouwillhavetousetobuildstairs
orprettycrappyalmostfallingapartandfilledwithtermites

输入2:

A
small
one
that
contains
equal
length
strings
for
the
special
rule

输出2:

A                   Or alternatively:       A
length                                      length
oneforthe                                   theforone
smallequal                                  equalsmall
stringsspecial                              specialstrings
thatrulecontains                            containsrulethat

步骤说明如下:2:

一阶的长度:

A
one
for
the
that
rule
small
equal
length
strings
special
contains

第一次合并:

A
oneforthe
thatrule
smallequal
length
stringsspecial
contains

长度二阶:

A
length
thatrule
contains
oneforthe
smallequal
stringsspecial

第二次合并:

A
length
thatrulecontains
oneforthe
smallequal
stringsspecial

长度的三阶:

A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

输入3:

Test,
test.
This
is
a
test.

输出3:

a                   Or alternatively:       a
is                                          is
TesttestThistest                            testThistestTest

输入4:

a
bc
d!
123

输出4:

123     Or alternatively:    123
adbc                         dabc

1
contains不应该出现在输出2中。它与thatrule
Keatinge,

2
您几乎与想要的完全相反,很难做到这一点。
巴林特,2016年

“可以自由使用比这个问题更新的语言”-因此,如果我创建一种语言,只是为了解决0字节的问题,从技术上讲是合法的,不是吗?
巴林(Bálint)

沙盒中有这个挑战吗?
巴林(Bálint)

1
@nimi我个人确实很喜欢完整的程序,但是如果您真的坚持要立即删除它,并且每个人都可以使用默认程序,那么我还是个新手,所以从现在开始使用默认程序确实更好。对不起,每个人都已经发布了完整程序。随时进行编辑,下次我不会在挑战中途尝试这些规则。
凯文·克鲁伊森

Answers:


4

外壳,11个字节

ωȯmΣġLÖLmf□

在线尝试!

赫斯基比这个挑战还年轻(这在正式上并没有什么区别,但仍然如此)。

说明

ωȯmΣġLÖLmf□  Implicit input (list of strings), say ["a","bc","d!","123"]
        mf□  Keep only alphanumeric chars of each: ["a","bc","d","123"]
ωȯ           Repeat until fixed point is reached:
      ÖL       Sort by length: ["a","d","bc","123"]
    ġL         Group by length: [["a","d"],["bc"],["123"]]
  mΣ           Concatenate each group: ["ad","bc","123"]
             Final result ["123","adbc"], print implicitly separated by newlines.

当“仅保留每个字母数字字符”时mf□,您应该会嫉妒。当“按长度分组” ġL为时,您应该会感到惊讶。
暴民埃里克(Erik the Outgolfer)'17年

我已经接受了你的回答。新的功能是可以使用比挑战更新颖的语言(我在发布挑战时也已经提到了这一点)。如我之前所说,很好的答案!
凯文·克鲁伊森

4

Python 3,264字节

我不太擅长编写代码,所以我有信心这不是Python 3的最佳答案。这将使用递归和有序dict,每个长度的所有单词都应使用。

from collections import*
def f(i):
 d = defaultdict(list)
 for l in i: x = "".join(c for c in l if c.isalnum());d[len(x)].append(x)
 n = (sorted(["".join(d[z]) for z in d.keys()], key=len))
 if n == i:return "\n".join(n)
 return f(n)
print(f(eval(input())))

将来自stdin的输入作为列表,例如,使用以下列表对其进行测试:

['A', 'small', 'one', 'that', 'contains', 'equal', 'length', 'strings', 'for', 'the', 'special', 'rule']

将输出:

A
length
oneforthe
smallequal
stringsspecial
thatrulecontains

1
好答案!关于打高尔夫球的几点提示:1)您不需要在=符号或==符号周围留空格。2)如果Python知道它不能是另一个变量名,则可以检测到关键字,例如您对“ import *”(例如,“ for”,“ return” \ n“”)所做的操作。3)我很肯定(不是肯定的)您不需要sorted()周围的括号。编码愉快!
蓝色

您可以使用filter(str.isalnum, l)"".join零件代替
njzk2,2016年

4

视网膜69 63字节

[^ \w¶] | _

{`\ b((。)+)¶((?。)+)\ b(?(2)(?!))
$ 1 $ 3
O $`(。)+
$#1 $ *

在线尝试!


我认为您可以将第一行更改为[^\w¶]|_。尽管我仍然不确定是否是最佳选择。
FryAmTheEggman '16

3

Oracle SQL 11.2,346字节

输入字符串中的行用“¤”分隔。这样,就不必创建用作输入的表。

This is a sample textthat you will have to use to build stairsThe wood may be of excellent qualityor pretty crappy almost falling apart and filled with termitesBla bla bla - some more text¤Ok, that will do
A¤small¤one¤that¤contains¤equal¤length¤strings¤for¤the¤special¤rule
TesttestThis¤is¤a¤test         

查询:

WITH v AS(SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))),r(s,i,l)AS(SELECT s,1,1 FROM v UNION ALL SELECT LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s)),ROW_NUMBER()OVER(PARTITION BY LENGTH(s)ORDER BY s),l+1 FROM r WHERE l<LENGTH(:1)AND i=1)SELECT s FROM r WHERE l=LENGTH(:1);  

未打高尔夫球

WITH v AS
( 
  -- Splits on ¤ and keeps only alphanum characters 
  SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^a-zA-Z0-9]')s FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))
)
-- Recursive view 
-- s : string
-- i : index of the string in case of duplicates
-- l : exit condition
,r(s,i,l)AS
(
  -- Start with every element of the input
  SELECT s,1,1 FROM v
  UNION ALL
  SELECT -- Concatenate elements of the same lengths
         LISTAGG(s)WITHIN GROUP(ORDER BY s)OVER(PARTITION BY LENGTH(s))
         -- Index of elements of the same length (listagg with over generates duplicates)
        ,ROW_NUMBER()OVER(PARTITION BY LENGTH(s) ORDER BY s)
        -- exit condition
        ,l+1 FROM r WHERE l<LENGTH(:1) AND i=1
)
-- Keep only the elements from the last iteration (automaticaly sorted on my system)
SELECT s FROM r WHERE l=LENGTH(:1)  

您可以用[\W_]
FliiFe '16

@FliiFe它不会删除“,”和“。” 在最后一个测试用例中
杰托

奇怪...但是你仍然可以替换0-9使用\d。也许正则表达式规则在sql中与在python / php / javascript中不同?(由于
回溯,

2

Haskell,129个字节

import Data.List
import Data.Char
l=length
print.(foldl(const.map concat.groupBy((.l).(==).l).sortOn l)=<<(filter isAlphaNum<$>))

接受并打印一个字符串数组。如果可以从函数返回结果(与打印到标准输出相反),则可以省略print.和保存6个字节。

它是如何工作的(请注意,我使用x的输入参数当然不会出现在上面的pointpoint版本中):

 (    )=<<(     )          -- (f =<< g) x is f (g x) x, so we fold over x with a
                           -- starting value of:
     filter isAlphaNum<$>x -- keep only alphanumeric chars in every line of x

                           -- during folding, I ignore the the elements of x.
                           -- However folding stops the repeatedly applied function
                           -- after (length x) steps, which is enough for combining
                           -- lines of equal length

 const                     -- ignore elements from x, deal only with start value
                sortOn l   -- sort lines from shortest to longest
      groupBy((.l).(==).l) -- group lines of equal length
    map concat             -- concatenate each group      

print                      -- print result after (length x) iterations

2

Python 3,184180字节

def f(x):l=len;m=filter;y=sorted([''.join(m(str.isalnum,i))for i in x],key=l);*z,=m(l,[''.join(i for i in y if-~j==l(i))for j in range(l(y[-1]))]);y==z and+print(*z,sep='\n')or f(z)

该函数通过参数将输入作为字符串列表,并将结果打印到STDOUT。执行会引发错误(由于在print语句之前使用了+运算符),但在输出输​​出之前未引发错误。

怎么运行的

def f(x):                              Function with input of list of strings
l=len;m=filter                         Redefine much-used functions: len gives the length
                                       of an object and filter chooses those items from an
                                       iterable for which a function is true
[''.join(m(str.isalnum,i))for i in x]  Strip to leave only alphanumeric characters...
y=sorted(...,key=l)                    ...and sort by length, into y
''.join(i for i in y if-~j==l(i))      Concatenate equal length strings...
[...for j in range(l(y[-1]))]          ...for all possible string lengths...
*z,=(m(l,...))                         ...and remove empty strings by filtering by length
                                       (the empty string has length 0, and is thus false),
                                       into z
y==z and+print(*z,sep='\n')...         If no change after concatenation, no more equal
                                       length strings exist, so print result to STDOUT...
...or f(z)                             ...else pass new list to function

在Ideone上尝试


2

J,48个字节

[:(/:#&>)[:(#&>,&.>//.])^:_(#~e.&AlphaNum_j_)&.>

在线尝试!

不打高尔夫球

[: (/: #&>) [: (#&> ,&.>//. ])^:_ (#~e.&AlphaNum_j_)&.>

说明

  • (#~e.&AlphaNum_j_)&.> 删除非字母数字
  • (#&> ,&.>//. ]) 结合相同长度的物品
  • ^:_ 继续结合直到停止变化
  • (/: #&>) 按长度排序

1

使用Javascript 198 188 186 179字节

这是我第二长的高尔夫javascript程序

s=>s.replace(/[^\w]|_/g,``,l=0).split(/\s/g).sort(g=(a,b)=>a[m=`length`]-b[m]).reduce((a,b,c)=>a+(a.split(/\s/g)[c-1][m]<b[m]?`
`:` `)+b).replace(/ /g,``).split`
`.sort(g).join`
`

可能可以进一步打高尔夫球


您将t变量用于什么?
gcampbell '16

好了,所以你可以通过声明Y =“拆分”,然后,而不是使用的高尔夫球也.split()可以使用[y]()
秃头班萨

@gcampbell那只是测试的残余
巴林特

@BaldBantha我不认为这将使它更短
巴林特

@BaldBantha我这样做,有长度虽然
巴林特

1

Perl 5,112字节

@F=<>;while($n-@F){$n=@F;%k=();s/[^a-z0-9]//gi,$k{y///c}.=$_ for@F;@F=values%k}say $k{$_}for sort{$a<=>$b}keys%k

在线尝试!


1

果冻,17个字节

f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY

在线尝试!

不确定为什么Ẏf¥€ØWṖ¤L€ĠịµÐLY不起作用...

说明:

f€ØWṖ¤L€Ġị⁸Ẏ€µÐLY Full program
             µÐL  Execute the following until we get a result a second time
     ¤              The following as a nilad
  ØW                  [A-Za-z0-9_]
    Ṗ                 Remove last element (_)
f€                  Filter the left argument (current result) with the above nilad
       €            Left map
      L               Length
        Ġ           Group indices of same values, sort values
          ⁸         Left argument
         ị          Index on ^^ and ^
            €       Left map
           Ẏ          Concatenate elements
                Y Join on newlines (full program will display correctly)

1

Pyth,22个字节

jlDusM.glkG@Ls++GrG1UT

在这里尝试。

说明:

jlDusM.glkG@Ls++GrG1UT
j                      join on newlines
 lD                     sort by length
   u                     run until duplicate result, return result (argument G, iteration number H)
    sM                    map concatenate elements
      .g                   group elements by function (argument k)
        l                   length
         k                   k
          G                 G
           @L             left map filter on presence (extra argument first)
             s             concatenate elements
              +             concatenate two items
               +             concatenate two items
                G             G (default = lowercase alphabet)
                 r 1          to uppercase
                  G            G
                    U        unary range [0..n)
                     T        T (default = 10)

1

Pyth,39个字节

回到打高尔夫球!

有程序:

=Qm:d"[\W_]"kQKYLmsd.glkolNb;WnKQ=KQ=yQ;jQ

=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j

在这里测试!

说明

=Qm:d"[\W_]"kQLmsd.glkolNb;WnYQ=YQ=yQ;j       (Implicit) Assign evaluated imput to Q (In this case, an array)
=Q                                            Reassign a value to Q
  m          Q                                map a function over Q
   :d"[\W_]"k                                 Replace any special character with an empty string
              L           ;                   Declare a function y(b)
                      olNb                      Sort b by length
                  .glk                          Group strings of same length in arrays
               msd                              Concat each inner array
                           WnYQ      ;        While Y != Q (previous array is not equal to current array)
                               =YQ              Assign the current array to Y (Y=Q)
                                  =yQ           Assign y(Q) to Q (Q=yQ). Here, the assigned variable name is implicit
                                      j       Display the resulting array

尝试使用RL不是m
Leaky Nun

1

Java 8,268字节

接受可变变量的空lambda List<String>(即,工具addremove;例如ArrayList)。输出被输出到标准输出,以换行符分隔,尾随换行符。投放到Consumer<List<String>>

l->{int i=0,z;while(i<l.size())l.set(i,l.get(i++).replaceAll("\\W| ",""));while(l.size()>0){l.sort((s,t)->s.length()-t.length());String s=l.remove(0);for(i=0,z=s.length();l.size()>0&&l.get(0).length()==z;i++)s+=l.remove(0);if(i<1)System.out.println(s);else l.add(s);}}

在线试用

结果比我预期的要长得多。正如凯文(Kevin)所观察到的那样,它比乍看之下要复杂得多。

非高尔夫λ

l -> {
    int i = 0, z;
    while (i < l.size())
        l.set(i, l.get(i++).replaceAll("\\W| ", ""));
    while (l.size() > 0) {
        l.sort((s, t) -> s.length() - t.length());
        String s = l.remove(0);
        for (
            i = 0, z = s.length();
            l.size() > 0 && l.get(0).length() == z;
            i++
        )
            s += l.remove(0);
        if (i < 1)
            System.out.println(s);
        else
            l.add(s);
    }
}

首先,我将输入减少为字母和数字。然后,我按长度分组处理输入。我将项目追加到列表中的第一个项目,直到达到下一个长度,然后将其删除。如果仅使用第一个元素,则它将是该长度的唯一字符串,因此将其打印出来。否则,将连接的字符串添加到列表中以进行另一次迭代。我在使用前按每次迭代的长度对列表进行排序。

我从一个可爱的解决方案开始,该解决方案使用优先级队列来跟踪中间字符串。不幸的是,java.util.PriorityQueue<String>它相当长(并且使用原始类型的时间更长),所以不得不去。


1

Japt v2.0a1,11 -h个字节

输入和输出为字符串数组。

£=mk\W üÊmq

尝试一下

£=mk\L üÊmq
                :Implicit input of string array U
£               :Map
  m             :  Map U
   k            :    Remove
    \W          :    /[^A-Z0-9]/gi
       ü        :  Sort & partition by
        Ê       :    Length
         m      :  Map
          q     :    Join
 =              :  Reassign to U for next iteration
                :Implicit output of last element

尽管我当时忘记为它添加测试用例(现在将添加一个),但数字也应保留在字符串中(以[a-zA-Z0-9]代替[a-zA-Z])。
凯文·克鲁伊森

@KevinCruijssen,已修复
毛茸茸的

1

JavaScript,119个字节

我觉得这应该短得多...

在输出中包括2条领先的换行符。

f=s=>s==(s.replace(/[^\w\n]|_/g,t=``).split`
`.sort((x,y)=>x[l=`length`]-y[l]).map(x=>t+=s==(s=x[l])?x:`
`+x),t)?t:f(t)

在线尝试


负字符范围似乎带有全局标志,因此您可以在g118
Jan

@Jan,看这里
Shaggy

然后必须是递归,仍然可以删除全局标志
Jan


1

Perl 6 6,85个字节

{.&([o] {my@a;@a[+.comb]~=$_ for $_;@a.grep(~*)}xx$_).sort(+*.comb)}o*.map:{S:g/\W//}

在线尝试!

输入和输出为字符串列表。


1

Pyth,21个字节

jusM.glkG:R"[^\w\d]"k

输入是字符串列表。在线试用这里,或验证所有的测试用例这里

jusM.glkG:R"[^\w\d]"kQ   Implicit: Q=eval(input()), k=""
                         Trailing Q inferred
          R          Q   For each string in Q...
         : "[^\w\d]"     ... replace non-alphanumerics...
                    k    ... with k (empty string)
 u                       Repeat the following until a fixed point occurs, current as G:
    .g  G                  Group the elements of G...
      lk                   ... by length
                             Groups ordered by the result of the inner function, i.e. length
                             This means that, in the final iteration, this acts as a sort by length
  sM                       Concatenate each group back into a string
j                        Join the resulting list on newlines, implicit print

0

05AB1E,16 个字节

εžKÃ}»Δ¶¡é.γg}J»

输入为字符串列表。

在线尝试验证所有测试用例

εžKÃ}Δé.γg}J}»if Δ可以是14个字节,也可以与字符串列表一起使用。

说明:

ε   }            # Map the (implicit) input-list of strings:
 žjà             #  Leave only the letters and digits of each string
                 #   i.e. ["a","bc","d!","123"] → ["a","bc","d","123"]
     »           # Join the list by newlines to a single string
                 #  i.e. ["a","bc","d","123"] → "a\nbc\nd\n123"
      Δ          # Loop until the string no longer changes:
       ¶¡        #  Split by newlines
                 #   i.e. "a\nbc\nd\n123" → ["a","bc","d","123"]
          }    #  Group the strings by:
           g     #   Their length
                 #    i.e. ["a","bc","d","123"] → [["a,"d"],["bc"],["123"]]
             J   #  Join each group-list to a single string
                 #   i.e. [["a,"d"],["bc"],["123"]] → ["ad","bc","123"]
              »  #  Join this list by newlines again
                 #   i.e. ["ad","bc","123"] → "ad\nbc\n123"
                 # (and the result is output implicitly after the loop)
                 #  i.e. "123\nadbc"

-1

Powershell,Windows 10,63字节

所以输入...

$n = @"
This is a sample text,
that you will have to use to build stairs.
The wood may be of excellent quality,
or pretty crappy almost falling apart and filled with termites.
Bla bla bla - some more text
Ok, that will do
"@

和代码...

((($n -Split '\n').Replace(" ","")) -Replace '[\W]','')|Sort *h

涵盖了输入/输出1,在2和3上工作...


欢迎来到PPCG!我们通常不允许通过设置变量来输入。您要么必须创建带有参数的函数,要么必须从STDIN,命令行arg或类似输入中获取输入。
斯蒂芬

1
欢迎来到PPCG!除了@StepHen所说的以外,对于特殊情况,您当前的答案也会失败。它只会将所有内容放在一起并进行一次排序,但不会将等大小的行合并在一起并再次进行排序。(请参见测试案例2。)
Kevin Cruijssen
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.