吉米将这些阵列放倒


23

我的同事Jimmy是C / C ++的新手。他也是一个学习缓慢的人。现在,公平地说,他的代码总是可以编译,但是他有一些很草率的习惯。例如,每个人都知道您可以定义如下数组:

int spam[] = {4, 8, 15, 16, 23, 42};

除了吉米,每个人都是。他深信制作数组的唯一方法是这样的:

int spam[6];
spam[0] = 4;
spam[1] = 8;
spam[2] = 15;
spam[3] = 16;
spam[4] = 23;
spam[5] = 42;

我在代码审查中一直为他修复此问题,但他不会学习。因此,我需要您编写一个工具,以便在他提交时自动为他完成操作¹。

挑战

我希望您编写一个完整的程序或一个将多行字符串作为输入并输出C数组的更紧凑版本的函数。输入将始终遵循此格式,包括空格:

identifier_one identifier_two[some_length];
identifier_two[0] = some_number;
identifier_two[1] = some_number;
identifier_two[2] = some_number;
...
identifier_two[some_length - 1] = some_number;

简而言之,输入将始终是有效且定义良好的C。更详细地:

所有标识符将仅由字母和下划线组成。该长度将始终至少为1,并且永远不会存在任何丢失或超出范围的索引。您还可以假设索引是有序的。例如:

foo bar[3];
bar[0] = 1
bar[2] = 9;

foo bar[1];
bar[0] = 1;
bar[1] = 3;

foo bar[3];
bar[2] = 9;
bar[0] = 1
bar[1] = 3

均为无效输入,可能会导致您的提交内容发生不确定的行为。您还可以假定所有数字都是有效的十进制数字,负数或正数。输入将没有多余的空间。输出应始终遵循以下格式,包括空格:

identifier_one identifier_two[] = {n1, n2, n3, ...};

以下是一些示例数据:

Input:
spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;

Output:
spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};

Input:
char ans[2];
ans[0] = 52;
ans[1] = 50;

Output:
char ans[] = {52, 50};

Input:
blah_blah quux[1];
quux[0] = 105;

Output:
blah_blah quux[] = {105};

您可以采用任何合理的格式输入和输出,例如STDIN / STDOUT,函数参数和返回值,读取和写入文件等。存在标准漏洞。以字节为单位的最短答案为胜!


¹这是消极的进取和可怕的想法。你是不是从我这里得到了这个想法。




@DLosc啊,那就是Jimmy在他的预提交脚本中使用的!
Bergi 2016年

9
当然,吉米不是打高尔夫球的人。
jimmy23013

这项挑战确实使我的吉米感到震惊
DanTheMan '16

Answers:


8

Vim, 43 36字节

您无需给吉米一个脚本,只需教他使用适当的文本编辑器即可。(为清楚起见,以书面形式返回)

:%s/.*=//|%s/;\n/,/<cr><cr>
3wcf ] = {<esc>
$s};

真好!在此特定情况下,<C-a>小于t],这是一个有趣的小技巧。另外,我认为您在技术上需要2,<cr>因为它要求确认。
DJMcMayhem


此外,norm df=比短s/.*=//g
DJMcMayhem

