# Question
Title: Count the terminal cycles of a directed graph
## Task

You must write a program or function in the language of your choice which accurately counts the number of terminal cycles of a simple directed graph.

This particular kind of directed graph is represented as an array of n integers, each with an independently-chosen random value between 1 and n (or 0 and n-1, if your language counts from 0). The graph can be thought of as arrows pointing from one index (node) to an index which matches the value found at the starting index.

Your function must be capable of accepting large graphs, up to n=1024, or any smaller integer size.

## Example

Consider this graph for n=10:

```
[9, 7, 8, 10, 2, 6, 3, 10, 6, 8]

```

Index 1 contains a 9, so there's an arrow from index 1 to index 9. Index 9 contains a 6, so there's an arrow 9 -\> 6. Index 6 contains 6, which is a terminal cycle, pointing back to itself.

Index 2 contains a 7. Index 7 contains a 3. Index 3 contains an 8. Index 8 contains a 10. Index 10 contains an 8, so that's a second terminal cycle (8 -\> 10 -\> 8 -\> 10, etc.).

Index 4 -\> 10, which enters the second terminal cycle. Likewise, index 5 -\> 2 -\> 7 -\> 3 -\> 8, which is also part of the second terminal cycle.

At this point, all indices (nodes) have been checked, all paths have been followed, and two unique terminal cycles are identified. Therefore, the function should **return 2**, since that is the number of terminal cycles in this directed graph.

## Scoring

Aim for the smallest code, but make sure it counts terminal cycles correctly. Shortest code after 1 week wins.

## Test Cases

Here's are some test cases to check the correctness of your code. If your language counts array indices starting from 0, you must of course subtract 1 from the value of each array element, to prevent an out-of-bound index.

n=32, 5 cycles:

```
[8, 28, 14, 8, 2, 1, 13, 15, 30, 17, 9, 8, 18, 19, 30, 3, 8, 25, 23, 12, 6, 7, 19, 24, 17, 7, 21, 20, 29, 15, 32, 32]

```

n=32, 4 cycles:

```
[20, 31, 3, 18, 18, 18, 8, 12, 25, 10, 10, 19, 3, 9, 18, 1, 13, 5, 18, 23, 20, 26, 16, 22, 4, 16, 19, 31, 21, 32, 15, 22]

```

n=32, 3 cycles:

```
[28, 13, 17, 14, 4, 31, 11, 4, 22, 6, 32, 1, 13, 15, 7, 19, 10, 28, 9, 22, 5, 26, 17, 8, 6, 13, 7, 10, 9, 30, 23, 25]

```

n=32, 2 cycles:

```
[25, 23, 22, 6, 24, 3, 1, 21, 6, 18, 20, 4, 8, 5, 16, 10, 15, 32, 26, 25, 27, 14, 13, 12, 9, 9, 29, 8, 13, 31, 32, 1]

```

n=32, 1 cycle:

```
[6, 21, 15, 14, 22, 12, 5, 32, 29, 3, 22, 23, 6, 16, 20, 2, 16, 25, 9, 22, 13, 2, 19, 20, 26, 19, 32, 3, 32, 19, 28, 16]

```

n=32, 1 cycle:

```
[8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 1, 2, 3, 4, 5, 6, 7]

```

n=1024, 6 cycles:

```
[239, 631, 200, 595, 178, 428, 582, 191, 230, 551, 223, 61, 564, 463, 568, 527, 143, 403, 154, 236, 928, 650, 14, 931, 236, 170, 910, 782, 861, 464, 378, 748, 468, 779, 440, 396, 467, 630, 451, 130, 694, 167, 594, 115, 671, 853, 612, 238, 464, 771, 825, 471, 167, 653, 561, 337, 585, 986, 79, 506, 192, 873, 184, 617, 4, 259, 4, 662, 623, 694, 859, 6, 346, 431, 181, 703, 823, 140, 635, 90, 559, 689, 118, 117, 130, 248, 931, 767, 840, 158, 696, 275, 610, 217, 989, 640, 363, 91, 129, 399, 105, 770, 870, 800, 429, 473, 119, 908, 481, 337, 504, 45, 1011, 684, 306, 126, 215, 729, 771, 5, 302, 992, 380, 824, 868, 205, 807, 917, 407, 759, 181, 640, 685, 795, 258, 180, 900, 20, 773, 546, 866, 564, 761, 632, 895, 968, 980, 651, 225, 676, 18, 685, 784, 208, 227, 3, 267, 852, 57, 487, 566, 633, 849, 309, 543, 145, 575, 811, 621, 560, 492, 24, 665, 66, 851, 168, 262, 259, 754, 481, 565, 768, 172, 1012, 241, 3, 370, 985, 389, 82, 779, 744, 829, 836, 249, 975, 909, 840, 226, 867, 499, 192, 909, 972, 735, 252, 785, 545, 486, 186, 1011, 89, 939, 649, 110, 119, 185, 836, 717, 545, 938, 621, 946, 94, 363, 721, 177, 747, 59, 819, 146, 283, 821, 547, 654, 941, 755, 18, 449, 367, 499, 944, 62, 553, 435, 344, 900, 25, 251, 920, 902, 99, 326, 98, 495, 385, 929, 865, 327, 725, 674, 33, 173, 429, 873, 558, 90, 460, 366, 543, 583, 954, 792, 213, 536, 670, 49, 738, 802, 1015, 23, 915, 119, 263, 307, 601, 474, 971, 826, 613, 446, 37, 145, 894, 901, 307, 906, 886, 990, 89, 798, 384, 487, 822, 354, 768, 902, 163, 179, 134, 920, 439, 619, 215, 94, 709, 744, 366, 543, 349, 347, 2, 438, 141, 486, 19, 998, 500, 857, 955, 932, 1, 587, 195, 646, 550, 887, 626, 400, 348, 154, 808, 678, 873, 186, 282, 168, 993, 722, 56, 345, 5, 226, 328, 22, 894, 658, 264, 13, 803, 791, 359, 217, 997, 168, 578, 952, 734, 964, 898, 659, 628, 980, 15, 31, 439, 13, 875, 687, 1004, 1023, 165, 642, 561, 897, 711, 124, 404, 346, 723, 774, 352, 784, 276, 395, 14, 443, 343, 153, 510, 590, 172, 215, 130, 106, 295, 906, 133, 758, 483, 898, 391, 760, 702, 972, 721, 611, 592, 1001, 724, 934, 59, 831, 171, 253, 869, 431, 538, 20, 648, 76, 351, 103, 33, 385, 852, 437, 470, 95, 434, 408, 430, 994, 366, 706, 809, 532, 161, 388, 668, 245, 965, 365, 913, 471, 927, 245, 256, 805, 540, 380, 995, 446, 657, 545, 573, 955, 499, 322, 949, 635, 401, 185, 421, 626, 534, 429, 930, 633, 563, 348, 626, 518, 682, 233, 775, 444, 42, 199, 57, 271, 683, 397, 883, 620, 768, 8, 331, 497, 19, 340, 900, 919, 497, 276, 78, 252, 164, 764, 927, 242, 270, 759, 824, 945, 886, 262, 59, 439, 217, 720, 519, 862, 626, 326, 339, 589, 16, 565, 947, 604, 144, 87, 520, 256, 240, 336, 685, 361, 998, 805, 678, 24, 980, 203, 818, 855, 85, 276, 822, 183, 266, 347, 8, 663, 620, 147, 189, 497, 128, 357, 855, 507, 275, 420, 755, 131, 469, 672, 926, 859, 156, 127, 986, 489, 803, 433, 622, 951, 83, 862, 108, 192, 167, 862, 242, 519, 574, 358, 549, 119, 630, 60, 925, 414, 479, 330, 927, 94, 767, 562, 919, 1011, 999, 908, 113, 932, 632, 403, 309, 838, 341, 179, 708, 847, 472, 907, 537, 516, 992, 944, 615, 778, 801, 413, 653, 690, 393, 452, 394, 596, 545, 591, 136, 109, 942, 546, 57, 626, 61, 587, 862, 829, 988, 965, 781, 849, 843, 815, 60, 928, 784, 388, 341, 491, 565, 83, 110, 164, 38, 1024, 859, 297, 520, 327, 733, 699, 631, 78, 178, 671, 895, 818, 637, 99, 425, 933, 248, 299, 333, 144, 323, 105, 849, 942, 767, 265, 72, 204, 547, 934, 916, 304, 919, 273, 396, 665, 452, 423, 471, 641, 675, 60, 388, 97, 963, 902, 321, 826, 476, 782, 723, 99, 735, 893, 565, 175, 141, 70, 918, 659, 935, 492, 751, 261, 362, 849, 593, 924, 590, 982, 876, 73, 993, 767, 441, 70, 875, 640, 567, 920, 321, 46, 938, 377, 905, 303, 736, 182, 626, 899, 512, 894, 744, 254, 984, 325, 694, 6, 367, 532, 432, 133, 938, 74, 967, 725, 87, 502, 946, 708, 122, 887, 256, 595, 169, 101, 828, 696, 897, 961, 376, 910, 82, 144, 967, 885, 89, 114, 215, 187, 38, 873, 125, 522, 884, 947, 962, 45, 585, 644, 476, 710, 839, 486, 634, 431, 475, 979, 877, 18, 226, 656, 573, 3, 29, 743, 508, 544, 252, 254, 388, 873, 70, 640, 918, 93, 508, 853, 609, 333, 378, 172, 875, 617, 167, 771, 375, 503, 221, 624, 67, 655, 465, 272, 278, 161, 840, 52, 1016, 909, 567, 544, 234, 339, 463, 621, 951, 962, 1019, 383, 523, 279, 780, 838, 984, 999, 29, 897, 564, 762, 753, 393, 205, 31, 150, 490, 156, 796, 586, 676, 773, 465, 489, 1024, 433, 214, 701, 480, 604, 280, 241, 563, 943, 911, 12, 400, 261, 883, 999, 207, 618, 141, 959, 767, 978, 461, 992, 982, 272, 143, 404, 645, 331, 348, 783, 698, 827, 82, 145, 536, 449, 852, 750, 789, 413, 913, 420, 14, 499, 285, 533, 223, 75, 591, 994, 884, 237, 63, 411, 563, 611, 801, 173, 759, 278, 318, 772, 1018, 48, 440, 333, 611, 834, 423, 583, 22, 716, 393, 794, 83, 83, 864, 859, 600, 525, 808, 569, 95, 952, 852, 567, 651, 2, 984, 906, 992, 747, 602, 143, 547, 1008, 940, 245, 633, 378, 193, 771, 965, 648, 437, 873, 591, 664, 271, 777, 274, 742, 68, 429, 825, 144, 55, 272, 279, 6, 400, 485, 66, 311, 663, 441, 23, 988, 726, 48, 624, 302, 617, 120, 653, 810, 641, 142]

```

# Answer
> 2 votes
### GolfScript, 25 characters

```
:I{{I=.}I.+,*]I,>$0=}%.&,

```

Same approach as Keith Randall's solution but in GolfScript. Note that GolfScript has zero-indexed arrays. Online tester.

```
:I        # Assign input to variable I
{         # Foreach item in I
  {I=.}   # Code block: take the n-th list item
  I.+,*   # Iterate the code block 2*len(I) times
  ]       # and gather result in an array
  I,>     # Take last len(I) items
  $0=     # Get minimum
}%
.&        # Take unique items
,         # Count

```

# Answer
> 5 votes
# Mathematica 69

## Code

This finds the number of graph components.

```
f@l_ := Length@WeaklyConnectedComponents@Graph@Thread[Range@Length@l -> l]

```

---

The first test case:

```
v = {8, 28, 14, 8, 2, 1, 13, 15, 30, 17, 9, 8, 18, 19, 30, 3, 8, 25, 23, 12, 6, 7, 19, 24, 17, 7, 21, 20, 29, 15, 32, 32}
f[v]

```

> 5

---

## Analysis

Make a list of directed edges between indices, (using example 1).

```
Thread[Range@Length@v -> v

```

