重复项目组


10

挑战说明

给定一个项目列表/数组,显示所有连续重复项目的组。

输入/输出说明

您的输入是一个列表/项目数组(您可以假设所有项目都是同一类型)。您不需要支持您的语言所拥有的每种类型,而必须支持至少一种int类型(最好是,但是像这样的类型boolean,虽然不是很有趣,但是也可以)。样本输出:

[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]

至于空列表,输出是不确定的-可以是什么,也可以是空列表,也可以是例外-最佳地适合您的高尔夫目的。您也不必创建单独的列表列表,因此这也是一个非常有效的输出:

[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

1 1 1
2 2
3 3 3
4
9

重要的是要以某种方式使组分开。


也许我们输出的列表具有一些特殊的分隔符值?
xnor

@xnor:您能举个例子吗?int用例如s分隔的s 数组0将是一个坏主意,因为0输入中可以有s ...
shooqie

例如,[4, 4, '', 2, 2, '', 9, 9][4, 4, [], 2, 2, [], 9, 9]
xnor

实际上,我们必须支持哪些类型。元素本身可以列出吗?我想象某些语言具有无法打印的内置类型或奇怪的相等性检查。
xnor

@xnor:是的,这就是我担心的问题-如果您的输入中包含列表,那么使用空列表作为分隔符可能会造成混淆。因此,我添加了“您可以假定所有项目都属于同一类型”的原因,以便可以使用其他类型作为分隔符。
shooqie '16

Answers:




8

视网膜15 8字节

感谢Lynn建议使用更简单的I / O格式。

!`(.)\1*

将输入视为一个字符列表(并使用换行符分隔各个组)。

在线尝试!

这只是通过匹配组并全部打印它们(自动使用换行符)来工作。


我询问abbcccddda bb ccc ddd是可以接受的I / O格式,并且OP批准了它,所以我想!`(.)\1*很好吗?
林恩

@Lynn哦,这确实要简单得多,谢谢。
Martin Ender

4

JavaScript(ES6),39 37字节

f=
s=>s.replace(/(\w+) (?!\1\b)/g,`$1
`)
;
<input oninput=o.textContent=f(this.value);><pre id=o>

适用于任何以空格分隔的类似单词的标记。@ MartinEnder♦节省了2个字节。对于数组输入和返回,我能做的最好的是68:

a=>a.reduce((l,r)=>(l==r?c.push(r):b.push(c=[r]),r),b=[c=[a[0]]])&&b

1
我在56
edc65 '16

4

MATL,9字节

Y'v"@Z}Y"

Y'     % Take input. Run-length encoding. Gives two row arrays: values and run lengths
v      % Concatenate vertically   
"      % For each column
  @Z}  %   Push column and split into its two elements
  Y"   %   Run-length decoding
       % End for. Implicitly display

输入是一个由数字组成的行数组,以空格或逗号作为分隔符。

在线尝试!使用非整数测试。


MATL,11个字节

lidgvYsG7XQ

输入是一个数字字符的列数组,;用作分隔符。

在线尝试!任意数字测试。用字符测试。

l     % Push 1
i     % Take input, say [4;4;2;2;9;9]
d     % Consecutive differences of input: [0;-2;0;7;0]
g     % Convert to logical: gives 1 if consecutive entries were different: [0;1;0;1;0]
v     % Concatenate vertically with the initial 1: [1;0;1;0;1;0]
Ys    % Cumulative sum. Each value is a group label: [1;1;2;2;3;3]
G     % Push input again
7XQ   % Split into horizontal arrays as indicated by group labels: {[4 4];[2 2];[9 9]}
      % Implicitly display

3

gs2,2个字节

c-

在线尝试!

c是一个内置的分组分组工具,可以做到这一点,因此我们在STDIN上调用它(它是一个字符串,即一个字符列表),并获得一个字符串列表。可悲的是,结果与输入是无法区分的,因此我们需要添加分隔符!-(以空格连接)可以解决问题。

另一个答案是(CP437的2个字节),它简单地包装c成一个匿名函数。


2

Brachylog,13个字节

:{s.dl1}fs.c?

警告:这是非常低效的,您将在解释中理解原因。

这需要一个列表(例如[1:1:2:2:2])作为输入。列表中的元素几乎可以是任何东西。

说明

:{     }f       Find all ordered subsets of the Input with a unique element in them
  s.                Output is a subset of the input
    dl1             Output minus all duplicates has a length of 1 (i.e. one unique value)
         s.     Output is an ordered subset of those subsets
           c?   The concatenation of those subsets is the Input

这仅由于s - Subset统一的方式起作用:最小的集合位于末尾。因此,它发现连接到Input的第一件事是最长的运行时间,例如,[[1:1]:[2:2:2]]而不是例如[[1:1]:[2:2]:[2]]


2

