What is spaghetti code? [closed] - terminology

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Can you post a short example of real, overdone spaghetti code, possibly saying what it does? Can you show me a little debugger's nightmare?
I don't mean IOCCC code, that is science fiction. I mean real life examples that happened to you...
Update
The focus has changed from "post some spaghetti code" to "what is exactly spaghetti code?". From a historical perspective, the current choices seem to be:
old Fortran code using computed gotos massively
old Cobol code using the ALTER statement

To me, a more modern example of spaghetti code is when you have 20 dlls and every DLL references each other in one way or another. Your dependency graph looks like a huge blob, and your code hops all over the place with no real order. Everything is inter-dependent.

I'm not pulling this out of my head. This is what I have had to work with, albeit simplified. Let's say that basically you have a program that needs an enum:
enum {
a, b, c;
} myenum;
But instead what we have is
HashTable t;
t["a"] = 0;
t["b"] = 1;
t["c"] = 2;
But of course, no implementation of a hash table is good enough so there is a local implementation of hash tables, which contains about 10 times more code than an average open source implementation with half the features and double the number of bugs. The HashTable is actually defined virtual, and there's a factory HashTableFactory to create instances of HashTables, but true to the pattern HashTableFactory is also virtual. To prevent an infite cascade of virtual classes there's a function
HashTableFactory *makeHashTableFactor();
Thus everywhere where the code needs myenum's it carries a reference to the instance of a HashTable and HashTableFactory, in case you want to make more HashTable's. But wait, that's not all! This is not how the hash table is initialized, but it's done by writing a code that reads XML:
<enum>
<item name="a" value="0"/>
<item name="b" value="1"/>
<item name="c" value="2"/>
</enum>
and inserts into a hash table. But the code is "optimised" so that it doesn't read an ascii file myenum.xml, but instead there's a compile time script which generates:
const char* myenumXML = [13, 32, 53 ....];
from myenum.xml and the hash table is initialized by a function:
void xmlToHashTable(char *xml, HashTable *h, HashTableFactory *f);
which is called:
HashTableFactory *factory = makeHashTableFactory();
HashTable *t = facotry.make();
xmlToHashTable(myenumXML, t, f);
Ok, so we have a lot of code to get an enum structure. It's basically used in a function:
void printStuff(int c) {
switch (c) {
case a: print("a");
case b: print("b");
case c: print("c");
}
}
and this is called in a context where:
void stuff(char* str) {
int c = charToEnum(str);
printStuff(c);
}
So what we actually have is instead of
void stuff(char *str) {
printf(str);
}
we have manged to generate thousands of lines of code (private new, buggy, complex, implementation of hashtables, and xml readers, and writer) in place of the above 3.

There's also Ravioli Code, which is the opposite. Nice little chunks of functionality, a clean interface neatly wrapped around meaty goodness, all sat in a nice sauce of framework.

From a Linux SCSI driver (which shall remain nameless to protect the guilty):
wait_nomsg:
if ((inb(tmport) & 0x04) != 0) {
goto wait_nomsg;
}
outb(1, 0x80);
udelay(100);
for (n = 0; n < 0x30000; n++) {
if ((inb(tmport) & 0x80) != 0) { /* bsy ? */
goto wait_io;
}
}
goto TCM_SYNC;
wait_io:
for (n = 0; n < 0x30000; n++) {
if ((inb(tmport) & 0x81) == 0x0081) {
goto wait_io1;
}
}
goto TCM_SYNC;
wait_io1:
inb(0x80);
val |= 0x8003; /* io,cd,db7 */
outw(val, tmport);
inb(0x80);
val &= 0x00bf; /* no sel */
outw(val, tmport);
outb(2, 0x80);
TCM_SYNC:
/* ... */
small_id:
m = 1;
m <<= k;
if ((m & assignid_map) == 0) {
goto G2Q_QUIN;
}
if (k > 0) {
k--;
goto small_id;
}
G2Q5: /* srch from max acceptable ID# */
k = i; /* max acceptable ID# */
G2Q_LP:
m = 1;
m <<= k;
if ((m & assignid_map) == 0) {
goto G2Q_QUIN;
}
if (k > 0) {
k--;
goto G2Q_LP;
}
G2Q_QUIN: /* k=binID#, */
How did I locate this gem?
find /usr/src/linux -type f -name \*.c |
while read f
do
echo -n "$f "
sed -n 's/^.*goto *\([^;]*\);.*/\1/p' $f | sort -u | wc -l
done |
sort +1rn |
head
The output is a series of lines listing files ordered by the number of gotos to distinct labels, like the following:
kernel/fork.c 31
fs/namei.c 35
drivers/infiniband/hw/mthca/mthca_main.c 36
fs/cifs/cifssmb.c 45
fs/ntfs/super.c 47

Don't forget to mention Object-oriented spaghetti.
This is when you try to use all the design patterns in the book, even when they don't make sense. This leads to spaghetti code at conceptual level, which is far more detrimental to quality than classical goto-based spaghetti code.

Real spaghetti code was done in COBOL and used the ALTER statement.
Here's an example, while listed a "humor", I've seen this kind of thing. Almost got fired once for noting that any program with an Alter statement was obviously in a state of sin. I refused to "maintain" that program, it was quicker to replace it than understand it.

You've asked for it, you'll get it:
This is the source of a DOS .com file that plays the Blue Danube waltz. The executable is just 176 bytes in size. Code is re-used as data and vice versa.
.286
.model tiny
g4 equ 55-48 ; removed note-decoding !
a4 equ 57-48 ; now: storing midi-notes for octaves 0..2 and convert
h4 equ 59-48 ; to 4..6 with a simple add 48.
c5 equ 60-48
d5 equ 62-48
e5 equ 64-48
g5 equ 67-48
h5 equ 71-48
c6 equ 72-48
d6 equ 74-48
e6 equ 76-48
g6 equ 79-48 ; = 00011111b
pp equ 0 ; c4 is not used in the walz, using it as play-pause.
EOM equ 1 ; c#4 is also available... End Of Music
; warning: experts only beyond this point !
pau1 equ 00100000b ; bitfield definitions for note-compression
pau2 equ 01000000b ; you can or a pau to each note!
pau3 equ 01100000b
;rep1 equ 01000000b ; rep1 is history (only used once).
;rep3 equ 11000000b ; rep3 was never used.
rep2 equ 10000000b ; or a rep2 to a note to play it 3 times.
drumsize equ 5
.code
org 100h
start:
mov ah,9
mov dx,offset msg
int 21h ; print our headerstring
mov dx,0330h ; gus midi megaem -port
mov si,offset music_code ; start of music data
mainloop:
; get new note (melody)
xor bp,bp ; bp= repeat-counter
lodsb ; get a new note
cmp al, EOM ; check for end
jne continue
ret
continue:
jns no_rep2 ; check for rep2-Bit
inc bp
inc bp ; "build" repeat-counter
no_rep2:
push ax ; save the note for pause
; "convert" to midi-note
and al,00011111b
jz skip_pp ; check pp, keep it 0
add al,48 ; fix-up oktave
skip_pp:
xchg ax,bx ; bl= midi-note
play_again:
mov cl,3
push cx ; patch program (3= piano)
push 0c8h ; program change, channel 9
; wait (cx:dx) times
mov ah,86h ; wait a little bit
int 15h
; prepare drums
dec di ; get the current drum
jns no_drum_underflow
mov di,drumsize
no_drum_underflow:
; play drum
push dx ; volume drum
push [word ptr drumtrk+di] ; note drum
mov al,99h
push ax ; play channel 10
; play melody
push dx ; volume melody
push bx ; note melody
dec ax ; replaces dec al :)
push ax ; play channel 9
; send data to midi-port
mov cl,8 ; we have to send 8 bytes
play_loop:
pop ax ; get the midi event
out dx,al ; and send it
loop play_loop
; repeat "bp" times
dec bp ; repeat the note
jns play_again
; check and "play" pause
xor bx,bx ; clear the note, so we can hear
; a pause
; decode pause value
pop ax
test al,01100000b
jz mainloop ; no pause, get next note
; decrement pause value and save on stack
sub al,20h
push ax
jmp play_again ; and play next drum
; don't change the order of the following data, it is heavily crosslinked !
music_code db pp or rep2
db g4 or rep2 or pau1
db h4 or pau1, d5 or pau1, d5 or pau3
db d6 or pau1, d6 or pau3, h5 or pau1, h5 or pau3
db g4 or rep2 or pau1
db h4 or pau1, d5 or pau1, d5 or pau3
db d6 or pau1, d6 or pau3, c6 or pau1, c6 or pau3
db a4 or rep2 or pau1
db c5 or pau1, e5 or pau1, e5 or pau3
db e6 or pau1, e6 or pau3, c6 or pau1, c6 or pau3
db a4 or rep2 or pau1
db c5 or pau1, e5 or pau1, e5 or pau3
db e6 or pau1, e6 or pau3, h5 or pau1, h5 or pau3
db g4 or rep2 or pau1
db h4 or pau1, g5 or pau1, g5 or pau3
db g6 or pau1, g6 or pau3, d6 or pau1, d6 or pau3
db g4 or rep2 or pau1
db h4 or pau1, g5 or pau1, g5 or pau3
db g6 or pau1, g6 or pau3, e6 or pau1, e6 or pau3
db a4 or rep2 or pau1
db c5 or pau1, e5 or pau1, e5 or pau3, pp or pau3
db c5 or pau1, e5 or pau1, h5 or pau3, pp or pau3, d5 or pau1
db h4 or pau1, h4 or pau3
db a4 or pau1, e5 or pau3
db d5 or pau1, g4 or pau2
; db g4 or rep1 or pau1
; replace this last "rep1"-note with two (equal-sounding) notes
db g4
db g4 or pau1
msg db EOM, 'Docking Station',10,'doj&sub'
drumtrk db 36, 42, 38, 42, 38, 59 ; reversed order to save some bytes !
end start

Real spaghetti-code requires a multitude of non-local gotos. Sadly this is not possible using most modern languages.
Edit: Some suggest exceptions and longjmp as substitutes for GOTO. But these are far to limited and structured, since they only allow you to return up the callstack. Real GOTO allows you to jump to any line anywhere in the program, which is necessary to create real spaghetti.

In simple terms spaghetti code is any code in any programming language in which it is not possible to trace the next post of execution, or at least difficult to determine where the next point goes in response of one action.

This is from a MIDI parser I wrote some time ago. It was a quick and dirty proof of concept, but nevertheless, I shall take the blame for its ugliness: 4 levels of nested conditionals plus the dreaded multiple returns. This code was meant to compare 2 MIDI events in order to sort them by priority when writing to a file. Ugly as it was, it did the job decently, though.
internal class EventContainerComparer : IComparer {
int IComparer.Compare(object a, object b) {
MIDIEventContainer evt1 = (MIDIEventContainer) a;
MIDIEventContainer evt2 = (MIDIEventContainer) b;
ChannelEvent chanEvt1;
ChannelEvent chanEvt2;
if (evt1.AbsoluteTime < evt2.AbsoluteTime) {
return -1;
} else if (evt1.AbsoluteTime > evt2.AbsoluteTime) {
return 1;
} else {
// a iguar valor de AbsoluteTime, los channelEvent tienen prioridad
if(evt1.MidiEvent is ChannelEvent && evt2.MidiEvent is MetaEvent) {
return -1;
} else if(evt1.MidiEvent is MetaEvent && evt2.MidiEvent is ChannelEvent){
return 1;
// si ambos son channelEvent, dar prioridad a NoteOn == 0 sobre NoteOn > 0
} else if(evt1.MidiEvent is ChannelEvent && evt2.MidiEvent is ChannelEvent) {
chanEvt1 = (ChannelEvent) evt1.MidiEvent;
chanEvt2 = (ChannelEvent) evt2.MidiEvent;
// si ambos son NoteOn
if( chanEvt1.EventType == ChannelEventType.NoteOn
&& chanEvt2.EventType == ChannelEventType.NoteOn){
// chanEvt1 en NoteOn(0) y el 2 es NoteOn(>0)
if(chanEvt1.Arg1 == 0 && chanEvt2.Arg1 > 0) {
return -1;
// chanEvt1 en NoteOn(0) y el 2 es NoteOn(>0)
} else if(chanEvt2.Arg1 == 0 && chanEvt1.Arg1 > 0) {
return 1;
} else {
return 0;
}
// son 2 ChannelEvent, pero no son los 2 NoteOn, el orden es indistinto
} else {
return 0;
}
// son 2 MetaEvent, el orden es indistinto
} else {
return 0;
}
}
}
}

Here is the Duff's Device, from Matt's answer to this question:
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while (--n > 0);
}

Spaghetti code: Originating in the early 60's in Italy as an alternate recipe for certain pasta dishes, spaghetti code was cooked up by one restaurant entrepreneur who attempted to automate the creation of a fool-proof entree. Pressed by the lack of time to complete the design the engineer/chef cut corners which introduced problems in the recipe early on. In a frantic attempt to remedy a good idea gone bad, various spices were quickly added to the concoction as the recipe grew out of control. The result was a stringy, twisty, yet potentially tasty pile of text that would later grow to be a practice cherished by developers world-wide.

