字符串压缩和排序


14

给定一个字符串列表,输出一个单个字符串,该字符串是通过从每个位置的每个字符串中提取一个字符,然后按ASCII序号对其进行排序,然后将它们附加到输出字符串中而形成的。换句话说,对于n输入字符串,n输出的第一个字符将是按顺序排序的每个输入的第一个n字符,输出的第二个字符将是按顺序排序的每个输入的第二个字符,因此上。您可以假设这些字符串的长度均相等,并且至少会有一个字符串。所有字符串将仅由ASCII可打印字符组成(序号32-127)。

Python中的参考实现(在线尝试):

def stringshuffle(strings):
  res = ''
  for i in range(len(strings[0])):
    res += ''.join(sorted([s[i] for s in strings],key=ord))
  return res

例子:

"abc","cba" -> "acbbac"
"HELLO","world","!!!!!" -> "!Hw!Eo!Lr!Ll!Od"

规则

  • 禁止出现标准漏洞
  • 这是,因此最短答案以字节为单位

排行榜

这篇文章底部的堆栈摘录从答案a)生成了排行榜,a)是每种语言的最短解决方案列表,b)则是总体排行榜。

为了确保您的答案显示出来,请使用以下Markdown模板以标题开头。

## Language Name, N bytes

N您提交的文件大小在哪里。如果您提高了分数,可以将旧分数保留在标题中,方法是将它们打掉。例如:

## Ruby, <s>104</s> <s>101</s> 96 bytes

如果您想在标头中包含多个数字(例如,因为您的分数是两个文件的总和,或者您想单独列出解释器标志罚分),请确保实际分数是标头中的最后一个数字:

## Perl, 43 + 2 (-p flag) = 45 bytes

您还可以将语言名称设置为链接,然后该链接将显示在代码段中:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

Answers:


11

GS2,4个字节

*Ü■/

这将从STDIN中读取字符串,并用换行符分隔。

源代码使用CP437编码。在线尝试!

测试运行

$ xxd -r -ps <<< '2a 9a fe 2f' > zip-sort.gs2
$ echo -e 'HELLO\nworld\n!!!!!' | gs2 zip-sort.gs2 
!Hw!Eo!Lr!Ll!Od

怎么运行的

*       Split the input into the array of its lines.
 Ü      Zip the resulting array.
  ■     Map the rest of the program over the resulting array.
   /        Sort.

6

Haskell,39 36字节

import Data.List
(>>=sort).transpose

用法示例:((>>=sort).transpose) ["HELLO","world","!!!!!"]-> "!Hw!Eo!Lr!Ll!Od"

转置字符串列表,sort在其上映射并连接结果字符串>>=列表(在list上下文中为concatMap)。


我想出了这个!
2015年

我没有; 我一直忘了利用Monad实例来处理列表。(+1)
ballesta25


5

TeaScript,9 个字节

_t¡ßlp¡)µ

TeaScript具有以所有错误方式实现的所有正确内置函数。

在线尝试

不打高尔夫球

