# 扩展一个C数组

36

``````int foo[] = {4, 8, 15, 16, 23, 42};      //Foo implicitly has a size of 6
``````

``````int foo;        //Give the array an explicit size of 6
foo = 4;
foo = 8;
foo = 15;
foo = 16;
foo = 23;
foo = 42;
``````

# 挑战

``````<type> <array_name>[] = {<int>, <int>, <int> ... };
``````

“ Type”和“ array_name”将完全由字母字符和下划线组成`_`。列表中的元素将始终是-2,147,483,648到2,147,483,647之间的数字。不需要处理任何其他格式的输入。

# 测试IO：

``````#in
short array[] = {4, 3, 2, 1};

#out
short array;
array = 4;
array = 3;
array = 2;
array = 1;

#in
spam EGGS[] = {42};

#out
spam EGGS;
EGGS = 42;

#in
terrible_long_type_name awful_array_name[] = {7, -8, 1337, 0, 13};

#out
terrible_long_type_name awful_array_name;
awful_array_name = 7;
awful_array_name = -8;
awful_array_name = 1337;
awful_array_name = 0;
awful_array_name = 13;
``````

# 排行榜：

2

Mego

@Mego那是不可接受的。空格是必需的。我会编辑英寸
DJMcMayhem

Luis Mendo

Mego

Vault

12

# Pyth，44个字节

``````++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
``````