Have you ever looked at code generated by Flex/Bison scanner and generator? A plethora of labels and preprocessor directives.
It's absolutely impossible to understand what's inside.. and absolutely impossible to follow flow of the program.
That's definetely spaghetti code.

Related

Creating a function in assembly language (TASM)

I wanted to print the first 20 numbers using loop.
Printing the first nine numbers is absolutely fine as the hexadecimal and decimal codes are the same, but from the 10th number I had to convert each number into its appropriate code and then convert it and store it to string and eventually display it
That is,
If (NUMBER > 9)
ADD 6D
;10d = 0ah --(+6)--> 16d = 10h
IF NUMBER IS > 19
ADD 12D
;20d = 14h --(+12)--> 32d = 20h
Then rotating and shifting each number to get the desired output number, that is,
DAA # let al = 74h = 0111.0100
XOR AH,AH # ah = 0 (Just in case it wasn't)
# ax = 0000.0000.0111.0100
ROR AX,4 # ax = 0100.0000.0000.0111 = 4007h
SHR AH,4 # ax = 0000.0100.0000.0111 = 0407h
ADD AX,3030h # ax = 0011.0100.0011.0111 = 3437h = ASCII "74" (Reversed due to little endian)
And then storing the result in to the string and displaying it, that is,
MOV BX,OFFSET Result ;Let Result is an empty string
MOV byte ptr[BX],5 ;Size of the string
MOV byte ptr[BX+4],'$' ;String terminator
MOV byte ptr[BX+3],AH ;storing number
MOV byte ptr[BX+2],AL
MOV DX,BX
ADD DX,02 ;Displaying the result
MOV AH,09H ;Interrupt 21 service to display string
INT 21H
And here is the complete code with proper commenting,
MOV CX,20 ;Number of iterations
MOV DX,0 ;First value of the sequence
L1:
PUSH DX
ADD DX,30H ; 30H is equal to 0 in hexadecimal , 31H = 1 and so on
MOV AH,02H ; INTERRUPT Service to print the DX content
INT 21H
POP DX
ADD DX,1
CMP DX,09 ; if number is > 9 i.e 0A then go to L2
JA L2
LOOP L1
L2:
PUSH DX
MOV AX,DX
CMP AX,14H ;If number is equal to 14H(20) then Jump to L3
JE L3
ADD AX,6D ;If less than 20 then add 6D
XOR AH,AH ;Clear the content of AH
ROR AX,4 ;Rotating and Shifting for to properly store
SHR AH,4
ADC AX,3030h
MOV BX,OFFSET Result
MOV byte ptr[BX],5
MOV byte ptr[BX+4],'$'
MOV byte ptr[BX+3],AH
MOV byte ptr[BX+2],AL
MOV DX,BX
ADD DX,02
MOV AH,09H
INT 21H
POP DX
ADD DX,1
LOOP L2
;If the number is equal to 20 come here, ->
; Every step is repeated here just to change 6D to 12D
L3:
ADD AX,12D
XOR AH,AH
ROR AX,1
ROR AX,1
ROR AX,1
ROR AX,1
SHR AH,1
SHR AH,1
SHR AH,1
SHR AH,1
ADC AX,3030h
MOV BX,OFFSET Result
MOV byte ptr[BX],5
MOV byte ptr[BX+4],'$'
MOV byte ptr[BX+3],AH
MOV byte ptr[BX+2],AL
MOV DX,BX
ADD DX,02
MOV AH,09H
INT 21H
Is there any proper way to do it, creating a function and using if/else (jumps) to get the desired output rather than repeating the code again and again?
PSEUDO CODE:
VAR = 6
IF Number is > 9
ADD AX,VAR
Else IF Number is > 19
ADD AX,(VAR*2)
ELSE IF NUMBER is > 29
ADD AX,(VAR*3)
So you just want to print 0 ... 20 as ASCII characters? It looks like you understand that the numerals are identified as 0x30 ... 0x39 for '0' to '9', so you could use integer division to generate the character for the tens digit:
I usually work with C but conversion to assembler shouldn't be too complicated since these are all fundamental operations and there are no function calls.
int i_value = 29;
int i_tens = i_value/10; //Integer division! 29/10 = 2, save for later use
char c_tens = '0' + i_tens;
char c_ones = '0' + i_value-(10*i_tens); // Subtract N*10 from value
The output will be c_tens = 0x32, c_ones = 0x39. You should be able to wrap this inside of a loop pretty easily using a pair of registers.
Pseudocode
regA <- num_iterations //For example, 20
regB <- 0 //Initialize counter register
LOOP:
//Do conversion for the current iteration.
//Manipulate bytes for output as necessary.
regB <- regB +1
branch not equal regA, regB LOOP
The following code counts from 0 up to 99 (ax contains the ASCII number):
count proc
mov cx, 100 ; loop runs the times specified in the cx register
xor bx, bx ; set counter to zero
print:
mov ax, bx
aam ; Converts binary to unpacked BCD
xor ax, 3030h ; Converts upacked BCD to ASCII
; Print here (ax now contains the numer in ASCII representation)
inc bx ; Increase counter
loop print
ret
count endp

