Створіть 100 класів Java Tuple


37

Напишіть сценарій, який записується на стандартний вихід, або еквівалент вашої мови, 100 рядків (дійсного) коду Java, який починається з:

class Tuple1 {public Object _0;}
class Tuple2 {public Object _0,_1;}
class Tuple3 {public Object _0,_1,_2;}
class Tuple4 {public Object _0,_1,_2,_3;}
class Tuple5 {public Object _0,_1,_2,_3,_4;}
class Tuple6 {public Object _0,_1,_2,_3,_4,_5;}
class Tuple7 {public Object _0,_1,_2,_3,_4,_5,_6;}
class Tuple8 {public Object _0,_1,_2,_3,_4,_5,_6,_7;}
class Tuple9 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8;}
class Tuple10 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9;}
class Tuple11 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10;}
class Tuple12 {public Object _0,_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11;}

Останній рядок повинен починатися з class Tuple100.

Це , тому найкоротший код у байтах виграє!


6
Я приймаю виклик! Насправді я збираюся це зробити на Java!
Ешвін Гупта

Чи можу я написати функцію або вона повинна бути повноцінною програмою?
Ешвін Гупта

3
Я новачок на сайті, тому просив сценарій, але я чув, що звичайно дозволяти функції, і це має багато сенсу для Java, щоб уникнути public static void main(String[] args)настільки визначеного функціонування, якщо вам це подобається.
Ray Toal

1
Чудово! Дякую Рей!
Ешвін Гупта

Це не десь поблизу достатньо малого, але я вважаю, що це ідеальне місце для спільного використання мого nгенератора-пар, про який я писав на Java: github.com/kenzierocks/Tuplocity . Це породжує повністю загальні кортежі!
Octavia Togami

Відповіді:


8

Джолф, 42 байти

Чи отримую я бонусні бали за побиття желе з найкращим рахунком коли-небудь? Містить недруковані матеріали, тому ви можете спробувати його в Інтернеті тут . Я замінив недруковані версії на їх відповідний індекс alt для читабельності.

‼Μz~1d"Ξ/êί Tuple% {Ξ0î⌂ Ξ2Qμ_ %;}"HRzH",_

Пояснення

‼Μz~1d"Ξ/êί Tuple% {Ξ0î⌂ Ξ2Qμ _%;}"HRzH",_
 Μz~1d                                     map the range 1..100 with the following function
      "                                    begin a string
       Ξ/êί                                short for "class"
            Tuple% {               H       string interpolate H (current number)
                    Ξ0î⌂ Ξ2Qμ              short for "public Object"
                              _%;}" RzH    string interpolate with a range from 1..H joined
                                       ",_  by the string ",_" (auto-closed quotes)

1
Я вважаю. Чи правильно на цьому сайті змінити прийняту відповідь, якщо пізніше з’явиться нова оцінка?
Рей Тол

6
@RayToal Так, це правильно і навіть пропонується зробити це.
Conor O'Brien

Яке кодування символів для цього? Я знаю, що мови для гольфу часто використовують власне кодування, але я не можу бачити, яким кодуванням може користуватися jolf. Я усвідомлюю, що це старе.
рекурсивна

@recursive Грецька ISO-8859-7, ця: en.wikipedia.org/wiki/ISO/IEC_8859-7
Conor O'Brien

23

vim 56 54 натискання клавіш

iclass Tuple1 {public Object _0;}<esc>qyYp<C-a>$y2bPr,<C-a>q98@y

Оскільки V назад сумісний, ви можете спробувати його в Інтернеті!

Це ідеальне завдання для vim! Я можу трохи пізніше взяти гольф. Також зауважте, що це <c-a>означає Control-A, і це вважається одним натисканням клавіш.

Пояснення:

iclass Tuple1 {public Object _0;}<esc>         'Enter the starting text


qy                          'Start recording in register y
  Yp                        'Yank the current line, the print on the line below
     <C-a>                  'Increment the next digit to occur by one
          $                 'Move to the end of this line
           y2b              '(yank) 2 words (b)ack. This will grab '_0;'
              P             'Print the previously yanked word before the cursor.
               r,           '(r)eplace the char under the cursor with a comma.
                 <c-a>q     'Increment the current digit, then stop recording
                       99@y 'Playback macro 'y' 99 times.

1
Якщо вважати Control-A , як одне натискання клавіші, ви можете замінити yyна Y.
seequ

