46

挑战

将输出莫里斯数列的按字符计数的最短代码。莫里斯数列,也称为Look-and-say数列,是一个以如下开头的数列:

1, 11, 21, 1211, 111221, 312211, ...

您可以无限生成序列(即,您不必生成特定数字)。

I/O 期望

该程序不需要接受任何输入(但接受输入的奖励积分,从而提供从任意起点或数字开始的选项)。至少你的程序必须从1.

至少期望输出是序列:

1
11
21
1211
111221
312211
...

额外学分

如果您要获得额外的学分,则需要执行以下操作:

$ morris 1
1
11
21
1211
111221
312211
...

$ morris 3
3
13
1113
3113
132113
...
4

41 回答 41

15

GolfScript - 41(额外学分:40)

1{.p`n+0:c:P;{:|P=c{c`P|:P!}if):c;}%~1}do
{~.p`n+0:c:P;{:|P=c{c`P|:P!}if):c;}%1}do

什么?
获取序列中下一个数字的过程:将当前数字转换为字符串,添加换行符并循环遍历字符。对于每个数字,如果前一个数字P相同,则递增计数器c。否则,将c和添加P到下一个数字,然后更新这些变量。我们附加的换行符允许将最后一组数字添加到下一个数字。

可以通过查看 GolfScript 文档获得确切的详细信息。(请注意,|它用作变量。)

于 2010-10-12T08:48:52.363 回答
14

哈斯克尔:115 88 85

import List
m x=do a:b<-group x;show(length b+1)++[a]
main=mapM putStrLn$iterate m"1"

这是无限序列。我知道它可以改进很多 - 我对 Haskell 还很陌生。

更短一点,内联 mapM 并迭代:

import List
m(a:b)=show(length b+1)++[a]
f x=putStrLn x>>f(group x>>=m)
main=f"1"
于 2010-10-11T19:15:06.157 回答
13

Perl(46 个字符)

$_="1$/";s/(.)\1*/length($&).$1/eg while print

额外学分(52 个字符)

$_=(pop||1).$/;s/(.)\1*/length($&).$1/eg while print
于 2010-10-11T22:31:58.897 回答
10

Javascript 100 97

for(x=prompt();confirm(y=x);)for(x="";y;){for(c=0;y[c++]&&y[c]==y[0];);x+=c+y[0];y=y.substr(c--)}

允许中断序列(通过单击“取消”),因此我们不会锁定用户代理并锁定 CPU。它还允许从任何正整数开始(额外信用)。

现场示例:http: //jsbin.com/izeqo/2

于 2010-10-11T20:35:50.400 回答
9

Perl,46 个字符

$_=1;s/(.)\1*/$&=~y!!!c.$1/ge while print$_,$/

额外学分,51 个字符:

$_=pop||1;s/(.)\1*/$&=~y!!!c.$1/ge while print$_,$/
于 2010-10-11T18:33:19.377 回答
9

Mathematica - 62 53 50 个字符 - 包括额外的学分