Code Golf: Conway's Game of Life

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The Challenge: Write the shortest program that implements John H. Conway's Game of Life cellular automaton. [link]
EDIT: After about a week of competition, I have selected a victor: pdehaan, for managing to beat the Matlab solution by one character with perl.
For those who haven't heard of Game of Life, you take a grid (ideally infinite) of square cells. Cells can be alive (filled) or dead (empty). We determine which cells are alive in the next step of time by applying the following rules:
Any live cell with fewer than two live neighbours dies, as if caused by under-population.
Any live cell with more than three live neighbours dies, as if by overcrowding.
Any live cell with two or three live neighbours lives on to the next generation.
Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
Your program will read in a 40x80 character ASCII text file specified as a command-line argument, as well as the number of iterations (N) to perform. Finally, it will output to an ASCII file out.txt the state of the system after N iterations.
Here is an example run with relevant files:
in.txt:
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
..................................XX............................................
..................................X.............................................
.......................................X........................................
................................XXXXXX.X........................................
................................X...............................................
.................................XX.XX...XX.....................................
..................................X.X....X.X....................................
..................................X.X......X....................................
...................................X.......XX...................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
Iterate 100 times:
Q:\>life in.txt 100
Resultant Output (out.txt)
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
..................................XX............................................
..................................X.X...........................................
....................................X...........................................
................................XXXXX.XX........................................
................................X.....X.........................................
.................................XX.XX...XX.....................................
..................................X.X....X.X....................................
..................................X.X......X....................................
...................................X.......XX...................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
................................................................................
The Rules:
You need to use file I/O to read/write the files.
You need to accept an input file and the number of iterations as arguments
You need to generate out.txt (overwrite if it exists) in the specified format
You don't need to deal with the edges of the board (wraparound, infinite grids .etc)
EDIT: You do need to have newlines in your output file.
The winner will be determined by character count.
Good luck!
Mathematica - 179 163 154 151 chars
a = {2, 2, 2};
s = Export["out.txt",
CellularAutomaton[{224, {2, {a, {2, 1, 2}, a}}, {1,1}},
(ReadList[#1, Byte, RecordLists → 2>1] - 46)/ 42, #2]〚#2〛
/. {0 → ".", 1 → "X"}, "Table"] &
Spaces added for readability
Invoke with
s["c:\life.txt", 100]
Animation:
You can also get a graph of the mean population over time:
A nice pattern for generating gliders from Wikipedia
AFAIK Mathematica uses a Cellular Automaton to generate random numbers using Rule 30.
MATLAB 7.8.0 (R2009a) - 174 171 161 150 138 131 128 124 characters
Function syntax: (124 characters)
Here's the easier-to-read version (with unnecessary newlines and whitespace added for better formatting):
function l(f,N),
b=char(importdata(f))>46;
for c=1:N,
b=~fix(filter2(ones(3),b)-b/2-3);
end;
dlmwrite('out.txt',char(b*42+46),'')
And here's how the program is run from the MATLAB Command Window:
l('in.txt',100)
Command syntax: (130 characters)
After a comment about calling functions with a command syntax, I dug a little deeper and found out that MATLAB functions can in fact be invoked with a command-line format (with some restrictions). You learn something new every day!
function l(f,N),
b=char(importdata(f))>46;
for c=1:eval(N),
b=~fix(filter2(ones(3),b)-b/2-3);
end;
dlmwrite('out.txt',char(b*42+46),'')
And here's how the program is run from the MATLAB Command Window:
l in.txt 100
Additional Challenge: Tweetable GIF maker - 136 characters
I thought for fun I'd see if I could dump the output to a GIF file instead of a text file, while still keeping the character count below 140 (i.e. "tweetable"). Here's the nicely-formatted code:
function l(f,N),
b=char(importdata(f))>46;
k=ones(3);
for c=1:N+1,
a(:,:,:,c)=kron(b,k);
b=~fix(filter2(k,b)-b/2-3);
end;
imwrite(~a,'out.gif')
Although IMWRITE is supposed to create a GIF that loops infinitely by default, my GIF is only looping once. Perhaps this is a bug that has been fixed in newer versions of MATLAB. So, to make the animation last longer and make the evolution steps easier to see, I left the frame delay at the default value (which seems to be around half a second). Here's the GIF output using the Gosper Glider Gun pattern:
Improvements
Update 1: Changed the matrix b from a logical (i.e. "boolean") type to a numerical one to get rid of a few conversions.
Update 2: Shortened the code for loading the file and used the function MAGIC as a trick to create the convolution kernel in fewer characters.
Update 3: Simplified the indexing logic, replaced ~~b+0 with b/42, and replaced 'same' with 's' as an argument to CONV2 (and it surprisingly still worked!).
Update 4: I guess I should have searched online first, since Loren from The MathWorks blogged about golfing and the Game of Life earlier this year. I incorporated some of the techniques discussed there, which required me to change b back to a logical matrix.
Update 5: A comment from Aslak Grinsted on the above mentioned blog post suggests an even shorter algorithm for both the logic and performing the convolution (using the function FILTER2), so I "incorporated" (read "copied") his suggestions. ;)
Update 6: Trimmed two characters from the initialization of b and reworked the logic in the loop to save 1 additional character.
Update 7: Eric Sampson pointed out in an e-mail that I could replace cell2mat with char, saving 4 characters. Thanks Eric!
Ruby 1.9 - 189 178 159 155 153 chars
f,n=$*
c=IO.read f
n.to_i.times{i=0;c=c.chars.map{|v|i+=1
v<?.?v:('...X'+v)[[83,2,-79].map{|j|c[i-j,3]}.to_s.count ?X]||?.}*''}
File.new('out.txt',?w)<<c
Edit:
Handles newlines with 4 chars less.
Can remove 7 more (v<?.?v:) if you allow it to clobber newlines when the live cells reach the edges.
perl, 127 129 135 chars
Managed to strip off a couple more characters...
$/=pop;#b=split'',<>;map{$n=-1;#b=map{++$n;/
/?$_:($t=grep/X/,#b[map{$n+$_,$n-$_}1,80..82])==3|$t+/X/==3?X:'.'}#b}1..$/;print#b
Python - 282 chars
might as well get the ball rolling...
import sys
_,I,N=sys.argv;R=range(3e3);B=open(I).read();B=set(k for k in R if'A'<B[k])
for k in R*int(N):
if k<1:b,B=B,set()
c=sum(len(set((k+o,k-o))&b)for o in(1,80,81,82))
if(c==3)+(c==2)*(k in b):B.add(k)
open('out.txt','w').write(''.join('.X\n'[(k in B)-(k%81<1)]for k in R))
Python 2.x - 210/234 characters
Okay, the 210-character code is kind of cheating.
#coding:l1
exec'xÚ=ŽA\nÂ#E÷sŠº1­ƒÆscS‰ØL™Æª··­âî¿GÈÿÜ´1iÖ½;Sçu.~H®J×Þ-‰­Ñ%ª.wê,šÖ§J®d꘲>cÉZË¢V䀻Eîa¿,vKAËÀå̃<»Gce‚ÿ‡ábUt¹)G%£êŠ…óbÒüíÚ¯GÔ/n×Xši&ć:})äðtÏÄJÎòDˆÐÿG¶'.decode('zip')
You probably won't be able to copy and paste this code and get it to work. It's supposed to be Latin-1 (ISO-8859-1), but I think it got perverted into Windows-1252 somewhere along the way. Additionally, your browser may swallow some of the non-ASCII characters.
So if it doesn't work, you can generate the file from plain-old 7-bit characters:
s = """
23 63 6F 64 69 6E 67 3A 6C 31 0A 65 78 65 63 27 78 DA 3D 8E 41 5C 6E C2
40 0C 45 F7 73 8A BA 31 13 AD 83 15 11 11 C6 73 08 63 17 05 53 89 D8 4C
99 C6 AA B7 B7 AD E2 EE BF 47 C8 FF DC B4 31 69 D6 BD 3B 53 E7 75 2E 7E
48 AE 4A D7 DE 90 8F 2D 89 AD D1 25 AA 2E 77 16 EA 2C 9A D6 A7 4A AE 64
EA 98 B2 3E 63 C9 5A CB A2 56 10 0F E4 03 80 BB 45 16 0B EE 04 61 BF 2C
76 0B 4B 41 CB C0 E5 CC 83 03 3C 1E BB 47 63 65 82 FF 87 E1 62 55 1C 74
B9 29 47 25 A3 EA 03 0F 8A 07 85 F3 62 D2 FC ED DA AF 11 47 D4 2F 6E D7
58 9A 69 26 C4 87 3A 7D 29 E4 F0 04 74 CF C4 4A 16 CE F2 1B 44 88 1F D0
FF 47 B6 27 2E 64 65 63 6F 64 65 28 27 7A 69 70 27 29
"""
with open('life.py', 'wb') as f:
f.write(''.join(chr(int(i, 16)) for i in s.split()))
The result of this is a valid 210-character Python source file. All I've done here is used zip compression on the original Python source code. The real cheat is that I'm using non-ASCII characters in the resultant string. It's still valid code, it's just cumbersome.
The noncompressed version weighs in at 234 characters, which is still respectable, I think.
import sys
f,f,n=sys.argv
e=open(f).readlines()
p=range
for v in p(int(n)):e=[''.join('.X'[8+16*(e[t][i]!='.')>>sum(n!='.'for v in e[t-1:t+2]for n in v[i-1:i+2])&1]for i in p(80))for t in p(40)]
open('out.txt','w').write('\n'.join(e))
Sorry about the horizontal scroll, but all newlines in the above are required, and I've counted them as one character each.
I wouldn't try to read the golfed code. The variable names are chosen randomly to achieve the best compression. Yes, I'm serious. A better-formatted and commented version follows:
# get command-line arguments: infile and count
import sys
ignored, infile, count = sys.argv
# read the input into a list (each input line is a string in the list)
data = open(infile).readlines()
# loop the number of times requested on the command line
for loop in range(int(count)):
# this monstrosity applies the rules for each iteration, replacing
# the cell data with the next generation
data = [''.join(
# choose the next generation's cell from '.' for
# dead, or 'X' for alive
'.X'[
# here, we build a simple bitmask that implements
# the generational rules. A bit from this integer
# will be chosen by the count of live cells in
# the 3x3 grid surrounding the current cell.
#
# if the current cell is dead, this bitmask will
# be 8 (0b0000001000). Since only bit 3 is set,
# the next-generation cell will only be alive if
# there are exactly 3 living neighbors in this
# generation.
#
# if the current cell is alive, the bitmask will
# be 24 (8 + 16, 0b0000011000). Since both bits
# 3 and 4 are set, this cell will survive if there
# are either 3 or 4 living cells in its neighborhood,
# including itself
8 + 16 * (data[y][x] != '.')
# shift the relevant bit into position
>>
# by the count of living cells in the 3x3 grid
sum(character != '.' # booleans will convert to 0 or 1
for row in data[y - 1 : y + 2]
for character in row[x - 1 : x + 2]
)
# select the relevant bit
& 1
]
# for each column and row
for x in range(80)
)
for y in range(40)
]
# write the results out
open('out.txt','w').write('\n'.join(data))
Sorry, Pythonistas, for the C-ish bracket formatting, but I was trying to make it clear what each bracket was closing.
Haskell - 284 272 232 chars
import System
main=do f:n:_<-getArgs;s<-readFile f;writeFile"out.txt"$t s$read n
p '\n'_='\n'
p 'X'2='X'
p _ 3='X'
p _ _='.'
t r 0=r
t r n=t[p(r!!m)$sum[1|d<-1:[80..82],s<-[1,-1],-m<=d*s,m+d*s<3240,'X'==r!!(m+d*s)]|m<-[0..3239]]$n-1
F#, 496
I could reduce this a lot, but I like this as it's still in the ballpark and pretty readable.
open System.IO
let mutable a:_[,]=null
let N y x=
[-1,-1;-1,0;-1,1;0,-1;0,1;1,-1;1,0;1,1]
|>Seq.sumBy(fun(i,j)->try if a.[y+i,x+j]='X' then 1 else 0 with _->0)
[<EntryPoint>]
let M(r)=
let b=File.ReadAllLines(r.[0])
a<-Array2D.init 40 80(fun y x->b.[y].[x])
for i=1 to int r.[1] do
a<-Array2D.init 40 80(fun y x->
match N y x with|3->'X'|2 when a.[y,x]='X'->'X'|_->'.')
File.WriteAllLines("out.txt",Array.init 40(fun y->
System.String(Array.init 80(fun x->a.[y,x]))))
0
EDIT
428
By request, here's my next stab:
open System
let mutable a,k=null,Array2D.init 40 80
[<EntryPoint>]
let M r=
a<-k(fun y x->IO.File.ReadAllLines(r.[0]).[y].[x])
for i=1 to int r.[1] do a<-k(fun y x->match Seq.sumBy(fun(i,j)->try if a.[y+i,x+j]='X'then 1 else 0 with _->0)[-1,-1;-1,0;-1,1;0,-1;0,1;1,-1;1,0;1,1]with|3->'X'|2 when a.[y,x]='X'->'X'|_->'.')
IO.File.WriteAllLines("out.txt",Array.init 40(fun y->String(Array.init 80(fun x->a.[y,x]))))
0
That's a 14% reduction with some basic golfing. I can't help but feel that I'm losing by using a 2D-array/array-of-strings rather than a 1D array, but don't feel like doing that transform now. Note how I elegantly read the file 3200 times to initialize my array :)
Ruby 1.8: 178 175 chars
f,n=$*;b=IO.read f
n.to_i.times{s=b.dup
s.size.times{|i|t=([82,1,-80].map{|o|b[i-o,3]||''}*'').count 'X'
s[i]=t==3||b[i]-t==?T??X:?.if s[i]>13};b=s}
File.new('out.txt','w')<<b
Newlines are significant (although all can be replaced w/ semicolons.)
Edit: fixed the newline issue, and trimmed 3 chars.
Java, 441... 346
Update 1 Removed inner if and more ugliness
Update 2 Fixed a bug and gained a character
Update 3 Using lots more memory and arrays while ignoring some boundaries issues. Probably a few chars could be saved.
Update 4 Saved a few chars. Thanks to BalusC.
Update 5 A few minor changes to go below 400 and make it just that extra bit uglier.
Update 6 Now things are so hardcoded may as well read in the exact amount in one go. Plus a few more savings.
Update 7 Chain the writing to the file to save a char. Plus a few odd bits.
Just playing around with BalusC's solution. Limited reputation means I couldnt add anything as a comment to his.
class M{public static void main(String[]a)throws Exception{int t=3240,j=t,i=new Integer(a[1])*t+t;char[]b=new char[i+t],p={1,80,81,82};for(new java.io.FileReader(a[0]).read(b,t,t);j<i;){char c=b[j],l=0;for(int n:p)l+=b[j+n]/88+b[j-n]/88;b[j+++t]=c>10?(l==3|l+c==90?88:'.'):c;}new java.io.FileWriter("out.txt").append(new String(b,j,t)).close();}}
More readable(?) version:
class M{
public static void main(String[]a)throws Exception{
int t=3240,j=t,i=new Integer(a[1])*t+t;
char[]b=new char[i+t],p={1,80,81,82};
for(new java.io.FileReader(a[0]).read(b,t,t);j<i;){
char c=b[j],l=0;
for(int n:p)l+=b[j+n]/88+b[j-n]/88;
b[j+++t]=c>10?(l==3|l+c==90?88:'.'):c;
}
new java.io.FileWriter("out.txt").append(new String(b,j,t)).close();
}
}
Scala - 467 364 339 chars
object G{def main(a:Array[String]){val l=io.Source.fromFile(new java.io.File(a(0)))getLines("\n")map(_.toSeq)toSeq
val f=new java.io.FileWriter("out.txt")
f.write((1 to a(1).toInt).foldLeft(l){(t,_)=>(for(y<-0 to 39)yield(for(x<-0 to 79)yield{if(x%79==0|y%39==0)'.'else{val m=t(y-1)
val p=t(y+1);val s=Seq(m(x-1),m(x),m(x+1),t(y)(x-1),t(y)(x+1),p(x-1),p(x),p(x+1)).count('X'==_)
if(s==3|(s==2&t(y)(x)=='X'))'X'else'.'}})toSeq)toSeq}map(_.mkString)mkString("\n"))
f.close}}
I think there is much room for improvement...
[Edit] Yes, it is:
object G{def main(a:Array[String]){var l=io.Source.fromFile(new java.io.File(a(0))).mkString
val f=new java.io.FileWriter("out.txt")
var i=a(1).toInt
while(i>0){l=l.zipWithIndex.map{case(c,n)=>if(c=='\n')'\n'else{val s=Seq(-83,-82,-81,-1,1,81,82,83).map(_+n).filter(k=>k>=0&k<l.size).count(l(_)=='X')
if(s==3|(s==2&c=='X'))'X'else'.'}}.mkString
i-=1}
f.write(l)
f.close}}
[Edit] And I have the feeling there is still more to squeeze out...
object G{def main(a:Array[String]){val f=new java.io.FileWriter("out.txt")
f.write(((1 to a(1).toInt):\(io.Source.fromFile(new java.io.File(a(0))).mkString)){(_,m)=>m.zipWithIndex.map{case(c,n)=>
val s=Seq(-83,-82,-81,-1,1,81,82,83)count(k=>k+n>=0&k+n<m.size&&m(k+n)=='X')
if(c=='\n')c else if(s==3|s==2&c=='X')'X'else'.'}.mkString})
f.close}}
The following solution uses my own custom domain-specific programming language which I have called NULL:
3499538
In case you are wondering how this works: My language consists of only of one statment per program. The statement represents a StackOverflow thread ID belonging to a code golf thread. My compiler compiles this into a program that looks for the best javascript solution (with the SO API), downloads it and runs it in a web browser.
Runtime could be better for new threads (it may take some time for the first upvoted Javascript answer to appear), but on the upside it requires only very little coding skills.
Javascript/Node.js - 233 236 characters
a=process.argv
f=require('fs')
m=46
t=f.readFileSync(a[2])
while(a[3]--)t=[].map.call(t,function(c,i){for(n=g=0;e=[-82,-81,-80,-1,1,80,81,82][g++];)t[i+e]>m&&n++
return c<m?c:c==m&&n==3||c>m&&n>1&&n<4?88:m})
f.writeFile('out.txt',t)
C - 300
Just wondered how much smaller and uglier my java solution could go in C. Reduces to 300 including the newlines for the preprocessor bits. Leaves freeing the memory to the OS! Could save ~20 by assuming the OS will close and flush the file too.
#include<stdio.h>
#include<stdlib.h>
#define A(N)j[-N]/88+j[N]/88
int main(int l,char**a){
int t=3240,i=atoi(a[2])*t+t;
char*b=malloc(i+t),*j;
FILE*f;
fread(j=b+t,1,t,fopen(a[1],"r"));
for(;j-b-i;j++[t]=*j>10?l==3|l+*j==90?88:46:10)
l=A(1)+A(80)+A(81)+A(82);
fwrite(j,1,t,f=fopen("out.txt","w"));
fclose(f);
}
MUMPS: 314 chars
L(F,N,R=40,C=80)
N (F,N,R,C)
O F:"RS" U F D C F
.F I=1:1:R R L F J=1:1:C S G(0,I,J)=($E(L,J)="X")
F A=0:1:N-1 F I=1:1:R F J=1:1:C D S G(A+1,I,J)=$S(X=2:G(A,I,J),X=3:1,1:0)
.S X=0 F i=-1:1:1 F j=-1:1:1 I i!j S X=X+$G(G(A,I+i,J+j))
S F="OUT.TXT" O F:"WNS" U F D C F
.F I=1:1:R F J=1:1:C W $S(G(N,I,J):"X",1:".") W:J=C !
Q
Java, 556 532 517 496 472 433 428 420 418 381 chars
Update 1: replaced 1st StringBuffer by Appendable and 2nd by char[]. Saved 24 chars.
Update 2: found a shorter way to read file into char[]. Saved 15 chars.
Update 3: replaced one if/else by ?: and merged char[] and int declarations. Saved 21 chars.
Update 4: replaced (int)f.length() and c.length by s. Saved 24 chars.
Update 5: made improvements as per hints of Molehill. Major one was hardcoding the char length so that I could get rid of File. Saved 39 chars.
Update 6: minor refactoring. Saved 6 chars.
Update 7: replaced Integer#valueOf() by new Integer() and refactored for loop. Saved 8 chars.
Update 8: Improved neighbour calculation. Saved 2 chars.
Update 9: Optimized file reading since file length is already hardcoded. Saved 37 chars.
import java.io.*;class L{public static void main(String[]a)throws Exception{int i=new Integer(a[1]),j,l,s=3240;int[]p={-82,-81,-80,-1,1,80,81,82};char[]o,c=new char[s];for(new FileReader(a[0]).read(c);i-->0;c=o)for(o=new char[j=s];j-->0;){l=0;for(int n:p)l+=n+j>-1&n+j<s?c[n+j]/88:0;o[j]=c[j]>13?l==3|l+c[j]==90?88:'.':10;}Writer w=new FileWriter("out.txt");w.write(c);w.close();}}
More readable version:
import java.io.*;
class L{
public static void main(String[]a)throws Exception{
int i=new Integer(a[1]),j,l,s=3240;
int[]p={-82,-81,-80,-1,1,80,81,82};
char[]o,c=new char[s];
for(new FileReader(a[0]).read(c);i-->0;c=o)for(o=new char[j=s];j-->0;){
l=0;for(int n:p)l+=n+j>-1&n+j<s?c[n+j]/88:0;
o[j]=c[j]>10?l==3|l+c[j]==90?88:'.':10;
}
Writer w=new FileWriter("out.txt");w.write(c);w.close();
}
}
Closing after writing is absoletely mandatory, else the file is left empty. It would otherwise have saved another 21 chars.
Further I could also save one more char when I use 46 instead of '.', but both javac and Eclipse jerks with a compilation error Possible loss of precision. Weird stuff.
Note: this expects an input file with \n newlines, not \r\n as Windows by default uses!
PHP - 365 328 322 Characters.
list(,$n,$l) = $_SERVER["argv"];
$f = file( $n );
for($j=0;$j<$l;$j++){
foreach($f as $k=>$v){
$a[$k]="";
for($i=0;$i < strlen( $v );$i++ ){
$t = 0;
for($m=-1;$m<2;$m++){
for($h=-1;$h<2;$h++){
$t+=ord($f[$k + $m][$i + $h]);
}
}
$t-=ord($v[$i]);
$a[$k] .= ( $t == 494 || ($t == 452 && ord($v[$i])==88)) ? "X" : "." ;
}
}
$f = $a;
}
file_put_contents("out.txt", implode("\n", $a ));
I'm sure this can be improved upon but I was curious what it would look like in PHP. Maybe this will inspire someone who has a little more code-golf experience.
Updated use list() instead of $var = $_SERVER["argv"] for both args. Nice one Don
Updated += and -= this one made me /facepalm heh cant believe i missed it
Updated file output to use file_put_contents() another good catch by Don
Updated removed initialization of vars $q and $w they were not being used
R 340 chars
cgc<-function(i="in.txt",x=100){
require(simecol)
z<-file("in.txt", "rb")
y<-matrix(data=NA,nrow=40,ncol=80)
for(i in seq(40)){
for(j in seq(80)){
y[i,j]<-ifelse(readChar(z,1) == "X",1,0)
}
readChar(z,3)
}
close(z)
init(conway) <- y
times(conway)<-1:x
o<-as.data.frame(out(sim(conway))[[100]])
write.table(o, "out.txt", sep="", row.names=FALSE, col.names=FALSE)
}
cgc()
I feel it's slightly cheating to have an add in package that does the actual automata for you, but I'm going with it cos I still had to thrash around with matricies and stuff to read in the file with 'X' instead of 1.
This is my first 'code golf', interesting....
c++ - 492 454 386
my first code golf ;)
#include<fstream>
#define B(i,j)(b[i][j]=='X')
int main(int i,char**v){for(int n=0;n<atoi(v[2]);++n){std::ifstream f(v[1]);v[1]="out.txt";char b[40][83];for(i=0;i<40;++i)f.getline(b[i],83);std::ofstream g("out.txt");g<<b[0]<<'\n';for(i=1;i<39;++i){g<<'.';for(int j=1;j<79;++j){int k=B(i-1,j)+B(i+1,j)+B(i,j-1)+B(i,j+1)+B(i-1,j-1)+B(i+1,j+1)+B(i+1,j-1)+B(i-1,j+1);(B(i,j)&&(k<2||k>3))?g<<'.':(!B(i,j)&&k==3)?g<<'X':g<<b[i][j];}g<<".\n";}g<<b[0]<<'\n';}}
A somewhat revised version, replacing some of the logic with a table lookup+a few other minor tricks:
#include<fstream>
#define B(x,y)(b[i+x][j+y]=='X')
int main(int i,char**v){for(int n=0;n<atoi(v[2]);++n){std::ifstream f(v[1]);*v="out.txt";char b[40][83], O[]="...X.....";for(i=0;i<40;++i)f>>b[i];std::ofstream g(*v);g<<b[0]<<'\n';for(i=1;i<39;++i){g<<'.';for(int j=1;j<79;++j){O[2]=b[i][j];g<<O[B(-1,0)+B(1,0)+B(0,-1)+B(0,1)+B(-1,-1)+B(1,1)+B(1,-1)+B(-1,1)];}g<<".\n";}g<<b[0]<<'\n';}}
Perl – 214 chars
What, no perl entries yet?
$i=pop;#c=<>;#c=map{$r=$_;$u='';for(0..79)
{$K=$_-1;$R=$r-1;$u.=((&N.(&N^"\0\W\0").&N)=~y/X//
|(substr$c[$r],$_,1)eq'X')==3?'X':'.';}$u}keys#c for(1..$i);
sub N{substr$c[$R++],$K,3}open P,'>','out.txt';$,=$/;print P#c
Run with: conway.pl infile #times
Another Java attempt, 361 chars
class L{public static void main(final String[]a)throws Exception{new java.io.RandomAccessFile("out.txt","rw"){{int e=88,p[]={-1,1,-80,80,-81,81,-82,82},s=3240,l=0,i=new Byte(a[1])*s+s,c;char[]b=new char[s];for(new java.io.FileReader(a[0]).read(b);i>0;seek(l=++l%s),i--){c=b[l];for(int n:p)c+=l+n>=0&l+n<s?b[l+n]/e:0;write(c>13?(c==49|(c|1)==91?e:46):10);}}};}}
And a little more readable
class L {
public static void main(final String[]a) throws Exception {
new java.io.RandomAccessFile("out.txt","rw"){{
int e=88, p[]={-1,1,-80,80,-81,81,-82,82},s=3240,l=0,i=new Byte(a[1])*s+s,c;
char[] b = new char[s];
for (new java.io.FileReader(a[0]).read(b);i>0;seek(l=++l%s),i--) {
c=b[l];
for (int n:p)
c+=l+n>=0&l+n<s?b[l+n]/e:0;
write(c>13?(c==49|(c|1)==91?e:46):10);
}
}};
}
}
Very similar to Molehill’s version. I've tried to use a different FileWriter and to count the cell's neighbors without an additional variable.
Unfortunately, RandomAccessFile is a pretty long name and it is required that you pass an file access mode.
RUST - 469 characters
Don't know if I should post this here, (this post is 3 years old) but anyway, my try on this, in rust (0.9):
use std::io::fs::File;fn main(){
let mut c=File::open(&Path::new(std::os::args()[1])).read_to_end();
for _ in range(0,from_str::<int>(std::os::args()[2]).unwrap()){
let mut b=c.clone();for y in range(0,40){for x in range(0,80){let mut s=0;
for z in range(x-1,x+2){for t in range(y-1,y+2){
if z>=0&&t>=0&&z<80&&t<40&&(x !=z||y !=t)&&c[t*81+z]==88u8{s +=1;}}}
b[y*81+x]=if s==3||(s==2&&c[y*81+x]==88u8){88u8} else {46u8};}}c = b;}
File::create(&Path::new("out.txt")).write(c);}
For people interested, here is the code before some agressive golfing:
use std::io::fs::File;
fn main() {
let f = std::os::args()[1];
let mut c = File::open(&Path::new(f)).read_to_end();
let n = from_str::<int>(std::os::args()[2]).unwrap();
for _ in range(0,n)
{
let mut new = c.clone();
for y in range(0,40) {
for x in range(0,80) {
let mut sum = 0;
for xx in range(x-1,x+2){
for yy in range(y-1,y+2) {
if xx >= 0 && yy >= 0 && xx <80 && yy <40 && (x != xx || y != yy) && c[yy*81+xx] == 88u8
{ sum = sum + 1; }
}
}
new[y*81+x] = if sum == 3 || (sum == 2 && c[y*81+x] == 88u8) {88u8} else {46u8};
}
}
c = new;
}
File::create(&Path::new("out.txt")).write(c);
}
ét voilà
you may want to use this html file. no file input, but a textarea that does the job!
there is also some html and initiation and vars. the main routine has only 235 characters.
It's hand-minified JS.
<!DOCTYPE html>
<html><body><textarea id="t" style="width:600px;height:600px;font-family:Courier">
</textarea></body><script type="text/javascript">var o,c,m=new Array(3200),
k=new Array(3200),y,v,l,p;o=document.getElementById("t");for(y=0;y<3200;y++)
{m[y]=Math.random()<0.5;}setInterval(function(){p="";for(y=0;y<3200;y++){c=0;
for(v=-1;v<2;v+=2){c+=m[y-1*v]?1:0;for(l=79;l<82;l++)c+=m[y-l*v]?1:0;}
k[y]=c==3||m[y]&&c==2;}p="";for(y=0;y<3200;y++){p+=(y>0&&y%80==0)?"\n":"";
m[y]=k[y];p+=(m[y]?"O":"-");}o.innerHTML=p;},100);</script></html>
One of the classic patterns
***
..*
.*
My avatar was created using my version of the Game of Life using this pattern and rule(note that it is not 23/3):
#D Thanks to my daughter Natalie
#D Try at cell size of 1
#R 8/1
#P -29 -29
.*********************************************************
*.*******************************************************.*
**.*****************************************************.**
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
****************************.*.****************************
***********************************************************
****************************.*.****************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
***********************************************************
**.*****************************************************.**
*.*******************************************************.*
.*********************************************************
IMHO - as I learned Conway's Game of Life the trick wasn't writing short code, but code that could do complex life forms quickly. Using the classic pattern above and a wrapped world of 594,441 cells the best I could ever do was around 1,000 generations / sec.
Another simple pattern
**********
.
................*
.................**
................**.......**********
And gliders
........................*...........
......................*.*...........
............**......**............**
...........*...*....**............**
**........*.....*...**..............
**........*...*.**....*.*...........
..........*.....*.......*...........
...........*...*....................
............**......................