``````++Khcz\]lJ:z"-?\d+"1"];"VJs[ecKd~hZ"] = "N\;
Implicit: z = input()
cz\]                                        Chop z on ']'
h                                            Take string before the ']'
K                                             Store it in K
:z"-?\d+"1                             Find all numbers in the input
J                                       Store them in J
l                                        Take its length.
+                  "];"                         Add on "];" and print.
VJ                       For N in J:
s[                     Print the following, concatenated:
cKd                 Chop K on spaces.
e                    Take the last piece (array name)
~hZ              The current interation number
"] = "        That string
N       The number from the input
\;     And the trailing semicolon.
``````

DJMcMayhem

28

# Vim，54、52、49 47击键

``````2wa0<esc>qqYp<c-a>6ldf @qq@q\$dT]dd:%norm dwf{xwC;<CR>gg"0P
``````

``````2wa0<esc>                     'Move 2 words forward, and insert a 0.
qq                   'Start recording in register Q
Yp                 'Duplicate the line
<c-a>6l          'Increment the next number then move 6 spaces right
df        'Delete until the next space
@qq@q  'Recursively call this macro
``````

``````int foo = {4, 8, 15, 16, 23, 42};
int foo = {8, 15, 16, 23, 42};
int foo = {15, 16, 23, 42};
int foo = {16, 23, 42};
int foo = {23, 42};
int foo = {42};
int foo = {42};
``````

``````\$                           'Move to the end of the line
dT]                        'Delete back until we hit a ']'
dd                      'Delete this whole line.
:%norm         <CR>   'Apply the following keystrokes to every line:
dw             'Delete a word (in this case "int")
f{x          '(f)ind the next '{', then delete it.
wC;       'Move a word, then (C)hange to the end of this line,
'and enter a ';'
``````

``````gg        'Move to line one
"0P     'Print buffer '0' behind us. Buffer '0' always holds the last deleted line,
'Which in this case is "int foo;"
``````

3

LordAro

@LordAro我可能应该提到过。这是因为q中已经有一个宏，并且在您录制时运行并将其弄乱。我在这里解释了如何解决该问题：codegolf.stackexchange.com/a/74663/31716
DJMcMayhem

1
@LordAro哦，我不知道是什么原因造成的。我更改`df<space>``dW`保存一个字节，但是我忘记了这`df<space>`将打破第6行的宏，但`dW`事实并非如此。我将回滚修订。感谢您指出了这一点！
DJMcMayhem

1

isaacg '16

10

# 视网膜，108个104 100 69字节

``````].+{((\S+ ?)+)
\$#2];\$1
+`((\w+\[).+;(\S+ )*)(-?\d+).+
\$1¶\$2\$#3] = \$4;
``````

## 代码说明

`短数组; 4，3，2，1};`

（注意右花括号和分号）

``````short array;4, 3, 2,
array = 1;
``````

``````short array;
array = 4;
array = 3;
array = 2;
array = 1;
``````

TL; DR：首先，我们稍微更改int列表格式。然后，我们获取列表的最后一个元素和名称，并将它们放在数组初始化之后。我们这样做直到int列表为空。然后，我们将更改后的代码返回。

CalculatorFeline

`M!```G``相似，但不完全相同。小心。
CalculatorFeline

CalculatorFeline

@CatsAreFluffy我刚刚尝试更改措辞。我的意思是在数字后面而不是前面的空格。我想我还没有完全意识到“背后”的含义。我真的不应该在凌晨2点写代码说明。
daavko '16

@daavko在口语中，“ Behind”通常是指“ after”，即“ following”。你还好
Nic Hartley

9

# V，37字节

``````2Eé0òYp6ldf ò\$dT]ddÎdwf{xwC;
gg"1P
``````

V是我编写的一种2D，基于字符串的高尔夫语言，是基于vim设计的。从提交17开始生效

``````2E                               "Move to the end of 2 words forward.
é0                             "Insert a single '0'
ò       ò                    "Recursively do:
Yp6ldf                      "Yank, paste, move 6 right, delete until space.
\$dT]                "Move to the end of line, delete backwards until ']'
dd              "Delete this line
Î             "Apply the following to every line:
dwf{xwC;<\n> "Delete word, move to '{' and delete it, Change to end of line, and enter ';'
``````

``````gg"1P     "Move to line 1, and paste buffer '1' behind us.
``````

``````00000000: 3245 e930 f259 7001 366c 6466 20f2 2464  2E.0.Yp.6ldf .\$d
00000010: 545d 6464 ce64 7766 7b78 7743 3b0d 6767  T]dd.dwf{xwC;.gg
00000020: 2231 500a                                "1P.
``````

``````python main.py c_array.v --f=file_with_original_text.txt
``````

1
`Designed off of vim.`2个注意事项：1.大多数人`from`不说`off of`，并且2.为什么不存在。+1
Rɪᴋᴇʀ

8

# C，215字节，196字节

@tucuxi节省了19个字节！

``````char i,o,b,z;t,x,n,c;main(){gets(i);sscanf(i,"%s %[^[]s",b,z);while(sscanf(i+t,"%*[^0-9]%d%n",&x,&n)==1)sprintf(o,"%s[%d] = %d;\n",z,c++,x),t+=n;printf("%s %s[%d];\n%s",b,z,c,o);}
``````

``````/*
*  Global strings:
*   i: input string
*   o: output string
*   b: input array type
*   z: input array name
*/
char i[ 99 ], o[ 999 ], b[ 99 ], z[ 99 ];

/* Global ints initialized to zeros */
t, x, n, c;

main()
{
/* Grab input string from stdin, store into i */
gets( i );

/* Grab the <type> <array_name> and store into b and z */
sscanf( i, "%s %[^[]s", b, z );

/* Grab only the int values and concatenate to output string */
while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
{
/* Format the string and store into a */
sprintf( o, "%s[%d] = %d;\n", z, c++, x );

/* Get the current location of the pointer */
t += n;
}

/* Print the <type> <array_name>[<size>]; and output string */
printf( "%s %s[%d];\n%s", b, z, c, o );
}
``````

http://ideone.com/h81XbI

``````%s          A string delimited by a space
%[^[]   The character set that contains anything but a `[` symbol
s  A string of that character set
``````

``````while( sscanf( i + t, "%*[^0-9]%d%n", &x, &n ) == 1 )
``````

• `i`是输入字符串（a `char*`
• `t` 是指针位置的偏移量 `i`
• `x``int`从字符串中实际解析出来的
• `n` 是消耗的总字符，包括找到的数字

`sscanf()`格式字符串含义：

``````%*            Ignore the following, which is..
[^0-9]      ..anything that isn't a digit
%d    Read and store the digit found
%n  Store the number of characters consumed
``````

``````int foo[] = {4, 8, 15, 16, 23, 42};
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
00000000001111111111222222222233333
01234567890123456789012345678901234
``````

``````Run 1)  String: "int foo[] = {4, 8, 15, 16, 23, 42};"
Starting string pointer: str[ 0 ]
Num chars consumed until after found digit: 14
Digit that was found: 4
Ending string pointer: str[ 14 ]

Run 2)  String: ", 8, 15, 16, 23, 42};"
Starting string pointer: str[ 14 ]
Num chars consumed until after found digit: 3
Digit that was found: 8
Ending string pointer: str[ 17 ]

Run 3)  String: ", 15, 16, 23, 42};"
Starting string pointer: str[ 17 ]
Num chars consumed until after found digit: 4
Digit that was found: 15
Ending string pointer: str[ 21 ]

Run 4)  String: ", 16, 23, 42};"
Starting string pointer: str[ 21 ]
Num chars consumed until after found digit: 4
Digit that was found: 16
Ending string pointer: str[ 25 ]

Run 5)  String: ", 23, 42};"
Starting string pointer: str[ 25 ]
Num chars consumed until after found digit: 4
Digit that was found: 23
Ending string pointer: str[ 29 ]

Run 6)  String: ", 42};"
Starting string pointer: str[ 29 ]
Num chars consumed until after found digit: 4
Digit that was found: 42
Ending string pointer: str[ 33 ]
``````

1

tucuxi

@tucuxi啊，很好。谢谢！
homersimpson

7

# C，195180字节

195字节原件：

``````char*a,*b,*c,*d;j;main(i){scanf("%ms %m[^]]%m[^;]",&a,&b,&c);
for(d=c;*d++;i+=*d==44);printf("%s %s%d];\n",a,b,i);
for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))printf("%s%d] = %s;\n",b,j,d);}``````

``````char*a,*b,*c,*d;
j;
main(i){
scanf("%ms %m[^]]%m[^;]",&a,&b,&c); // m-modifier does its own mallocs
for(d=c;*d++;i+=*d==44);            // count commas
printf("%s %s%d];\n",a,b,i);        // first line
for(d=strtok(c,"] =,{}");j<i;j++,d=strtok(0," ,}"))
printf("%s%d] = %s;\n",b,j,d);  // each array value
}``````

180字节更新：

``````char*a,*b,*c,e;i;main(){scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),
c=strtok(0," ,"););printf("%s %s%d];\n%s",a,b,i,e);}``````

``````char*a,*b,*c,e;
i;
main(){
scanf("%ms %m[^]]%m[^}]",&a,&b,&c);
for(c=strtok(c,"] =,{}");sprintf(e,"%s%s%d] = %s;\n",e,b,i++,c),c=strtok(0," ,"););
printf("%s %s%d];\n%s",a,b,i,e);
}``````

6

## Python 3.6（预发布），133

``````m,p=str.split,print;y,u=m(input(),'[');t,n=m(y);i=m(u[5:-2],', ')
l=len(i);p(t,n+f'[{l}];')
for x in range(l):p(n+f'[{x}] = {i[x]};')``````

``````y, u = input().split('[')
t, n = y.split()
i = u[5:-2].split(', ')
l = len(i)
print(t, n + f'[{l}];')
for x in range(l):
print(n + f'[{x}] = {i[x]};')``````

1

Morgan Thrapp '16

someonewithpc '16

@someonewithpc：不，它实际上会增加1个额外的字节
vaultah '16

5

# Ruby，127 110 108 99 88字节

@TimmyD吹牛他们的解决方案击败所有其他非esolangs作为挑战，并最终克服了（在撰写本文时）他们发布的114字节Powershell解决方案。奥伯奇科（CᴏɴᴏʀO'Bʀɪand）的诀窍是分拆`]`并拼接下半场以得到帮助。

``````t,n,*l=gets.scan /-?\w+/;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}
``````

AFAICT的任务是编写完整的程序。
vaultah '16

@vaultah代码高尔夫的默认值是程序或功能
Mego

@Mego：OP说“您必须编写程序”
vaultah '16

@vaultah通常我会说代码高尔夫允许我使用一个函数，但是完整的程序为我节省了2个字节，所以为什么不呢？

4

# 05AB1E，52 50 47字节

``````… = ¡`¦¨¨ð-',¡©gr¨s«„];«,®v¹ð¡¦¬s\¨N"] = "y';J,
``````

1

WorseDoughnut

1
@WorseDoughnut谢谢！有人对我说过关于05AB1E :)的最好的事情！

