将字符串拆分为n个(或长度为n的片段)


11

挑战

在此挑战中,您必须根据输入的顺序执行两个不同(但相关)的任务。
您的程序将接收一个字符串s和一个整数n作为输入,并将

  • 分裂s成长度的片段n,如果s是第一位。如果需要,最后一个元素将更短。
  • 分割sn相等长度的块,如果n是第一位。如果len(s)不是,n则第一个len(s) mod n元素的倍数将更长。

您只能接受这2个输入。s永远不会只包含数字。

笔记

  • 您可以使用反向映射。如果这样做,请在您的答案中注明。
  • s将仅包含可打印的ASCII字符(无换行符)。
  • 您可能不使用任何直接解决这两个任务的内置程序。允许所有其他内置程序。
  • 您必须从同一来源获得两个参数。
  • 您可以采用有序列表或其他任何可以清楚表明其顺序的格式来表示参数,只要它们是明确的即可。
  • 您可以将输入作为一个字符串/流,并使用不是有效输入的字符(如空字节)来分隔它们。
  • n将始终等于或小于长度s且大于零。
  • 您可以以任何合理的格式输出结果列表,只要它能清楚表明特定的部分及其顺序即可。

输入: programming, 3
最后一个元素仅包含2个字符,因为11不能被3整除。
输出: ["pro", "gra", "mmi", "ng"]

输入: 3, programming
11不是3的倍数,因此前2个元素将更长:
输出: ["prog", "ramm", "ing"]

规则

测试用例

Pyth程序生成了测试用例(使用内置函数,因此没有有效答案)。感谢@FryAmTheEggman提供的基本版本!

3,helloworld-> ['hell','owo','rld']
helloworld,3-> ['hel','low','orl','d']
1,编程-> ['编程']
编程,1-> ['p','r','o','g','r','a','m','m','i','n','g']
8,编程-> ['pr','og','ra','m','m','i','n','g']
编程,8-> ['programm','ing']
9,代码高尔夫-> ['c','o','d','e',','g','o','l','f']
代码高尔夫,9-> ['代码高尔夫']
4,133峰值-> ['133','ts','pe','ak']
133峰值,4-> ['133t','spea','k']

编码愉快!


您不得使用任何可解决这两个任务的内置程序。是否包括其他内置函数,例如从字符串中获取第n个字符在出现时进行拆分
丹尼斯

@Dennis这只是要排除直接解决此问题的内建函数。我澄清了
Denker

如果我们的语言不支持数组,我们应该如何输出?字符串的每个结果之间的换行符是否可以接受?
科纳·奥布莱恩

另外,对于输入是模棱两可的数字数组的语言,该过程应该是什么?
科纳·奥布莱恩

@CᴏɴᴏʀO'Bʀɪᴇɴ不可能发生。永远不会只包含数字。此外,您可以输出任何合理的格式生成的列表中,只要它清楚地表明的特定部件和它们的顺序其中当然包括多输出。
Denker

Answers:


3

MATL,46 26 21 27 29 42字节

jtU?jtbUe!tn2Gn>?0t(]tgbw(}ie]!2t$X{Oc''Zt

在线尝试!(稍作更新以使用该语言的最新版本)

说明

j           % Explicitly grab the first input as a string
t           % Duplicate
U           % Attempt to convert it to a number
?           % If the conversion to a number was successful
    j       % Explicitly grab the second input as a string
    t       % Duplicate the value
    b       % Bubble-up the first element in the stack
    U       % Convert to a number from a string
    e       % Reshape the string into a nGroup x nPerGroup matrix
    !       % Take the transpose
    t       % Duplicate the result
    n       % Number of characters in the repmat result
    2Gn     % Number of characters in the string
    >?      % If chars in repmat > chars in string
        O   % Zero
        t   % Duplicate 
        (   % Assign the last element to a null character (bug in MATL)
    ]       % End if statement
    t       % Duplicate this matrix
    g       % Convert to a logical matrix
    b       % Bubble-up the original string
    w       % Flip the top two elements
    (       % Assign the non-empty characters to the chars from the input string
}           % Else the string comes first
    i       % Explicitly grab the second input (the number)
    e       % Reshape the characters into an nPerGroup x nGroup 2D array
]           % End of if statement
!           % Take the transpose so it reads left-to-right
2           % Number literal
t           % Duplicate
$X{         % Call num2cell to convert to a cell array
Oc          % Null character
''          % Empty string
Zt          % Replace null chars with empty strings
            % Implicit display of stack contents

在某些列表元素末尾出现的那些不可打印的内容是什么?这些都不是输入的一部分,因此也不应该是输出的一部分。
Denker

难道不是e内置的吗?
FliiFe

也许取代XUZN?...U?...和交换两个if分支。此外,您不需要3$
Luis Mendo

@DenkerAffe抱歉。现在应该修复。
Suever 2016年

@FliiFe根据最初帖子中的评论,e并不能直接解决问题,所以我不认为它是禁止的,不。
Suever,2016年

4

JavaScript(ES6),132个字节

(s,t)=>+t?[...Array(-~(~-s.length/+t))].map((_,i)=>s.substr(i*t,t)):[...Array(s=+s)].map(_=>t.slice(p,p-=~((t.length-p-1)/s--)),p=0)

这可能是无可救药的过度设计。


好吧,我(已故)的解决方案设计得很差。为您+1
edc65 '16

4

JavaScript(Firefox),88 87字节

a=>b=>(s=+b?a:b,i=x=0,l=s.length,[for(c of s)if(r=s.slice(x,x+=+b||l/a+(i++<l%a)|0))r])

(...)("programming")(3)使用Firefox 30+ 一样调用它。


2

Ruby,119个字节

->x,y{r=[t=0];x.to_s==x ?(r.push x[t...t+=y]while x[t]):x.times{r.push y[t...t+=y.size/x+(r[y.size%x]? 0:1)]};r[1..-1]}

而且我以2个字节排在第一位...


Ruby中的Regex对象可以使用与字符串相同的方式向其中注入值,因此x.scan(/.{,#{y}})在第一种情况下拆分字符串也同样有效。还是算作内置的?
价值墨水

2

AWK,121 130 128 122个字节

$1~/^[0-9]+$/{s=1}{a=$(s+1)
b=s?$1:$2
$0=""
for(j=-b;j<=c=length(a);)$0=$0 substr(a,j+=b+s,b+(s=s&&j<c%b*(b+1)?1:0))" "}1

唯一的问题是,如果第一个条目是一个以数字开头的字符串。这将导致AWK将字符串视为该数字,将第二个条目视为该字符串。

OK ...解决了数字问题,但增加了9个字节:(。

重做一点以节省几个字节。

几乎恢复到原来的长度。:)


好的,@DenkerAffe,将其修复为可以正常使用,并且仅(最终)添加了1个字节。
罗伯特·本森

1

Haskell,131个字节

import Data.Lists
q(d,m)=splitPlaces$(d+1<$[1..m])++[d,d..]
a#b|all(`elem`['0'..'9'])a=q(divMod(length b)$read a)b|1<2=q(read b,0)a

用法示例:

*Main> "8" # "programming"
["pr","og","ra","m","m","i","n","g"]
*Main> "programming" # "8"
["programm","ing"]

工作原理:主要工作是通过helper函数完成的,该函数q需要一对数字(d,m)和一个字符串s。它首先建立一个时间列表,然后是无数m次(例如-> )。然后,它用于拆分列表给定长度的块。如果元素用完,则停止,因此可以使用无限列表。d+1d(1,3)[2,2,2,1,1,1,1,1,...]splitPlacesssplitPlacess

main函数#检查哪个参数是数字n/字符串,str然后q使用(div (length str) n, mod (length str) n)or或(n, 0)plus进行调用str


0

C#(LINQPAD)-335字节

var y=Util.ReadLine().Split(',');int x,j=0;var t=int.TryParse(y[0].Trim(),out x);x=x==0?int.Parse(y[1].Trim()):x;var i=t?y[1].Trim():y[0];var z="";if(!t){while(i.Substring(j).Length>x){z+=i.Substring(j).Length>x?i.Substring(j,x)+", ":"";j+=x;}z+=i.Substring(j);}else z=string.Join(", ",i.Split(x).Select(s=>string.Concat(s)));z.Dump();

输入读取部分占用了一些空间。最长答案的获胜者。

用法1:

$ 3, helloworld

>> hell, owo, rld

用法2:

$ helloworld, 3

>>hel, low, orl, d

哦,这是什么?
本杰明·厄克特

0

Pyth,181个字节

让我们假设最长的代码以字节为单位胜出\ o /

DyGK@G0J:@G1"."1=YJV%lJKW<l@YN.EclJK=YXYN+@YN@YhN=Y.DYhN)FNr%lJK/-lJ%lJK/-lJ%lJKKW<l@YNsclJK=YXYN+@YN@YhN=Y.DYhN))RY)DPG=K@G1=J:@G0"."1=YJV/lJKW<l@YNK=YXYN+@YN@YhN=Y.DYhN))RY).xyQPQ