1
@Seeq Ха-ха, я просто зрозумів те саме і відредагував це прямо перед тим, як побачив ваш коментар. Великі уми мислять однаково!
DJMcMayhem

Це, здається, збирається class Tuple101не так, class Tuple100як задається питанням.
numbermaniac

1
@numbermaniac Проста помилка по одному. Дякуємо, що вказали на це! Виправлено зараз :)
DJMcMayhem

10

Желе, 44 байти

R’j“,_”
“¤>%,oỊȤʠ“ØụĊ5D³ṃṠɼQ»j;Ç;“;}¶”
ȷ2RÇ€

Моя перша відповідь желе. Спробуйте в Інтернеті!


Я роблю це неправильно чи це просто виводить гігантський список замість рядка?
Денкер

@DenkerAffe Здається, це працює зараз! У Желлі була тимчасова помилка. (Також посилання було на стару версію мого рішення, тому я його оновив.)
Lynn

Приємно ... зараз це на 9 байт коротше, ніж рішення CJam!
Ray Toal

8

Pyth, 53 50 48 байт

VS100%." }SüÆðQ´Ó3Ô«%&a´4UçõÛ"[Nj",_"UN

Спробуйте в Інтернеті!

Пряма ітерація в межах діапазону (1100) та побудова корроспондірованного рядка з упакованого рядка шляхом його форматування.

Пояснення

VS100%. "} SüÆðQ´Ó3Ô«% & a´4UçõÛ "[Nj", _ "ООН

VS100 # Ітерація в межах діапазону (1100)
     %. "} SüÆðQ´Ó3Ô«% & a´4UçõÛ "# Розпакуйте рядок і відформатуйте
                              [# Список для форматування аргументів
                               N # Кількість кортежу
                                j UN # Приєднати номери об’єктів ...
                                 ", _" # ... на сепараторі ", _"

Розпакований рядок є class Tuple%i {public Object _%s;}


Два гольфи: Використовуйте s[замість усіх цих +. [складає список довільної довжини та sпоєднує його. Крім того, оскільки ви хочете [1, 2, ... 100], не [0, 1, .. 99]використовуйте VS100, і вам не потрібно буде h.
isaacg

@isaacg Спасибі, не знав про- Sтрюк! :) Я вже сидів, щоб позбутися від усіх ++++, я знав, що є кращий спосіб.
Денкер

Ласкаво просимо. До речі, ви, здається, додали трейлінг "без необхідності.
isaacg

1
@isaacg Чи є якась - або причина j<str><int>НЕ U?
lirtosiast

1
Ні, не дуже. Зроблю.
isaacg

7

CoffeeScript, 86 84 байт

console.log "class Tuple#{i} {public Object _#{[0...i].join ',_'};}"for i in[1..100]

Перегляньте рішення в Інтернеті


Welcome to PPCG! Just to let you know edits that improve answers are generally frowned (and should be rejected if they end up in the review queue). So it's more likely that people will comment with suggestions, so you can review them yourself. :) (As for actual tips I think you need neither the space in front of for nor the one after in.)
Martin Ender

Does console.log" work? (Don't know coffee script, that's a general trick.
Addison Crump

No, as in, removing the space. :P I know it exists, I just don't know if that's valid syntax.
Addison Crump

@VoteToClose I tried that earlier (using the live transpiler on coffeescript.org and it didn't work).
Martin Ender

@VoteToClose Oh sorry didn't see that. No. somehow the space is required by the grammar, but it is not exactly clear to me why (yet). Spacing matters a lot in CoffeeScript, for instance, x? y:z is completely different from x ? y:z. You can say console.log?"hello" but not console.log"hello". Significant whitespace. Sometimes nice, sometimes weird.
Ray Toal

7

Java, 160, 125 Bytes

Thanks to @DenkerAffe, @Denham Coote and @Mathias Ettinger for the improvements.

Java writing java( because someone had to!)

void z(){String s="_0";for(int i=1;i<101;){System.out.println("class Tuple"+(i++)+" {public Object "+s+";}");s+=",_"+i;}}

And the un-golfed version

void z(){
    String s = "_0";
    for(int i = 1 ;i < 101;){
        System.out.println("class Tuple" + (i++) + " {public Object "+ s + ";}");
        s += ",_" + i;
        }
    }

2
Welcome to Programming Puzzles & Code Golf! Unless stated otherwise in the challenge, you can alwasy use functions instead of full programs. So you should use a Java8-lambda (which returns the result) here to save you all the public static void main...stuff.
Denker

4
Welcome to PPCG. This answer includes an extra comma at the end of the Object declarations... class Tuple1 {public Object _0,;} class Tuple2 {public Object _0,_1,;}
Denham Coote

3
You can save a further 3 bytes by incrementing your loop counter in the sysout (++i) instead of (i+1) and removing i++ from the for loop setup
Denham Coote

You should start your String s = "_0" so you can s += ",_" + i and save a byte. It will also solve the problem with the trailing coma. You’ll need to start the for loop going from 1 to less than 101 and will be able to remove an extra 4 bytes by converting the (i+1) in your output message to only i. Obviously, you’ll need to print before incrementing s.
409_Conflict

Thanks, have done all these things, and am definitely going to have a gander at java8-lambda.
SoloKix

6

Oracle SQL 9.2, 138 137 Bytes

SELECT REPLACE('class Tuple'||LEVEL||' {public Object'||SYS_CONNECT_BY_PATH(LEVEL-1,',_')||';}','t,','t ')FROM DUAL CONNECT BY LEVEL<101;

@Peter Thanks for pointing the 0/1 mistake.

The query use the CONNECT BY CLAUSE of hierarchical query to generate 100 rows.

The LEVEL pseudocolumn contains the row number of each row.

SYS_CONNECT_BY_PATH concatenate the first parameter, the row number, of each row, and use the second parameter as the separator.


please add some explanation
Eumel

Clever :) This starts with Object _1 instead of Object _0, so that will take another two bytes (-1). However, the _ can be added to the char of SYS_CONNECT_BY_PATH instead of concatenating, reducing it by two those bytes again: REPLACE('class Tuple'||LEVEL||' {public Object'||SYS_CONNECT_BY_PATH(LEVEL-1,',_')||';}','t,_','t _')
Peter Lang

6

Batch, 128 bytes

@set m=_0
@for /l %%t in (1,1,100)do @call:b %%t
@exit/b
:b
@echo class Tuple%1 {public Object %m%;}&set m=%m%,_%1

Edit: Saved 10 bytes thanks to @Bob. Saved 1 byte thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.


3
I always get really happy to see batch on code golf, also, instead of using @ everywhere, you could redirect output to append to a file called x and use that as output
Dennis van Gils

@DennisvanGils Sadly commands get echoed to standard output.
Neil

Eliminated enabledelayedexpansion for 117 bytes: gist.github.com/Elusive138/4cea555114a979954dcb -- if you don't mind the console window closing you can save two more by removing the /b arg from exit.
Bob

@Neil lol okay so I just tried running it and now I realize what you did. Very clever.
Ashwin Gupta

At beginning, use @echo off
Elliot A.


5

Powershell - 65 bytes

(Amended in response to comment)

All credit to TimmyD

1..100|%{"class Tuple$_ {public Object _$(0..($_-1)-Join",_");}"}

Why the vote down? (Please note this is my first ever post, not a great welcome?)
bulletprooffool


4

R - 199 132 123 118 bytes

Version 4

p=paste0;for(i in 1:10)cat(p("class Tuple",i," {public Object ",toString(sapply(0:(i-1),function(x)p("_",x))),";}\n"))

Version 3

p=paste0;for(i in 1:8)cat(p("class Tuple",i," {public Object ",p(sapply(0:(i-1),function(x)p("_",x)),collapse=","),";}\n"))

Version 2

p=paste0;for(i in 1:100)cat(p("class Tuple",i," {public Object ",p(sapply(0:(i-1),function(x)p("_",x)),collapse=","),";}"),sep="\n")

Version 1

for (i in 1:100){
  foo <- paste0("class Tuple", i, " {public Object ")
  for (j in 0:(i - 1)){
    foo <- if (j < (i - 1)) paste0(foo, "_", j, ",") else paste0(foo, "_", j, ";}")
  }
  print(foo)
}

3
Welcome to Programming Puzzles & Code Golf! Since this is a code golf competition, you'll want to make your code as short as possible. You could start by shortening variable names to a single character each, removing whitespace, and using = for assignment rather than <-.
Alex A.

144 bytes: for(i in 1:100){f=(p=paste0)("class Tuple",i," {public Object ");for(j in 0:(i-1))f=if(j<i-1)p(f,"_",j,",")else p(f,"_",j,";}");cat(f,sep="\n")}
Alex A.

No problem. :) Also, you don't need to keep track of your versions in the post body since the revision history is accessible via the link that says "edited X minutes ago."
Alex A.

(though it may be worthwhile to give some indication, either in your edit summaries or in the post what you changed with each revision so that others could learn from your revision process)
quintopia


4

Java, 103 bytes

s->{s="_0";for(int i=0;i++<100;s+=",_"+i)System.out.printf("class Tuple%s {public Object %s;}\n",i,s);}

My first time here. Hi there! I went for a Java8 lambda expression (aka an anonymous function).

Ungolfed version

s -> {
    s = "_0";
    for (int i = 0; i++ < 100; s += ",_" + i)
        System.out.printf("class Tuple%s {public Object %s;}\n", i, s);
}

To actually use this, as usual in Java8, you have to assign it to a variable of (or cast it to) an appropriate functional interface and then call its method; but technically, the function is only the lambda expression itself, so I am counting only that.

It also requires an input parameter, which saves me a couple bytes, since I can abuse it as a local variable without having to specify its type. I'm not sure if that's considered cheating, but to me it appears to be within the rules: I only saw people state that posting a function is allowed, not how that function needs to be invoked. :) And it doesn't actually read the parameter, so the function is still self-contained; you can pass any String to it, or even null, and it will still produce the correct output.

And here is how to use it:

import java.util.function.Consumer;

public class Main {
    public static void main(String[] args) {
        Consumer<?> r =
            s->{s="_0";for(int i=0;i++<100;s+=",_"+i)System.out.printf("class Tuple%s {public Object %s;}\n",i,s);}
        ;
        r.accept(null); 
    }
}

3

Python 2, 96

def f(n=99):s=n and f(n-1)+',_'+`n`or"class Tuple%d {public Object _0";print s%-~n+';}';return s

Python 3, 98

def f(n=99):s=n and f(n-1)+',_%d'%n or"class Tuple%d {public Object _0";print(s%-~n+';}');return s

Usage:

f()

Ungolfed:

def javatuple(n=99):
    if n == 0:
        s = "class Tuple%d {public Object _0"
    else:
        s = javatuple(n-1) + ',_' + str(n)
    print(s%(n+1) + ';}')
    return s

formers:

103

r=range
for i in r(100):
 print"class Tuple%d {public Object _%s;}"%(i+1,',_'.join(`j`for j in r(i+1)))

108

def f(n=99):
 if n:f(n-1)
 print"class Tuple%d {public Object _%s;}"%(n+1,',_'.join(`i`for i in range(n+1)))

In your python2 answer the last line seems to be incomplete : print f(3) gives : class Tuple1 {public Object _0;} class Tuple2 {public Object _0,_1;} class Tuple3 {public Object _0,_1,_2;} class Tuple4 {public Object _0,_1,_2,_3;} class Tuple%d {public Object _0,_1,_2,_3
dieter

@dieter The last line is a result. It's printed only when you run it interactively.
pacholik


2

Groovy, 74 chars

"join()" is unbeatable... New solution, thanks to @yariash

100.times{println"class Tuple$it {public Object _${(0..it-1).join',_'};}"}

Old solution, 78 chars:

(1..100).each{println"class Tuple$it {public Object _${(0..it-1).join',_'};}"}

2
You can use 100.times{} instead of (1..100).each{}.
Krzysztof Atłasik

@yariash Thanks for the hint!
t0r0X

1

Julia, 77 bytes

for i=1:100;println("class Tuple$i {public Object _$(join(0:i-1,",_"));}")end

1

Lua, 128 106 Bytes

I'm still trying to find a way to directly work on a printed value, and not on a string.

Edit : Partially found it! I still need a string for the "_0,_1..." part, but it already is better :).

s=""for i=0,99 do s=(s..",_"..i):gsub("^,",s)print(("class Tuple"..(i+1).." {public Object ")..s..";}")end

Old 128 Bytes solution

s="class Tuple1 {public Object _0;}"print(s)for i=1,99 do s=s:sub(1,s:find";"-1):gsub("e%d+","e"..i+1)..",_"..i..";}"print(s)end

Ungolfed

s=""
for i=0,99
do
  s=(s..",_"..i)              -- concatenate s with ",_i"
      :gsub("^,",s)           -- remove the leading "," for ",_0"
  -- then print the concatenated string
  print(("class Tuple"..(i+1).." {public Object ")..s..";}")
end

1

Python 3, 111 109 105 bytes

[print('class Tuple%s {public Object %s;}'%(i,','.join('_%i'%j for j in range(i))))for i in range(1,101)]

It's not the shortest thing in the world, I'm just participating.

edit1: down 2 bytes by removing 0, in first range

edit2: I was unnecessarily casting int to str instead of just using %i... Down to 105.


Welcome, nice start! If interested, try range(i) in place of range(0,i) or since you used range twice, try r=range early then reference each call with just r (as in the other Python solutions).
Ray Toal

Ugh, I forgot range starts at 0 by default. Down 2 bytes, however, adding r=range; in the beginning results in exactly the same character count, I've tried that! :D
Issak

Same comment than I did to Dair: ',_'.join(map(str,range(i))) is 7 bytes shorter here.
409_Conflict

1

Mathematica, 130 Bytes

{"class Tuple",ToString[#]," {public Object ",StringReplace[ToString[#-1&/@Range@#],{" "|"{" ->"_","}"->";}\n"}]}&/@Range[100]<>""

Hint: \n can be replaced with a literal newline character.
LegionMammal978

1

Scala, 85 Bytes

for(u<-1 to 100)println(s"class Tuple$u {public Object _${0 to u-1 mkString ",_"};}")

1

Java, 116

(for the printing function only - according to some comments, this is in line with the rules)

import static java.lang.System.*;
public class T
{
    public static void main(String[] args)
    {
        T t = new T();
        t.p();
    }

    void p(){String s="_0";for(int i=0;i<100;){out.println("class Tuple"+ ++i+" {public Object "+ s + ";}");s+=",_"+i;}}
}

1

PHP, 112 bytes

<?php for($i=0;$i<100;$i++){$m.=$i==0?'_'.$i:',_'.$i;echo 'class Tuple'.($i+1).' {public Object '.$m.';}<br/>';}

You can save a few bytes by switching echo to double quotes where possible: <?php for($i=0;$i<100;$i++){$m.=$i==0?"_$i":",_$i";echo 'class Tuple'.($i+1)." {public Object $m;}\n";}
Samsquanch

1
@Samsquanch Also, instead of echo 'class Tuple'.($i+1)." {public Object $m;}\n";, you can use echo'class Tuple',$i+1," {public Object $m;}\n";, which is 3 bytes shorter. Also, according to the meta, you can remove the <?php and assume that your code will be executed with php -r "code". Also, you can do for(;++$i<101;)echo"class Tuple$i {public Object ",$m=($m?"$m,":'')."_$i",";}\n"; for 80 bytes (you need to replace the \n with a real newline). Try it here: ideone.com/oOzKtP
Ismael Miguel

1

Seriously, 55 bytes

2╤R`;r"$'_+"£M',j@k"c╙ò T╒α%d {pu▐V Object %s;}"⌡%`M'
j

Hexdump (reversible with xxd -r):

00000000: 32e2 95a4 5260 3b72 2224 275f 2b22 c2a3  2...R`;r"$'_+"..
00000010: 4d27 2c6a 406b 2263 e295 99c3 b220 54e2  M',j@k"c..... T.
00000020: 9592 ceb1 2564 207b 7075 e296 9056 204f  ....%d {pu...V O
00000030: 626a 6563 7420 2573 3b7d 22e2 8ca1 2560  bject %s;}"...%`
00000040: 4d27 0a6a                                M'.j

Try it online!

Yes, that newline is supposed to be there.

Explanation (newline replaced with \n):

2╤R`;r"$'_+"£M',j@k"c╙ò T╒α%d {pu▐V Object %s;}"⌡%`M'\nj
2╤R                                                       push range [1,100]
   `                                              `M      map:
    ;r                                                      push a, range(a)
      "$'_+"£M                                              map:
       $'_+                                                   stringify, prepend "_"
              ',j                                           join with commas
                 @k                                         swap and push stack as list
                   "c╙ò T╒α%d {pu▐V Object %s;}"⌡           decompress, result is
                                                              "class Tuple%d {public Object %s;}"
                                                 %          string format
                                                    '\nj  join with newlines

1

Japt, 52 bytes

Lo £`cÓ? TÕà{X} \{puÞV Object {Xò ®'_+Z}&}` r&59d} ·

The ? should be the literal byte 0x95. Test it online!

Japt has:

  • concise syntax to help shorten your code.
  • string compression to help shorten it even further.
  • lots of bugs to make you want to throw your computer out the window.

I can't even use a semicolon in the string because the function it's wrapped in wants to return everything after the semicolon. This should only be 46 bytes:

Lo £`cÓ? TÕà{X} \{puÞV Object {Xò ®'_+Z};}`} ·

But alas, it is not. I'll see if I can fix these bugs over the next couple of hours.

How it works

Lo £       }  // Generate the range [0..100), and map each item X in this range to:
`cÓ? TÕà{X}   //  "class Tuple" + X +
\{puÞV Object //  "{public Object" +
{Xò ®'_+Z}    //   Create the range [0..X] and map each item Z to "_" + Z.
              //   Upon stringification, this automatically inserts the commas.
&}`           //  + "&}"
r&59d         //  Replace the "&" with String.fromCharCode(59), or ";".
·             // Join the result with newlines.

Bah! Ninjaed by ~18 months! You need to increment the first X, by the way.
Shaggy

1

Javascript, 112 110 bytes

2 bytes off thanks @CᴏɴᴏʀO'Bʀɪᴇɴ.

_=>[...Array(100)].map((x,i)=>`class Tuple${++i} {public Object ${[...Array(i)].map((y,j)=>'_'+j)};}`).join`
`

Ungolfed:

_=>                                         // anonymous function
    [...Array(100)].map((x,i)=>             // 100 times [0..99]
        `class Tuple${++i} {public Object   // Tuple index + 1
            ${[...Array(i)].map(            // (index + 1) times
                (y,j)=>'_'+j                // _+j with j in [0..index]
            )}                              // Array without join prints comma in between
        ;}`                                 // as literal string
    ).join`\n`                              // display array line by line

1
I think you can replace ${i+1} with ${i++} and replace ${[...Array(i++)] with ${[...Array(i)].
Conor O'Brien

@CᴏɴᴏʀO'Bʀɪᴇɴ. Thanks, I've updated with ++i
removed

1

Groovy, 97 bytes

(1..100).each{println "class Tuple${it} {public Object ${(0..it-1).collect{"_$it"}.join(',')};}"}

Try it online!


1
You can user 100.times{} instead of (1..100).each{}, which saves 4 bytes.
Krzysztof Atłasik

You can also omit braces in join (join','), remove space after println, and replace .collect{} with *.with{}
Krzysztof Atłasik

1

Python 2, 96 Bytes

r=range
for i in r(1,101):print"class Tuple%d {public Object _%s;}"%(i,',_'.join(map(str,r(i))))

Thanks @DenkerAffe for the suggestion of using lambda.

Thanks @MathiasEttinger for the join idea.


2
You can golf this down to 111 bytes if you use a lambda in your reduce-call instead of defining a function for this: reduce(lambda x,y:'%s,_%s'%(x,y), r(i))
Denker

1
Or use ',_'.join(map(str,r(i))) for an extra 14 bytes removal (or 15, since you left an extra space in your reduce).
409_Conflict

1

C++, 164 159 157 bytes (155 as function only)

#include <iostream>
#define o std::cout<<
int main(){int j,i=0;for(;i<100;++i){o"class Tuple"<<i+1<<" {public Object _0";for(j=0;++j<=i;)o",_"<<j;o";}\n";}}

This is a full program. You can save 2 bytes in function only form if you replace int main() with void f().

Run code in Ideone

Ungolfed, including macro expansion

#include <iostream>
int main()
{
    int j,i=0;
    for(;i<100;++i)
    {
        std::cout << "class Tuple"<< i+1 <<" {public Object _0";
        for(j=0;++j<=i;)
            std::cout << ",_" << j;
        std::cout << ";}\n";
    }
}

Welcome to Programming Puzzles & Code Golf! Nice first answer! Unless stated otherwise in the challenge, you can always use functions instead of full programs, so you can save a few bytes by doing that. You still have to include iostream tho, since its needed for the output.
Denker

You might also want to do j=1 in your for loop, thus not having the if(j).
Ethiraric

@Ethiraric But of course! How sloppy of me. I guess I got too focused on the idea "remember to skip additions on first line" and ended up writing that too literally.
sendaran

@sendaran Or even may be for(int j=0;++j<=i;) would save one more byte.
Ethiraric

@Ethiraric Did that and shaved off an extra byte by extracting variable declarations, which enabled another empty expression.
sendaran
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.