4

## JavaScript（ES6），100字节

``````(s,[t,n,...m]=s.match(/-?\w+/g))=>t+` \${n}[\${m.length}];`+m.map((v,i)=>`
\${n}[\${i}] = \${v};`).join``
``````

`[t,n,...m]`几乎是一个神秘的视觉
edc65 '16

4

# Pyth- 53 50 46 45 44字节

@FryAmTheEggman节省了2个字节。

``````+Jhcz\[+`]lKcPecz\{d\;j.es[ecJd`]kd\=dPb\;)K
``````

4

# 点，48 47字节

``````qR`(\S+)(. = ).(.+)}`{[b#Yd^k']';.n.b.,#y.c.y]}
``````

### 说明

Tl; dr：使用捕获组和回调函数构造结果来进行正则表达式替换。

`q`特殊变量读取一行的输入。正则表达式为`(\S+)(. = ).(.+)}`，它匹配类型（包括尾随空格）和最后一个分号以外的所有内容。利用问题的第一个例子中，捕获组获得`foo[``] = ``4, 8, 15, 16, 23, 42`

``````["foo[" 6 "]"
[";" n "foo[" 0 "] = " 4]
[";" n "foo[" 1 "] = " 8]
[";" n "foo[" 2 "] = " 15]
[";" n "foo[" 3 "] = " 16]
[";" n "foo[" 4 "] = " 23]
[";" n "foo[" 5 "] = " 42]
]
``````

``````"foo;
foo = 4;
foo = 5;
foo = 15;
foo = 16;
foo = 23;
foo = 42"
``````

4

## Perl 5.10的，73 72 68 66 + 1（对于-n开关）= 67字节

``````perl -nE '(\$t,\$n,@a)=/[-[\w]+/g;say"\$t \$n".@a."];";say\$n,\$i++,"] = \$_;"for@a'
``````

``````(\$t, \$n, @a) = /[-[\w]+/g;
say "\$t \$n" . @a . "];";
say \$n, \$i++, "] = \$_;" for @a;
``````

4

## PowerShell v2 +，114105字节

``````\$a,\$b,\$c,\$d=-split\$args-replace'\[]';"\$a \$b[\$((\$d=-join\$d|iex|iex).length)];";\$d|%{"\$b[\$((\$i++))] = \$_;"}
``````

### 例

``````PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar;
bar = 1;
bar = 2;
bar = 3;
bar = -99;
bar = 100;
``````

ew！通过将您的评论打败其他非以eolangs作为挑战，我设法使Ruby的答案超越了您！不错，但是+1。

@KevinLau谢谢！现在回到105。;-)

CalculatorFeline

3

## C，278280字节

``````x,e,l,d;char *m,*r,*a;char i;c(x){return isdigit(x)||x==45;}main(){gets(i);m=r=&i;while(*r++!=32);a=r;while(*++r!=93);l=r-a;d=r-m;for(;*r++;*r==44?e++:1);printf("%.*s%d];\n",d,m,e+1);r=&i;while(*r++){if(c(*r)){m=r;while(c(*++r));printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);}}}
``````

``````/* global ints
* x = generic counter
* e = number of elements
* l = length of the array type
* d = array defination upto the first '['
*/
x,e,l,d;
/* global pointers
* m = memory pointer
* r = memory reference / index
* a = pointer to the start of the array type string
*/
char *m,*r,*a;
/* data storage for stdin */
char i;
c(x){return isdigit(x)||x=='-';}
main(){
gets(i);
m=r=&i;
while(*r++!=32);                // skip first space
a=r;
l=r-a;
d=r-m;
for(;*r++;*r==44?e++:1);        // count elements
printf("%.*s%d];\n",d,m,e+1);   // print array define
r=&i;
while(*r++) {                   // print elements
if(c(*r)) {                 // is char a - or a digit?
m=r;
while(c(*++r));         // count -/digit chars
printf("%.*s%d] = %.*s;\n",l,a,x++,r-m,m);
}
}
}
``````

2

# Awk，101个字节

``````{FS="[^[:alnum:]_-]+";printf"%s %s[%d];\n",\$1,\$2,NF-3;for(i=3;i<NF;i++)printf\$2"[%d] = %d;\n",i-3,\$i}
``````

``````{
FS="[^[:alnum:]_-]+"
printf "%s %s[%d];\n", \$1, \$2, NF - 3
for (i=3; i < NF; i++)
printf \$2"[%d] = %d;\n", i-3, \$i
}
``````
• 我将字段分隔符设置为除字母，数字，下划线和以外的所有内容`-`。因此，这些字段将是类型名称，变量名称和数字。
• 字段数将是1（对于类型）+1（对于名称）+ N（数字）+1（在结尾处为空字段`};`）。因此，数组的大小为`NF - 3`
• 然后，它只是为声明打印一行，然后遍历数字。
• 应该`FS`在调用awk时（使用`-F`）或在一个`BEGIN`块中进行分配。为了简洁起见，……。

1

@RobertBenson您说得对，所以命令将是`awk '-F[^[:alnum:]_-]+' '{printf"%s %s[%d];\n",\$1,\$2,NF-3;for(i=3;i<NF;i++)printf\$2"[%d] = %d;\n",i-3,\$i}'`，这是102个字节，不计算`awk`自身。嗯 我可以排除报价吗？
muru

2

# JavaScript的ES6，134个132 130 129字节

``````x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m+` `+(q=m)+`[\${q.length-1}];
`+m.split`, `.map((t,i)=>q+`[\${i}] = \${t};`).join`
`)``````