在这里尝试!(在线解释器似乎有一个错误,它会显示输入,而不应显示)

这是终端的输出:

» pyth split.pyth <<<'["helloworld", 3]' 
['hel', 'low', 'orl', 'd']
» pyth split.pyth <<<'[3, "Helloworld"]'
['Hell', 'owo', 'rld']

认真地说,我愿意接受新方法。我是python的新手,所以我可能错过了一些速记。

我的意思是,我认为我的答案与javascript答案相比要更长一些……


您可以提供样本输入和输出吗?
Leaky Nun

注意标题下的官方解决方案testcases。测试用例由Pyth生成。解决方案是.xcsJKcJsK,其中JK是两个参数。
Leaky Nun

@KennyLau我添加了一个指向在线pyth解释器的链接。奇怪的是,它也输出输入,而我确定昨天还没有...将尝试解决该问题。
FliiFe

使用空格来抑制打印
Leaky Nun

@KennyLau空间在哪里?
FliiFe

0

PHP,114字节

[$t,$n,$p]=$argv;for(@+$p?$s=$n:$f=$n*($p=strlen($s=$p)/$n)%$n;$t;)echo$t=substr($s,$a+=$e,$e=$p+($i++<$f)|0),"
";
  • 字符串不应以数字开头。
    (替换+@$pis_numeric($p)于修复。)
  • 输出不应包含块“ 0”。
    ~为可打印的ASCII 插入,a&$t;修复前的任何ASCII 插入。)
  • 运行-nr在线尝试

0

PowerShell中122个 118字节

param($a,$b)if($a-is[int]){$a,$b=$b,((($l=$b|% Le*)-($c=$l%$a))/$a)}$a-split("(..{$b})"*$c+"(.{0,$b})"*$a.Length)-ne''

在线尝试!

少打高尔夫球:

param($a,$b)
if($a-is[int]){
    $length=$b|% Length
    $c=$length%$a
    $a,$b=$b,(($length-$c)/$a)  # recalc length and swap
}
$pattern="(..{$b})"*$c+"(.{0,$b})"*$a.Length
$parts=$a -split $pattern       # pattern like '(..{3})(..{3})(.{0,3})(.{0,3})(.{0,3})'
$parts -ne ''                   # output not empty parts
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.