1
而且,3wC] = {<esc>比短<C-a>di]$s = {<esc>
DJMcMayhem

1
@Geobits您的Emacs答案在哪里?
尼尔

7

CJam,43 36字节

qN/('[/~;"[] = {"@{S/W=W<}%", "*"};"

在线示例

说明:

qN/                                     |Read all lines to array
   ('[/~;                               |slice first line left of [
         "[] = {"                       |add formatting to stack
                 @                      |rotate to remaining lines
                  {      }%             |for each line in array
                   S/W=                 |split after last space
                       W<               |remove last character (;)
                           ", "*        |insert ", " to array
                                "};"    |add formatting

非常感谢Martin Ender对我的第一个CJam答案的改进。


6

JavaScript(ES6),65 64 63字节

s=>`${s.split`[`[0]}[] = {${s.match(/-?\d+(?=;)/g).join`, `}};`

5

视网膜30 28字节

字节数假定为ISO 8859-1编码。

\d+];¶.+ 
] = {
;¶.+=
,
;
};

在线尝试!

说明

我们将使用以下输入作为示例:

spam eggs[4];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;

阶段1

\d+];¶.+ 
] = {

请注意,第一行上有一个尾随空格。

我们先匹配一个数字];,后跟一个换行符,然后匹配所有内容,直到下一行的最后一个空格。只能在第一行的末尾找到此匹配项(由于];)。所有这些都被替换为] = {。也就是说,它将示例输入转换为:

spam eggs[] = {0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;

第二阶段

;¶.+=
,

现在,我们匹配从;下到=上的所有内容,并替换为,。这会将字符串转换为:

spam eggs[] = {0, 4, 8, -3;

第三阶段

;
};

所有的左边是固定的结束,我们通过更换仅存这样做;};

spam eggs[] = {0, 4, 8, -3};

5

利亚,112个 108个 105字节

f(s)=string(split(s,'[')[1],"[] = {",join([m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],", "),"};")

说明

string(                                                         # build output string
split(s,'[')[1],                                                # get declaration (e.g. spam eggs)
"[] = {",                                                       # add [] = {
join(                                                           # collect numbers
    [m[1] for m in [eachmatch(r"= *(-?\d+)",s)...]],            # regex out (signed) numbers
    ", "),                                                      # and join comma separated
"};"                                                            # add };
)                                                               # close string(

通过使用[eachmatch()...]和较短的正则表达式替换collect(eachmatch())来节省字节


嗨,欢迎来到PPCG!这看起来像是一个很好的第一个答案。向我+1。由于质询状态为“ 您可以采用任何合理的格式输入和输出 ”,因此可以在eachmatch函数调用中的逗号分隔符后面删除空格,以减少输出的美观和-1字节。我本人从未编写过Julia的程序,但是您可能会发现这篇文章有趣有趣:Julia打高尔夫球的技巧。再次欢迎您,并祝您逗留愉快。:)
Kevin Cruijssen

1
非常感谢您的客气:) PPCG看起来很有趣,所以我想尝试一下。选择朱莉娅(Julia)回答这个问题,因为它还没有出现
nyro_0 '16

使用matchall可能比喷溅要短eachmatch
Alex A.

我尝试过首先使用Matchall,但它不允许我使用正则表达式组(括号中我特别感兴趣的部分)而不是每次匹配。(或者我只是在文档中找不到它?)
nyro_016年

3

Lua,121字节。

function g(s)print(s:gmatch('.-%[')()..'] = {'..s:gsub('.-\n','',1):gsub('.-([%d.-]+);\n?','%1, '):gsub(',%s+$','};'))end

解释

function g(s)
    print(                              -- Print, Self Explaintry.
        s:gmatch('.-%[')()..'] = {'     -- Find the 'header', match the first line's class and assignment name (everything up to the 'n]') and append that. Then, append ] = {.
                                        -- In the eggs example, this looks like; 'spam eggs[] = {' now
        ..                              -- concatenate...
        s:gsub('.-\n','',1)             -- the input, with the first line removed.
        :gsub('.-([%d.-]+);\n?','%1, ') -- Then that chunk is searched, quite boringly, a number followed by a semicolon, and the entire string is replaced with an array of those,
                                        -- EG, '1, 2, 3, 4, 5, 6, '
        :gsub(',%s+$','};')          -- Replace the final ', ' (if any) with a single '};', finishing our terrifying combination
    )
end

3

批处理,160字节