``[\${i}] = `+t+";"`应该``[\${i}] = \${t};``吗？

@尼尔，谢谢，保存了一个字节！
Conor O'Brien

2

## bash中，133个 129字节

``````read -a l
d="\${l[@]:0:2}"
e=("\${l[@]:3}")
echo "\${d%?}\${#e[@]}];"
for i in "\${!e[@]}"
{
echo "\${l}[\$i] = \${e[\$i]//[!0-9]/};"
}``````

2

# D，197、188字节

``````import std.array,std.stdio;void main(){string t,n,e;readf("%s %s] = {%s}",&t,&n,&e);auto v=e.replace(",","").split;writeln(t,' ',n,v.length,"];");foreach(i,c;v)writeln(n,i,"] = ",c,";");}
``````

``````import std.array, std.stdio;

void main() {
string type, nameAndBracket, elems;
readf("%s %s] = {%s}", &type, &nameAndBracket, &elems);

// remove all commas before splitting the string into substrings
auto vector = elems.replace(",","").split();

// writeln is shorter than fln by 1 char when filled in
writeln(type, ' ', nameAndBracket, vector.length, "];");

// print each element being assigned
foreach(index, content; vector)
writeln(nameAndBraket, index, "] = ", content, ";");
}
``````

DLosc

2