J,13个字节

<;.1~1,2~:/\]

由于J不支持参差不齐的数组,因此将每次运行的等价元素装箱。输入是值的数组,输出是盒装数组的数组。

用法

   f =: <;.1~1,2~:/\]
   f 4 4 2 2 9 9
┌───┬───┬───┐
│4 4│2 2│9 9│
└───┴───┴───┘
   f 1 1 1 3 3 1 1 2 2 2 1 1 3
┌─────┬───┬───┬─────┬───┬─┐
│1 1 1│3 3│1 1│2 2 2│1 1│3│
└─────┴───┴───┴─────┴───┴─┘
   f 'ABBBCDXYYZ'
┌─┬───┬─┬─┬─┬──┬─┐
│A│BBB│C│D│X│YY│Z│
└─┴───┴─┴─┴─┴──┴─┘
   f 0
┌─┐
│0│
└─┘

说明

<;.1~1,2~:/\]  Input: s
            ]  Identify function to get s
       2       The constant 2
           \   Operate on each overlapping sublist of size 2
        ~:/      Are the two values unequal, 1 if true else 0
     1,        Prepend a 1 to it
<;.1~          Using the list just made, chop s at each index equal to 1 and box it
               Return this as the result

2

Dyalog APL,9 个字节

⊢⊂⍨1,2≠/⊢

参数
⊂⍨在分配
1在所述第一元件
,,然后
2≠/在那里随后对不同
的参数


2

Python 2,43个字节

p=-1
for x in input():print"|"[:x^p],x,;p=x

适用于布尔值列表。例:

>> [True,True,False,False,False,True,False,True,False]
 True  True | False  False  False | True | False | True | False

遍历输入列表,存储最后看到的元素。在与前一个元素不同的每个元素之前打印一个分隔条,并检查其按位异或^为0。初始化p=-1避免在第一个元素之前使用分隔符。


太糟糕groupby
真是

2

CJam,9个字节

两种解决方案:

{e`:a:e~}
{e`{(*}%}

在这里测试。

说明

e`   e# Run-length encode (gives a list of pairs [run-length value]).
:a   e# Wrap each pair in a singleton list.
:e~  e# Run-length decode each list.

要么

e`   e# Run-length encode.
{    e# Map this block over each pair...
  (  e#   Pull out the run length.
  *  e#   Repeat the list containing only the value that many times.
}%


2

MATL,8个 7字节

由于@Suever删除了1个字节

ly&Y'Y{

适用于整数/浮点数/字符/布尔值/独角兽点/其他虚构输入。
对于布尔值,输入为T/F,输出为1/0

在线尝试!


分组并重复

ly&Y'Y{
l          % push 1 onto the stack
 y         % duplicate the input
  &Y'      % run-length encoding (secondary output only)
     Y{    % break up array into cell array of subarrays

1

C#,117个字节

void f(List<String>m){Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));}

松散(不是真的)

    public static void f(List<String>m)
    {
        Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));
    }

1

Pyth,9个 7字节

mr9]dr8

感谢2个字节的@LeakyNun!

说明:

             input
     r8      run-length decode
m            for each...
   ]d        ...treat each run as standalone encoded form...
 r9          ...decode 
             print

旧答案,12个字节

hf.Am!t{dT./

忘记了内置的游程长度,但是我认为这是一个好的方法,所以我保留了它。

说明:

                input
          ./    all possible partitions
 f       T      filter by...
  .A            ...whether all groups of integers...
    m!t{d       ...have length one after deduplication
h               get the first element (first one has no adjacent [1,1] and [1])
                print

是7个字节
漏嫩

@LeakyNun哦,对了!这很酷。
busukxuan

1
我相信对6人
有用。– FryAmTheEggman

@FryAmTheEggman好滥用m
Leaky Nun

@FryAmTheEggman哇,我听不懂
busukxuan 2016年

1

Pyth36 35字节

VQIqNk=hZ).?=+Y]*]kZ=Z1=kN;t+Y]*]kZ

测试链接

编辑:解释:

                                      standard variables: Y=[], Z=0, k='', Q=input
VQ                                    iterate over input
  IqNk                                if the current entity is equal to k:
      =hZ)                            increase Z.
          .?                          else:
               ]*]kZ                  list of length Z filled with k
            =+Y                       add it to Y
                    =Z1               set Z to 1
                       =kN            set k to the current entity
                          ;           end loop
                              ]*]kZ   list of length Z filled with k
                            +Y        add it to Y
                           t          implicitly print the tail of Y (removing the first element)

1

视网膜24 22字节

2字节感谢Martin Ender。

一个15字节的答案已经存在,因此这只是另一种花费更多字节的方法。