@echo off
set/ps=
set s=%s:[=[] = {&rem %
set r=
:l
set t=
set/pt=
if "%t%"=="" echo %r%};&exit/b
set t=%t:* =%
set r=%r%%s%%t:~2,-1%
set s=, 
goto l

注意:该行set s=,以空格结尾。在STDIN上输入。怪异的第3行接受输入(例如int spam[6];,将in [转换为[] = {&rem结果set s=int spam[] = {&rem 6];,然后将其解释为两个语句,set s=int spam[] = {rem 6];,后者则是注释。然后,对于每一行,我们将文本删除到第一个空格(因为您可以不能=用于模式,并且匹配是非贪婪的)并提取值。


3

C,121字节

n=2;main(i){for(;putchar(getchar())^91;);for(printf("] = {");~scanf("%*[^=]%*c%d",&i);n=0)printf(", %d"+n,i);puts("};");}

3

112 111

对我来说很简单,请提出任何建议。

def f(l):
 a,*b=l.split('\n')
 return a[:a.index('[')]+'[] = {'+', '.join(r.split(' = ')[1][:-1]for r in b)+'};'


# TEST

lines = """spam eggs[10];
eggs[0] = 0;
eggs[1] = 4;
eggs[2] = 8;
eggs[3] = -3;
eggs[4] = 3;
eggs[5] = 7;
eggs[6] = 888;
eggs[7] = 555;
eggs[8] = 0;
eggs[9] = -2;"""
print (f(lines))
assert f(lines) == 'spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};'

快速查看,我发现处有一个无用的空格[:-1] for
Yytsi '16

2

05AB1E31 30 28字节

žh-|vy#¤¨ˆ\}¨… = ¯ïžuDÀÀ‡';J

说明

žh-¨                            # remove numbers and ";" from first input
    |v      }                   # for each of the rest of the inputs
      y#                        # split on spaces
        ¤¨                      # take the last element (number) minus the last char (";") 
          ˆ\                    # store in global array and throw the rest of the list away
             … =                # push the string " = "
                 ¯ï             # push global array and convert to int
                   žuDÀÀ‡       # replace square brackets of array with curly ones
                         ';     # push ";"
                           J    # join everything and display

在线尝试!

多亏了Adnan,节省了一个字节


žuDÀÀ而不是„[]„{}保存一个字节:)。
阿德南

@Adnan:对,好收获!
Emigna '16

2

Java 7中,159个 158 149 154字节

String c(String[]a){a[0]=a[0].split("\\d")[0]+"] = {\b";for(String i:a)a[0]+=i.split("= [{]*")[1];return a[0].replace(";",", ").replaceFirst("..$","};");}

多亏@cliffroot节省了多个字节。

取消测试的代码:

在这里尝试。

class M{
  static String c(String[] a){
    a[0] = a[0].split("\\d")[0] + "] = {\b";
    for(String i : a){
      a[0] += i.split("= [{]*")[1];
    }
    return a[0].replace(";", ", ").replaceFirst("..$", "};");
  }

  public static void main(String[] a){
    System.out.println(c(new String[]{ "spam eggs[10];", "eggs[0] = 0;", "eggs[1] = 4;",
      "eggs[2] = 8;", "eggs[3] = -3;", "eggs[4] = 3;", "eggs[5] = 7;", "eggs[6] = 888;",
      "eggs[7] = 555;", "eggs[8] = 0;", "eggs[9] = -2;" }));
    System.out.println(c(new String[]{ "char ans[2]", "ans[0] = 52;", "ans[1] = 50;" }));
    System.out.println(c(new String[]{ "blah_blah quux[1];", "quux[0] = 105;" }));
  }
}

输出:

spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};
char ans[] = {52, 50};
blah_blah quux[] = {105};

1
保存了几个字节String c(String[]a){a[0]=a[0].split("\\d")[0]+"]={ \b";for(String i:a)a[0]+=i.split("=[{]*")[1];return a[0].replace(';',',').replaceFirst(".$","};");}
悬崖根

@cliffroot谢谢!确实,有一些不错的技巧,例如重用Stringin参数,并用"};");而不是代替最后一个字符"")+"};";
凯文·克鲁伊森

2

Perl,42 + 2(-0p)= 44字节

s%\d+].*%] = {@{[join",",/(-?\d+);/g]}};%s

需要-p-0标志运行。例如 :

perl -0pe 's%\d+].*%] = {@{[join",",/(-?\d+);/g]}};%s' <<< "blah_blah quux[1];
quux[0] = 105;"

1

果冻,27个字节

Ỵ©ḢḟØDṖ“ = {”®Ḳ€Ṫ€Ṗ€j⁾, ⁾};

在线尝试!

说明

Ỵ         Split into lines
 ©Ḣ       Take the first one, store the others in ®
   ḟØD    Remove digits
      Ṗ   Remove trailing ;

“ = {”    Print a literal string

®         Recall the remaining lines
 Ḳ€       Split each into words
   Ṫ€     Keep each last word
     Ṗ€   Remove each trailing ;

j⁾,       Join by “, ”
    ⁾};   Literal “};”

1

sed 51