# 利亚，154个134 101字节

``````f(s,c=matchall(r"-?\w+",s),n=endof(c)-2)=c[]" "c"[\$n];
"join([c"[\$i] = "c[i+3]";
"for i=0:n-1])``````

``````function f(s, c = matchall(r"-?\w+", s), n = endof(c) - 2)
c[] " " c "[\$n];\n" join([c "[\$i] = " x[i+3] ";\n" for i = 0:n-1])
end``````

1

## Python 2，159字节

``````s=input().split()
t,n,v=s,s[:-2],''.join(s[3:])
a=v[1:-2].split(',')
print'%s %s[%d];'%(t,n,len(a))
for i in range(len(a)):print'%s[%d] = %s;'%(n,i,a[i])``````

1

## Python 3，116个字节

``````t,v,_,*l=input().split();v=v[:-1]+'%s]'
print(t,v%len(l)+';');i=0
for x in l:print(v%i,'= %s;'%x.strip('{,};'));i+=1``````

Python 2中的另一种方法达到了122个字节：

``````a,b=input()[:-2].split('] = {')
l=eval(b+',')
print a+`len(l)`+"];"
for y in enumerate(l):print a.split()+'%s] = %s;'%y``````

1

## PHP，143字节

``````<?\$t=count(\$n=explode(' ',preg_replace('/[^\s\w]/','',\$argv)))-3;echo"\$n {\$n}[\$t];";for(\$i=2;\$t>\$j=++\$i-3;)echo\$n."[\$j] = \$n[\$i];";
``````

``````<?
\$t = count(                                  // Get the number of elements for our array...
\$n = explode(' ',                            // After split the input on whitespace...
preg_replace('/[^\s\w]/','',\$argv)))-3;  // After removing all special characters.
echo "\$n {\$n}[\$t];";                     // First line is type, name, and count.
for(\$i=2;                                        // Loop through array elements
\$t > \$j = ++\$i-3;)                         // Assign j to be the actual index for our new array
echo \$n."[\$j] = \$n[\$i];";                // Print each line
``````

``````C:\(filepath)>php Expand.php "int foo[] = {4,8,15,16,23,42};"
``````

``````int foo;foo = 4;foo = 8;foo = 15;foo = 16;foo = 23;foo = 42;
``````

0

# MATL，68 64 58字节

``````'\w+'XX2:H#)XKxXIZc'['KnV'];'v!K"I2X)'['X@qV'] = '@g';'6\$h
``````

``````          % Take input implicitly
'\w+'XX   % Find substrings that match regex '\w+'. Gives a cell array
2:H#)     % Split into a subarray with the first two substrings (type and name), and
% another with the rest (numbers that form the array)
XKx       % Copy the latter (numbers) into clipboard K. Delete it
XI        % Copy the former (type and name) into clipboard I
Zc        % Join the first two substrings with a space
'['       % Push this string
K         % Paste array of numbers
nV        % Get its length. Convert to string
'];'      % Push this string
v!        % Concatenate all strings up to now. Gives first line of the output
K"        % For each number in the array
I2X)    %   Get name of array as a string
'['     %   Push this string
X@qV    %   Current iteration index, starting at 0, as a string
'] = '  %   Push this string
@g      %   Current number of the array, as a string
';'     %   Push this string
5\$h     %   Concatenate top 6 strings. This is a line of the output
% Implicity end for each
% Implicitly display
``````

0

## Clojure，115字节

``````#(let[[t n & v](re-seq #"-?\w+"%)](apply str t" "n\[(count v)"];\n"(map(fn[i v](str n"["i"] = "v";\n"))(range)v))))
``````