S-`(?<=(\d+)) (?!\1\b)

在线尝试!

它在前面的数字与前面的数字不同的空格上分割。

这是环视的演示。


1

05AB1E,13个字节

¬svyÊi¶}yðJ?y

解释

¬s             # push first element of list to stack and swap with input
  v            # for each X in input
   yÊi¶}       # if X is different from last iteration, push a newline
        yðJ?   # push X followed by a space to stack and join stack to string
            y  # push X to stack for next iterations comparison

应该适用于任何列表。
在int和char上测试。

在线尝试


1

迅捷,43个字节

var p=0;i.map{print($0==p ?"":",",$0);p=$0}

假设我是一个相等的对象数组;适用于从整数到字符串再到自定义对象的所有内容。有点厚脸皮,因为输出包含许多换行符,但使该页面更漂亮将花费字节。

更漂亮的非高尔夫版本:

var prev = Int.max // unlikely to be the first element, but not the end of the world if it happens to be.
i.map { n in
    print(n == prev ? " " : "\n•", n, terminator: "")
    prev = n
}

此版本将每个组打印在新行上,但要花费更多代码。

改善思路

i.reduce(0){print($0==$1 ?"":"•",$1);return $1}

这个版本有47个字节,但这是一种不同的方法,所以也许还有一些要优化的地方?最大的问题是return语句。


1

C,88 77字节

移动 strmcmp 内部 printf 节省11个字节

f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}

用法:

f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
main(c,v)char**v;{f(v);}

样本输入:

(命令行参数)

1 1 1 1 2 2 2 2 3 3 3 3 4 5 6 7777

样本输出:

1 1 1 1
2 2 2 2
3 3 3 3
4
5
6
7777

经过测试:

gcc 4.4.7 (Red Hat 4.4.7-16)  - OK
gcc 5.3.0 (Cygwin)            - Segmetation Fault
gcc 4.8.1 (Windows)           - OK

我正在尝试修复5.3.0隔离错误。

88版本

f(char**a){*a++;char*x;for(;*a;x=*a++)strcmp(*a,x)?printf("\n%s ",*a):printf("%s ",*a);}

1

Java 134字节

void a(String[]a){int i=0,l=a.length;for(;i<l-1;i++)System.out.print(a[i]+((a[i].equals(a[i+1]))?" ":"\n"));System.out.print(a[l-1]);}

进行迭代,并确定是用新行还是空格分隔。


对于初学者,您可以删除publicstatic关键字。您也可以在for循环中删除大括号
user902383 '16

完成@ user902383
Rohan Jhunjhunwala

1

ListSharp,134个字节

STRG l = READ[<here>+"\\l.txt"]
[FOREACH NUMB IN 1 TO l LENGTH-1 AS i]
{
[IF l[i] ISNOT l[i-1]]
STRG o=o+"\n"
STRG o=o+l[i]
}
SHOW = o

ListSharp不支持功能,因此该数组保存在一个名为本地文件中 l.txt 文件



0

TSQL,132个字节

这与其他答案略有不同-sql没有数组,sql的明显输入是表。

打高尔夫球:

DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT REPLICATE(v+' ',COUNT(*))FROM(SELECT i,i-row_number()over(partition
by v order by i)x,v FROM @)z GROUP BY x,v ORDER BY max(i)

取消高尔夫:

DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT
  REPLICATE(v+' ',COUNT(*))
FROM 
  (
     SELECT
       i,
       i-row_number()over(partition by v order by i)x,
       v
     FROM @
  )z
GROUP BY
  x,v
ORDER BY
  max(i)

小提琴



0

Pyke,2个字节(非竞争性)

仅支持整数

$f

在这里尝试!

split_at(input, delta(input))

添加了split_at节点,当第二个参数为true时拆分输入


0

sed,33 23 + 1 = 24字节

s/([^ ]+)( \1)* */&\n/g

它需要-r选项。

用法示例:

$ echo '1 1 1 2 2 3 3 3 4 9 9' | sed -r 's/([^ ]+)( \1)* */&\n/g'
1 1 1 
2 2 
3 3 3 
4 
9 9

0

JavaScript(ES6),56

输入:数字或字符串数​​组

输出:数组数组

第一次在高尔夫代码中使用精确比较

a=>a.map(x=>x!==p?o.push(g=[p=x]):g.push(x),p=o=g=[])&&o

0

Clojure,19个字节

#(partition-by + %)

它是内置的,但是具有映射功能。在这种情况下,+用作身份功能。


0

Javascript(使用外部库)(178字节)

(s)=>_.From(s).Aggregate((t,e)=>{if(0===t.Items.length)return t.Items.push([e]),t;var s=t.Items[t.Items.length-1];return s[0]===e?(s.push(e),t):(t.Items.push([e]),t)},{Items:[]})

免责声明:我正在使用编写的库从C#到JS实现LINQ。并不能完全帮助我赢球,但是哦

图片

图片2

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.