_t()m(#lp())j``

说明

_t()        // Transposes input array
    m(#     // Loops through inputs
       lp() // Sorts characters by char code
     )
j``         // Joins back into string

@intrepidcoder对我来说很好。也许您的浏览器已经缓存了一些文件?也许清除缓存可能有用。我正在使用Safari。我将尝试刷新文件
Downgoat 2015年


4

Python,50 48字节

lambda x,y=''.join:y(map(y,map(sorted,zip(*x))))

感谢@xnor -2个字节!


4
您可以保存"".join到变量。
xnor

哦,我不知道。谢谢!
丹尼斯

4

JavaScript(ES6),57个字节

a=>a[0].replace(/./g,(c,i)=>a.map(w=>w[i]).sort().join``)

3

八度,15字节

@(a)sort(a)(:)'

例:

octave:1> (@(a)sort(a)(:)')(["abc";"cba"])
ans = acbbac
octave:2> (@(a)sort(a)(:)')(["HELLO";"world";"!!!!!"])
ans = !Hw!Eo!Lr!Ll!Od

2

朱莉娅46字节

x->(j=join)(map(i->j(sort([i...])),zip(x...)))

这将创建一个未命名的函数,该函数接受字符串数组并返回一个字符串。要给它起个名字,例如f=x->...

取消高尔夫:

function zipsort{T<:AbstractString}(x::Array{T,1})
    # Splat the input array and zip into an iterable
    z = zip(x...)

    # For each tuple consisting of corresponding characters
    # in the input array's elements, splat into an array,
    # sort the array, and join it into a string
    m = map(i -> join(sort([i...])), z)

    # Take the resulting string array and join it
    return join(m)
end

1

Minkolang 0.13,46字节

$od0Z2:$zIz:$xd0G2-[i1+z[di0c*+c$r]xz$(sr$Ok].

在这里尝试。期望输入像"HELLO""world""!!!!!"这样的(因此不加逗号)。

说明

$o     Read in whole input as characters
d      Duplicate top of stack (the ")
0Z     Count how often this appears in the stack
2:     Divide by two
$z     Store this in the register (z)
Iz:    Length of stack divided by z (k)
$x     Dump one element from the front/bottom of stack
d      Duplicate top of stack (which is k)
0G     Insert it at the front/bottom of stack
2-     k-2

  [                              Open for loop that repeats k-2 times
   i1+                           Loop counter + 1 (i)
      z[                         Open for loop that repeats z times
        d                        Duplicate top of stack (which is i)
         i                       Loop counter (j)
          0c                     Copy k from front of stack
            *                    Multiply (j*k)
             +                   Add (j*k + i)
              c                  Copy character at position j*k+i to the top
               $r                Swap top two elements of stack (so i is on top)
                 ]               Close for loop
                  x              Dump the top of stack (dump i)
                   z$(           Start a new loop with the top z elements
                      s          Sort
                       r$O       Reverse and output the whole (loop) stack as characters
                          k      Break - exits while loop
                           ].    Close for loop and stop

1

GolfScript,8个字节

~zip{$}%

Web GolfScript上在线尝试。

怎么运行的

~         # Evaluate the input.
 zip      # Zip it.
    {$}%  # Map sort ($) over the resulting array.

1

K,10个字节

,/{x@<x}'+

连接(,/)字符串列表的转置()中的({x@<x})每个()的种类。'+

实际上:

  ,/{x@<x}'+("HELLO";"world";"!!!!!")
"!Hw!Eo!Lr!Ll!Od"

很简单,但是这里K没有一个单字符排序函数,而是将该操作分为一个散布聚集索引运算符@和一个基元,该基元产生可以对列表进行排序的置换向量,因此有点受伤害<


1

C ++ 14,152字节

#include<iostream>
#include<regex>
[](auto s){for(int i=0;i<s[0].size();++i){auto r=""s;for(auto k:s)r+=k[i];std::sort(begin(r),end(r));std::cout<<r;}};

没有利用map + zip的任何优势(猜测原因)

脱胶+用法

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

int main()
{
    auto lambda = [](auto s)
    {
        for (int i = 0; i < s[0].size(); ++i)
        {
            auto r = ""s;
            for (auto k : s)
                r += k[i];
            std::sort(begin(r), end(r));
            std::cout << r;
        }
    };

    std::vector<std::string> data = { "HELLO", "world", "!!!!!" };
    lambda(data);
}

1

Mathematica,51个字节

""<>SortBy@ToCharacterCode/@Transpose@Characters@#&

Mathematica中的字符串操作非常昂贵。


1

Japt,12字节20

Ny m_q n q)q

在线尝试!

说明

Ny       // Transpose inputs
  m_     // Maps through each new string
    q    // Split string
    n    // Sort string
    q    // Join
)q       // Join again

1

的PHP92 91个字节

for($argv[0]='';$a=array_column(array_map(str_split,$argv),$i++|0);print join($a))sort($a);

在线尝试!

我相信可以通过不尝试使用PHP的内置数组函数来缩短操作时间,但必须尝试一下!

或85个字节

@ Night2的摆动,通过不尝试使用PHP的内置数组函数来缩短:

for(;''<$argv[1][$i++];print join($a))for($a=[];''<$a[]=$argv[++$$i][$i-1];sort($a));

在线尝试!


@ Night2做得很好!您应该将其发布为自己的。太糟糕了,array_column无法在字符串数组上使用,否则对CG有用得多。当然,跳过$argv[0]也总是很痛苦的……
640KB,

0

Clojure / ClojureScript,43个字节

#(apply str(mapcat sort(apply map list %)))

创建一个匿名函数。用ClojueScript REPL编写的,也应该是有效的Clojure。

在这里输入,然后通过致电(*1 ["HELLO" "world" "!!!!!"])。或先做(def f *1)再用(f ["abc" "cba"])


0

锡兰166

String z(String+l)=>String(expand(t(l).map(sort)));[T+]n<T>(T?+i)=>[for(e in i)e else nothing];{[X+]*}t<X>([{X*}+]l)=>l[0].empty then{}else{n(*l*.first),*t(l*.rest)};

尽管锡兰具有一个zip函数,但它只需要两个可迭代对象,而不是它们的一个可迭代对象。unzip另一方面,它需要一个可重复的元组,并且我不想将字符串转换为元组。因此,我实现了自己的转置函数,这受到Google 在某处为我找到的Haskell实现的启发。

// zip-sort
//
// Question:  http://codegolf.stackexchange.com/q/64526/2338
// My answer: ...

// Takes a list of strings (same length), and produces
// a string made by concatenating the results of sorting
// the characters at each position.
String z(String+ l) =>
        String(expand(t(l).map(sort)));

// Narrow an iterable of potential optionals to their non-optional values,
// throwing an AssertionError if a null is in there.
[T+] n<T>(T?+ i) =>
        [for (e in i) e else nothing];

// Transpose a nonempty sequence of iterables, producing an iterable of
// sequences.
// If the iterables don't have the same size, either too long ones are
// cut off or too short ones cause an AssertionError while iterating.
{[X+]*} t<X>([{X*}+] l) =>
        l[0].empty
        then {}
        else { n(*l*.first), *t(l*.rest) };

该类型的nt可以被更普遍定义,但是这是Codegolf ;-)(n是一个什么样的特殊情况下,我提议为assertNarrow两个星期前)。


0

Perl 6、33字节

{[~] flat ([Z] @_».comb)».sort}

用法示例:

say {[~] flat ([Z] @_».comb)».sort}(< abc cba >) # acbbca

my &code = my $code = {[~] flat ([Z] @_».comb)».sort}

say code "HELLO","world","!!!!!"; # !Hw!Eo!Lr!Ll!Od

say ((<cba abc>),(<testing gnitset gttseni>)).map($code);
# (acbbac ggtentiststteisenngit)



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.