Code Golf: Rotating Maze

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
Code Golf: Rotating Maze
Make a program that takes in a file consisting of a maze. The maze has walls given by #. The maze must include a single ball, given by a o and any number of holes given by a #. The maze file can either be entered via command line or read in as a line through standard input. Please specify which in your solution.
Your program then does the following:
1: If the ball is not directly above a wall, drop it down to the nearest wall.
2: If the ball passes through a hole during step 1, remove the ball.
3: Display the maze in the standard output (followed by a newline).
Extraneous whitespace should not be displayed.
Extraneous whitespace is defined to be whitespace outside of a rectangle
that fits snugly around the maze.
4: If there is no ball in the maze, exit.
5: Read a line from the standard input.
Given a 1, rotate the maze counterclockwise.
Given a 2, rotate the maze clockwise.
Rotations are done by 90 degrees.
It is up to you to decide if extraneous whitespace is allowed.
If the user enters other inputs, repeat this step.
6: Goto step 1.
You may assume all input mazes are closed. Note: a hole effectively acts as a wall in this regard.
You may assume all input mazes have no extraneous whitespace.
The shortest source code by character count wins.
Example written in javascript:
http://trinithis.awardspace.com/rotatingMaze/maze.html
Example mazes:
######
#o ##
######
###########
#o #
# ####### #
#### #
#########
###########################
# #
# # # #
# # # ##
# # ####o####
# # #
# #
# #########
# #
######################
Perl, 143 (128) char
172 152 146 144 143 chars,
sub L{my$o;$o.=$/while s/.$/$o.=$&,""/meg;$_=$o}$_.=<>until/
/;{L;1while s/o / o/;s/o#/ #/;L;L;L;print;if(/o/){1-($z=<>)||L;$z-2||L&L&L;redo}}
Newlines are significant.
Uses standard input and expects input to contain the maze, followed by a blank line, followed by the instructions (1 or 2), one instruction per line.
Explanation:
sub L{my$o;$o.="\n"while s/.$/$o.=$&,""/meg;$_=$o}
L is a function that uses regular expressions to rotate the multi-line expression $_ counterclockwise by 90 degrees. The regular expression was used famously by hobbs in my favorite code golf solution of all time.
$_.=<>until/\n\n/;
Slurps the input up to the first pair of consecutive newlines (that is, the maze) into $_.
L;1 while s/o / o/;s/o#/ */;
L;L;L;print
To drop the ball, we need to move the o character down one line is there is a space under it. This is kind of hard to do with a single scalar expression, so what we'll do instead is rotate the maze counterclockwise, move the ball to the "right". If a hole ever appears to the "right" of the ball, then the ball is going to fall in the hole (it's not in the spec, but we can change the # to an * to show which hole the ball fell into). Then before we print, we need to rotate the board clockwise 90 degrees (or counterclockwise 3 times) so that down is "down" again.
if(/o/) { ... }
Continue if there is still a ball in the maze. Otherwise the block will end and the program will exit.
1-($z=<>)||L;$z-2||L+L+L;redo
Read an instruction into $z. Rotate the board counterclockwise once for instruction "1" and three times for instruction "2".
If we used 3 more characters and said +s/o[#*]/ */ instead of ;s/o#/ */, then we could support multiple balls.
A simpler version of this program, where the instructions are "2" for rotating the maze clockwise and any other instruction for rotating counterclockwise, can be done in 128 chars.
sub L{my$o;$o.=$/while s/.$/$o.=$&,""/meg;$_=$o}$_.=<>until/
/;L;{1while s/o / o/+s/o#/ #/;L,L,L;print;if(/o/){2-<>&&L,L;redo}}
GolfScript - 97 chars
n/['']/~{;(#"zip-1%":|3*~{{." o"/"o "*"#o"/"# "*.#>}do}%|~.n*."o"/,(}{;\~(2*)|*~\}/\[n*]+n.+*])\;
This isn't done as well as I hoped (maybe later).
(These are my notes and not an explanation)
n/['']/~ #[M I]
{
;(# #[I c M]
"zip-1%":|3*~ #rotate
{{." o"/"o "*"#o"/"# "*.#>}do}% #drop
|~ #rotate back
.n* #"display" -> [I c M d]
."o"/,( #any ball? -> [I c M d ?]
}{ #d is collected into an array -> [I c M]
;\~(2*)|*~ #rotate
\ #stack order
}/
\[n*]+n.+*])\; #output
Rebmu: 298 Characters
I'm tinkering with with my own experiment in Code Golf language design! I haven't thrown matrix tricks into the standard bag yet, and copying GolfScript's ideas will probably help. But right now I'm working on refining the basic gimmick.
Anyway, here's my first try. The four internal spaces are required in the code as it is, but the line breaks are not necessary:
.fFS.sSC L{#o#}W|[l?fM]H|[l?m]Z|[Tre[wH]iOD?j[rvT]t]
Ca|[st[xY]a KrePC[[yBKx][ntSBhXbkY][ntSBhYsbWx][xSBwY]]ntJskPCmFkSk]
Ga|[rtYsZ[rtXfZ[TaRE[xY]iTbr]iTbr]t]B|[gA|[ieSlFcA[rnA]]]
MeFI?a[rlA]aFV[NbIbl?n[ut[++n/2 TfCnIEfLtBRchCbSPieTHlTbrCHcNsLe?sNsZ]]
gA|[TfCaEEfZfA[prT][pnT]nn]ulBbr JmoADjPC[3 1]rK4]
It may look like a cat was on my keyboard. But once you get past a little space-saving trick (literally saving spaces) called "mushing" it's not so bad. The idea is that Rebmu is not case sensitive, so alternation of capitalization runs is used to compress the symbols. Instead of doing FooBazBar => foo baz bar I apply distinct meanings. FOObazBAR => foo: baz bar (where the first token is an assignment target) vs fooBAZbar => foo baz bar (all ordinary tokens).
When the unmush is run, you get something more readable, but expanded to 488 characters:
. f fs . s sc l: {#o#} w: | [l? f m] h: | [l? m] z: | [t: re [w h] i od?
j [rv t] t] c: a| [st [x y] a k: re pc [[y bk x] [nt sb h x bk y] [nt sb
h y sb w x] [x sb w y]] nt j sk pc m f k s k] g: a| [rt y s z [rt x f z
[t: a re [x y] i t br] i t br] rn t] b: | [g a| [ie s l f c a [rn a]]]
m: e fi? a [rl a] a fv [n: b i bl? n [ut [++ n/2 t: f c n ie f l t br
ch c b sp ie th l t br ch c n s l e? s n s z]] g a| [t: f c a ee f z f
a [pr t] [pn t] nn] ul b br j: mo ad j pc [3 1] r k 4]
Rebmu can run it expanded also. There are also verbose keywords as well (first instead of fs) and you can mix and match. Here's the function definitions with some comments:
; shortcuts f and s extracting the first and second series elements
. f fs
. s sc
; character constants are like #"a", this way we can do fL for #"#" etc
L: {#o#}
; width and height of the input data
W: | [l? f m]
H: | [l? m]
; dimensions adjusted for rotation (we don't rotate the array)
Z: | [t: re [w h] i od? j [rv t] t]
; cell extractor, gives series position (like an iterator) for coordinate
C: a| [
st [x y] a
k: re pc [[y bk x] [nt sb h x bk y] [nt sb h y sb w x] [x sb w y]] nt j
sk pc m f k s k
]
; grid enumerator, pass in function to run on each cell
G: a| [rt y s z [rt x f z [t: a re [x y] i t br] i t br] t]
; ball position function
B: | [g a| [ie sc l f c a [rn a]]]
W is the width function and H is the height of the original array data. The data is never rotated...but there is a variable j which tells us how many 90 degree right turns we should apply.
A function Z gives us the adjusted size for when rotation is taken into account, and a function C takes a coordinate pair parameter and returns a series position (kind of like a pointer or iterator) into the data for that coordinate pair.
There's an array iterator G which you pass a function to and it will call that function for each cell in the grid. If the function you supply ever returns a value it will stop the iteration and the iteration function will return that value. The function B scans the maze for a ball and returns coordinates if found, or none.
Here's the main loop with some commenting:
; if the command line argument is a filename, load it, otherwise use string
m: e fi? a [rl a] a
; forever (until break, anyway...)
fv [
; save ball position in n
n: B
; if n is a block type then enter a loop
i bl? n [
; until (i.e. repeat until)
ut [
; increment second element of n (the y coordinate)
++ n/2
; t = first(C(n))
t: f C n
; if-equal(first(L), t) then break
ie f l t br
; change(C(B), space)
ch C B sp
; if-equal(third(L),t) then break
ie th L t br
; change(C(n), second(L))
ch C n s L
; terminate loop if "equals(second(n), second(z))"
e? s n s z
]
]
; iterate over array and print each line
g a| [t: f c a ee f z f a [pr t] [pn t] nn]
; unless the ball is not none, we'll be breaking the loop here...
ul b br
; rotate according to input
j: mo ad j pc [3 1] r k 4
]
There's not all that much particularly clever about this program. Which is part of my idea, which is to see what kind of compression one could get on simple, boring approaches that don't rely on any tricks. I think it demonstrates some of Rebmu's novel potential.
It will be interesting to see how a better standard library could affect the brevity of solutions!
Latest up-to-date commented source available on GitHub: rotating-maze.rebmu
Ruby 1.9.1 p243
355 353 characters
I'm pretty new to Ruby, so I'm sure this could be a lot shorter - theres probably some nuances i'm missing.
When executed, the path to the map file is the first line it reads. I tried to make it part of the execution arguments (would have saved 3 characters), but had issues :)
The short version:
def b m;m.each_index{|r|i=m[r].index(?o);return r,i if i}end;def d m;x,y=b m;z=x;
while z=z+1;c=m[z][y];return if c==?#;m[z-1][y]=" "; return 1 if c==?#;m[z][y]=?o;end;end;
def r m;m.transpose.reverse;end;m=File.readlines(gets.chomp).map{|x|x.chomp.split(//)};
while a=0;w=d m;puts m.map(&:join);break if w;a=gets.to_i until 0<a&&a<3;
m=r a==1?m:r(r(m));end
The verbose version:
(I've changed a bit in the compressed version, but you get the idea)
def display_maze m
puts m.map(&:join)
end
def ball_pos m
m.each_index{ |r|
i = m[r].index("o")
return [r,i] if i
}
end
def drop_ball m
x,y = ball_pos m
z=x
while z=z+1 do
c=m[z][y]
return if c=="#"
m[z-1][y]=" "
return 1 if c=="#"
m[z][y]="o"
end
end
def rot m
m.transpose.reverse
end
maze = File.readlines(gets.chomp).map{|x|x.chomp.split(//)}
while a=0
win = drop_ball maze
display_maze maze
break if win
a=gets.to_i until (0 < a && a < 3)
maze=rot maze
maze=rot rot maze if a==1
end
Possible improvement areas:
Reading the maze into a clean 2D array (currently 55 chars)
Finding and returning (x,y) co-ordinates of the ball (currently 61 chars)
Any suggestions to improve are welcome.
Haskell: 577 509 527 244 230 228 chars
Massive new approach: Keep the maze as a single string!
import Data.List
d('o':' ':x)=' ':(d$'o':x)
d('o':'#':x)=" *"++x
d(a:x)=a:d x
d e=e
l=unlines.reverse.transpose.lines
z%1=z;z%2=l.l$z
t=putStr.l.l.l
a z|elem 'o' z=t z>>readLn>>=a.d.l.(z%)|0<1=t z
main=getLine>>=readFile>>=a.d.l
Nods to #mobrule's Perl solution for the idea of dropping the ball sideways!
Python 2.6: ~ 284 ~ characters
There is possibly still room for improvement (although I already got it down a lot since the first revisions).
All comments or suggestions more then welcome!
Supply the map file on the command line as the first argument:
python rotating_maze.py input.txt
import sys
t=[list(r)[:-1]for r in open(sys.argv[1])]
while t:
x=['o'in e for e in t].index(1);y=t[x].index('o')
while t[x+1][y]!="#":t[x][y],t[x+1][y]=" "+"o#"[t[x+1][y]>" "];x+=1
for l in t:print''.join(l)
t=t[x][y]=='o'and map(list,(t,zip(*t[::-1]),zip(*t)[::-1])[input()])or 0
C# 3.0 - 650 638 characters
(not sure how newlines being counted)
(leading whitespace for reading, not counted)
using System.Linq;
using S=System.String;
using C=System.Console;
namespace R
{
class R
{
static void Main(S[]a)
{
S m=S.Join("\n",a);
bool u;
do
{
m=L(m);
int b=m.IndexOf('o');
int h=m.IndexOf('#',b);
b=m.IndexOf('#',b);
m=m.Replace('o',' ');
u=(b!=-1&b<h|h==-1);
if (u)
m=m.Insert(b-1,"o").Remove(b,1);
m=L(L(L(m)));
C.WriteLine(m);
if (!u) return;
do
{
int.TryParse(C.ReadLine(),out b);
u=b==1|b==2;
m=b==1?L(L(L(m))):u?L(m):m;
}while(!u);
}while(u);
}
static S L(S s)
{
return S.Join("\n",
s.Split('\n')
.SelectMany(z => z.Select((c,i)=>new{c,i}))
.GroupBy(x =>x.i,x=>x.c)
.Select(g => new S(g.Reverse().ToArray()))
.ToArray());
}
}
}
Reads from commandline, here's the test line I used:
"###########" "#o #" "# ####### #" "#### #" " #########"
Relied heavily on mobrule's Perl answer for algorithm.
My Rotation method (L) can probably be improved.
Handles wall-less case.

Code Golf - π day

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The Challenge
Guidelines for code-golf on SO
The shortest code by character count to display a representation of a circle of radius R using the *character, followed by an approximation of π.
Input is a single number, R.
Since most computers seem to have almost 2:1 ratio you should only output lines where y is odd. This means that when R is odd you should print R-1 lines. There is a new testcase for R=13 to clarify.
eg.
Input
5
Output Correct Incorrect
3 ******* 4 *******
1 ********* 2 *********
-1 ********* 0 ***********
-3 ******* -2 *********
2.56 -4 *******
3.44
Edit: Due to widespread confusion caused by odd values of R, any solutions that pass the 4 test cases given below will be accepted
The approximation of π is given by dividing twice the number of * characters by R².
The approximation should be correct to at least 6 significant digits.
Leading or trailing zeros are permitted, so for example any of 3, 3.000000, 003 is accepted for the inputs of 2 and 4.
Code count includes input/output (i.e., full program).
Test Cases
Input
2
Output
***
***
3.0
Input
4
Output
*****
*******
*******
*****
3.0
Input
8
Output
*******
*************
***************
***************
***************
***************
*************
*******
3.125
Input
10
Output
*********
***************
*****************
*******************
*******************
*******************
*******************
*****************
***************
*********
3.16
Bonus Test Case
Input
13
Output
*************
*******************
*********************
***********************
*************************
*************************
*************************
*************************
***********************
*********************
*******************
*************
2.98224852071
C: 131 chars
(Based on the C++ solution by Joey)
main(i,j,c,n){for(scanf("%d",&n),c=0,i|=-n;i<n;puts(""),i+=2)for(j=-n;++j<n;putchar(i*i+j*j<n*n?c++,42:32));printf("%g",2.*c/n/n);}
(Change the i|=-n to i-=n to remove the support of odd number cases. This merely reduces char count to 130.)
As a circle:
main(i,j,
c,n){for(scanf(
"%d",&n),c=0,i=1|
-n;i<n;puts(""),i+=
0x2)for(j=-n;++j<n;
putchar(i*i+j*j<n*n
?c++,0x02a:0x020));
printf("%g",2.*c/
n/n);3.1415926;
5358979;}
XSLT 1.0
Just for fun, here's an XSLT version. Not really code-golf material, but it solves the problem in a weird-functional-XSLT-kind of way :)
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" >
<xsl:output method="html"/>
<!-- Skip even lines -->
<xsl:template match="s[#y mod 2=0]">
<xsl:variable name="next">
<!-- Just go to next line.-->
<s R="{#R}" y="{#y+1}" x="{-#R}" area="{#area}"/>
</xsl:variable>
<xsl:apply-templates select="msxsl:node-set($next)"/>
</xsl:template>
<!-- End of the line?-->
<xsl:template match="s[#x > #R]">
<xsl:variable name="next">
<!-- Go to next line.-->
<s R="{#R}" y="{#y+1}" x="{-#R}" area="{#area}"/>
</xsl:variable><!-- Print LF-->
<xsl:apply-templates
select="msxsl:node-set($next)"/>
</xsl:template>
<!-- Are we done? -->
<xsl:template match="s[#y > #R]">
<!-- Print PI approximation -->
<xsl:value-of select="2*#area div #R div #R"/>
</xsl:template>
<!-- Everything not matched above -->
<xsl:template match="s">
<!-- Inside the circle?-->
<xsl:variable name="inside" select="#x*#x+#y*#y < #R*#R"/>
<!-- Print "*" or " "-->
<xsl:choose>
<xsl:when test="$inside">*</xsl:when>
<xsl:otherwise> </xsl:otherwise>
</xsl:choose>
<xsl:variable name="next">
<!-- Add 1 to area if we're inside the circle. Go to next column.-->
<s R="{#R}" y="{#y}" x="{#x+1}" area="{#area+number($inside)}"/>
</xsl:variable>
<xsl:apply-templates select="msxsl:node-set($next)"/>
</xsl:template>
<!-- Begin here -->
<xsl:template match="/R">
<xsl:variable name="initial">
<!-- Initial state-->
<s R="{number()}" y="{-number()}" x="{-number()}" area="0"/>
</xsl:variable>
<pre>
<xsl:apply-templates select="msxsl:node-set($initial)"/>
</pre>
</xsl:template>
</xsl:stylesheet>
If you want to test it, save it as pi.xslt and open the following XML file in IE:
<?xml version="1.0"?>
<?xml-stylesheet href="pi.xslt" type="text/xsl" ?>
<R>
10
</R>
Perl, 95 96 99 106 109 110 119 characters:
$t+=$;=1|2*sqrt($r**2-($u-2*$_)**2),say$"x($r-$;/2).'*'x$;for 0..
($u=($r=<>)-1|1);say$t*2/$r**2
(The newline can be removed and is only there to avoid a scrollbar)
Yay! Circle version!
$t+=$;=
1|2*sqrt($r**
2-($u-2*$_)**2)
,say$"x($r-$;/2
).'*'x$;for 0..
($u=($r=<>)-1|1
);$pi=~say$t*
2/$r**2
For the uninitiated, the long version:
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
# Read the radius from STDIN
my $radius = <>;
# Since we're only printing asterisks on lines where y is odd,
# the number of lines to be printed equals the size of the radius,
# or (radius + 1) if the radius is an odd number.
# Note: we're always printing an even number of lines.
my $maxline = ($radius - 1) | 1;
my $surface = 0;
# for ($_ = 0; $_ <= $maxline; $_++), if you wish
for (0 .. $maxline) {
# First turn 0 ... N-1 into -(N/2) ... N/2 (= Y-coordinates),
my $y = $maxline - 2*$_;
# then use Pythagoras to see how many stars we need to print for this line.
# Bitwise OR "casts" to int; and: 1 | int(2 * x) == 1 + 2 * int(x)
my $stars = 1 | 2 * sqrt($radius**2-$y**2);
$surface += $stars;
# $" = $LIST_SEPARATOR: default is a space,
# Print indentation + stars
# (newline is printed automatically by say)
say $" x ($radius - $stars/2) . '*' x $stars;
}
# Approximation of Pi based on surface area of circle:
say $surface*2/$radius**2;
FORTRAN - 101 Chars
$ f95 piday.f95 -o piday && echo 8 | ./piday
READ*,N
DO I=-N,N,2
M=(N*N-I*I)**.5
PRINT*,(' ',J=1,N-M),('*',J=0,M*2)
T=T+2*J
ENDDO
PRINT*,T/N/N
END
READ*,N
K=N/2*2;DO&
I=1-K,N,2;M=&
(N*N-I*I)**.5;;
PRINT*,(' ',J=&
1,N-M),('*',J=&
0,M*2);T=T+2*J;
ENDDO;PRINT*&
,T/N/N;END;
!PI-DAY
x86 Machine Code: 127 bytes
Intel Assembler: 490 chars
mov si,80h
mov cl,[si]
jcxz ret
mov bx,10
xor ax,ax
xor bp,bp
dec cx
a:mul bx
mov dl,[si+2]
sub dl,48
cmp dl,bl
jae ret
add ax,dx
inc si
loop a
mov dl,al
inc dl
mov dh,al
add dh,dh
mov ch,dh
mul al
mov di,ax
x:mov al,ch
sub al,dl
imul al
mov si,ax
mov cl,dh
c:mov al,cl
sub al,dl
imul al
add ax,si
cmp ax,di
mov al,32
ja y
or al,bl
add bp,2
y:int 29h
dec cl
jnz c
mov al,bl
int 29h
mov al,13
int 29h
sub ch,2
jnc x
mov ax,bp
cwd
mov cl,7
e:div di
cmp cl,6
jne z
pusha
mov al,46
int 29h
popa
z:add al,48
int 29h
mov ax,bx
mul dx
jz ret
dec cl
jnz e
ret
This version handles the bonus test case as well and is 133 bytes:
mov si,80h
mov cl,[si]
jcxz ret
mov bx,10
xor ax,ax
xor bp,bp
dec cx
a:mul bx
mov dl,[si+2]
sub dl,48
cmp dl,bl
jae ret
add ax,dx
inc si
loop a
mov dl,al
rcr dl,1
adc dl,dh
add dl,dl
mov dh,dl
add dh,dh
dec dh
mov ch,dh
mul al
mov di,ax
x:mov al,ch
sub al,dl
imul al
mov si,ax
mov cl,dh
c:mov al,cl
sub al,dl
imul al
add ax,si
cmp ax,di
mov al,32
jae y
or al,bl
add bp,2
y:int 29h
dec cl
jnz c
mov al,bl
int 29h
mov al,13
int 29h
sub ch,2
jnc x
mov ax,bp
cwd
mov cl,7
e:div di
cmp cl,6
jne z
pusha
mov al,46
int 29h
popa
z:add al,48
int 29h
mov ax,bx
mul dx
jz ret
dec cl
jnz e
ret
Python: 101 104 107 110 chars
Based on the other Python version by Nicholas Riley.
r=input()
t=0
i=1
exec"n=1+int((2*i*r-i*i)**.5)*2;t+=2.*n/r/r;print' '*(r-n/2)+'*'*n;i+=2;"*r
print t
Credits to AlcariTheMad for some of the math.
Ah, the odd-numbered ones are indexed with zero as the middle, explains everything.
Bonus Python: 115 chars (quickly hacked together)
r=input()
t=0
i=1
while i<r*2:n=1+int((2*i*r-i*i)**.5)*2;t+=2.*n/r/r;print' '*(r-n/2)+'*'*n;i+=2+(r-i==2)*2
print t
In dc: 88 and 93 93 94 96 102 105 129 138 141 chars
Just in case, I am using OpenBSD and some supposedly non-portable extensions at this point.
93 chars. This is based on same formula as FORTRAN solution (slightly different results than test cases). Calculates X^2=R^2-Y^2 for every Y
[rdPr1-d0<p]sp1?dsMdd*sRd2%--
[dd*lRr-vddlMr-32rlpxRR42r2*lpxRRAP4*2+lN+sN2+dlM>y]
dsyx5klNlR/p
88 chars. Iterative solution. Matches test cases. For every X and Y checks if X^2+Y^2<=R^2
1?dsMdd*sRd2%--sY[0lM-[dd*lYd*+lRr(2*d5*32+PlN+sN1+dlM!<x]dsxxAPlY2+dsYlM>y]
dsyx5klNlR/p
To run dc pi.dc.
Here is an older annotated version:
# Routines to print '*' or ' '. If '*', increase the counter by 2
[lN2+sN42P]s1
[32P]s2
# do 1 row
# keeping I in the stack
[
# X in the stack
# Calculate X^2+Y^2 (leave a copy of X)
dd*lYd*+
#Calculate X^2+Y^2-R^2...
lR-d
# .. if <0, execute routine 1 (print '*')
0>1
# .. else execute routine 2 (print ' ')
0!>2
# increment X..
1+
# and check if done with line (if not done, recurse)
d lM!<x
]sx
# Routine to cycle for the columns
# Y is on the stack
[
# push -X
0lM-
# Do row
lxx
# Print EOL
10P
# Increment Y and save it, leaving 2 copies
lY 2+ dsY
# Check for stop condition
lM >y
]sy
# main loop
# Push Input value
[Input:]n?
# Initialize registers
# M=rows
d sM
# Y=1-(M-(M%2))
dd2%-1r-sY
# R=M^2
d*sR
# N=0
0sN
[Output:]p
# Main routine
lyx
# Print value of PI, N/R
5klNlR/p
Powershell, 119 113 109 characters
($z=-($n=$args[($s=0)])..$n)|?{$_%2}|%{$l="";$i=$_
$z|%{$l+=" *"[$i*$i+$_*$_-lt$n*$n-and++$s]};$l};2*$s/$n/$n
and here's a prettier version:
( $range = -( $R = $args[ ( $area = 0 ) ] ) .. $R ) |
where { $_ % 2 } |
foreach {
$line = ""
$i = $_
$range | foreach {
$line += " *"[ $i*$i + $_*$_ -lt $R*$R -and ++$area ]
}
$line
}
2 * $area / $R / $R
HyperTalk: 237 characters
Indentation is not required nor counted. It is added for clarity. Also note that HyperCard 2.2 does accept those non-ASCII relational operators I used.
function P R
put""into t
put 0into c
repeat with i=-R to R
if i mod 2≠0then
repeat with j=-R to R
if i^2+j^2≤R^2then
put"*"after t
add 1to c
else
put" "after t
end if
end repeat
put return after t
end if
end repeat
return t&2*c/R/R
end P
Since HyperCard 2.2 doesn't support stdin/stdout, a function is provided instead.
C#: 209 202 201 characters:
using C=System.Console;class P{static void Main(string[]a){int r=int.Parse(a[0]),s=0,i,x,y;for(y=1-r;y<r;y+=2){for(x=1-r;x<r;s+=i)C.Write(" *"[i=x*x+++y*y<=r*r?1:0]);C.WriteLine();}C.Write(s*2d/r/r);}}
Unminified:
using C = System.Console;
class P {
static void Main(string[] arg) {
int r = int.Parse(arg[0]), sum = 0, inside, x, y;
for (y = 1 - r; y < r; y += 2) {
for (x = 1 - r; x < r; sum += inside)
C.Write(" *"[inside = x * x++ + y * y <= r * r ? 1 : 0]);
C.WriteLine();
}
C.Write(sum * 2d / r / r);
}
}
Haskell 139 145 147 150 230 chars:
x True=' ';x _='*'
a n=unlines[[x$i^2+j^2>n^2|j<-[-n..n]]|i<-[1-n,3-n..n]]
b n=a n++show(sum[2|i<-a n,i=='*']/n/n)
main=readLn>>=putStrLn.b
Handling the odd numbers: 148 chars:
main=do{n<-readLn;let{z k|k<n^2='*';z _=' ';c=[[z$i^2+j^2|j<-[-n..n]]|i<-[1,3..n]];d=unlines$reverse c++c};putStrLn$d++show(sum[2|i<-d,i=='*']/n/n)}
150 chars:
(Based on the C version.)
a n=unlines[concat[if i^2+j^2>n^2then" "else"*"|j<-[-n..n]]|i<-[1-n,3-n..n]]
main=do n<-read`fmap`getLine;putStr$a n;print$2*sum[1|i<-a n,i=='*']/n/n
230 chars:
main=do{r<-read`fmap`getLine;let{p=putStr;d=2/fromIntegral r^2;l y n=let c m x=if x>r then p"\n">>return m else if x*x+y*y<r*r then p"*">>c(m+d)(x+1)else p" ">>c m(x+1)in if y>r then print n else c n(-r)>>=l(y+2)};l(1-r`mod`2-r)0}
Unminified:
main = do r <- read `fmap` getLine
let p = putStr
d = 2/fromIntegral r^2
l y n = let c m x = if x > r
then p "\n" >> return m
else if x*x+y*y<r*r
then p "*" >> c (m+d) (x+1)
else p " " >> c m (x+1)
in if y > r
then print n
else c n (-r) >>= l (y+2)
l (1-r`mod`2-r) 0
I was kinda hoping it would beat some of the imperative versions, but I can't seem to compress it any further at this point.
Ruby, 96 chars
(based on Guffa's C# solution):
r=gets.to_f
s=2*t=r*r
g=1-r..r
g.step(2){|y|g.step{|x|putc' * '[i=t<=>x*x+y*y];s+=i}
puts}
p s/t
109 chars (bonus):
r=gets.to_i
g=-r..r
s=g.map{|i|(g.map{|j|i*i+j*j<r*r ?'*':' '}*''+"\n")*(i%2)}*''
puts s,2.0/r/r*s.count('*')
PHP: 117
Based on dev-null-dweller
for($y=1-$r=$argv[1];$y<$r;$y+=2,print"\n")for($x=1-$r;$x<$r;$x++)echo$r*$r>$x*$x+$y*$y&&$s++?'*':' ';echo$s*2/$r/$r;
You guys are thinking way too hard.
switch (r) {
case 1,2:
echo "*"; break;
case 3,4:
echo " ***\n*****\n ***"; break;
// etc.
}
J: 47, 46, 45
Same basic idea as other solutions, i.e. r^2 <= x^2 + y^2, but J's array-oriented notation simplifies the expression:
c=:({&' *',&":2*+/#,%#*#)#:>_2{.\|#j./~#i:#<:
You'd call it like c 2 or c 8 or c 10 etc.
Bonus: 49
To handle odd input, e.g. 13, we have to filter on odd-valued x coordinates, rather than simply taking every other row of output (because now the indices could start at either an even or odd number). This generalization costs us 4 characters:
c=:*:({&' *'#],&":2%(%+/#,))]>(|#j./~2&|#])#i:#<:
Deminimized version:
c =: verb define
pythag =. y > | j./~ i:y-1 NB. r^2 > x^2 + y^2
squished =. _2 {.\ pythag NB. Odd rows only
piApx =. (2 * +/ , squished) % y*y
(squished { ' *') , ": piApx
)
Improvements and generalizations due to Marshall Lochbam on the J Forums.
Python: 118 characters
Pretty much a straightforward port of the Perl version.
r=input()
u=r+r%2
t=0
for i in range(u):n=1+2*int((r*r-(u-1-2*i)**2)**.5);t+=n;print' '*(r-n/2-1),'*'*n
print 2.*t/r/r
C++: 169 characters
#include <iostream>
int main(){int i,j,c=0,n;std::cin>>n;for(i=-n;i<=n;i+=2,std::cout<<'\n')for(j=-n;j<=n;j++)std::cout<<(i*i+j*j<=n*n?c++,'*':' ');std::cout<<2.*c/n/n;}
Unminified:
#include <iostream>
int main()
{
int i,j,c=0,n;
std::cin>>n;
for(i=-n;i<=n;i+=2,std::cout<<'\n')
for(j=-n;j<=n;j++)
std::cout<<(i*i+j*j<=n*n?c++,'*':' ');
std::cout<<2.*c/n/n;
}
(Yes, using std:: instead of using namespace std uses less characters)
The output here doesn't match the test cases in the original post, so here's one that does (written for readability). Consider it a reference implementation (if Poita_ doesn't mind):
#include <iostream>
using namespace std;
int main()
{
int i, j, c=0, n;
cin >> n;
for(i=-n; i<=n; i++) {
if (i & 1) {
for(j=-n; j<=n; j++) {
if (i*i + j*j <= n*n) {
cout << '*';
c++;
} else {
cout << ' ';
}
}
cout << '\n';
}
}
cout << 2.0 * c / n / n << '\n';
}
C++: 168 characters (with output I believe is correct)
#include <iostream>
int main(){int i,j,c=0,n;std::cin>>n;for(i=-n|1;i<=n;i+=2,std::cout<<"\n")for(j=-n;j<=n;j++)std::cout<<" *"[i*i+j*j<=n*n&&++c];std::cout<<2.*c/n/n;}
PHP: 126 132 138
(based on Guffa C# solution)
126:
for($y=1-($r=$argv[1]);$y<$r;$y+=2,print"\n")for($x=1-$r;$x<$r;$s+=$i,++$x)echo($i=$x*$x+$y*$y<=$r*$r)?'*':' ';echo$s*2/$r/$r;
132:
for($y=1-($r=$argv[1]);$y<$r;$y+=2){for($x=1-$r;$x<$r;#$s+=$i,++$x)echo($i=$x*$x+$y*$y<=$r*$r?1:0)?'*':' ';echo"\n";}echo$s*2/$r/$r;
138:
for($y=1-($r=$argv[1]);$y<$r;$y+=2){for($x=1-$r;$x<$r;#$s+=$i){$t=$x;echo($i=$t*$x++ +$y*$y<=$r*$r?1:0)?'*':' ';}echo"\n";}echo$s*2/$r/$r;
Current full:
for( $y = 1 - ( $r = $argv[1]); $y < $r; $y += 2, print "\n")
for( $x = 1-$r; $x < $r; $s += $i, ++$x)
echo( $i = $x*$x + $y*$y <= $r*$r) ? '*' : ' ';
echo $s*2 /$r /$r;
Can be without # before first $s but only with error_reporting set to 0 (Notice outputs is messing the circle)
Ruby 1.8.x, 93
r=$_.to_f
q=0
e=r-1
(p(('*'*(n=1|2*(r*r-e*e)**0.5)).center r+r)
q+=n+n
e-=2)while-r<e
p q/r/r
Run with $ ruby -p piday
APL: 59
This function accepts a number and returns the two expected items. Works correctly in bonus cases.
{⍪(⊂' *'[1+m]),q÷⍨2×+/,m←(2|v)⌿(q←⍵*2)>v∘.+v←2*⍨⍵-⍳1+2×⍵-1}
Dialect is Dyalog APL, with default index origin. Skill level is clueless newbie, so if any APL guru wants to bring it down to 10 characters, be my guest!
You can try it online on Try APL, just paste it in and put a number after it:
{⍪(⊂' *'[1+m]),q÷⍨2×+/,m←(2|v)⌿(q←⍵*2)>v∘.+v←2*⍨⍵-⍳1+2×⍵-1} 13
*************
*******************
*********************
***********************
*************************
*************************
*************************
*************************
***********************
*********************
*******************
*************
2.98225
And a bash entry: 181 186 190 chars
for((y=-(r=$1,r/2*2);y<=r;y+=2));do for((x=-r;x<=r;++x));do((x*x+y*y<r*r))&&{((++n));echo -n '*';}||echo -n " ";((x<r))||echo;done;done;((s=1000,p=n*2*s/r/r,a=p/s,b=p%s));echo $a.$b
Run with e.g. bash py.sh 13
Python: 148 characters.
Failed (i.e. not short enough) attempt to abuse the rules and hardcode the test cases, as I mentioned in reply to the original post. Abusing it with a more verbose language may have been easier:
a=3.0,3.125,3.16
b="1","23","3677","47899"
r=input()
for i in b[r/3]+b[r/3][::-1]:q=1+2*int(i);print ' '*(int(b[r/3][-1])-int(i))+'*'*q
print a[r/5]
bc: 165, 127, 126 chars
Based on the Python version.
r=read()
for(i=-1;r*2>i+=2;scale=6){n=sqrt(2*i*r-i*i)
scale=0
n=1+n/1*2
j=r-n/2
t+=2*n
while(j--)" "
while(n--)"*"
"
"}
t/r/r
(New line after the last line cannot be omitted here.)
JavaScript (SpiderMonkey) - 118 chars
This version accepts input from stdin and passes the bonus test cases
r=readline()
for(t=0,i=-r;i<r;i++)if(i%2){for(s='',j=-r;j<r;j++){t+=q=i*i+j*j<r*r
s+=q?'*':' '}print(s)}print(t*2/r/r)
Usage: cat 10 | js thisfile.js -- jsbin preview adds an alias for print/readline so you can view in browser
Javascript: 213 163
Updated
r=10;m=Math;a=Array;t=0;l=document;for(i=-r;i<r;i+=2){w=m.floor(m.sqrt(r*r-i*i)*2);t+=w*2;l.writeln(a(m.round(r-w/2)).join(' ')+a(w).join('*'));}l.writeln(t/(r*r))
Nobody said it had to render correctly in the browser - just the output. As such I've removed the pre tags and optimised it further. To view the output you need to view generated source or set your stylesheet accordingly. Pi is less accurate this way, but it's now to spec.
r=10;m=Math;a=Array;t=0;s='';for(i=-r;i<r;i++){w=m.floor((m.sqrt(m.pow(r,2)-m.pow(i,2)))*2);t+=w;if(i%2){z=a(m.round(r-w/2)).join(' ')+a(w).join('*');s+=z+'\n';}}document.write('<pre>'+(s+(t/m.pow(r,2)))+'</pre>')
Unminified:
r=10;
m=Math;
a=Array;
t=0;
s='';
for(i=-r;i<r;i++){
w=m.floor((m.sqrt(m.pow(r,2)-m.pow(i,2)))*2);
t+=w;
if(i%2){
z=a(m.round(r-w/2)).join(' ')+a(w).join('*');
s+=z+'\n';
}
}
document.write('<pre>'+(s+(t/m.pow(r,2)))+'</pre>');
Java: 234
class C{public static void main(String[] a){int x,y,s=0,r=Integer.parseInt(a[0]);for(y=1-r;y<r;y+=2){for(x=1-r;x<r;++x){boolean b=x*x+y*y<=r*r;s+=b?1:0;System.out.print(b?'*':' ');}System.out.println();}System.out.println(s*2d/r/r);}}
Unminified:
class C{
public static void main(String[] a){
int x,y,s=0,r=Integer.parseInt(a[0]);
for(y=1-r;y<r;y+=2){
for(x=1-r;x<r;++x) {
boolean b=x*x+y*y<=r*r;
s+=b?1:0;
System.out.print(b?'*':' ');
}
System.out.println();
}
System.out.println(s*2d/r/r);
}
}
GAWK: 136, 132, 126, 125 chars
Based on the Python version.
{r=$1
for(i=-1;r*2>i+=2;print""){n=1+int((2*i*r-i*i)**.5)*2
t+=2*n/r/r
printf"%*s",r-n/2,""
while(n--)printf"%c","*"}print t}

Code Golf: Triforce

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
This is inspired by/taken from this thread: http://www.allegro.cc/forums/thread/603383
The Problem
Assume the user gives you a numeric input ranging from 1 to 7. Input should be taken from the console, arguments are less desirable.
When the input is 1, print the following:
***********
*********
*******
*****
***
*
Values greater than one should generate multiples of the pattern, ending with the one above, but stacked symmetrically. For example, 3 should print the following:
*********** *********** ***********
********* ********* *********
******* ******* *******
***** ***** *****
*** *** ***
* * *
*********** ***********
********* *********
******* *******
***** *****
*** ***
* *
***********
*********
*******
*****
***
*
Bonus points if you print the reverse as well.
*********** ***********
********* *********
******* *******
***** *****
*** ***
* *
***********
*********
*******
*****
***
*
*
***
*****
*******
*********
***********
* *
*** ***
***** *****
******* *******
********* *********
*********** ***********
Can we try and keep it to one answer per language, that we all improve on?
Assembler, 165 bytes assembled
Build Instructions
Download A86 from here
Add a reference to the A86 executable into your DOS search path
Paste the code below into a text file (example: triforce.asm)
Invoke the assembler: a86 triforce.asm
This will create a .COM file called triforce.com
Type triforce to run
This was developed using the standard WinXP DOS box (Start->Programs->Accessories->Command Prompt). It should work with other DOS emulators.
Assemble using A86 and requires WinXP DOS box to run the .COM file it produces. Press 'q' to exit, keys 1-7 to draw the output.
l20:mov ah,7
int 21h
cmp al,'q'
je ret
sub al,'0'
cmp al,1
jb l20
cmp al,7
ja l20
mov [l0-1],al
mov byte ptr [l7+2],6
jmp $+2
mov ah,2
mov ch,0
mov bh,3
l0:mov bl,1
l1:mov dh,0
l3:cmp dh,ch
je l2
mov dl,32
int 21h
inc dh
jmp l3
ret
l2:mov dh,bh
l6:mov cl,12
l5:mov dl,42
cmp cl,bl
ja l4
mov dl,32
cmp dh,1
je l21
l4:int 21h
dec cl
jnz l5
l21:dec dh
jnz l6
mov dl,10
int 21h
mov dl,13
int 21h
l10:inc ch
l9:add bl,2
l7:cmp ch,6
jne l1
l13:add byte ptr [l7+2],6
l11:dec bh
l12:cmp bh,0
jne l0
xor byte ptr [l0+1],10
xor byte ptr [l9+1],40
xor byte ptr [l10+1],8
xor byte ptr [l13+1],40
sub byte ptr [l7+2],12
mov dh,[l0-1]
inc dh
xor [l12+2],dh
xor byte ptr [l11+1],8
xor byte ptr [l1+1],1
inc bh
cmp byte ptr [l0+1],11
je l0
jmp l20
It uses lots of self-modifying code to do the triforce and its mirror, it even modifies the self-modifying code.
GolfScript - 43 chars
~:!6*,{:^' '
*'*'12*' '
^6%.+)*+
-12>!^
6/-*
n}
/
~:!6*,{:^' '*'*'12*' '^6%.+)*+-12>!^6/-*n}/
48 Chars for the bonus
~:!6*,.-1%+{
:^' '*'*'12
*' '^6%.+
)*+-12>
!^6/-
*n}
/
~:!6*,.-1%+{:^' '*'*'12*' '^6%.+)*+-12>!^6/-*n}/
Python - 77 Chars
n=input()
for k in range(6*n):print' '*k+('*'*12+' '*(k%6*2+1))[-12:]*(n-k/6)
n=input()
for k in range(6*n):j=1+k%6*2;print' '*k+('*'*(12-j)+' '*j)*(n-k/6)
89 Chars for the bonus
n=input();R=range(6*n)
for k in R+R[::-1]:print' '*k+('*'*11+' '*11)[k%6*2:][:12]*(n-k/6)
114 Chars Version just using string replacements
u,v=' *';s=(v*11+u)*input()
while s.strip():print s;s=u+s.replace(*((v*2+u,u*3),(v*1+u*10,v*11))[' * 'in s])[:-2]
Unk Chars all in one statement, should work w/ 2.x and 3.x. The enumerate() is to allow the single input() to work for both places you need to use it.
print ('\n'.join('\n'.join(((' '*(6*n))+' '.join(('%s%s%s'%(' '*(5-x),'*'*(2*x+1),' '*(5-x)) for m in range(i + 1)))) for x in range(5,-1,-1)) for n, i in enumerate(range(int(input())-1,-1,-1))))
Yet Another Method
def f(n): print '\n'.join(' '*6*(n-r)+(' '*(5-l)+'*'*(l*2+1)+' '*(5-l)+' ')*r for r in xrange(1, n+1) for l in xrange(6))
f(input())
Ruby - 74 Chars
(6*n=gets.to_i).times{|k|puts' '*k+('*'*(11-(j=k%6*2))+' '*(j+1))*(n-k/6)}
COBOL - 385 Chars
$ cobc -free -x triforce.cob && echo 7| ./triforce
PROGRAM-ID.P.DATA DIVISION.WORKING-STORAGE SECTION.
1 N PIC 9.
1 M PIC 99.
1 value '0100***********'.
2 I PIC 99.
2 K PIC 99.
2 V PIC X(22).
2 W PIC X(99).
PROCEDURE DIVISION.ACCEPT N
COMPUTE M=N*6
PERFORM M TIMES
DISPLAY W(1:K)NO ADVANCING
PERFORM N TIMES
DISPLAY V(I:12)NO ADVANCING
END-PERFORM
DISPLAY ''
ADD 2 TO I
IF I = 13 MOVE 1 TO I ADD -1 TO N END-IF
ADD 1 TO K
END-PERFORM.
K could be returned to outside the group level. An initial value of zero for a numeric with no VALUE clause is compiler-implementation dependent, as is an initial value of space for an alpha-numeric field (W has been cured of this, at no extra character cost). Moving K back would save two characters. -free is compiler-dependant as well, so I'm probably being over-picky.
sed, 117 chars
s/$/76543210/
s/(.).*\1//
s/./*********** /gp
:
s/\*(\**)\*/ \1 /gp
t
:c
s/\* {11}\*/ ************/
tc
s/\* / /p
t
Usage: $ echo 7 | sed -rf this.sed
First attempt; improvements could probably be made...
Ruby 1.9 - 84 characters :
v=gets.to_i
v.times{|x|6.times{|i|puts' '*6*x+(' '*i+'*'*(11-2*i)+' '*i+' ')*(v-x)}}
Perl - 72 chars
die map$"x$_.("*"x(12-($l=1+$_%6*2)).$"x$l)x($n-int$_/6).$/,0..6*($n=<>)
78 chars
map{$l=$_%6*2;print$"x$_,("*"x(11-$l).$"x$l.$")x($n-int$_/6),$/}0..6*($n=<>)-1
87 chars
$n=<>;map{$i=int$_/6;$l=$_%6*2;print$"x$_,("*"x(11-$l).$"x$l.$")x($n-$i),$/}(0..6*$n-1)
97 chars
$n=<>;map{$i=int$_/6;$l=$_%6;print$"x(6*$i),($"x$l."*"x(11-2*$l).$"x$l.$")x($n-$i),$/}(0..6*$n-1)
108 chars
$n=<>;map{$i=int$_/6;$l=$_%6;print ""." "x(6*$i),(" "x$l."*"x(11-2*$l)." "x$l." ")x($n-$i),"\n";}(0..6*$n-1)
Powershell, 78 characters
0..(6*($n=read-host)-1)|%{" "*$_+("*"*(12-($k=1+$_%6*2))+" "*$k)*(.4+$n-$_/6)}
Bonus, 92 characters
$a=0..(6*($n=read-host)-1)|%{" "*$_+("*"*(12-($k=1+$_%6*2))+" "*$k)*(.4+$n-$_/6)}
$a
$a|sort
The output is stored in an array of strings, $a, and the reverse is created by sorting the array. We could, of course, just reverse the array, but it would be more characters to type :)
Haskell - 131 138 142 143 Chars
(⊗)=replicate
z o=[concat$(6*n+m)⊗' ':(o-n)⊗((11-m-m)⊗'*'++(1+m+m)⊗' ')|n<-[0..o-1],m<-[0..5]]
main=getLine>>=mapM_ putStrLn.z.read
This one is longer (146 148 chars) at present, but an interesting, alternate line of attack:
(⊗)=replicate
a↑b|a>b=' ';_↑_='*'
z o=[map(k↑)$concat$(6*n)⊗' ':(o-n)⊗"abcdefedcba "|n<-[0..o-1],k<-"abcdef"]
main=getLine>>=mapM_ putStrLn.z.read
FORTRAN - 97 Chars
Got rid of the #define and saved 8 bytes thanks to implict loops!
$ f95 triforce.f95 -o triforce && echo 7 | ./triforce
READ*,N
DO K=0,N*6
M=2*MOD(K,6)
PRINT*,(' ',I=1,K),(('*',I=M,10),(' ',I=0,M),J=K/6+1,N)
ENDDO
END
125 bytes for the bonus
READ*,N
DO L=1,N*12
K=L+5
If(L>N*6)K=N*12-L+6
M=2*MOD(K,6)
PRINT"(99A)",(32,I=7,K),((42,I=M,10),(32,I=0,M),J=K/6,N)
ENDDO
END
FORTRAN - 108 Chars
#define R REPEAT
READ*,N
DO I=0,6*N
J=MOD(I,6)*2
PRINT*,R(' ',I)//R(R('*',11-J)//R(' ',J+1),N-I/6)
ENDDO
END
JavaScript 1.8 - SpiderMonkey - 118 chars
N=readline()
function f(n,c)n>0?(c||' ')+f(n-1,c):''
for(i=0;i<N*6;i++)print(f(i)+f(N-i/6,f(11-(z=i%6*2),'*')+f(z+1)))
w/ bonus - 151 chars
N=readline()
function f(n,c)n>0?(c||' ')+f(n-1,c):''
function l(i)print(f(i)+f(N-i/6,f(11-(z=i%6*2),'*')+f(z+1)))
for(i=0;i<N*6;i++)l(i)
for(;i--;)l(i)
Usage: js thisfile.js
JavaScript - In Browser - 154 characters
N=prompt()
function f(n,c){return n>0?(c||' ')+f(n-1,c):''}
s='<pre>'
for(i=0;i<N*6;i++)s+=f(i)+f(N-i/6,f(11-(z=i%6*2),'*')+f(z+1))+'\n'
document.write(s)
The non-obfuscated version (before optimizations by gnarf):
var N = prompt();
var S = ' ';
function fill(c, n) {
for (ret=''; n--;)
ret += c;
return ret;
}
var str = '<pre>';
for (i=0; i<N*6; i++) {
str += fill(S, i);
for (j=0; j<N-i/6; j++)
str += fill('*', 11-i%6*2) + fill(S, i%6*2+1);
str += '\n';
}
document.write(str);
Here's a different algorithm that uses replace() to go from one line to the next of each line of a triangle row:
161 characters
N=readline()
function f(n,c){return n>0?(c||' ')+f(n-1,c):''}l=0
for(i=N;i>0;){r=f(i--,f(11,'*')+' ');for(j=6;j--;){print(f(l++)+r)
r=r.replace(/\*\* /g,' ')}}
F#, 184 181 167 151 147 143 142 133 chars
let N,r=int(stdin.ReadLine()),String.replicate
for l in[0..N*6-1]do printfn"%s%s"(r l" ")(r(N-l/6)((r(11-l%6*2)"*")+(r(l%6*2+1)" ")))
Bonus, 215 212 198 166 162 158 157 148 chars
let N,r=int(stdin.ReadLine()),String.replicate
for l in[0..N*6-1]#[N*6-1..-1..0]do printfn"%s%s"(r l" ")(r(N-l/6)((r(11-l%6*2)"*")+(r(l%6*2+1)" ")))
C - 120 Chars
main(w,i,x,y){w=getchar()%8*12;for(i=0;i<w*w/2;)y=i/w,x=i++%w,putchar(x>w-2?10:x<y|w-x-1<y|(x-y)%12>=11-2*(y%6)?32:42);}
Note that this solution prints some trailing spaces (which is okay, right?). It also relies on relational operators having higher precedence than bitwise OR, saving two characters.
124 Chars
main(n,i,k){n=getchar()&7;for(k=0;k<6*n;k++,putchar(10))for(i=-k-1;++i<12*n-2*k-1;putchar(32+10*(i>=0&&(11-i%12>2*k%12))));}
C - 177 183 Chars
#define P(I,C)for(m=0;m<I;m++)putchar(C)
main(t,c,r,o,m){scanf("%d",&t);for(c=t;c>0;c--)for(r=6;r>0;r--){P((t-c)*6+6-r,32);for(o=0;o<c;o++){P(r*2-1,42);P(13-r*2,32);}puts("");}}
C - 222 243 Chars (With Bonus Points)
#define P(I,C)for(m=0;m<I;m++)putchar(C)
main(t,c,r,o,m){scanf("%d",&t);for(c=t-1;-c<2+t;c-=1+!c)for(r=c<0?1:6;c<0?r<7:r>0;r+=c<0?1:-1){P((t-abs(c+1))*6+6-r,32);for(o=0;o<abs(c+1);o++){P(r*2-1,42);P(13-r*2,32);}puts("");}}
This is my first Code Golf submission as well!
Written in C
Bonus points (492 chars):
p(char *t, int c, int s){int i=0;for(;i<s;i++)printf(" ");for(i=0;i<c;i++)printf("%s",t);printf("\n");}main(int a, char **v){int i=0;int k;int c=atoi(v[1]);for(;i<c;i++){p("*********** ",c-i,i);p(" ********* ",c-i,i);p(" ******* ",c-i,i);p(" ***** ",c-i,i);p(" *** ",c-i,i);p(" * ",c-i,i);}for(i=0;i<c;i++){k=c-i-1;p(" * ",1+i,k);p(" *** ",1+i,k);p(" ***** ",1+i,k);p(" ******* ",1+i,k);p(" ********* ",1+i,k);p("*********** ",i+1,k);}}
Without bonus points (322 chars):
p(char *t, int c, int s){int i=0;for(;i<s;i++)printf(" ");for(i=0;i<c;i++)printf("%s",t);printf("\n");}main(int a, char **v){int i=0;int k;int c=atoi(v[1]);for(;i<c;i++){p("*********** ",c-i,i);p(" ********* ",c-i,i);p(" ******* ",c-i,i);p(" ***** ",c-i,i);p(" *** ",c-i,i);p(" * ",c-i,i);}}
First time posting, too!
Lua, 121 chars
R,N,S=string.rep,io.read'*n',' 'for i=0,N-1 do for j=0,5 do X=R(S,j)print(R(S,6*i)..R(X..R('*',11-2*j)..X..S,N-i))end end
123
R,N,S=string.rep,io.read'*n',' 'for i=0,N-1 do for j=0,5 do print(R(S,6*i)..R(R(S,j)..R('*',11-2*j)..R(S,j)..S,N-i))end end
PHP, 153
<?php $i=fgets(STDIN);function r($n,$c=' '){return$n>0?$c.r($n-1,$c):'';}for($l=0;$l<$i*6;){$z=$l%6*2;echo r($l).r($i-$l++/6,r(11-$z,'*').r($z+1))."\n";}
with Bonus, 210
<?php $i=fgets(STDIN);function r($n,$c=' '){return$n>0?$c.r($n-1,$c):'';}$o=array();for($l=0;$l<$i*6;){$z=$l%6*2;$o[]=r($l).r($i-$l++/6,r(11-$z,'*').r($z+1));}print join("\n",array_merge($o,array_reverse($o)));
dc 105 chars
123 129 132 139 141
[rdPr1-d0<P]sP?sn
0sk[1lk6%2*+sj32lkd0<Plnlk6/-si
[[*]12lj-d0<P32ljd0<Pli1-dsi0<I]dsIx
10Plk1+dskln6*>K]dsKx
Mathematica, 46 characters
The answer prints sideways.
TableForm#{Table["*",{l,#},{l},{j,6},{2j-1}]}&
HyperTalk - 272 chars
function triforce n
put"******" into a
put n*6 into h
repeat with y=0 to h-1
put" " after s
put char 1 to y of s after t
repeat n-y div 6
get y mod 6*2
put char 1 to 11-it of (a&a)&&char 1 to it of s after t
end repeat
put return after t
end repeat
return t
end triforce
Indentation is neither needed nor counted (HyperCard automatically adds it).
Miscellanea:
Since there is no notion of console or way to access console arguments in HyperCard 2.2 (that I know of), a function is given instead. It can be invoked with:
on mouseUp
ask "Triforce: "
put triforce(it) into card field 1
end mouseUp
To use this, a card field would be created and set to a fixed-width font. Using HyperCard's answer command would display a dialog with the text, but it doesn't work because:
The answer dialog font (Chicago) is not fixed-width.
The answer command refuses to display long text (even triforce(2) is too long).
Common Lisp, 150 characters:
(defun f(n o)(unless(= n 0)(dotimes(x 6)(format t"~v#{~a~:*~}~-1:*~v#{~?~2:*~}~%"
o" "n"~11#: "(list(- 11(* 2 x))#\*)))(f(1- n)(+ 6 o))))
77 char alternative python solution based on gnibbler's:
n=input()
k=0
exec"print' '*k+('*'*12+' '*(k%6*2+1))[-12:]*(n-k/6);k+=1;"*6*n
Amazingly the bonus came out exactly the same also (101 chars, oh well)
n=input()
l=1
k=0
s="print' '*k+('*'*12+' '*(k%6*2+1))[-12:]*(n-k/6);k+=l;"*6*n
exec s+'l=-1;k-=1;'+s