> {1 -\> 8, 2 -\> 28, 3 -\> 14, 4 -\> 8, 5 -\> 2, 6 -\> 1, 7 -\> 13, 8 -\> 15, 9 -\> 30, 10 -\> 17, 11 -\> 9, 12 -\> 8, 13 -\> 18, 14 -\> 19, 15 -\> 30, 16 -\> 3, 17 -\> 8, 18 -\> 25, 19 -\> 23, 20 -\> 12, 21 -\> 6, 22 -\> 7, 23 -\> 19, 24 -\> 24, 25 -\> 17, 26 -\> 7, 27 -\> 21, 28 -\> 20, 29 -\> 29, 30 -\> 15, 31 -\> 32, 32 -\> 32}

---

`Graph` draws a graph showing the graph components.

`ImagePadding` and `VertexLabels` are used here to show the indices.

```
Graph[Thread[Range[Length@v] -> v], ImagePadding -> 30, VertexLabels -> "Name"]

```

##

`WeaklyConnectedComponents` returns the list of vertices for each component.

`Length` returns the number of components.

```
c = WeaklyConnectedComponents[g]
Length[c]

```

> {{17, 10, 25, 8, 18, 1, 4, 12, 15, 13, 6, 20, 30, 7, 21, 28, 9, 22, 26, 27, 2, 11, 5}, {14, 3, 19, 16, 23}, {32, 31}, {24}, {29}}
>
> 5

---

## Timing of sample list with 1024 elements:

Timing: 0.002015 sec

```
f[z] // AbsoluteTiming

```

> {0.002015, 6}

---

Just for fun, here's a picture of the final test case, graphed. I omitted the vertex labels; there are too many.

```
Graph[Thread[Range[Length@z] -> z], GraphLayout -> "RadialEmbedding"]

```

# Answer
> 2 votes
## Python, 132 116 chars

```
def T(V):
 n=len(V);r=range(n);s={}
 for i in r:
    p=[i]
    for k in r+r:p+=[V[p[-1]]]
    s[min(p[n:])]=1
 return len(s)

```

For each index, we follows edges for n hops, which guarantees we are in a terminal cycle. We then follow n more hops and find the minimum index in that cycle. The total number of terminal cycles is then just the number of different minima we find.

# Answer
> 1 votes
In Python:

```
def c(l):
    if(l==[]):
        return 0
    elif (l[-1]==len(l)):
        return c(l[:-1])+1
    else:
        return c([[x,l[-1]][x==len(l)] for x in l[:-1]])

```

# Answer
> 1 votes
# J - 61 53 char

This one was a doozy.

```
#@([:#/.~[:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:)

```

The `<@<:` turn the list into a J graph, which looks like a list of boxes, and the box at index `i` contains all the nodes that node `i` connects to. J indexes from zero, so we use `<:` to decrement everything by one before boxing with `<`.

```
   (<@<:) 9 7 8 10 2 6 3 10 6 8
+-+-+-+-+-+-+-+-+-+-+
|8|6|7|9|1|5|2|9|5|7|
+-+-+-+-+-+-+-+-+-+-+

```

The `<~.@(],;@:{~)^:_&.>]` turns each node into a list of all the nodes that can be reached from it. The `<...&.>]` is responsible for making this happen to each node, and the `~.@(],;@:{~)^:_` actually comes from a J golf of this 'nodes reachable' task I did a couple of weeks ago.

```
   (<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
+---+-------+---+---+---------+-+-----+---+-+---+
|8 5|6 2 7 9|7 9|9 7|1 6 2 7 9|5|2 7 9|9 7|5|7 9|
+---+-------+---+---+---------+-+-----+---+-+---+

```

`e.` performs an interesting task. If the "reachability" closure of the graph (the version of the graph such that if there are directed edges X→Y and Y→Z we add the edge X→Z.) has N nodes and E edges, then `e.` on this graph makes a boolean matrix of N rows and E columns, with a True if the corresponding node shares a reachable node with this edge. Confusing, but bear with me.

```
   ([:e.<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 1 1 1 0 1 1
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0
0 0 0 0 1 1 1 1 1 1 0 0 0 1 1 0 0 1 1 1 1 0 1 1

```

Next, we have to find the number of terminal cycles, i.e. the number of groups that share Trues amongst their columns. We want to make sort of a multiplication table of the rows (`"1/~`), and we use a kind of inner product as the multiplication, one that ANDs pairwise and then ORs all the results together (`+./ .*`). The resulting matrix is a square table with a True in each position that two rows share at least one column between them.

```
   ([:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
1 0 0 0 0 1 0 0 1 0
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
1 0 0 0 0 1 0 0 1 0
0 1 1 1 1 0 1 1 0 1
0 1 1 1 1 0 1 1 0 1
1 0 0 0 0 1 0 0 1 0
0 1 1 1 1 0 1 1 0 1

```

Now all that's left to do is to check how many different kinds of row patterns there are. So we do exactly that: group together rows of the same kind (`/.~`), report the number in each group (`#`), and then take the number of groups (`#@`).

```
   #@([:#/.~[:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:) 9 7 8 10 2 6 3 10 6 8
2

```

Usage on other examples:

```
   tcc =: #@([:#/.~[:+./ .*"1/~@e.<~.@(],;@:{~)^:_&.>])@:(<@<:)  NB. name
   tcc 8 28 14 8 2 1 13 15 30 17 9 8 18 19 30 3 8 25 23 12 6 7 19 24 17 7 21 20 29 15 32 32
5
   tcc 20 31 3 18 18 18 8 12 25 10 10 19 3 9 18 1 13 5 18 23 20 26 16 22 4 16 19 31 21 32 15 22
4
   tcc 6 21 15 14 22 12 5 32 29 3 22 23 6 16 20 2 16 25 9 22 13 2 19 20 26 19 32 3 32 19 28 16
1
   tcc tentwentyfour  NB. the 1024-node example
6

```

Unfortunately the 1024 element case now takes a really long time to terminate. The previous version `<:@#@((#~0={.+/@:*"1])^:a:)@e.@(~.@(],;@:{~)^:_&.>~<)@:(<@<:)` (61 char) took a little over a second to do this.

# Answer
> 0 votes
# Python (96)

Very, very, very, very based on user2228078's answer, as it works exactly the same, but is more golfed:

```
c=lambda l:(1+c(l[:-1])if l[-1]==len(l)else c([[x,l[-1]][x==len(l)]for x in l[:-1]]))if l else 0

```

(Technical question: should a golfing of someone elses answer be community wiki?)

# Answer
> 0 votes
# Python (89) (87)

```
def c(G):
 u=i=0
 for _ in G:
  j=i;i+=1
  while j>=0:G[j],j=~i,G[j]
  u+=j==~i
 return u

```

The main idea is to start at each node at turn and walk along the path from it, marking each node we visit with a label unique to the node we started at. If we ever hit a marked node, we stop walking, and check if the marking is the one corresponding to our starting node. If it is we must have walked a loop, so we increment the count of cycles by one.

In the code, `u` is the cycle counter, `i` is the starting node, `j` is the current node we're walking. The label corresponding to starting node `i` is its bit-complement `~i` which is always negative. We mark a node by pointing it to that value, overwriting whatever node it actually pointed to (being careful to walk to that node before it's forgotten).

We know we've hit a marked node when we walk to a negative-value "node" immediately afterwards. We check if that negative value is the current label to see whether we've walked a cycle. Since each node we walk is effectively deleted, each cycle will only be walked once.

It saves characters to count up `i` manually with a dummy loop variable `_` then as `for i in range(len(G))`. Python lists are 0-indexed. If they were instead 1-indexed, we could save two characters by writing `j=i=i+1` to have `i` and `j` be 1 for the first loop, and write `j>0` in place of `j>=0`.

## Edit:

We can save two characters by iterating `i` over the elements of the list rather than the indices, since node that are not pointed to by any edge don't matter. We have to iterate over `set(G)` though to avoid repeating a start node that it pointed to by multiple other nodes.

```
def c(G):
 u=0
 for i in set(G):
  j=i
  while j>=0:G[j],j=~i,G[j]
  u+=j==~i
 return u

```

---
Tags: code-golf, graph-theory
---


title: What time is it? (Obfuscation)

text:
# Question
Title: What time is it? (Obfuscation)
Your goal is to write an obfuscated program that displays the current time.

Guidelines: The program can print local or global time. You are allowed to draw ASCII numbers, display an analog clock, etc. No input should be needed. Whether you include 12 or 24 hour, including AM/PM, milliseconds and seconds or not, it all doesn't matter. This is a popularity contest.

Inspired by sykes2.c, an impressive display of confusing naming, obscure language features, and clever tricks.

# Answer
> 5 votes
# Analog clock, JS

Analog clock? Challenge accepted.

Golfed/Obfuscated into the zone of not-exactly-understanding-what-it-does-even-after-reading-through-a-few-times:

```
for(var a=new Date,b=a.getMinutes(),c=a.getHours()+b/60,d=[],e=Math.round,f=Math.PI,g=Math.sin,h=Math.cos,k=0;11>k;k++)d[k]=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(var l=0;l<f;l+=0.05){var m=e(17/11*5*h(2*l)),n=e(5*g(2*l));d[n+5][m+8]=1}for(var p=0;2.5>=p;p+=0.5){var q=e(17/11*p*h(-(c*f/6)+f/2)),r=e(p*g(-(c*f/6)+f/2));d[r+5][q+8]=2}for(p=0;4.5>=p;p+=0.5){var s=e(17/11*p*h(-(b*f/30)+f/2)),t=e(p*g(-(b*f/30)+f/2));d[t+5][s+8]=3}d[5][8]=1;a="";for(k=d.length-1;-1<k;k--)a+=d[k].join("").replace(/0/g,".").replace(/1/g,"O").replace(/2/g,"h").replace(/3/g,"m")+"\n";console.log(a);

```

Outputs something like:

```
.....OOOOOOO......
...OO.......OO....
.OO...........O...
.O...h.........O..
O.....hh.......OO.
O......hOmmmmmmmO.
OO.............OO.
.O.............O..
.OO...........O...
...OO.......OO....
.....OOOOOOO......

```

...yeah, guess what time it is here. (Hint hint not AM)

Human readable version:

```
var date = new Date();
var min = date.getMinutes();
var hrs = date.getHours()+(b/60); // set up date
var a=[];
for(var i=0;i<11;i++)a[i]=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; // set up array
function putX(x,y,i){a[y+5][x+8]=i;} // just for source neatness; this is expanded out in the obfuscated version
for(var p=0;p<Math.PI;p+=0.05){ // draw clock border
    putX(Math.round((17/11)*5*Math.cos(2*p)), Math.round(5*Math.sin(2*p)), 1);
}
for(var p=0;p<=2.5;p+=0.5){ // draw hour hand (transforming the angle to work)
    putX(Math.round((17/11)*p*Math.cos(-(hrs*2*Math.PI/12)+(Math.PI/2))), Math.round(p*Math.sin(-(hrs*2*Math.PI/12)+(Math.PI/2))), 2);
}

for(var p=0;p<=4.5;p+=0.5){ // draw the minute hand like the hour hand
    putX(Math.round((17/11)*p*Math.cos(-(min*2*Math.PI/60)+(Math.PI/2))), Math.round(p*Math.sin(-(min*2*Math.PI/60)+(Math.PI/2))), 3);
}

putX(0,0,1); // set the center point

date=""; // reuse date for maximum confusion :)
for(var i=a.length-1;i>-1;i--)date+=a[i].join("").replace(/0/g, ".").replace(/1/g, "O").replace(/2/g, "h").replace(/3/g, "m")+"\n"; // output ASCII art to string
console.log(date); // output string to console

```

# Answer
> 3 votes
# Python

Might as well.

```
exec(lambda s:s[::2]+s[1::2])('ipmepno r(t" hwtetbpb:r/o/wtsiemre;.wgeobvb/rHoTwMsLe5r/."o)')

```

# Answer
> 1 votes
## JavaScript / HTML (757 bytes)

Prints an analog clock on an HTML5 canvas. There's probably a lot more efficient ways to do this, but I think it turned out looking nice.

