Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

In the C programming language, arrays are defined like this:

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

The size of the array is inferred from the initializing elements, which in this case is 6. You can also write a C array this way, explicitly sizing it then defining each element in order:

int foo[6];        //Give the array an explicit size of 6
foo[0] = 4;
foo[1] = 8;
foo[2] = 15
foo[3] = 16;
foo[4] = 23;
foo[5] = 42;

The challenge

You must write a program or function that expands arrays from the first way to the second. Since you are writing a program to make code longer, and you love irony, you must make your code as short as possible.

The input will be a string representing the original array, and the output will be the expanded array-definition. You can safely assume that the input will always look like this:

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

"Type" and "array_name" will made up entirely of alphabet characters and underscores _. The elements of the list will always be a number in the range -2,147,483,648 to 2,147,483,647. Inputs in any other format do not need to be handled.

The whitespace in your output must exactly match the whitespace in the test output, although a trailing newline is allowed.

Test IO:

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

#out
short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;


#in
spam EGGS[] = {42};

#out
spam EGGS[1];
EGGS[0] = 42;


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

#out
terrible_long_type_name awful_array_name[5];
awful_array_name[0] = 7;
awful_array_name[1] = -8;
awful_array_name[2] = 1337;
awful_array_name[3] = 0;
awful_array_name[4] = 13;

Submissions in any language are encouraged, but bonus points if you can do it in C.

Leaderboard:

Here is a leaderboard showing the top answers:

var QUESTION_ID=77857,OVERRIDE_USER=31716;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

share|improve this question
1  
Are the spaces between the array index, the equals sign, and the values required in the output? For example, would foo[0]=1; be acceptable? – Mego yesterday
    
@Mego That would not be acceptable. The whitespace is required. I'll edit that in. – Dr Green Eggs and Ham DJ yesterday
    
Trailing newline allowed? – Luis Mendo yesterday
    
@LuisMendo sure. – Dr Green Eggs and Ham DJ yesterday
    
@muru I'm just really bad about checking my sample output. >_< Fixing now. – Dr Green Eggs and Ham DJ yesterday

19 Answers 19

Vim, 54, 52, 49 47 keystrokes


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

Explanation:

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

Now our buffer looks like this:

int foo[0] = {4, 8, 15, 16, 23, 42};
int foo[1] = {8, 15, 16, 23, 42};
int foo[2] = {15, 16, 23, 42};
int foo[3] = {16, 23, 42};
int foo[4] = {23, 42};
int foo[5] = {42};
int foo[6] = {42};

Second half:

$                           '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               
               f{x          '(f)ind the next '{' the delete it.
                  wC;       'Move a word, then (C)hange to the end of this line, 
                            'and enter a ';'

Now everything looks good, we just need to add the original array-declaration. So we do:

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[6];"
share|improve this answer
2  
Whenever I read a vim-golf, I realise all the coding I do (mostly keyboard commands in my miscellaneous GUI editors) looks much like this, and my mind kind of bends for a minute (Vim is just turing complete (and cooler)) :P – cat yesterday
    
I can't get this to work - when I type the first "@q" (of "@qq@q"), the macro runs then, and apparently runs further than it should, getting things like int foo[6] = { and ending with int foo[12 (cursor on the "2") – LordAro 12 hours ago
    
@LordAro I probably should have mentioned that. That's because there's already a macro in q, and that runs while you're recording, messing it up. I explained how to get around that here: codegolf.stackexchange.com/a/74663/31716 – Dr Green Eggs and Ham DJ 9 hours ago
    
Hmm. OK, it now doesn't run the macro "early", but i still get the above output (runs to 12, instead of stopping at 6, which is missing anything beyond '{') – LordAro 7 hours ago
1  
@LordAro Oh, duh, I know what's causing that. I changed df<space> to dW to save a byte, but I forgot that df<space> will break out of the macro on line 6, but dW doesn't. I'll rollback a revision. Thanks for pointing that out! – Dr Green Eggs and Ham DJ 7 hours ago

Pyth, 44 bytes

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

Test suite

Regular expression and string chopping. Not particularly clever.

Explanation:

++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
 +                                              Add to that
         :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.
share|improve this answer
    
Is it as clever as a lever? – CatsAreFluffy yesterday
    
This answer is the thorn in my side. I thought I would be able to win it in vim, but for the life of me, I can't get the last 2-3 bytes off. =D Nice answer! – Dr Green Eggs and Ham DJ 9 hours ago

Retina, 108 104 100 69 bytes

Byte count assumes ISO 8859-1 encoding.

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

Beat this, PowerShell...

Code explanation

First line: ].+{((\S+ ?)+)

First, we need to keep the type, array name, and opening bracket (it saves a byte), so we don't match them. So we match the closing bracket, any number of characters, and an opening curly brace: ].+{. Then we match the number list. Shortest I've been able to find so far is this: ((\S+ ?)+). We match any number of non-space characters (this includes numbers, possible negative sign, and possible comma), followed by a space, that may or may not be there: \S+ ?. This group of characters is then repeated as many times as needed: (\S+ ?)+ and put into the large capturing group. Note that we don't match the closing curly brace or semicolon. Third line explanation tells why.

Second line: $#2];$1

Since we only matched a part of input, the unmatched parts will still be there. So we put the length of the list after the unmatched opening bracket: $#2. The replace modifier # helps us with that, as it gives us the number of matches a particular capturing group made. In this case capturing group 2. Then we put a closing bracket and a semicolon, and finally our whole list.

With input short array[] = {4, 3, 2, 1};, the internal representation after this replacing is:

short array[4];4, 3, 2, 1};

(note the closing curly brace and semicolon)

Third line: +`((\w+[).+;(\S+ )*)(-?\d+).+

This is a looped section. That means it runs until no stage in the loop makes a change to the input. First we match the array name, followed by an opening bracket: (\w+\[). Then arbitrary number of characters and a semicolon: .+;. Then we match the list again, but this time only numbers, which a space behind them (this excludes the last one): (\S+ )*. Then we take the last number in the list: (-?\d+) and any remaining characters behind it: .+.

Fourth line: $1¶$2$#3] = $4;

We then replace it with the array name and list followed by a newline: $1¶. Next, we put the array name, followed by the length of previously matched list, without the last element (essentially list.length - 1): $2$#3. Followed by a closing bracket and assigment operator with spaces, and this followed by the last element of our number list: ] = $4;

After first replacing, the internal representation looks like this:

short array[4];4, 3, 2, 
array[3] = 1;

Note that the closing curly brace and the semicolon disappeared, thanks to the .+ at the end of third line. After three more replacings, the internal representation looks like this:

short array[4];
array[0] = 4;
array[1] = 3;
array[2] = 2;
array[3] = 1;

Since there's nothing more to match by third line, fourth doesn't replace anything and the string is returned.

TL;DR: First we change up the int list format a bit. Then we take the last element of the list and the name, and put them after the array initialization. We do this until the int list is empty. Then we give the changed code back.

Try it online!

share|improve this answer
    
Someone beat me to it....:( – CatsAreFluffy yesterday
    
M!` and G` are similar, but not quite the same. Be careful. – CatsAreFluffy yesterday

Python 3.6 (pre-release), 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]};')

Makes heavy use of f-strings.

Ungolfed version:

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]};')
share|improve this answer
1  
Woah, I forgot about f-strings. Those are going to be super useful for golf! – Morgan 'Venti' Thrappuccino yesterday
    
I think you can save a byte by using a list comprehension instead of the normal loop – someonewithpc yesterday
    
@someonewithpc: nope, it would actually add 1 extra byte – vaultah 18 hours ago

05AB1E, 52 50 47 bytes

Code:

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

Uses CP-1252 encoding. Try it online!.

share|improve this answer

Pyth - 53 50 46 45 bytes

1 bytes saved thanks to @FryAmTheEggman.

+Jhcz\[+`]lKc<1ecz\{d\;j.es[ecJd`]kd\=dPb\;)K

Test Suite.

share|improve this answer
    
Oh, you know I suggested that because it was a synonym, but I didn't realise, isn't it the same as P? – FryAmTheEggman yesterday
    
@FryAmTheEggman well, I need to remove the last two elements. I don't know why <1 is working – Maltysen yesterday
    
But it works with P? Are you sure you don't just need to remove 1? – FryAmTheEggman yesterday
    
Oh yeah you only need that P because you use a P later in the enumerate. To remove the trailing comma from each other number, so the last number with a } isn't any different. – FryAmTheEggman yesterday

JavaScript (ES6), 100 bytes

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

Since only the words are important, this works by just matching all the words in the original string, plus leading minus signs, then building the result. (I originally thought I was going to use replace but that turned out to be a red herring.)

share|improve this answer
    
[t,n,...m] almost a mystic vision – edc65 yesterday

C, 286 bytes

i,j,n;f(s,z,t)char*s,*z,*t;{z=s;for(j=i=0;z[i]-32;putchar(z[i++]));for(;z[i++]-91;t[j++]=z[i]);t[j]=0;for(n=1;z[i]-'}';)n+=z[i++]==44;printf(" %s%i]",t,n);for(i=j=0;z[i++]-'{';);for(;j<n;i++){printf(";\n%s%i] = ",t,j++);for(;z[i]-44&&z[i]-'}';i++)if(z[i]-32)putchar(z[i]);}printf(";");}

Ideone link

share|improve this answer

JavaScript ES6, 134 132 130 129 bytes

Saved 1 byte thanks to Neil.

x=>(m=x.match(/(\w+) (\w+).+{(.+)}/),m[1]+` `+(q=m[2])+`[${q.length-1}];
`+m[3].split`, `.map((t,i)=>q+`[${i}] = ${t};`).join`
`)
share|improve this answer
    
Shouldn't `[${i}] = `+t+";" be `[${i}] = ${t};`? – Neil yesterday
    
@Neil Thanks, saved a byte! – Cᴏɴᴏʀ O'Bʀɪᴇɴ yesterday

Python 2, 159 bytes

s=input().split()
t,n,v=s[0],s[1][:-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])

Try it online

Thanks Kevin Lau for some golfing suggestions

share|improve this answer

Awk, 101 bytes

{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}

More readably:

{
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
}
  • I set the field separator to everything except alphabets, digits, the underscore and -. So, the fields would be the type name, the variable name, and the numbers.
  • The number of fields will be 1 (for the type) + 1 (for the name) + N (numbers) + 1 (an empty field after the trailing };). So, the size of the array is NF - 3.
  • Then it's just printing a special line for the declaration, and looping over the numbers.
  • I should assign FS either when invoking awk (using -F) or in a BEGIN block. In the interests of brevity, ….
share|improve this answer

PowerShell v2+, 114 105 bytes

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

Currently beating the other non-esolangs, and closing in on beating Retina. Woo!

Takes input string $args and -replaces the square bracket with nothing, then performs a -split on whitespace. We store the first bit into $a, the second bit into $b, the = into $c, and the array elements into $d. For the example below, this stores foo into $a and bar into $b, and all of the array into $d.

We then output our first line with "$a ..." and in the middle transform $d from a an array of strings of form {1,,2,,...100}; to a regular int array by -joining it together into one string, then running it through iex twice (similar to eval). We store that resultant array back in $d before calling the .length method to populate the appropriate number in between the [] in the output line.

We then send $d through a loop with |%{...}. Each iteration we output "$b..." with a counter variable $i encapsulated in brackets and the current value $_. The $i variable starts uninitialized (equivalent to $null) but the ++ will cast it to an int before the output, so it will start output at 0, all before incrementing $i for the next loop iteration.

All output lines are left on the pipeline, and output to the terminal is implicit at program termination.

Example

PS C:\Tools\Scripts\golfing> .\expand-a-c-array.ps1 "foo bar[] = {1, 2, 3, -99, 100};"
foo bar[5];
bar[0] = 1;
bar[1] = 2;
bar[2] = 3;
bar[3] = -99;
bar[4] = 100;
share|improve this answer
    
Whew! I managed to get my Ruby answer golfed past yours by taking your comment about beating the other non-esolangs as a challenge! Good work, though, +1. – Kevin Lau yesterday
    
@KevinLau Thanks! Back at ya with a 105 now. ;-) – TimmyD yesterday
    
I'll call your 105, and raise you a 99! :D – Kevin Lau yesterday

Ruby, 127 110 108 99 bytes

Anonymous function with a single argument as input. Full program, reads the input from STDIN. (If you pipe a file in, the trailing newline is optional.) Returns Prints the output string.

Took @TimmyD bragging about their solution beating all other non-esolangs as a challenge, and finally overcome the (at the time of writing) 114 byte Powershell solution they had posted. Cᴏɴᴏʀ O'Bʀɪᴇɴ's trick with splitting on ] and splicing the second half to get the numbers helped.

I need to use the splat operator more. It's so useful!

t,n,*l=gets.gsub(/[^ \w]/,"").split;i=-1
puts t+" #{n}[#{l.size}];",l.map{|e|n+"[#{i+=1}] = #{e};"}
share|improve this answer
    
AFAICT the task is to write a full program. – vaultah yesterday
    
@vaultah The default for code golf is a program or function – Mego yesterday
    
@Mego: the OP said "You must write a program" – vaultah yesterday
    
@vaultah normally I would say that code golf allows me to use a function, but a full program saved me 2 bytes, so why not? – Kevin Lau yesterday

Pip, 48 bytes

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

Takes input from stdin and prints to stdout.

Full explanation pending, but essentially this does a regex replacement using capture groups and a callback function to construct the result.

share|improve this answer

bash, 133 129 bytes

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

First attempt, sure its posible to get it shorter.

share|improve this answer

Julia, 154 148 144 137 134 bytes

f(s,c=match(r"(\w+ (\w+)).+{(.+)}",s).captures,x=split(c[3],", "),n=endof(x))=c[1]"[$n];\n"join([c[2]"[$i] = "x[i+1]";\n"for i=0:n-1])

This is a function that accepts a string and returns a string with a single trailing newline.

Ungolfed:

function f(s,
           c = match(r"((\w+ (\w+)).+{(.+)}", s).captures,
           x = split(c[3], ", "),
           n = endof(x))

    c[1] "[$n];\n" join([c[2] "[$i] = " x[i+1] ";\n" for i = 1:n-1])
end

We define c to be an array of capture groups where the first element is the type and array name, the second is the array's name, and the third is the list of values. We set x as the result of splitting the list of values into an array, then store n as the length of x. The output is constructed as the type, name and length string interpolated, combined with each definition line separated by newlines.

share|improve this answer

MATL, 68 64 58 bytes

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

This isn't C, but it does use C-like sprintf function Nah, that was wasting 4 bytes.

Try it online!

          % 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
share|improve this answer

Python 3, 116 bytes

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

Splits the input into the type, name, and the list of numbers. After printing the array declaring, prints the elements by manually enumerating through the numbers, removing excess punctuation that attached to the first and last one.

A different approach in Python 2 came out to 122 bytes:

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

The idea is to eval the list of numbers as a tuple, with a comma at the end so that a single number is recognized as a type. The enumerated list of numbers provides tuples to string-format in.

share|improve this answer

D, 197 bytes

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,";");}

or ungolfed:

import std.array, std.stdio;

void main() {
    string type, name, elems;
    readf("%s %s[] = {%s}", &type, &name, &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, ' ', name, '[', vector.length, "];");

    // print each element being assigned
    foreach(index, content; vector)
        writeln(name, "[", index, "] = ", content, ";");
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.