编辑:40个字符......但从右到左:(

奇怪的是,如果我们从右到左读取序列(即 1、11、12、1121、..),40 个字符就足够了

NestList[Flatten[Tally /@ Split@#] &, #2, #] &

那是因为 Tally 生成了一个列表 {elem,counter} !

编辑:50个字符

NestList[Flatten@Reverse[Tally /@ Split@#, 3] &, #2, #] &

解剖:(向上阅读评论)

NestList[               // 5-Recursively get the first N iterations
    Flatten@            // 4-Convert to one big list
       Reverse          // 3-Reverse to get {counter,element}
          [Tally /@     // 2-Count each run (generates {element,counter})
               Split@#, // 1-Split list in runs of equal elements
                 3] &,
                     #2,// Input param: Starting Number 
                     #] // Input param: Number of iterations

编辑:重构

NestList[Flatten[{Length@#, #[[1]]} & /@ Split@#, 1] &, #2, #1] &

结束编辑 ///

NestList[Flatten@Riffle[Length /@ (c = Split@#), First /@ c] &, #2, #1] &

为了清楚起见,不需要/添加空格

调用

%[NumberOfRuns,{Seed}]

我第一次使用“Riffle”,将 {1,2,3} 和 {a,b,c} 组合成 {1,a,2,b,3,c} :)

于 2010-10-12T00:38:30.893 回答
8

蟒蛇,97 102 115

空白应该是制表符:

x='1'
while 1:
    print x;y=d=''
    for c in x+'_':
        if c!=d:
            if d:y+=`n`+d
            n,d=0,c
        n+=1
    x=y

例如:

$ python morris.py | head
1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211
于 2010-10-11T18:34:27.633 回答
8

这是我使用 LINQ 的 C# 尝试和 Code Golf 的第一次尝试:

C# - 205 194 211 198 字节,额外加分(包括 C# 样板文件)

using System.Linq;class C{static void Main(string[]a){var v=a[0];for(;;){var r="";while(v!=""){int i=v.TakeWhile(d=>d==v[0]).Count();r+=i;r+=v[0];v=v.Remove(0,i);}System.Console.WriteLine(r);v=r;}}}

可读版本:

static void Main(string[] args)
{
    string value = args[0];
    for (;;)
    {
        string result = "";
        while (value != "")
        {
            int i = value.TakeWhile(d => d == value[0]).Count();
            result += i;
            result += value[0];
            value = value.Remove(0, i);
        }
        Console.WriteLine(result);
        value = result;
    }
}

样本输出:

11
21
1211
111221
312211
13112221
1113213211
...
于 2010-10-12T00:35:24.820 回答
6

这是我的实现(在Prolog中):

带有 DCG 的 Prolog(174 个字符):

m(D):-write(D),nl,m(1,write(D),T,[nl|T],_).
m(C,D,T)-->[D],{succ(C,N)},!,m(N,D,T).
m(C,D,[G,D|T])-->[N],{G=write(C),G,D,(N=nl->(M-T-O=0-[N|R]-_,N);M-T-O=1-R-N)},!,m(M,O,R).

普通的 prolog,代码更易读(225 个字符):

m(D):-
  ((D=1->write(D),nl);true),
  m([], [1,D]).

m([], [C,D|M]):-
  write(C), write(D),nl,
  reverse([D,C|M],[N|X]),
  !,
  m([N|X],[0,N]).
m([D|T], [C,D|M]):-
  succ(C,N),
  !,
  m(T,[N,D|M]).
m([Y|T],[C,D|M]):-
  write(C), write(D),
  !,
  m(T,[1,Y,D,C|M]).

输出莫里斯序列:m(D)。其中 D 是“起始”数字。

于 2010-10-11T18:29:10.870 回答
6

Perl,67 个字符

包括-l国旗。

sub f{$_=pop;print;my$n;$n.=$+[0].$1while(s/(.)\1*//);f($n)}f(1)

Perl,72 个字符,额外加分

sub f{$_=pop;print;my$n;$n.=$+[0].$1while(s/(.)\1*//);f($n)}f(pop||1)
于 2010-10-11T18:37:51.577 回答
6

红宝石 - 52

s=?1;loop{puts s;s.gsub!(/(.)\1*/){"#{$&.size}"+$1}}

任务太简单了,也太失败了……

于 2010-10-12T07:26:47.653 回答
5

C,128 个字符

使用静态缓冲区,保证会导致分段错误

main(){char*c,v[4096],*o,*b,d[4096]="1";for(;o=v,puts(d);strcpy(d,v))for(c=d;*c;o+=sprintf(o,"%d%c",c-b,*b))for(b=c;*++c==*b;);}
于 2010-10-11T22:19:19.897 回答
4

爪哇

我第一次尝试“代码高尔夫”我只是在我的 IB CS 课程的一部分中把它放在一起:

238浓缩

浓缩:

String a="1",b="1",z;int i,c;while(true){System.out.println(b);for(c=0,i=0,b="",z=a.substring(0,1);i<a.length();i++){if(z.equals(a.substring(i,i+1)))c++;else{b+=Integer.toString(c)+z;z=a.substring(i,i+1);c=1;}}b+=Integer.toString(c)+z;a=b;}

正确格式化:

    String a = "1", b = "1", z;
    int i, c;

    while (true) {      
      System.out.println(b);

      for (c = 0, i = 0, b = "", z = a.substring(0, 1); i < a.length(); i++) {
        if (z.equals(a.substring(i, i + 1))) c++;
        else {
          b += Integer.toString(c) + z;
          z = a.substring(i, i + 1);
          c = 1;
        }
      }

      b += Integer.toString(c) + z;
      a = b;
    }
于 2010-10-11T18:26:18.750 回答
4

如果字符串只包含数字 1-3,并且不包含任何超过三个数字的运行,则调用字符串“Morris-ish”。如果初始字符串是 Morris-ish,则从它迭代生成的所有字符串也将是 Morris-ish。同样,如果初始字符串不是 Morris-ish,则生成的字符串不会是 Morris-ish,除非大于 10 的数字被视为数字组合(例如,如果 11111111111 被视为折叠为三个,而不是“十一”和一个)。

鉴于这一观察,从莫里斯种子开始的每次迭代都可以按照以下查找/替换操作序列完成:

111 -> 加利福尼亚州
11 -> 巴
1 -> AA
第222章
22 -> BB
2 -> AB
333 -> 抄送
33 -> 公元前
3 -> 交流
A -> 1
B -> 2
C -> 3

请注意,在上述替换之前,序列是 Morris-ish,每个生成对的第二个字符将不同于前后对的第二个字符;因此,序列中的相同字符不可能超过三个。

我想知道有多少不相交的莫里斯式序列?

于 2010-10-11T22:47:24.720 回答
4

Perl(额外学分),47 个字符

$_=pop.$/;{print;s/(.)\1*/$&=~y|||c.$1/ge;redo}
于 2010-10-12T02:20:34.010 回答
3

J,44 个字符,加分

(([:,#;.1@{:,.{:#{.)@(,:0<1,[:|2-/\]))^:(<9)

不幸的是,这只产生了 9 次迭代,但迭代次数<9可以调整为任何值。将其设置为a:生成无限序列,但显然无法打印。

用法:

   (([:,#;.1@{:,.{:#{.)@(,:0<1,[:|2-/\]))^:(<9) 1
1 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 0 0 0 0 0 0 0 0 0 0 0 0
2 1 0 0 0 0 0 0 0 0 0 0 0 0
1 2 1 1 0 0 0 0 0 0 0 0 0 0
1 1 1 2 2 1 0 0 0 0 0 0 0 0
3 1 2 2 1 1 0 0 0 0 0 0 0 0
1 3 1 1 2 2 2 1 0 0 0 0 0 0
1 1 1 3 2 1 3 2 1 1 0 0 0 0
3 1 1 3 1 2 1 1 1 3 1 2 2 1

   (([:,#;.1@{:,.{:#{.)@(,:0<1,[:|2-/\]))^:(<11) 4
4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
3 1 1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 3 2 1 1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 3 1 2 2 1 1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
3 1 1 3 1 1 2 2 2 1 1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 3 2 1 1 3 2 1 3 2 2 1 1 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 3 1 2 2 1 1 3 1 2 1 1 1 3 2 2 2 1 1 4 0 0 0 0 0 0 0 0
3 1 1 3 1 1 2 2 2 1 1 3 1 1 1 2 3 1 1 3 3 2 2 1 1 4 0 0 0 0
1 3 2 1 1 3 2 1 3 2 2 1 1 3 3 1 1 2 1 3 2 1 2 3 2 2 2 1 1 4
于 2010-10-12T18:06:14.127 回答
2

这是我第一次尝试代码高尔夫,所以请不要对我太苛刻!

PHP,128 122112 字节带开始标签

122 116106 个字节,没有开始标记和前导空格。

<?php for($a="1";!$c="";print"$a\n",$a=$c)for($j=0,$x=1;$a[$j];++$j)$a[$j]==$a[$j+1]?$x++:($c.=$x.$a[$j])&&$x=1;

(很遗憾我必须初始化$a为一个字符串,花费了我 2 个额外的字节,否则我不能在它上面使用索引符号。)

输出

$ php morris.php
1
11
21
1211
111221
312211
...

PHP(额外学分),133 127117 字节带开始标签

127 121111 个字节,没有开始<?php标记和前导空格。

<?php for($a=$argv[1];!$c="";print"$a\n",$a=$c)for($j=0,$x=1;$a[$j];++$j)$a[$j]==$a[$j+1]?$x++:($c.=$x.$a[$j])&&$x=1;

输出

$ php morris.php 3
3
13
1113
3113
132113
1113122113
...
^C
$ php morris.php 614
614
161114
11163114
3116132114
1321161113122114
1113122116311311222114
...

PHP(额外的学分),没有开始和结束标签

<?php

for ($a = $argv[1]; !$c = ""; print "$a\n", $a = $c)
{
    for ($j = 0, $x = 1; $a[$j]; ++$j)
    {
        // NB: this was golfed using ternary and logical AND operators:
        // $a[$j] == $a[$j + 1] ? $x++ : ($c .= $x . $a[$j]) && $x = 1;
        if ($a[$j] == $a[$j + 1])
        {
            $x++;
        }
        else
        {
            $c .= $x . $a[$j];
            $x = 1;
        }
    }
}

?>
于 2010-10-11T20:58:57.637 回答
2

德尔福

Delphi 是一种糟糕的高尔夫语言,但仍然:

var i,n:Int32;s,t,k:string;u:char;label l;begin s:='1';l:writeln(s);t:='';u:=s[1
];n:=1;for i:=2to length(s)do if s[i]=u then inc(n)else begin str(n,k);t:=t+k+u;
u:=s[i];n:=1;end;str(n,k);t:=t+k+u;s:=t;goto l;end.

这是211 个字节(它按原样编译)。

于 2010-10-12T01:06:30.873 回答
2

比索:111

我第一次尝试代码高尔夫,对结果非常满意。

for($x=1;;){echo$y=$x,"\n";for($x="";$y;){for($c=0;$y[$c++]&&$y[$c]==$y[0];);$x.=$c.$y[0];$y=substr($y,$c--);}}

给出:

> php htdocs/golf.php
1
11
21
... (endless loop)

PHP 加分:118

for($x=$argv[1];;){echo$y=$x,"\n";for($x="";$y;){for($c=0;$y[$c++]&&$y[$c]==$y[0];);$x.=$c.$y[0];$y=substr($y,$c--);}}

给出:

> php htdocs/golf.php 4
4
14
1114
3114
... (to infinity and beyond)
于 2010-10-12T18:19:52.107 回答
2

Java - 167 个字符(附赠)

(122 没有类/主要样板)


class M{public static void main(String[]a){for(String i=a[0],o="";;System.out.println(i=o),o="")for(String p:i.split("(?<=(.)(?!\\1))"))o+=p.length()+""+p.charAt(0);}}

使用换行符:

class M{
 public static void main(String[]a){
  for(String i=a[0],o="";;System.out.println(i=o),o="")
   for(String p:i.split("(?<=(.)(?!\\1))"))
    o+=p.length()+""+p.charAt(0);
 }
}
于 2010-10-13T00:04:41.917 回答
1

C++,310 个字符。

#include <iostream>
#include <list>
using namespace std;
int main(){list<int> l(1,1);cout<<1<<endl;while(1){list<int> t;for(list<int>::iterator i=l.begin();i!=l.end();){list<int>::iterator p=i;++i;while((i!=l.end())&&(*i==*p)){++i;}int c=distance(p,i);cout<<c<<*p;t.push_back(c);t.push_back(*p);}cout<<'\n';l=t;}}

正确缩进:

#include <iostream>
#include <list>
using namespace std;

int main() {
    list <int> l(1,1);
    cout << 1 << endl;
    while(1) {
        list <int> t;
        for (list <int>::iterator i = l.begin(); i != l.end();) {
            const list <int>::iterator p = i;
            ++i;
            while ((i != l.end()) && (*i == *p)) {
                ++i;
            }
            int c = distance(p, i);
            cout << c << *p;
            t.push_back(c);
            t.push_back(*p);
        }
        cout << '\n';
        l = t;
    }
}
于 2010-10-11T19:04:45.623 回答
1

C w/额外学分,242(或 184)

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define s malloc(1<<20)
main(int z,char**v){char*j=s,*k=s;strcpy(k,*++v);for(;;){strcpy(j,k);z=1;*k=0;while(*j){if(*j-*++j)sprintf(k+strlen(k),"%d%c",z,*(j-1)),z=1;else++z;}puts(k);}}

如果省略包含,您可以再保存约 60 个字符,gcc 仍将编译并带有警告。

$ ./a.out 11111111 | head
81
1811
111821
31181211
132118111221
1113122118312211
31131122211813112221
132113213221181113213211
111312211312111322211831131211131221
3113112221131112311332211813211311123113112211
于 2010-10-11T19:50:40.923 回答
1

蟒蛇 - 117

我的 python-fu 不强,所以我为此做了很多谷歌搜索。:)

a='1'
while 1:
 print a
 a=''.join([`len(s)`+s[0]for s in''.join([x+' '*(x!=y)for x,y in zip(a,(2*a)[1:])]).split()])

这个想法是使用 zip 生成 (a[i],a[i+1]) 对的列表,使用内部推导在 a[i]!=a[i+1] 时插入一个空格,加入将结果列表转换为字符串,并在空格上拆分,在此拆分列表上使用另一个推导式将每个元素替换为元素的运行长度和第一个字符,最后连接以获取序列中的下一个值。

于 2010-10-11T22:01:26.037 回答
1

Python - 98 个字符

from itertools import *
L='1'
while 1:print L;L=''.join('%s'%len(list(y))+x for x,y in groupby(L))

106 个字符作为奖金

from itertools import *
L=raw_input()
while 1:print L;L=''.join('%s'%len(list(y))+x for x,y in groupby(L))
于 2010-10-12T19:50:09.090 回答
1

C#,204 字节(256 有额外的学分)

我第一次尝试代码高尔夫

static void Main(){var v="1";for(;;){Console.Write(v + "\n");var r=v.Aggregate("", (x, y) => x.LastOrDefault()==y?x.Remove(0, x.Length-2)+(int.Parse(x[x.Length-2].ToString())+1).ToString()+y:x+="1"+y);v=r;}}

可读版,和别人不同的是我用的是Linq的Aggregate函数

static void Main(){
    var value="1";
    for(;;)
    {
        Console.Write(value + "\n");
        var result = value.Aggregate("", (seed, character) => 
                        seed.LastOrDefault() == character ? 
                            seed.Remove(seed.Length-2) + (int.Parse(seed[seed.Length-2].ToString())+1).ToString() + character
                            : seed += "1" + character
                    );
        value = result;
    }
}
于 2010-10-12T22:33:03.737 回答
1

Python - 92 个字符

98 加分

无限输出。我建议将输出重定向到文件,然后快速点击Ctrl+ C

x=`1`;t=''
while 1:
 print x
 while x:c=x[0];n=len(x);x=x.lstrip(c);t+=`n-len(x)`+c
 x,t=t,x

对于额外信用版本,请替换

x=`1`

x=`input()`
于 2010-10-14T06:09:15.697 回答
1

C - 120 个字符

129 加分

main(){char*p,*s,*r,x[99]="1",t[99];for(;r=t,puts(p=x);strcpy(x,t))
for(;*p;*r++=p-s+48,*r++=*s,*r=0)for(s=p;*++p==*s;);}

换行只是为了便于阅读。

当它出现段错误时(至少 15 次迭代后),这将停止。如果您的 C 库使用缓冲 I/O,那么在段错误之前您可能看不到任何输出。如果是这样,请使用以下代码进行测试:

#include<stdio.h>
main(){char*p,*s,*r,x[99]="1",t[99];for(;r=t,puts(p=x),fflush(stdout),1;
strcpy(x,t))for(;*p;*r++=p-s+48,*r++=*s,*r=0)for(s=p;*++p==*s;);}

这会fflush在每个输出之后添加一个。

Ungolfed,它看起来像这样:

int main(){
    char *p, *start, *result, number[99] = "1", temp[99];

    while(1){ /* loop forever */
        puts(number);

        result = temp; /* we'll be incrementing this pointer as we write */
        p = number;    /* we'll be incrementing this pointer as we read */

        while(*p){ /* loop till end of string */
            start = p; /* keep track of where we started */

            while(*p == *start) /* find all occurrences of this character */
                p++;

            *result++ = '0' + p - start; /* write the count of characters, */
            *result++ = *start;          /* the character just counted, */
            *result   = 0;               /* and a terminating null */
        }

        strcpy(number, temp); /* copy the result back to our working buffer */
    }
}

您可以在ideone上看到它的实际效果。

加上额外的功劳,代码如下所示:

main(){char*p,*s,*r,x[99],t[99];for(scanf("%s",x);r=t,puts(p=x);strcpy(x,t))
for(;*p;*r++=p-s+48,*r++=*s,*r=0)for(s=p;*++p==*s;);}
于 2010-10-14T07:26:54.563 回答
1

Common Lisp - 124 122 115 个字符

(do((l'(1)(do(a r)((not l)r)(setf a(1+(mismatch(cdr l)l))r(,@r,a,(car l))l(nthcdr a l)))))((format t"~{~s~}~%"l)))

带格式:

(do ((l '(1) (do (a r) ((not l) r) (setf a (1+ (mismatch (cdr l) l))
                                         r `(,@r ,a ,(car l)) l (nthcdr a l)))))
    ((format t "~{~s~}~%" l)))
于 2010-10-14T15:00:00.020 回答
1

F# - 135

let rec m l=Seq.iter(printf "%i")l;printfn"";m(List.foldBack(fun x s->match s with|c::v::t when x=v->(c+1)::v::t|_->1::x::s)l [])
m[1]

格式化代码

let rec m l=
    Seq.iter(printf "%i")l;printfn"";
    m (List.foldBack(fun x s->
        match s with
        |c::v::t when x=v->(c+1)::v::t
        |_->1::x::s) l [])
m[1]

仍然希望我能找到更好的方法来打印列表或使用 string/bigint 代替。

于 2010-10-23T02:44:36.650 回答
1

PHP 72 字节

<?for(;;)echo$a=preg_filter('#(.)\1*#e','strlen("$0"). $1',$a)?:5554,~õ;

该脚本可能会进一步优化。但由于我们在 PHPGolf ({http://www.phpgolf.org/?p=challenge&challenge_id=28}) 的序列完全相同,所以我保持这种方式。

于 2011-01-20T19:48:35.587 回答
0

C++, 264

#include <iostream>
#include <sstream>
#include <string>
using namespace std;int main(){string l="1\n";for(;;){ostringstream o;int e=1;char m;cout<<l;for(int i=1;i<l.size();i++){m=l[i-1];if(l[i]==m)e++;else if(e){if(m!='\n')o<<e<<m;e=1;}}l=o.str()+'\n';}return 0;}

有适当的缩进:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string l="1\n";
    for(;;)
    {
        ostringstream o;
        int e=1;
        char m;
        cout<<l;
        for(int i=1; i<l.size(); i++)
        {
            m=l[i-1];
            if(l[i]==m)
                e++;
            else if(e)
            {
                if(m!='\n')
                    o<<e<<m;
                e=1;
            }
        }
        l=o.str()+'\n';
    }
    return 0;
}

样本输出:

matteo@teoubuntu:~/cpp$ g++ morris.cpp -O3 -o morris.x && ./morris.x | head1
11
21
1211
111221
312211
13112221
1113213211
31131211131221
13211311123113112211

C++,276(有额外学分)

#include <iostream>
#include <sstream>
#include <string>
using namespace std;int main(){string l;getline(cin,l);for(;;){ostringstream o;int e=1;char m;l+='\n';cout<<l;for(int i=1;i<l.size();i++){m=l[i-1];if(l[i]==m)e++;else if(e){if(m!='\n')o<<e<<m;e=1;}}l=o.str();}return 0;}

有适当的缩进:

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main()
{
    string l;
    getline(cin,l);
    for(;;)
    {
        ostringstream o;
        int e=1;
        char m;
        l+='\n';
        cout<<l;
        for(int i=1; i<l.size(); i++)
        {
            m=l[i-1];
            if(l[i]==m)
                e++;
            else if(e)
            {
                if(m!='\n')
                    o<<e<<m;
                e=1;
            }
        }
        l=o.str();
    }
    return 0;
}

样本输出:

matteo@teoubuntu:~/cpp$ g++ morris.cpp -O3 -o morris.x && ./morris.x | head
7754 <-- notice: this was inserted manually
7754
271514
121711151114
1112111731153114
31123117132115132114
13211213211711131221151113122114
11131221121113122117311311222115311311222114
3113112221123113112221171321132132211513211321322114
132113213221121321132132211711131221131211132221151113122113121113222114
111312211312111322211211131221131211132221173113112221131112311332211531131122211311123113322114
于 2010-10-11T20:47:37.463 回答
0

C# 315 236228

好的,首先尝试代码高尔夫


static void Main(string[]args)
    {string o,s="1";int l=11;while(l-- >0)
    {Console.WriteLine(s);o="";while(s!=""){var c=s.Substring(0,1);int i=Regex.Match(s,"("+c+"*)").Length;o+=i.ToString()+c;s=s.Substring(i);}s=o;}}

这是带有换行符空格的来源> 8.9999999999


static void main( string[] args )
    {
        string sp = "1";
        string ou = "";
        int It = 11;
        while ( It-- > 0 )
        {

            Console.WriteLine(sp);
            ou = "";
            while ( sp != "" )
            {
                var c = sp.Substring(0, 1);
                int i = Regex.Match(sp, "(" + c + "*)").Length;
                ou += i.ToString() + c;
                sp = sp.Substring(i);

            }
            sp = ou;
        }
    }

额外学分

static void Main(string[]a)
{string o,s=a[0];int l=11;while(l-- >0)
{Console.WriteLine(s);o="";while(s!=""){var c=s.Substring(0,1);int i=Regex.Match(s,"("+c+"*)").Length;o+=i.ToString()+c;s=s.Substring(i);}s=o;}}
于 2010-10-11T22:54:04.107 回答
0

C#,140 个工作字符(177 171 个样板)

class C{static void Main(){var x="1\n";for(;;){System.Console.Write(x);var y="";for(int n,i=0;i<x.Length-1;y+=n+""+x[i],i+=n)n=x[i+1]!=x[i]?1:x[i+2]!=x[i]?2:3;x=y+"\n";}}}

该漏洞利用 Conway 的观察 (IIRC),即序列中不能出现大于 3 的数字。

        var x = "1\n";
        for (; ; )
        {
            Console.Write(x);
            var y = "";
            var i = 0;
            while (i < x.Length - 1)
            {
                var n = x[i + 1] != x[i] ? 1 : x[i + 2] != x[i] ? 2 : 3;
                y += n + "" + x[i];
                i += n;
            }
            x = y + "\n";
        }
于 2010-10-12T01:01:32.733 回答
0

Delphi,163 字节(166 额外)

对 Andreas Rejbrand 版本进行了重大修改。很好 str() 不检查参数类型,否则我必须转换 integer(s)-integer(u)。

var q,t,k:string;s,u:pchar;label l,z;begin t:='1';l:writeln(t);q:=t;s:=@q[1];
t:='';z:u:=s;while s^=u^do Inc(s);str(s-u,k);t:=t+k+u^;if s^=#0then goto l;
goto z;end.

额外的,改变 t:='1'; 到 t:=readln;

于 2010-10-12T11:55:42.860 回答
0

Javascript:87

这是受到BoltClock代码和我自己的 PHP 尝试的启发。

for(a="1";!(c="");alert(a),a=c)for(j=0,x=1;a[j];j++)a[j]==a[j+1]?x++:(c+=x+a[j])&&(x=1)

带有额外的Javascript:92

for(a=prompt();!(c="");alert(a),a=c)for(j=0,x=1;a[j];j++)a[j]==a[j+1]?x++:(c+=x+a[j])&&(x=1)

美化:

// Start with a=1, an set c to "" every start of the loop
// alert a and set a=c at the end of a loop
for (a = "1"; !(c = ""); alert(a), a = c)

  // Set iterator j to 0, set counter x to 1 at the initialisation
  // detect if a[j] exists at the start of the loop and incremement j at the end
  for (j = 0, x = 1; a[j]; j++)

    // check if the jth and (j+1)th characters are equal
    // if so, increment x,
    // if not, the end of a row is found, add it to c and set x to 1 again
    a[j] == a[j + 1] ? x++ : (c += x + a[j]) && (x = 1)
于 2010-10-12T22:02:16.347 回答
0

Clojure 111 个字符

(loop[a"1"](pr a)(let[x(reduce(fn[a b](str a(count(first b))(nth b 1)))(str)(re-seq #"(.)\1*" a))](recur x)))

奖励 119 个字符

(loop[a(read-line)](pr a)(let[x(reduce(fn[a b](str a(count(first b))(nth b 1)))(str)(re-seq #"(.)\1*" a))](recur x)))
于 2010-10-13T11:18:34.383 回答
0

285 248 个字符是我在 C# 中能做的最好的(这也是没有额外的!)

编辑:这也是我的第一个代码高尔夫......非常喜欢这样做:D

static void Main(){string s="1",x=s;for(;;){char[]c=x.ToCharArray();char d=c[0];x="";int a=0;for(inti=0;i<=c.Length;i++){char q;if(i!=c.Length)q=c[i];else q='0';if (d != q){x+=a.ToString();x+=d.ToString();d=q;a=1;}else a++;}Console.WriteLine(x);}}

可读代码:

using System;
class Program
{
    static void Main()
    {
        string startPoint = "1";
        string currentPoint = startPoint;
        while (true)
        {
            char[] currentPointAsCharArray = currentPoint.ToCharArray();
            char previousCharacter = currentPointAsCharArray[0];
            currentPoint = "";
            int countOfCharInGroup = 0;
            for(int i=0;i<=currentPointAsCharArray.Length;i++)
            {
                char c;
                if (i != currentPointAsCharArray.Length)
                    c = currentPointAsCharArray[i];
                else
                    c = '0';
                if (previousCharacter != c)
                {
                    currentPoint += countOfCharInGroup.ToString();
                    currentPoint += previousCharacter.ToString();
                    previousCharacter = c;
                    countOfCharInGroup = 1;
                }
                else
                    countOfCharInGroup++;
            }
            Console.Write(currentPoint + "\n");
        }
    }
}
于 2010-10-13T11:51:26.513 回答
0

Scala - 97 个字符

深受@BalusC 令人印象深刻的回答的启发:

def m(s:String){println(s);m((""/:(s split"(?<=(.)(?!\\1))")){(a,s)=>a+s.size+s(0)})};m(args(0))
于 2010-10-27T15:16:37.313 回答
0

J,61 个字符

J: las=: ,@((# , {.);.1~ 1 , 2 ~:/\ ])&.(10x&#.inv)@]^:(1+i.@[)

例子:

10 las 1
1 11 21 1211 111221 312211 13112221 1113213211 31131211131221 13211311123113112211 11131221133112132113212221

请注意,结果是一个实际的数字序列(参见其他语言给出的文本解决方案)。

来源:http ://rosettacode.org/wiki/Look-and-say_sequence#J

于 2010-11-17T09:51:46.613 回答
0

Lua,114 字节(有奖金)

浓缩:

x=arg[1]while 1 do print(x)i=1 y=''while i<=#x do a=x:sub(i,i)s,e=x:find(a..'+',i)y=y..e+1-s..a;i=e+1 end x=y end

正确格式化:

x=arg[1]
for k=1,10 do
    print(x)
    i=1
    y=''
    while i <= #x do
        a=x:sub(i,i)
        s,e=x:find(a..'+',i)
        y=y..e+1-s ..a
        i=e+1
    end
    x=y
end
于 2010-11-25T11:20:52.210 回答
0

Groovy(86 个字符)加额外功劳:

def f={m,n->n.times{println m;m=(m=~/(\d)\1*/).collect{it[0].size()+""+it[1]}.join()}}

调用:f(1,10)f(x,n)用于信用。

于 2014-05-22T08:39:40.587 回答