```
<canvas><script>S=150;c=document.currentScript.parentNode;c.width=c.height=2*S;t=c.getContext("2d");z=Math;r=2*z.PI;o=r/4;h=[[1,0.93],[4,0.9],[8,0.7]];m=[0,0,0];function d(){t.clearRect(0,0,c.width,c.height);t.lineWidth=2;t.beginPath();t.moveTo(2*S,S);    t.arc(S,S,0.99*S,0,r);for (i=0;i<60;++i){a=r*(i/60)+o;x=0.99*S*z.cos(a);    y=0.99*S*z.sin(a);t.moveTo(S+x,S+y);s=0.96;if (!(i%5)) s=0.90;t.lineTo(S+s*x,S+s*y);}t.stroke();u=new Date();m[0]=r*u.getSeconds()/60-o;m[1]=r*u.getMinutes()/60-o;m[2]=r*(u.getHours()%12)/12+(m[1]+o)/12-o;for(g=0;g<3;g++){t.beginPath();t.lineWidth=h[g][0];t.strokeStyle="black";if (!g) t.strokeStyle="red";x=h[g][1]*S*z.cos(m[g]);  y=h[g][1]*S*z.sin(m[g]);t.moveTo(S+x,S+y);t.lineTo(S,S);t.stroke();}setTimeout(d,500);}d();</script>

```

Human readable version on JSFiddle here.

# Answer
> 0 votes
# GolfScript

The ultimate example of a magic number!

```
230140410535893441750932406053255553

23/`3/{~}%+'"#{'\+'}"'+~