1s,\[.*,[] = {,
:
N
s,\n.*= ,,
s/;/, /
$s/, $/};/
t

1

Java,106个字节

与往常一样,Java中的字符串操作非常麻烦。

a->a[0].join("",a).replaceAll(";\\w+\\[\\d+\\] = ",", ").replaceAll("\\d+\\], ","] = {").replace(";","};")

这是一个纯正则表达式答案。进行单个串联String,然后执行replaceXxx直到确定。

测试和取消高尔夫:

import java.util.function.Function;

public class Main {

  public static void main(String[] args) {
    Function<String[], String> f = a ->
        String.join("", a)                          // I think this would join. Not sure, though. Golfed into a[0].join because static members are accessible from instances.
            .replaceAll(";\\w+\\[\\d+\\] = ", ", ") // replace with regex
            .replaceAll("\\d+\\], ", "] = {")       // replace with regex
            .replace(";", "};");                    // replace no regex

    String[] spam = {
      "int spam[6];",
      "spam[0] = 4;",
      "spam[1] = 8;",
      "spam[2] = 15;",
      "spam[3] = 16;",
      "spam[4] = 23;",
      "spam[5] = 42;"
    };
    test(f, spam, "int spam[] = {4, 8, 15, 16, 23, 42};");

    String[] eggs = {
      "spam eggs[10];",
      "eggs[0] = 0;",
      "eggs[1] = 4;",
      "eggs[2] = 8;",
      "eggs[3] = -3;",
      "eggs[4] = 3;",
      "eggs[5] = 7;",
      "eggs[6] = 888;",
      "eggs[7] = 555;",
      "eggs[8] = 0;",
      "eggs[9] = -2;"
    };
    test(f, eggs, "spam eggs[] = {0, 4, 8, -3, 3, 7, 888, 555, 0, -2};");

    String[] ans = {
      "char ans[2];",
      "ans[0] = 52;",
      "ans[1] = 50;"
    };
    test(f, ans, "char ans[] = {52, 50};");

    String[] quux = {
      "blah_blah quux[1];",
      "quux[0] = 105;"
    };
    test(f, quux, "blah_blah quux[] = {105};");

  }

  static void test(Function<String[], String> f, String[] input, String expected) {
    System.out.printf("Result:   %s%nExpected: %s%n", f.apply(input), expected);
  }
}

0

果冻,33 字节

ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j
ỴḢḟØDṖ,⁾ =,ÇK

在线试用

怎么样?

ỴḊḲ€Ṫ€K⁾;,yṖ“{“};”j - Link 1, parse and reform the values, same input as the Main link
Ỵ                   - split on line feeds
 Ḋ                  - dequeue (remove the first line)
  Ḳ€                - split each on spaces
    Ṫ€              - tail each (get the numbers with trailing ';')
      K             - join on spaces
       ⁾;,          - ";,"
          y         - map (replace ';' with ',')
           Ṗ        - pop (remove the last ',')
            “{“};”  - list of strings ["{","};"]
                  j - join (making "{" + "n0, n1, ,n2, ..." + "};")

ỴḢḟØDṖ,⁾ =,ÇK - Main link, takes one argument, the multiline string
Ỵ             - split on line feeds
 Ḣ            - head (just the first line)
   ØD         - digits yield "0123456789"
  ḟ           - filter out
     Ṗ        - pop (remove the trailing ';')
      ,   ,   - pair
       ⁾ =    - the string " ="
           Ç  - call the previous Link (1)
            K - join on spaces (add the space after the '=')

下选民-这是怎么了?
乔纳森·艾伦


0

JavaScript,125个字节

我知道它比其他的更长,但是我真的很想使用eval。只是为了好玩。

f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}

要运行,请将以下内容粘贴到此处

s='int spam[6];\
spam[0] = 4;\
spam[1] = 8;\
spam[2] = 15;\
spam[3] = 16;\
spam[4] = 23;\
spam[5] = 42;'
f=function(s){m=/^(\w+ )(\w+).*?(;.*)/.exec(s)
eval("var "+m[2]+"=new Array()"+m[3]+'alert(m[1]+m[2]+"={"+eval(m[2])+"};")')}
f(s)

0

Haxe,234个字节

function R(L:Array<String>){var S=L[0];var W=S.indexOf(" ");var T=S.substr(0,W),M=S.substring(W+1,S.indexOf("["));var r=[for(i in 1...L.length)L[i].substring(L[i].lastIndexOf(" ")+1,L[i].length-1)].join(', ');return'$T $M[] = {$r};';}

长函数名杀死了这个:D

这里尝试测试用例!


0

V25,24字节

3wC] = {òJd2f $s, òhC};

在线尝试! 它包含一个不可打印的<esc>字符,因此这是一个十六进制转储:

0000000: 3377 435d 203d 207b 1bf2 4a64 3266 2024  3wC] = {..Jd2f $
0000010: 732c 20f2 6843 7d3b                      s, .hC};

说明:

3w                              "Move forward 3 words
  C     <esc>                   "Delete everything until the end of the line, and enter this text:
   ] = {                        "'] = {'
             ò         ò        "Recursively:
              J                 "  Join these two lines (which enters a space)
               d                "  Delete everything until you
                2f              "  (f)ind the (2)nd space
                   $            "  Move to the end of this line
                    s           "  Delete a character, and enter:
                     ,          "  ', '
                                "
                        h       "Move one character to the left
                         C      "Delete everything until the end of the line, and enter this text:
                          };    "'};'
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.