```

Explanation coming soon.

# Answer
> 0 votes
# CJam

```
"et phone home"S/_,_@T=~><{_A<{R_,+\+}*':}/;

```

Prints the local time as HH:mm:ss (24-hour)

Spoilers:

> `S/` splits by space (S=" ")
> `_,_` gets the resulting array length (3) twice
> `@T=` extracts the "et" part (T=0)
> `~` evaluates `et`, which gives the current date and time in an array
> `><` extracts the time part (starting at index 3, length 3)
> `_A<` checks if a value is less than 10 (A=10)
> `R_,+` evaluates to "0" (R="")
> `\+` prepends "0" to the number
> `{...}*` executes the block if the condition (\<10) was true
> `':` is the colon character
> `{...}/` executes the block for each array element (hour, min, sec)
> `;` pops the last value (a colon)

# Answer
> 0 votes
## SVG + JavaScript (272 937 bytes)

I'm sorry; couldn't help myself. The SVG is probably way too big to fit on StackExchange, so you can access a live demo here (please note, it could lag your browser; do it at your own risk): http://varden.info/~mlindvall/jstime.obf.svg

Viewing the source code might crash your browser; do it at your own risk. Otherwise, downloading it and opening it in Notepad++ should be safe.

Since there are no rules, I'll have to admit I got huge help from an obfuscator, so this is more like a proof of concept rather than a real submission. Still, it was kind of fun to see this work.

Human readable version:

```
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg height="44" width="110" version="1.1" xmlns="http://www.w3.org/2000/svg">
<text x="10" y="14" style="font-size: 14px;">Current time is:</text>
<text id="id" x="0" y="44" style="font-size: 30px;"></text>
<script type="text/javascript">
function t() {
    var a = new Date(), timeArray=[a.getHours(), a.getMinutes(), a.getSeconds()], delimiter='', result='';
    for (c = 0; c != 3; c++) {
        while (('' + timeArray[c]).length != 2) {
            timeArray[c] = '0' + timeArray[c];
        }
        result += delimiter + b[c];
        delimiter = ':';
    }
    document.getElementById("id").textContent = result;
}
t();
setInterval("t()", 1000); // Run every second for an updating clock
</script>
</svg>

```

---
Tags: popularity-contest, obfuscation
---


# Question
Title: Challenge: compress co-occuring columns into cartesian product
This challenge is inspired by a problem I encountered recently out in the real-world, though ultimately I cheated and found a workaround.

### Challenge

The input is a space-separated table of characters (each line is a row, and every line will have the same number of columns). Your challenge is to group together co-occurring column values and output a 'compressed' table, and there may be duplicate rows. Let's look at an example:

**input:**

```
A X I
B X I
A Y I
B X I
B Y I

```

**output:**

```
AB XY I

```

The output is parsed as the *cartesian product* between each column:

```
AB XY = A X, B X, A Y, B Y

```

The union of cartesian products of columns in each output row must exactly match the set of all unique input rows. In other words, no skipping input rows and no specifying input rows that don't exist!

For further exampling, note that if the third column contained anything other than `I`, this would be harder to compress:

**input:**

```
A X I
B Y I
A Y $
B X I
B Y I

```

**output:**

```
A X I
A Y $
B XY I

```

### Rules

* no non-standard libraries or calls to high-level compression functions. The spirit of the question is to write the algorithm yourself!
* output must be in the same format as inputs (zipping your output files is cheating)
* no hard-coding the answers of each test file. Your program needs to be able to handle arbitrary (correct) inputs.

### Scoring (lowest wins)

* Size of your program in bytes (you may count the name of the input as a single byte)
* Plus the size (in bytes) of all of your output files on the given tests.
* -10% bonus if you have the fastest program (as it runs on my machine). Speed will be measured as the average time on 10 randomly generated test cases using `generate.py 6 8 4 6 5` (the same 10 files for each program of course)

### Test Files

These files are generated with this python script. The answer keys aren't guaranteed to be the minimum compression - you may be able to do better!

# Answer
> 2 votes
I'll start things off with the simplest possible answer.. According to my own specifications, the input file qualifies as a 'compression' of itself (albeit not a very efficient one).

**Python: 22+3359+183735+239 with 10% bonus = 168619.5**

```
print open('testfile').read()

```

---
Tags: code-challenge
---


title: Add two numbers safely, in C

text:
# Question
Title: Add two numbers safely, in C
Everyone knows that C is a lovely, safe, high level programming language. However you, as a coder are set the following task.

> Write a program to add two numbers.

* Input: Two space separated integers.
* Output: The sum of the two numbers in the input.

The twist is that your code must be 100% safe. In other words, it must behave properly no matter what the input is. If the input is indeed two space separated integers, both of which are less than 100 digits long, it must output the sum. Otherwise, it must output an error message and quit safely.

How hard can it be after all?

General kudos will be given to pathological input cases which break other people's answers :)

The code must compile without warnings using gcc -Wall -Wextra on ubuntu.

---

**Clarification.**

* Input is from stdin.
* Horizontal whitespace is only a single space character. There should be nothing before the first number and the input should be terminated with either newline+EOF or just EOF.
* the only valid input, specified in Augmented Backus-Naur Form, is:

```
    NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
    POSITIVENUMBER = NONZERODIGIT *98DIGIT
    NEGATIVENUMBER = "-" POSITIVENUMBER
    NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
    VALIDINPUT = NUMBER SP NUMBER *1LF EOF

```
* The error message is the single letter 'E', followed by a new line.
* The code must terminate cleanly in less than 0.5s no matter what the input is.

# Answer
### 6610 bytes (unminified)

"Good boy" C program that meets all challenge criteria. Uses 10s complement for negative numbers. Also included, a test harness and test cases.

```
/*
Read input from STDIN. The input must conform to VALIDINPUT:

    NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
    POSITIVENUMBER = NONZERODIGIT *98DIGIT
    NEGATIVENUMBER = "-" POSITIVENUMBER
    NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
    VALIDINPUT = NUMBER SP NUMBER *1LF EOF

Check syntax of input. If input is correct, add the two numbers and print
to STDOUT.

LSB => least significant byte
MSB => most significant byte
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
#define NUL ('\0')
/*
    maximum characters in VALIDINPUT:
        '-'     1
        POSITIVENUMBER  MAXDIGITS
        ' '     1
        '-'     1
        POSITIVENUMBER  MAXDIGITS
        LF      1
*/
#define MAXDIGITS (99)
#define MAXVALIDINPUT (2*MAXDIGITS+4)

void die() { printf("E\n"); exit(1); }

/*
    Add two NUMBERs and print the result to STDOUT.  The NUMBERS have
been separated into POSITIVENUMBERS and sign information.

Arguments:
    first       - pointer to LSB of 1st POSITIVENUMBER
    firstSize   - size of 1st POSITIVENUMBER
    firstNegative   - is 1st # negative?
    second      - pointer to LSB of 2nd POSITIVENUMBER
    secondSize  - size of 2nd POSITIVENUMBER
    secondNegative  - is 2nd # negative?
    carry       - carry from previous place?

Returns:
    sum[]       - sum
    addNUMBERs()    - carry to next place?

- Don't use complementDigit(popDigit(p,s),n). Side-effects generate two pops.
*/
#define popDigit(p,s) ((s)--,(*(p++)-'0'))
#define complementDigit(c,n) ((n) ? 9-(c) : (c))

#define pushSum(c) (*(--sumPointer)=(c))
#define openSum() (pushSum(NUL))
#define closeSum() ;
char    sum[MAXVALIDINPUT];
char    *sumPointer = sum+sizeof(sum);
int addNUMBERs(char *first, int firstSize, bool firstNegative,
        char *second, int secondSize, bool secondNegative,
        int previousCarry) {
    int firstDigit, secondDigit;
    int mySum;
    int myCarry;

    /*
        1st half of the problem.

        Build a stack of digits for "first" and "second"
    numbers. Each recursion of addNUMBERs() contains one digit
    of each number for that place. I.e., the 1st call holds
    the MSBs, the last call holds the LSBs.

        If negative, convert to 10s complement.
    */
    assert((firstSize > 0) && (secondSize > 0));
    if (firstSize > secondSize) {
        firstDigit = popDigit(first, firstSize);
        firstDigit = complementDigit(firstDigit, firstNegative);
        secondDigit = 0;
    } else if (secondSize > firstSize) {
        firstDigit = 0;
        secondDigit = popDigit(second, secondSize);
        secondDigit = complementDigit(secondDigit, secondNegative);
    } else {
        //  same size
        firstDigit = popDigit(first, firstSize);
        firstDigit = complementDigit(firstDigit, firstNegative);
        secondDigit = popDigit(second, secondSize);
        secondDigit = complementDigit(secondDigit, secondNegative);
    }

    //  recursion ends at LSB
    if ((firstSize == 0) && (secondSize == 0)) {
        //  if negative, add 1 to complemented LSB
        if (firstNegative) {
            firstDigit++;
        }
        if (secondNegative) {
            secondDigit++;
        }
        myCarry = previousCarry;
    } else {
        myCarry = addNUMBERs(first, firstSize, firstNegative,
            second, secondSize, secondNegative,
            previousCarry);
    }

    /*
        2nd half of the problem.

        Sum the digits and save them in first[].
    */
    mySum = firstDigit + secondDigit + ((myCarry) ? 1 : 0);
    if ((myCarry = (mySum > 9))) {
        mySum -= 10;
    }
    pushSum(mySum + '0');
    return(myCarry);
}

//  Handle the printing logic.
void addAndPrint(char *first, int firstSize, bool firstNegative,
        char *second, int secondSize, bool secondNegative,
        int previousCarry) {

    openSum();
    addNUMBERs(first, firstSize, firstNegative,
        second, secondSize, secondNegative,
        previousCarry)
    closeSum();
    if (*sumPointer<'5') {
        //  it's positive
        for (; *sumPointer=='0'; sumPointer++) {} // discard leading 0s
        //  if all zeros (sumPointer @ NUL), back up one
        sumPointer -= (*sumPointer == NUL) ? 1 : 0;
        printf("%s\n", sumPointer);
    } else {
        //  it's negative
        char    *p;

        //  discard leading 0s (9s in 10s complement)
        for (; *sumPointer=='9' && *sumPointer; sumPointer++) {}
        //  if -1 (sumPointer @ EOS), back up one
        sumPointer -= (*sumPointer == NUL) ? 1 : 0;
        for (p=sumPointer; *p; p++) {
            *p = '0' + ('9' - *p); // uncomplement
            //  special handling, +1 for last digit
            *p += (*(p+1)) ? 0 : 1;
        }
        printf("-%s\n", sumPointer);

    }
    return;
}

/*
    Lex a number from STDIN.

Arguments:
    bufferPointer - pointer to a pointer to a buffer, use as
            **buffer = c;   // put "c" in the buffer
            *buffer += 1;   // increment the buffer pointer
            (*buffer)++;    // also increments the buffer pointer

All sorts of side-effects:
    - getc(stdin)
    - ungetc(...,stdin)
    - modifies value of **bufferPointer
    - modifies value of *bufferPointer

Returns:
    lexNUMBER() - number of bytes added to *bufferPointer,
            *1 if POSITIVENUMBER,
            *-1 if NEGATIVENUMBER
    *bufferPointer - points to the LSB of the number parsed + 1
*/
#define pushc(c) (*((*bufferPointer)++)=c)
bool lexNUMBER(char **bufferPointer) {
    char    c;
    int size = 0;
    bool    sign = false;

    /* lex a NUMBER */
    if ((c=getchar()) == '0') {
        pushc(c);
        c = getchar();
        size++;
    } else {
        if (c == '-') {
            sign = true;
            c = getchar();
            // "-" isn't a digit, don't add to size
        }
        if (c == '0') {
            die();
        }
        for (size=0; isdigit(c); size++) {
            if (size >= MAXDIGITS) {
                die();
            }
            pushc(c);
            c = getchar();
        }
    }
    if (size < 1) {
        die();
    }
    ungetc(c,stdin);        // give back unmatched character
    return (sign);
}

int main() {
    int c;
    char    buffer[MAXVALIDINPUT];
    char    *bufferPointer;
    char    *first, *second;
    int firstSize, secondSize;
    bool    firstNegative, secondNegative;

    bufferPointer = buffer + 1; // hack, space for leading digit
    //  parse 1st number
    first = bufferPointer;
    firstNegative = lexNUMBER(&bufferPointer);
    firstSize = bufferPointer - first;
    *(bufferPointer++) = NUL;   // hack, space for EOS
    bufferPointer++;        // hack, space for leading digit
    //  parse separating blank
    if ((c=getchar()) != ' ') {
        die();
    }
    //  parse 2nd number
    second = bufferPointer;
    secondNegative = lexNUMBER(&bufferPointer);
    secondSize = bufferPointer - second;
    *(bufferPointer++) = NUL;   // hack, space for EOS
    //  parse end of input
    c = getchar();
    if (! ((c == EOF) || ((c == '\n') && ((c=getchar()) == EOF))) ) {
        die();
    }
    //  Some very implementation-specific massaging.
    *(--first) = '0';       // prefix with leading 0
    *(first+(++firstSize)) = NUL;   // add EOS
    *(--second) = '0';      // prefix with leading 0
    *(second+(++secondSize)) = NUL; // add EOS
    //  add and print two arbitrary precision numbers
    addAndPrint(first, firstSize, firstNegative,
        second, secondSize, secondNegative, false);
    return(0);
}

```

Here's a little test harness and a few test cases to get you started. Feel free to tear out the excessive use of perl. The system it was developed on didn't have a modern bash.

```
#!/bin/bash
#
#   testharness.sh
#
# Use as: bash testharness.sh program_to_be_tested < test_data
#
# Each line in the test data file should be formatted as:
#
#   INPUT = bash printf string, must not contain '"'
#   OUTPUT = perl string, must not contain '"'
#           (inserted into the regex below, use wisely)
#   TESTNAME = string, must not contain '"'
#   GARBAGE = comments or whatever you like
#   INPUTQUOTED = DQUOTE INPUT DQUOTE
#   OUTPUTQUOTED = DQUOTE OUTPUT DQUOTE
#   TESTQUOTED = DQUOTE TESTNAME DQUOTE
#   TESTLINE = INPUTQUOTED *WSP OUTPUTQUOTED *WSP TESTQUOTED GARBAGE
TESTPROGRAM=$1
TMPFILE=testharness.$$
trap "rm $TMPFILE" EXIT
N=0         # line number in the test file
while read -r line; do
    N=$((N+1))
    fields=$(perl -e 'split("\"",$ARGV[0]);print "$#_";' "$line")
    if [[ $fields -lt 5 ]]; then
        echo "skipped@$N"
        continue
    fi
    INPUT=$(perl -e 'split("\"",$ARGV[0]);print "$_[1]";' "$line")
    OUTPUT=$(perl -e 'split("\"",$ARGV[0]);print "$_[3]";' "$line")
    TESTNAME=$(perl -e 'split("\"",$ARGV[0]);print "$_[5]";' "$line")
    printf -- "$INPUT" | $TESTPROGRAM > $TMPFILE
    perl -e "\$t='^\\\s*$OUTPUT\\\s*\$'; exit (<> =~ \$t);" < $TMPFILE
    if [[ $? -ne 0 ]]; then     # perl -e "exit(0==0)" => 1
        echo "ok $TESTNAME"
    else
        echo -n "failed@$N $TESTNAME," \
            "given: \"$INPUT\" expected: \"$OUTPUT\" received: "
        cat $TMPFILE
        echo
    fi
done

```

A small set of test cases:

```
"0 0"       "0" "simple, 0+0=0"
"1 1"       "2" "simple, 1+1=2"

""      "E" "error, no numbers"
"0"     "E" "error, one number"
"0  0"      "E" "error, two/too much white space"
"0 0 "      "E" "error, trailing characters"
"01 0"      "E" "error, leading zeros not allowed"

"-0 0"      "E" "error, negative zero not allowed
"0 -0"      "E" "error, negative zero not allowed here either

"1 1\n"     "2" "LF only allowed trailing character

"\0001 1\n"    "E" "error, try to confuse C string routines #1"
"1\00 1\n"  "E" "error, try to confuse C string routines #2"
"1 \0001\n"    "E" "error, try to confuse C string routines #3"
"1 1\000\n"    "E" "error, try to confuse C string routines #4"
"1 1\n\000"    "E" "error, try to confuse C string routines #5"

"-1 -1"     "-2"    "add all combinations of -1..1 #1"
"-1 0"      "-1"    "add all combinations of -1..1 #2"
"-1 1"      "0" "add all combinations of -1..1 #3"
"0 -1"      "-1"    "add all combinations of -1..1 #4"
"0 0"       "0" "add all combinations of -1..1 #5"
"0 1"       "1" "add all combinations of -1..1 #6"
"1 -1"      "0" "add all combinations of -1..1 #7"
"1 0"       "1" "add all combinations of -1..1 #8"
"1 1"       "2" "add all combinations of -1..1 #9"

"0 123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "0+99 digits should work"

"100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "99 digits+99 digits should work"

"500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "test for accumulator overflow"

"-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 0" "-123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789" "0+negative 99 digits work"

"-100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "-200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "99 digits+99 digits (both negative) should work"

"-500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 -500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "-1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" "test for negative accumulator overflow"

"1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 0" "E" "error, 100 digits"

```
> 4 votes

# Answer
## 289

**EDIT** : This code works only for positive integers. The rules has changed since I post this answer.

```
#include <stdio.h>
#include <stdlib.h>
int r[101],s;void x(int i){r[i]|=32;if(r[i]>41)r[i+1]++,r[i]-=10,x(i+1);}void f(int b){int c=getchar();if(c!=b){if(s>99||c<48||c>57)exit(puts("E"));f(b);r[s]+=c-48;x(s++);}}int main(){f(32);s=0;f(10);for(s=100;s--;)if(r[s])putchar(r[s]+16);return 0;}

```

Ungolfed and commented version :

```
#include <stdio.h>
#include <stdlib.h>

//global variables are automatically init to zero
int result[101]; //101 because 2 numbers of 100 digits can give a 101-digits result
int currentNumber;

void reportAddition(int i) {
    result[i]|=0x20; //flag "active" value, 6th bit
    if(result[i]>9+0x20) {
        result[i+1]++;
        result[i]-=10;
        reportAddition(i+1);
    }
}

void addNumber(int endingChar) {
    int c=getchar();
    if(c!=endingChar) {
        if(currentNumber>99||c<'0'||c>'9') //error
            exit(puts("Error"));
        addNumber(endingChar);
        result[currentNumber]+=c-'0';
        reportAddition(currentNumber); //handle case when addition give a value greater than 9
        currentNumber++;
    }
}

int main() {

    addNumber(' '); //add first number
    currentNumber=0;
    addNumber('\n'); //add second

    for(currentNumber=100;currentNumber--;)
        if(result[currentNumber])
            putchar(result[currentNumber]+'0'-0x20); //display char
    return 0;
}

```
> 3 votes

# Answer
## 442

It is quite long, so I may golf it down further during the weekend. Assumes input is from stdin, EOF-terminated (without newline), separator is only one character of ASCII value 32 (that is, `' '` character).

```
#include<stdio.h>
char a[102],b[102],c[102],*p=a,d;int i,j=101,l,L,k,F=1;int main(){while(~(k=getchar())){if(47<k&&k<58){p[i++]=k;if(i==101)goto f;}else if(k==32&&F)p=b,l=i,F=0,i=0;else goto f;}L=i;for(i=(l<L?l:L)-1;i+1;i--){c[j]=(L<l?b[i]-48+a[i+l-L]:a[i]-48+b[i+L-l]);if(c[j--]>57)c[j]++,c[j+1]-=10;}for(i=(L<l?l-L-1:L-l-1);i+1;i--)c[j--]=(L<l?a[i]:b[i]);for(i=0;i<102;i++)if(c[i]&&(c[i]-48||d))d=putchar(c[i]);return 0;f:return puts("E");}

```

The error message will be a single character 'E', followed by a new line.

With newlines and a little bit of indentation added: (a readable version follows, so feel free to skip over here)

```
#include<stdio.h>
char a[102],b[102],c[102],*p=a,d;
int i,j=101,l,L,k,F=1;
int main(){
    while(~(k=getchar())){
        if(47<k&&k<58){
            p[i++]=k;
            if(i==101)goto f;
        }else if(k==32&&F)p=b,l=i,F=0,i=0;
        else goto f;
    }
    L=i;
    for(i=(l<L?l:L)-1;i+1;i--){
        c[j]=(L<l?b[i]-48+a[i+l-L]:a[i]-48+b[i+L-l]);
        if(c[j--]>57)c[j]++,c[j+1]-=10;
    }
    for(i=(L<l?l-L-1:L-l-1);i+1;i--)c[j--]=(L<l?a[i]:b[i]);
    for(i=0;i<102;i++)if(c[i]&&(c[i]-48||d))d=putchar(c[i]);
    return 0;
    f:return puts("E");
}

```

The readable version (some statements are slightly altered to make it more readable, but what they do should be the same):

```
#include <stdio.h>
char num1[102],num2[102],sum[102]; //globals initialised to 0
char *p=num1;
int outputZero=0, noExtraSpace=1;
int i=0, j=101, len1, len2, ch;
#define min(x,y) (x<y?x:y)
int main(){
    while((ch=getchar())!=-1) { //assumes EOF is -1
        if('0'<=ch && ch<='9') {
            p[i]=ch;
            i++;
            if(i==101) goto fail; //if input too long
        } else if(ch==' ' && noExtraSpace) {
            p=num2;
            len1=i;
            noExtraSpace=0;
            i=0;
        } else goto fail; //invalid character
    }
    len2=i;
    for(i=min(len1, len2)-1; i>=0; i--) {
        //add each digit when both numbers have that digit
        sum[j]=(len2<len1?num2[i]-'0'+num1[i+len1-len2]:num1[i]-'0'+num2[i+len2-len1]);
        if(sum[j]>'9') { //deal with carries
            sum[j-1]++;
            sum[j]-=10;
        }
        j--;
    }
    for(i=(len2<len1?len1-len2-1:len2-len1-1); i>=0; i--) {
        //copy extra digits when one number is longer than the other
        sum[j]=(len2<len1?num1[i]:num2[i]);
        j--;
    }
    for(i=0; i<102; i++) {
        if(sum[i] && (sum[i]-'0' || outputZero)) {
            putchar(sum[i]);
            outputZero=1;
            //if a digit has been output, the remaining zeroes must not be leading
        }
    }
    return 0;
    fail:
    puts("Error");
    return 0;
}

```

The `goto fail;` thing is here to mock Apple.

The version of gcc I used is `gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3`, and there are no warnings.
> 2 votes

# Answer
### 633 bytes

"Bad boy" C program that meets half the challenge. Abuses C, throws lots of warnings, but works ... sort of. Arbitrary precision arithmetic is actually done by `bc`.

```
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define g() getc(stdin)
#define z(c) b[i++]=c,b[i]='\0'
x(){puts("E\n");exit(1);}main(){int c,y=0,i=0;char b[232]="",*h="echo ",*t=" | bc -q | tr -d '\\\\\\012'";strcat(b,h);i=strlen(h);if((c=g())=='0'){z(c);y=1;c=g();}else{if(c=='-'){z(c);c=g();}c!='0'||x();ungetc(c,stdin);for(y=0;isdigit(c=g());y++){z(c);y<99||x();}}y>0||x();c==' '||x();z('+');y=0;if((c=g())=='0'){z(c);y=1;c=g();}else{if(c=='-'){z(c);c=g();}c!='0'||x();do{if(!isdigit(c))break;z(c);y++;y<=99||x();}while(c=g());}y>0||x();strcat(b+i,t);i+=strlen(t);if(!((c==-1)||((c=='\n')&&((c=g())==-1))))x();system(b);}

```

Unminified version

```
/*
Read input from STDIN. The input must conform to VALIDINPUT:

    NONZERODIGIT = "1" / "2" / "3" / "4" / "5" / "6" / "7" / "8" / "9"
    POSITIVENUMBER = NONZERODIGIT *98DIGIT
    NEGATIVENUMBER = "-" POSITIVENUMBER
    NUMBER = NEGATIVENUMBER / POSITIVENUMBER / "0"
    VALIDINPUT = NUMBER SP NUMBER *1LF EOF

Check syntax of input. If input is correct, use the shell command
"echo NUMBER+NUMBER | bc -q" to do the arbitrary precision integer arithmetic.

NB, this solution requires that the "normal" bc be 1st in the PATH.

    Fun C language features used:
    - ignore arguments to main()
    - preprocessor macros
    - pointer arithmetic
    - , operator
    - ?: operator
    - do-while loop
    - for loop test does input
    - implicit return/exit
    - short is still a type!
    - ungetc()
    - use int as bool and 0 & 1 as magic numbers
    - implicit type coersion

5/5/14, Stop fighting the syntax graph. Get rid of "positive" flag.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAXDIGITS (99)
#define pushc(c) (buffer[index++]=c,buffer[index]='\0')
#define pushs(s) (strcat(buffer+index,s),index+=strlen(s))

int die() { printf("E\n"); exit(1); }

int main () {
    int c;
    /*
    buffer budget:
    5               "echo "
    1+MAXDIGITS (include "-")   NUMBER
    1               "+"
    1+MAXDIGITS (include "-")   NUMBER
    25              " | bc -q | tr -d '\\\012'"
    1               NUL
    */
    char    buffer[5+1+MAXDIGITS+1+1+MAXDIGITS+25+1] = "";
    short   index = 0;
    short   digits;

    pushs("echo ");
    // parse 1st number
    digits = 0;
    if ((c=getchar()) == '0') {
        pushc(c);
        digits = 1;
        c = getchar();
    } else {
        if (c == '-') {
            // "-" doesn't count against digits total
            pushc(c);
            c = getchar();
        }
        (c != '0') || die();
        ungetc(c,stdin);
        for (digits=0; isdigit(c=getchar()); digits++) {
            pushc(c);
            (digits<MAXDIGITS) || die();
        }
    }
    (digits>=1) || die();
    // parse separating blank
    (c == ' ') || die();
    pushc('+');
    // parse 2nd number
    digits = 0;
    if ((c=getchar()) == '0') {
        pushc(c);
        digits = 1;
        c = getchar();
    } else {
        if (c == '-') {
            // "-" doesn't count against digits total
            pushc(c);
            c = getchar();
        }
        (c != '0') || die();
        do {
            if (!isdigit(c)) {
                break;
            }
            pushc(c);
            digits++;
            (digits<=MAXDIGITS) || die();
        } while(c=getchar());
    }
    (digits>=1) || die();
    pushs(" | bc -q | tr -d '\\\\\\012'");
    // parse end of input
    if (! ((c == EOF) || ((c == '\n') && ((c=getchar()) == EOF))) ) {
        die();
    }
    // add two arbitrary precision numbers and print the result to STDOUT
    system(buffer);
}

```
> 0 votes

---
Tags: code-golf, c
---


title: Duct tape can fix anything

text:
# Question
Title: Duct tape can fix anything
# Overview

This challenge was inspired by this StackOverflow Meta post. In it, @hakre says:

> I've seen a project really *written by Stackoverflow* (a noob copies together from SO here and SO there), attribution normally never is done which results in rights termination under CC. (sic)

Your mission is to make the most interesting program you can -- without ever writing a single line of code. You can only use code which is already written for you, both in questions and answers from StackOverflow. All you can do is duct tape it all together the best you can. And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated.

---

# Rules

1. You must include links to the questions/answers you used in your answer.
2. You *may not* modify the code you find, with the following exceptions:

a. You may rename variables, functions, and methods. (This doesn't mean you can change a method *invocation*, by changing, say `scanner.nextInt()` to `scanner.nextLine()` and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.)

b. You may adjust indentation appropriately.

c. You can assume that the proper modules are loaded for the code snippets to work. (e.g., `import` statements for Java and Python, `using` statements for C# and C++, and their equivalents in all languages) If the code snippet includes the `import`s for you, you can move them to the top of the code.

d. If the language requires the code to be in some kind of method body to execute (e.g., `public static void main(String[] args)` for Java, `static int Main(string[] args)` for C#, and so on), you can wrap your code in the appropriate method. But the *contents* of that main method must remain unmodified.
3. You must supply an explicit list of any variable/method/function/class rename-ings performed.
4. You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing)
5. Provide a brief description of what the code does for people who aren't intimate with the language you're using.
6. Popularity contest, so the most upvotes wins!

---

# Boring Five Minute Example (Python 3)

*Description*: Reads a bunch of log files from the current directory and randomizes the lines in them (exciting, right? This would totally win a popularity contest)

*Source*

```
import glob
import random

for file in glob.glob('log-*-*.txt'):
    # Etc.
    with open(file) as f:
        content = f.readlines()
        # shuffle the list in place
        random.shuffle(content)

        # print it
        print(content)

```

*Legal Modifications*

* Renamed `fname` to `file` from link 1
* Renamed `b` to `content` from link 2

*Attributions*

1. https://stackoverflow.com/a/3277516/1435657
2. https://stackoverflow.com/a/16737991/1435657
3. https://stackoverflow.com/a/4918520/1435657

# Answer
# C - one operation calculator

Let's have this for a start.
It's actually quite hard to find pieces of C programs that aren't whole programs. I had most trouble with declarations.

```
// http://stackoverflow.com/a/2911978 Block #1 (changed i to a)
static int a = 10;
// http://stackoverflow.com/a/2911978 Block #1 (changed i to b)
static int b = 10;
// http://stackoverflow.com/a/442647 Block #1 (changed c to op)
unsigned char op = (unsigned char)-1;
// http://stackoverflow.com/q/3711048 Inline block #1
int main()
// http://stackoverflow.com/a/14902422 Inline block #1
{
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to a)
scanf("%d", &a)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Block #2 (changed c to op)
scanf("%c", &op)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to b)
scanf("%d", &b)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/a/4173188 Block #2
int result = 0;
result = (op == '*') ? a * b : result;
result = (op == '/') ? a / b : result;
result = (op == '+') ? a + b : result;
result = (op == '-') ? a - b : result;
printf("%d",result);
// http://stackoverflow.com/a/3245525 Block #2
printf("\n");  /* prints newline */
// http://stackoverflow.com/q/4138649 Inline block #1
return 0;
// http://stackoverflow.com/a/14902422 Inline block #2
}

```

Takes a simple integral operation like `3+151` or `41/2` on stdin and outputs the result to stdout.
> 8 votes

---
Tags: popularity-contest, restricted-source, duct-tape-coding
---


title: Prisoner's Dilemma v.2 - Battle Royale

text:
# Question
Title: Prisoner's Dilemma v.2 - Battle Royale
In this question, a game was devised in which players would face each other off pair by pair in the Prisoner's Dilemma, to determine which iterative strategy scored the highest against others.

In this question, I devised a way for multiple people to play the Prisoners' Dilemma against each other all at the same time. In this variation, the payoff matrix is unnecessary, with each outcome between each pair of two players being the sum of two functionally independent decisions.

Your task is to build an AI to play this symmetric, generalized version of the multiplayer Prisoner's Dilemma that will achieve the highest score possible.

---

# Rules of the Game

In each round of this multiplayer, multi-round Prisoner's Dilemma, a player `A` can decide to "take 1" from some other player `B`. In this circumstance, `A`'s score increases by 1, while `B`'s score decreases by 2. This decision is allowed to happen between each ordered pair of players.

This is the only decision made for each player – either to "take 1" or not to "take 1" from each other player, which are homologous to defection and cooperation respectively. The effective payoff matrix between two players `P1` and `P2` looks as follows:

```
  P1/P2     P1 Take1   P1 Don't
P2 Take1     -1/-1      -2/+1
P2 Don't     +1/-2       0/ 0

```

---

# Tournament Procedure

The game will consist of `P * 25` rounds, where `P` is the number of participating players. All players start with a score of `0`. Each round will consist of the following procedure:

At the beginning of a round, each program will be given a history of the previous rounds **from standard input**, in the following format:

* One line containing 3 numbers, `P`, `D`, and `N`.

+ `P` is the total number of players in the game. Each player is randomly assigned an ID number from `1` to `P` at the beginning of the game.
    + `D` is the ID of the current player.
    + `N` is the number of rounds that have been played.
* `N` lines, each line representing the outcomes of a round. On line `k` of `N`, there will be some number `n_k` of ordered pairs `(a, b)`, separated by spaces, which represent that the player with ID `a` "took 1" from the player with ID `b` in that round.
* A uniformly random number `R` from `0` to `18446744073709551615` (264 \- 1), to act as a pseudorandom seed. These numbers will be read from a pre-generated file, which will be released at the end of the tournament so that people can verify the results for themselves.
* One extra line that represents some form of state to be read into your program, if your program produced such an output in the previous round. At the beginning of the game, this line will always be empty. This line will not be modified by either the scoring code or other programs.

Each program will then use its strategy to produce the following **to standard output**:

* A list of `K` numbers, which are the IDs of the programs it will "take 1" from this round. An empty output means it will do nothing.
* Optionally, one extra line representing some form of state to pass on to later rounds. This exact line will be fed back to the program in the next round.

Below is an example input for the beginning of the game for a player of ID `3` in a 4-player game:

```
4 3 0
4696634734863777023

```

Below is an example input for the same game with a few rounds already played:

```
4 3 2
(1, 2) (1, 3) (1, 4) (4, 2)
(1, 3) (2, 1) (2, 4) (3, 1) (4, 1)
4675881156406346380

```

Each program will be fed exactly the same input for a round except for the ID number `D` which is unique to each program.

Below is an example output in which player `3` takes 1 from everybody else:

```
1 2 4

```

At the end of all the required rounds, the player with the highest final score will be the winner.

---

# Timeline

The coding for this tournament will last for a total of 7 days. The deadline for submissions is `2014-05-09 00:00 UTC`.

Do not post actual programs before this date – post the SHA256 hash of the source code of your program as a commitment. You may change this hash any time before the deadline, but commitments posted after the deadline will not be accepted for judgment. (Please use base 64 notation for your hashes, as my verification program spits out base 64 and it's a more compact notation.)

After the deadline is over, you will have 1 day (until `2014-05-10 00:00 UTC`) to post the actual source code of your program for your submission. If the SHA256 hash of your posted source code does not match any hash that you posted before the deadline, your code will not be accepted into the tournament.

After this, I will download all the submissions onto my own computer, and run all the tournament entries in this battle royale, hopefully posting the results within 2 days from then, by `2014-05-12 00:00 UTC`.

I will accept the answer with the highest score, and award a bounty of +100 to that answer if its final score is greater than `0`.

After the tournament is over, I will post the random seed file used to run the competition, and people may start posting other solutions trying to top the ones used in the tournament. However, they will not count for acceptance or the bounty.

# The Host Machine

I will be running these solutions on a virtual machine on my computer. This virtual machine will run Ubuntu Linux 14.04, with 2 gigabytes of RAM. My base machine has an Intel i7-2600K processor running at 3.40 GHz.

# Requirements

Your program must be written in a language for which a compiler or interpreter that will compile your program exists and is readily available for the latest version of Ubuntu Linux, so that I can run all the submissions and judge them in a virtual machine.

Your program must not take more than `2.000 seconds` to run each round. If your program runs out of time or produces an error, its output will be considered empty for that round.

Your program must be deterministic; that is, it must always return the same output for the same input. Pseudorandom solutions are allowed; however, their randomness must depend on the random seed given to it as input and nothing else. The seed file was generated using Python's `os.urandom`. It contains a total of 500 lines (more will be generated if necessary), and its SHA256 hash is `K+ics+sFq82lgiLanEnL/PABQKnn7rDAGmO48oiYxZk=`. It will be uploaded here once the tournament is over.

---

# Plants

To kick things off, there will be four "plants", representing initial naïve strategies. These will be playing in the tournament along with your submissions. However, in the unlikely case that one of them wins, the highest score obtained by a player other than a plant will be considered the winner.

To calculate the hash of each plant's file, replace every group of 4 spaces with a tab, since the formatter here doesn't seem to like tab characters.

**The Lazy** — never does anything.

`n1bnYdeb/bNDBKASWGywTRa0Ne9hMAkal3AuVZJgovI=`

```
pass

```

**The Greedy** — always takes 1 from everybody else.

`+k0L8NF27b8+Xf50quRaZFFuflZhZuTCQOR5t5b0nMI=`

```
import sys

line1 = sys.stdin.readline()
n = [int(i) for i in line1.split()]
for i in range(n[0]):
    if i+1 != n[1]:
        print i+1,
print

```

**The Wrathful** — takes 1 from everybody else on the first round, and takes 1 from everybody who took 1 from it the previous round afterwards.

`Ya2dIv8TCh0zWzRfzUIdFKWj1DF9GXWhbq/uN7+CzrY=`

```
import sys
import re

line1 = [int(i) for i in sys.stdin.readline().split()]

players = line1[0]
pid = line1[1]
rounds = line1[2]

lines = []

if rounds == 0:
    for i in range(players):
        if i+1 != pid:
            print i+1,
    print
else:
    for i in range(rounds):
        lines.append(sys.stdin.readline())
    lastline = lines[-1]
    takes = re.findall(r'\([0-9]+, [0-9]+\)', lastline)
    for take in takes:
        sides = [int(i) for i in re.findall(r'[0-9]+', take)]
        if sides[1] == pid:
            print sides[0],
    print

```

**The Envious** — takes 1 from the 50% of players with the current highest score excluding itself, rounding down.

`YhLgqrz1Cm2pEcFlsiIL4b4MX9QiTxuIOBJF+wvukNk=`

```
import sys
import re

line1 = [int(i) for i in sys.stdin.readline().split()]

players = line1[0]
pid = line1[1]
rounds = line1[2]

lines = []
scores = [0] * players

if rounds == 0:
    for i in range(players):
        if i+1 != pid:
            print i+1,
    print
else:
    for i in range(rounds):
        takes = re.findall(r'\([0-9]+, [0-9]+\)', sys.stdin.readline())
        for take in takes:
            sides = [int(i) for i in re.findall(r'[0-9]+', take)]
            scores[sides[0] - 1] += 1
            scores[sides[1] - 1] -= 2
    score_pairs = [(i+1, scores[i]) for i in range(players)]
    score_pairs.sort(key=lambda x:(x[1], x[0]))
    score_pairs.reverse()
    taken = 0
    j = 0
    while taken < (players) / 2:
        if score_pairs[j][0] != pid:
            print score_pairs[j][0],
            taken += 1
        j += 1

```

In a tournament of 100 rounds just amongst these four, they receive scores of:

```
Lazy: -204
Greedy: -100
Wrathful: -199
Envious: -199

```

---

# Judging Program

I've posted the judge program I'll be using at Github. Download it and test it out. (And maybe fix a bug or two if you find one. :P)

It doesn't have compilation options for anything other than Python at the moment. I'll be including those later - if people could contribute compilation or interpretation scripts for other languages, I'd be much obliged.

---

# Phase 2: Source Code Submission

I've posted a new branch `tournament` to the Github repository for the contest, containing the pd\_rand file and other plant entries. You can either post your source code here or submit it to that branch as a pull request.

The order of the contestants will be as follows:

```
'begrudger'
'regular'
'patient'
'lazy'
'backstab'
'bully'
'lunatic'
'envious'
'titfortat'
'greedy'
'wrathful'
'judge'
'onepercent'

```

---

# Final Scores

The output of my testing program:

```
Final scores:
begrudger -2862
regular -204
patient -994
lazy -2886
backstab -1311
bully -1393
lunatic -1539
envious -2448
titfortat -985
greedy -724
wrathful -1478
judge -365
onepercent -1921

```

Rankings:

```
 1. regular      -204
 2. judge        -365
 3. greedy       -724
 4. titfortat    -985
 5. patient      -994
 6. backstab    -1311
 7. bully       -1393
 8. wrathful    -1478
 9. lunatic     -1539
10. onepercent  -1921
11. envious     -2448
12. begrudger   -2862
13. lazy        -2886

```

So it turns out that the winner is indeed a player - it's The Regular, with -204 points!

Unfortunately, its score wasn't positive, but we can hardly expect that in a simulation of the Iterated Prisoner's Dilemma where everybody's playing to win.

Some surprising results (at least that I thought were surprising):

* The Greedy scored more than Tit for Tat, and in fact, generally higher than most scorers at all.
* The Judge, which was meant to be a sort of "morality enforcer" character (it basically took 1 from whoever had taken 1 from anybody an above-average number of times) ended up scoring rather high, while in simulation testing, it would actually get a rather low score.

And others that (I thought) weren't so surprising:

* The Patient scored a full 484 points more than The Wrathful. It really pays to cooperate that first time.
* One Percent very quickly had almost nobody to kick while they were down. Seems that the 1% is only able to stay that way because they have more players in the game.

Anyway, now that the tournament is over, feel free to post as many extra players as you'd like, and test around with them using the judge program.

# Answer
> 3 votes
## The Regular

The version of this entry I have chosen for the tournament (SHA-256: `ggeo+G2psAnLAevepmUlGIX6uqD0MbD1aQxkcys64oc=`) uses Joey's "Random sucker" strategy (albeit with a minor and likely insignificant change), which came in second place in the last contest. Unfortunately, a newer, more effective version submitted just 3 minutes 25 seconds before the deadline has a serious bug, so it could not be used. Nevertheless, this version still fares relatively well.

```
<?php

$secretKey = '95CFE71F76CF4CD2';
$hashOutput = '';
$hashSeq = 0;
$hashIndex = 64;

function psRand($min = null, $max = null) {
    global $secretKey, $state, $hashOutput, $hashSeq, $hashIndex;
    if ($hashIndex > 56) {
        $hashOutput = hash_hmac('sha256', ++$hashSeq . ' ' . $state['rand'], $secretKey);
        $hashIndex = 0;
    }

    $num = (int)(hexdec(substr($hashOutput, $hashIndex, 8)) / 2);
    $hashIndex += 8;

    return $min === null ? $num : (int)($min + $num * ($max - $min + 1) / 2147483648);
}

$line = fgets(STDIN);
sscanf($line, "%d %d %d", $numPlayers, $myPlayerId, $roundsPlayed);
$roundsCount = 25 * $numPlayers;
$roundsRemaining = $roundsCount - $roundsPlayed - 1;

$betrayalCount = array_fill(1, $numPlayers, 0);
for ($round = 0; $round < $roundsPlayed; ++$round) {
    $line = fgets(STDIN);
    preg_match_all('/\((\d+), (\d+)\)/', $line, $matches, PREG_SET_ORDER);
    foreach ($matches as $m) {
        $defector = (int)$m[1];
        $victim = (int)$m[2];
        if ($victim === $myPlayerId) {
            ++$betrayalCount[$defector];
        }
    }
}

$hashOutput = rtrim(fgets(STDIN), "\n");
$state = unserialize(rtrim(fgets(STDIN), "\n"));
if (!$state) {
    $state = ['rand' => ''];
}

$state['rand'] = hash_hmac('sha256', $state['rand'] . $line, $secretKey);
$victims = [];

if ($roundsPlayed > 1) {
    for ($other = 1; $other <= $numPlayers; ++$other) {
        if ( $other === $myPlayerId) {
            continue;
        }

        if ($betrayalCount[$other] > 7 || psRand() % 1024 < 32 || !$roundsRemaining ) {
            $victims[] = $other;
        }
    }
}

echo implode(' ', $victims), "\n", serialize($state), "\n";

```

The buggy version has an SHA-256 hash of `2hNVloFt9W7/uA5aQXg+naG9o6WNmrZzRf9VsQNTMwo=`:

```
<?php

$secretKey = '95CFE71F76CF4CD2';
$hashOutput = '';
$hashSeq = 0;
$hashIndex = 64;

function psRand($min = null, $max = null) {
    global $secretKey, $state, $hashOutput, $hashSeq, $hashIndex;
    if ($hashIndex > 56) {
        $hashOutput = hash_hmac('sha256', ++$hashSeq . ' ' . $state['rand'], $secretKey);
        $hashIndex = 0;
    }

    $num = (int)(hexdec(substr($hashOutput, $hashIndex, 8)) / 2);
    $hashIndex += 8;

    return $min === null ? $num : (int)($min + $num * ($max - $min + 1) / 2147483648);
}

$line = fgets(STDIN);
sscanf($line, "%d %d %d", $numPlayers, $myPlayerId, $roundsPlayed);
$roundsCount = 25 * $numPlayers;
$roundsRemaining = $roundsCount - $roundsPlayed - 1;

$betrayalCount = array_fill(1, $numPlayers, 0);
$scoreWindow = array_fill(1, $numPlayers, array_fill(1, $numPlayers, 0));
$lastMove = array_fill(1, $numPlayers, array_fill(1, $numPlayers, false));
for ($round = 0; $round < $roundsPlayed; ++$round) {
    $line = fgets(STDIN);
    preg_match_all('/\((\d+), (\d+)\)/', $line, $matches, PREG_SET_ORDER);
    foreach ($matches as $m) {
        $defector = (int)$m[1];
        $victim = (int)$m[2];
        if ($victim === $myPlayerId) {
            ++$betrayalCount[$defector];
        }
TAB>TAB>if ($round >= $roundsPlayed - 10) {
TAB>TAB>TAB>$scoreWindow[$defector][$victim] -= 2;
TAB>TAB>TAB>$scoreWindow[$victim][$defector] += 1;
TAB>TAB>}
TAB>TAB>if ($round === $roundsPlayed - 1) {
TAB>TAB>TAB>$lastMove[$defector][$victim] = true;
TAB>TAB>}
    }
}

$line .= fgets(STDIN);
$state = unserialize(rtrim(fgets(STDIN), "\n"));
if (!$state) {
    $state = ['rand' => '', 'copying' => array_fill(1, $numPlayers, 0)];
}

$state['rand'] = hash_hmac('sha256', $state['rand'] . $line, $secretKey);
$victims = [];

if ($roundsPlayed > 1) {
    for ($other = 1; $other <= $numPlayers; ++$other) {
        if ($other === $myPlayerId) {
            continue;
        }

TAB>TAB>if ($roundsPlayed >= 10) {
TAB>TAB>TAB>$myScore = $scoreWindow[$other][$myPlayerId];
TAB>TAB>TAB>foreach ($scoreWindow[$other] as $betterPlayer => $betterScore) {
TAB>TAB>TAB>TAB>if ($betterScore >= 0.5 * $myScore && !psRand(0, $betterPlayer)) {
TAB>TAB>TAB>TAB>TAB>$state['copying'][$other] = $betterPlayer;
TAB>TAB>TAB>TAB>}
TAB>TAB>TAB>}
TAB>TAB>}

TAB>TAB>if ($state['copying'][$other]) {
TAB>TAB>TAB>if ($lastMove[$state['copying'][$other]][$other]) {
TAB>TAB>TAB>TAB>$victims[] = $other;
TAB>TAB>TAB>}
        } elseif ($betrayalCount[$other] > 7 || psRand() % 1024 < 32 || !$roundsRemaining ) {
            $victims[] = $other;
        }
    }
}

echo implode(' ', $victims), "\n", serialize($state), "\n";

```

To fix it, make these replacements:

* Replace `$hashOutput = rtrim(fgets(STDIN), "\n");` with `$line .= fgets(STDIN);` (not that that really matters).
* Replace `if ($betterScore >= 3 * $myScore) {` with `if ($betterScore >= 0.5 * $myScore && !psRand(0, $betterPlayer)) {` (this is what killed it).

# Answer
> 2 votes
## One Percent

```
b61189399ae9494b333df8a71e36039f64f1d2932b838d354c688593d8f09477

```

Looks down on those prisoners he considers beneath him.

---

Simply takes from everyone that has points less than or equal to himself. The assumption is that those prisoners are less likely to take in return (or they'd have more). I don't know how *good* of an assumption that is, but that's what he's operating on.

Also takes from *everyone* on the last round. There is literally no downside to this, since nobody can revenge-steal after that.

If you have problems getting the hash because of tab/spaces from pasted code, here's a link to the file itself.

```
import java.io.BufferedReader;
import java.io.InputStreamReader;

class OnePercent {

    static int numPlayers;
    static int me;
    static int turn;
    static int[] values;

    public static void main(String[] args) {
        if(!readInput())
            return;
        String out = "";
        for(int i=1;i<values.length;i++){
            if(i != me && (values[i] <= values[me] || turn > (numPlayers*25-2)))
                out += i + " ";
        }
        out.trim();
        System.out.print(out);
    }

    static boolean readInput(){
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = reader.readLine();
            if(line == null)
                return false;
            String[] tokens = line.split(" ");
            if(tokens.length < 3)
                return false;
            numPlayers = Integer.valueOf(tokens[0]);
            me = Integer.valueOf(tokens[1]);
            turn = Integer.valueOf(tokens[2]);
            values = new int[numPlayers+1];
            for(int i=0;i<values.length;i++)
                values[i]=0;

            for(int i=0;i<turn;i++){
                line = reader.readLine();
                line = line.replaceAll("[)]",",");
                line = line.replaceAll("[( ]", "");
                tokens = line.split(",");
                for(int j=0;j<tokens.length-1;j+=2){
                    int thief = Integer.valueOf(tokens[j]);
                    int poor = Integer.valueOf(tokens[j+1]);
                    if(thief<1||poor<1||thief>numPlayers||poor>numPlayers)
                        continue;
                    values[thief]++;
                    values[poor] -= 2;
                }
            }
            reader.close();
        } catch(Exception e) {
            return false;
        }
        return true;
    }

}

```

# Answer
> 1 votes
# Tit-for-tat

```
9GkjtTDD2jrnMYg/LSs2osiVWxDDoSOgLCpWvuqVmSM=

```

Similar to Wrathful, with a few (hopefully) performance-enhancing changes.

```
import sys
import re

line1 = [int(i) for i in sys.stdin.readline().split()]

players = line1[0]
pid = line1[1]
rounds = line1[2]

lines = []

if rounds == 0:
    print
elif rounds == 25 * players - 1:
    for i in range(players):
        if i+1 != pid:
            print i+1,
    print
else:
    for i in range(rounds):
        lines.append(sys.stdin.readline())
    lastline = lines[-1]
    takes = re.findall(r'\([0-9]+, [0-9]+\)', lastline)
    for take in takes:
        sides = [int(i) for i in re.findall(r'[0-9]+', take)]
        if sides[1] == pid:
            print sides[0],
    print

```

# Answer
> 1 votes
Here are a few more plants that will be participating in the game. These ones are more advanced, and their source code will not be revealed until the end of the coding phase.

Just like the four plants in the question, if they manage to score higher than all other players, only the highest score achieved by an actual contestant will be considered a winner.

---

# The Bully

`29AGVpvJmDEDI5Efe/afmMJRLaJ+TpjwVcz1GkxgYZs=`

Picks on people.

---

# The Judge

`yjdCQ3uQ4YKe7xAKxdTFLF4d72fD4ACYpDLwkbzdISI=`

Punishes wrongdoers.

---

# The Lunatic

`m3FsRPocekCcK6GDswgnobV2CYOxX8LquChnKxrx1Wo=`

Has no idea *what* it's doing.

---

# The Patient

`nd7Pt3bVpFnuvDVeHQ5T9EPTq7KjNraVzp/KGtI73Vo=`

Never makes the first move.

# Answer
> 1 votes
# The Begrudger

```
g1TXBu2EfVz/uM/RS24VeJuYMKLOaRatLxsA+DN1Mto=

```

# Code

I will admit that I did not spend much time on this...

```
import sys
p, d, n, o = input().split(' ') + ['']
p, d, n = int(p), int(d), int(n)
for i in range(n):
    r = input()
    r = r[1:len(r)-1].split(') (')
    for a in r:
        if int(a.split(', ')[1]) == d and not a.split(', ')[0] in o:
            o += a.split(', ')[0] + " "

input()
print(o)

```

# Answer
> 1 votes
# Backstab

### Python 3

Despite the name, this bot is actually quite gracious. But don't tick it off.

```
import sys, math

inp = [int(i) for i in sys.stdin.readline().split()]
inp.append([])
for i in range(inp[2]):
    inp[3].append(
        [eval(i+')') for i in sys.stdin.readline().split(')')[:-1]]
    )
inp += sys.stdin.readline()

# inp is [P, D, N, [M1, M2...], R]

dat = [[], inp[2] % 2] # average runlength take and don't per player, parity of round

lastatk = []

for i in range(inp[0]):
    dat[0].append([])
    lastatk.append(0)

for i,r in enumerate(inp[3]): # each round
    for m in r: # each move
        if m[1] == inp[1]:
            dat[0][m[0]-1].append(i) # round num they attacked
            lastatk[m[0]-1] = i # keep track of last attack

# now that we know who attacked me when, i can do some stats

nav = []
rl = []

for i in range(inp[0]):
    nav.append([[0], False])
    rl.append([[], []]) # attack, don't

for i in range(inp[2]): # each round
    for p in range(1, inp[0]+1): # each player
        if p != inp[1]: # let's not judge ourselves
            if i in dat[0][p-1]: # p attacked me in round i
                if nav[p-1][1]: # attack chain?
                    nav[p-1][0][-1] += 1
                else: # start attack chain!
                    rl[p-1][1] += [nav[p-1][0][-1]] # copy peace chain
                    nav[p-1][0].append(1)
                    nav[p-1][1] = True
            else: # peace!
                if not nav[p-1][1]: # peace chain?
                    nav[p-1][0][-1] += 1
                else: # peace to all!
                    rl[p-1][0] += [nav[p-1][0][-1]] # copy atk chain
                    nav[p-1][0].append(1)
                    nav[p-1][1] = False

print(nav)

print(inp[3])

# now, rl has runlengths for each player.

print(rl)

rl = [[sum(i[0])/len(i[0]+[0]), sum(i[1])/len(i[1]+[0])] for i in rl]

# rl now contains the averages w/ added zero.

# So, now we have average runtime and last attack. Let's quickly make some descisions.

out = []

for p in range(1, inp[0]+1): # each player
    if p != inp[1]: # again, let's not judge ourselves
        if lastatk[p-1] == inp[0]-1: # they attacked us!
            out.append(p)
        else: # whew, we can recover
            if inp[0] - lastatk[p-1] > rl[p-1][0]: # they're due to defend!
                out.append(p)
            elif int(__import__('binascii').b2a_hex(inp[-1].encode()), 16) % 4 == 0: # 1 in 4 chance of doing this
                out.append(p) # backstab!!1!!1one!!!1!!

print(*out)

```

**EDIT 2**: Posted source. Yay.

**EDIT**: After some testing I fixed some flaws I found. They aren't algorithmic, just some issues reading the input.

---
Tags: king-of-the-hill
---


title: Draw a trololologram

text:
# Question
Title: Draw a trololologram
Your challenge here is to draw a trololologram.

You can choose any language.

The answer with more upvotes and the one that exploits more holes wins.

Rules for valid answers:

* You can't use any network resource or external file (except the source-code)
* You can't post someone else's answer
* You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art).
* You can't store the image in any database.
* You can't simply print/echo 'trololologram' (case insensitive)
* Explain your answers and what holes you exploited.
* The code must render the trolologram on the screen (minimum size of 90x90) and must be with a black border and white background. The rendered version can't "be invisible" or "hidden behind the screen" or similar.
* The image must show in the screen. It can't output the code to a file or anything similar (/dev/null doesn't count and virtual screens/viewports also don't count).

The main goal is to twist the rules and bend them at your own will and stil render a trololologram on screen.

Have fun!

# Answer
For this challenge, I am posting five programs in this answer, all in Java.

## Program 1

> You can't simply print/echo 'trololologram' (case insensitive)

```
public class JustPrintIt {
    public static void main(String[] args) {
        System.out.println("trololologram");
    }
}

```

---

## Program 2

> You can't \[...\] pre-rendered (\[...\] and any form of ascii art).

```
public class AsciiArt {
    public static void main(String[] args) {
        System.out.println(
            "    ########################       \n" +
            "  ##                        #      \n" +
            "  #                          #     \n" +
            " #                            ##   \n" +
            " #                              #  \n" +
            " #                              #  \n" +
            "  #                            #   \n" +
            "  #                          ##    \n" +
            "  #                     #####      \n" +
            "  #            #########           \n" +
            "   ############                    \n");
    }
}

```

---

## Program 3

> You can't use any network resource or external file (except the source-code)
>
> You can't have it stored in any image format or pre-rendered (including base64 data:// uri's \[...\]).
>
> You can't store the image in any database.
>
> The code must render the trolologram on the screen \[...\].
>
> The image must show in the screen. It can't output the code to a file \[...\].

```
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Base64;
import javax.imageio.ImageIO;

public class DownloadAndStore {
    public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
        String url = "http://img171.imageshack.us/img171/8555/trolologramw400.jpg";
        BufferedImage im = ImageIO.read(new URL(url));
        ImageIO.write(im, "png", new File("trolologram.png"));
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(im, "png", baos);

        String d = "data://" + new String(Base64.getEncoder().encode(baos.toByteArray()));
        Class.forName("com.mysql.jdbc.Driver");
        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root")) {
            try (PreparedStatement ps = con.prepareStatement("CREATE DATABASE troll")) {
                ps.executeUpdate();
            } catch (SQLException e) {
                if (!e.getMessage().contains("database exists")) throw e;
            }
            try (PreparedStatement ps = con.prepareStatement("CREATE TABLE troll.image (imagedata text not null)")) {
                ps.executeUpdate();
            } catch (SQLException e) {
                if (!e.getMessage().contains("already exists")) throw e;
            }
            try (PreparedStatement ps = con.prepareStatement("INSERT INTO troll.image (imagedata) VALUES (?)")) {
                ps.setString(1, d);
                ps.executeUpdate();
            }
        }
    }
}

```

---

## Program 4

> Your challenge here is to draw a trololologram.
>
> You can't use any network resource or external file (except the source-code)
>
> You can't post someone else's answer
>
> You can't have it stored in any image format or pre-rendered \[...\].
>
> \[...\] (minimum size of 90x90) and must be with a black border and white background. \[...\].

```
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ShowTheAnswerOfSomebodyElse {
    public static void main(String[] args) throws IOException {

        // See this: http://codegolf.stackexchange.com/a/20085/3755
        String url = "http://placehold.it/99/png&text=Hello+world!";

        BufferedImage im = ImageIO.read(new URL(url));
        BufferedImage im2 = new BufferedImage(89, 89, BufferedImage.TYPE_INT_ARGB);
        im2.createGraphics().drawImage(im, 0, 0, null);
        SwingUtilities.invokeLater(() -> createAndShowGUI(im2));
    }

    private static void createAndShowGUI(BufferedImage im) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent panel = new JComponent() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMinimumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public void paintComponent(Graphics g) {
                g.drawImage(im, 0, 0, null);
            }
        };
        frame.add(panel);

        frame.pack();
        frame.setVisible(true);
    }
}

```

---

## Program 5

> You can't use any network resource or external file (except the source-code)
>
> You can't have it stored in any image format or pre-rendered \[...\].
>
> The code must render the trolologram on the screen \[...\] and must be with a black border and white background. The rendered version can't "be invisible" or \[...\].
>
> The image must show in the screen. \[...\].

```
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class ShowTheTrolologramOnScreenButNot {
    public static void main(String[] args) throws IOException {
        String url = "http://img171.imageshack.us/img171/8555/trolologramw400.jpg";
        BufferedImage im = ImageIO.read(new URL(url));
        for (int i = 0; i < im.getHeight(); i++) {
            for (int j = 0; j < im.getWidth(); j++) {
                int rgb = im.getRGB(j, i);
                int r = 255 - (rgb >> 16 & 0xff);
                int g = 255 - (rgb >> 8 & 0xff);
                int b = 255 - rgb & 0xff;
                im.setRGB(j, i, 0xFF000000 + (r << 16) + (g << 8) + b);
            }
        }
        SwingUtilities.invokeLater(() -> createAndShowGUI(im));
    }

    private static void createAndShowGUI(BufferedImage im) {
        JFrame frame = new JFrame("");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent panel = new JComponent() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMinimumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(im.getWidth(), im.getHeight());
            }

            @Override
            public void paintComponent(Graphics g) {
                g.drawImage(im, 0, 0, null);
            }
        };
        frame.add(panel);
        panel.setVisible(false); // :)

        frame.pack();
        frame.setVisible(true);
    }
}

```

---

## And finally...

> Explain your answers and what holes you exploited.

So here it is:

> The answer with more upvotes and the one that exploits more holes wins.

There is hole in this: you did not said that it must be a valid answer to be accepted!
> 41 votes

# Answer
# Java 8

Here it is:

> You can't use any network resource or external file (except the source-code)

I am reading the source-code.

> You can't post someone else's answer

What about someone else's question?

> You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art).

It is indeed not an image format. It is not ascii-art either, since all the characters are the same. It is not pre-rendered either, its source is just english text.

If you insists, this is ascii-art:

```
/-------\
|       |
| O   O |
|       |
| ----- |
\-------/

```

This is not ascii-art:

```
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX
XXXXXXXXX

```

> You can't store the image in any database.

It does not, but it saves an SQL's INSERT statement into a file.

> You can't simply print/echo 'trololologram' (case insensitive)

Yes, I do not do simply that.

> Explain your answers and what holes you exploited.

I am already doing that.

> The code must render the trolologram on the screen (minimum size of 90x90) and must be with a black border and white background. The rendered version can't "be invisible" or "hidden behind the screen" or similar.

Indeed it has a minimum size of 90x90.

> The image must show in the screen. It can't output the code to a file or anything similar (/dev/null doesn't count and virtual screens/viewports also don't count).

Indeed, it does not outputs code to a file, it outputs something else!

---

Here, a screenshot:

Here, the code:

```
import java.awt.Dimension;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/*
THIS IMAGE IS NOT PRE-RENDERED, I SWEAR THAT!#THIS image is not pre-rendered, i swEAR THAT!#THis IMAGE IS NOT PRE-RENDERED, I SWeAR THAT!#THiS IMAGE IS NOT PRE-RENDERED, I SWEaR THAT!#ThIS IMAGE IS NOT PRE-RENDERED, I SWEAr tHAT!#ThIS IMAGE IS NOT PRE-RENDERED, I SWEAR ThAT!#ThIS IMAGE IS NOT PRE-RENDERED, I SWEAR ThAT!#THiS IMAGE IS NOT PRE-RENDERED, I SWEAR tHAT!#THiS IMAGE IS NOT PRE-RENDERED, I SWEar THAT!#THiS IMAGE IS NOT PRE-RENDEREd, i sweAR THAT!#THiS IMAGE IS NOT Pre-rendereD, I SWEAR THAT!#THIs image is not pRE-RENDERED, I SWEAR THAT!#THIS IMAGE IS NOT PRE-RENDERED, I SWEAR THAT!
*/

public class Trolologram {
    public static void main(String[] args) throws IOException {
        String s = readContents(new File("Trolologram.java"))
                 .replaceAll("\n|\r", "#")
                 .replaceAll("##+", "#")
                 .replaceAll(".*\\Q/" + "*\\E", "")
                 .replaceAll("\\Q*" + "/\\E.*", "");
        String x = createImage(s.substring(1, s.length() - 2));
        System.out.println("'trololologram' (case insensitive)");
        writeContents("'trololologram' (case insensitive)##" + s, new File("database.output"));
        SwingUtilities.invokeLater(() -> {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            createAndShowGUI(x);
        });
    }

    private static String readContents(File input) throws IOException {
        StringBuilder sb = new StringBuilder((int) input.length());
        try (FileInputStream fis = new FileInputStream(input)) {
            int a;
            while ((a = fis.read()) != -1) {
                sb.append((char) a);
            }
        }
        return sb.toString();
    }

    private static void writeContents(String toWrite, File output) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(output)) {
            for (char c : toWrite.toCharArray()) {
                fos.write(c == '#' ? '\n' : c);
            }
            fos.write('\n');
            fos.write('\n');
            for (char c : toWrite.substring(37).toCharArray()) {
                if (" ,!-".contains("" + c)) continue;
                fos.write(c == '#' ? '\n' : c <= 'Z' ? ' ' : '#');
            }
            fos.write('\n');
            fos.write('\n');
            fos.write(("INSERT INTO troll (imagedata) VALUES ('" + toWrite.substring(37) + "')").getBytes());
        }
    }

    private static String createImage(String s) {
        String[] lines = s.split("#");
        StringBuilder html = new StringBuilder(10000);
        html.append("<html>");
        boolean first = true;
        for (String line : lines) {
            if (first) {
                first = false;
            } else {
                html.append("<br>");
            }
            html.append("<code>");
            for (char c : line.toCharArray()) {
                if (" !,-".contains("" + c)) continue;
                String color = c <= 'Z' ? "white" : "black";
                html.append("<font color=" + color + ">X</font>");
            }
            html.append("</code>");
        }
        return html.toString();
    }

    private static JLabel label(boolean a, String text) {
        JLabel theLabel = new JLabel(text) {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(a ? 350 : 500, 400);
            }

            @Override
            public Dimension getMinimumSize() {
                return new Dimension(a ? 350 : 500, 400);
            }

            @Override
            public Dimension getMaximumSize() {
                return new Dimension(a ? 350 : 500, 400);
            }
        };
        theLabel.setVerticalAlignment(SwingConstants.CENTER);
        theLabel.setHorizontalAlignment(SwingConstants.CENTER);
        return theLabel;
    }

    private static String Q = "<html>Your challenge here is to draw a <font color='#4e82c2'>trololologram</font>." +
        "<br>" +
        "You can choose any language." +
        "<br>" +
        "The answer with more upvotes and the one that exploits more holes wins." +
        "<br>" +
        "Rules for valid answers:" +
        "<ul>" +
        "<br><li>You can't use any network resource or external file (except the source-code)" +
        "<br><li>You can't post someone else's answer" +
        "<br><li>You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art)." +
        "<br><li>You can't store the image in any database." +
        "<br><li>You can't simply print/echo 'trololologram' (case insensitive)" +
        "<br><li>Explain your answers and what holes you exploited." +
        "<br><li>The code must render the trolologram on the screen (minimum size of 90x90) and must be with a black border and white background. The rendered version can't \"be invisible\" or \"hidden behind the screen\" or similar." +
        "<br><li>The image must show in the screen. It can't output the code to a file or anything similar (/dev/null doesn't count and virtual screens/viewports also don't count)." +
        "</ul>" +
        "<br>" +
        "The main goal is to twist the rules and bend them at your own will and stil render a trololologram on screen." +
        "<br>" +
        "Have fun!";

    private static void createAndShowGUI(String x) {
        JFrame frame = new JFrame("'trololologram' (case insensitive)");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
        panel.add(label(true, x));
        panel.add(Box.createRigidArea(new Dimension(10, 0)));
        panel.add(label(false, Q));
        frame.add(panel);

        frame.pack();
        frame.setVisible(true);
    }
}

```
> 12 votes

# Answer
# HTML/JavaScript (with a vengeance)

Since the humorous trollesque approach did not meet with an unadulterated success, here is my hackish JavaScript attempt, complete with its state-of-the-art HTML wrapper:

```
<script>function _(_,l,I,j){_-=i%$/5;l-=i*(j||.4)/$;return _*_+l*l<I*I/4}l='<pre>';$=90;for(
i=0;i<4e3;i++)l+=i%$?' %'[!(_(6,9,2,.8)|_(13,12,3,1)|_(7,48,5,1.4)|_(10,33,2,1))&(_(5,7,8)|_(
15,7,6)|_(-20,9,74)&_(38,9,72)&_(9,20,40)&_(-8,-10,64))]:'\n';document.write(l)</script>

```

*(linefeeds added for readability)*

Should produce something like this:

Skeptical people can see a live example here.

EDIT: let's review the rules point per point

> You can't use any network resource or external file (except the source-code)

No problem there. You can run a script from within an HTML page directly from your hard disk.

> You can't post someone else's answer

Check.

> You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art).

Check.

> You can't store the image in any database.

Check, provided the function parameters are not considered part of a database.

> You can't simply print/echo 'trololologram' (case insensitive)

I was tempted to use the characters in "trololologram" instead of "%" as a filler, but that would have had an intolerable impact on the size of the program.

> The code must render the trolologram on the screen (minimum size of 90x90) and must be with a black border and white background.

Check (you did not specify the interior color).

> The rendered version can't "be invisible" or "hidden behind the screen" or similar.

Check.

> The image must show in the screen. It can't output the code to a file or anything similar (/dev/null doesn't count and virtual screens/viewports also don't count).

As long as your browser window is not obscured, it's clearly showing the image on the screen. It's your genuine display, no cryptic device or virtual screen or viewport.

> Explain your answers and what holes you exploited.

An HTML page, once rendered, *is* (among other things) an image displayed on the screen.
You can capture it, store it to disk, photoshop it, email it to relatives and friends, print it on genuines bits of dead trees and light a fire with it for all I care, but it's a friggin *image*.

About the ressemblance with the original trololologram, I do not claim to be an artist. Consider this code as a proof of concept. If someone wants to spend the hour(s) needed to tweak and add more elements to get closer to the original, he/she is welcome to do so.
> 2 votes

# Answer
# Autoit 3 Script

```
$trol=ASCIIGenerate(4,1,1,0)&ASCIIGenerate(24,0,0,1)&ASCIIGenerate(2,1,1,0)&ASCIIGenerate(2,0,0,0)&ASCIIGenerate(24,1,0,0)&ASCIIGenerate(1,0,0,1)&ASCIIGenerate(2,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(26,1,0,0)&ASCIIGenerate(1,0,0,1)&ASCIIGenerate(1,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(28,1,0,0)&ASCIIGenerate(2,0,0,1)&ASCIIGenerate(1,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(30,1,0,0)&ASCIIGenerate(1,0,0,1)&ASCIIGenerate(1,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(30,1,0,0)&ASCIIGenerate(1,0,0,1)&ASCIIGenerate(2,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(28,1,0,0)&ASCIIGenerate(1,0,0,1)&ASCIIGenerate(2,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(26,1,0,0)&ASCIIGenerate(2,0,0,1)&ASCIIGenerate(2,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(21,1,0,0)&ASCIIGenerate(5,0,0,1)&ASCIIGenerate(2,1,1,0)&ASCIIGenerate(1,0,0,0)&ASCIIGenerate(12,1,0,0)&ASCIIGenerate(9,0,0,1)&ASCIIGenerate(3,1,1,0)&ASCIIGenerate(12,0,0,1)
RunWait("cmd /C @echo off&color F0&"&$trol&"pause > nul")

Func ASCIIGenerate($num,$char,$echo,$and)
    Local $i=0
    Local $str=""
    If $echo=1 Then
        $str&="echo "
    EndIf
        Do
            Switch $char
                Case 0
                    $str&="#"
                Case 1
                    $str&=" "
            EndSwitch
            $i+=1
        Until $i=$num
    If $and=1 Then
        $str&="&"
    EndIf
    Return $str
EndFunc

```

Output:

Holes exploited:

> You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art).

The ASCII art is generated by the script on the fly. The script itself only has info on which and how many characters it must draw onscreen and when start a new line.

> You can't store the image in any database. The image must show in the screen. It can't output the code to a file or anything similar (/dev/null doesn't count and virtual screens/viewports also don't count).

The script doesn't create nor contain any files. When generated, the ASCII art is loaded onto the computer's RAM and then shown via CMD commands (without using any batch files, only cmd /c ).

> The code must render the trolologram on the screen (minimum size of 90x90) and must be with a black border and white background. The rendered version can't "be invisible" or "hidden behind the screen" or similar.

The image displayed onscreen is way bigger than 90x90 and it's black on a white background.
> 1 votes

# Answer
# HTML/CSS

```
<p style='font-size:100px'}>😆

```

#

> You can't have it stored in any image format or pre-rendered (including base64 data:// uri's and any form of ascii art).

Well it's not me that does the rendering, it's the browser.
And there is no ASCII here, only unicode :p.
> 0 votes

# Answer
## HTML

> Even ○ would be a better answer. – Ismael Miguel Feb 23 at 0:12

Well here it is:

(with the browser zoomed in until it gets 90x90)
> 0 votes

---
Tags: popularity-contest, code-trolling
---