title: Acrostic Poem - Programming

text:
# Question
Title: Acrostic Poem - Programming
TASK:

Make an acrostic poem in the lines.
e.g.

BATCH

```
break
attrib -h acrostic.txt
type acrostic.txt
cls
help

```

The output CAN also be an acrostic poem.

RULES:

* Popularity Contest - the answer with highest vote wins!
* You may create more than one.
* Any language is accepted.
* Every line must be executable.

# Answer
**Java**

```
class s {
//acrostic starts below this line
public static void main(String[] args) { int
a; int
n;
class b {}
a=1; int
k; int
e;
System.out.println("are very tasteful."); } }

```
> 2 votes

# Answer
# bash - every man dies alone

This line writes the poem:

```
echo echo view echo renice yes make apropos nice date identify echo start apropos locate octave nice echo | xargs -n 1 | awk '{s = s substr($1, 1, 1); if ($1 == "echo"){print $1, "-n", s; s = "";}else print $1, "--they >.said 2>&1";}' > acrostic.sh

```

To see the poem:

```
$ cat acrostic.sh

```

To see the poem within the poem:

```
$ sh acrostic.sh

```
> 2 votes

# Answer
## Batch

Quite lazy, I'll admit -

```
@(
Code
Other than that which
Does
Echo Code^
Golf
Often
Lacks the
Fun
) 2>nul

```

```
H:\uprof>accro.bat
CodeGolf

```
> 1 votes

# Answer
Yay! **Java**!

```
import java.io.*;public
class poem{static String[]
a =
new String[1];
public static void main(String[] args){a();fin();
return;}static
Object myMethod(){String
g = "This is my ";
return g;} static void a(){
a[0] = "output";}static boolean fin(){System.out.println(
myMethod().toString()+a[0]);Boolean fin =
!(0==1);return fin;}}

```
> 1 votes

# Answer
# Befunge-93

```
go down, "Dev" 00ps -- 2*4-10 \ please
um I guess 1 - 3 \, is that right "hmm", @
maybe

```

run as `./befungee.py acrostic` for the output `gum`.

Note sure how rule #3 should be interpreted in this context.
> 1 votes

# Answer
**Ruby**

```
ruby = "rubylicious"; control = true
unless (!ruby)
begin y = ruby
y.each_char do |l| print (
l)
if (l=='s') then
control=false end
if (!control) then puts "!" end
over = true
unless
self == true then over = false end end end end

```

This prints `Rubylicious!`. I am not happy with some of the lines (especially last line), so future edits are possible.
> 1 votes

# Answer
# Javascript

```
document.getElementById("dog).appendChild(document.createElement('div'));
o = [];
e = [];
s = [];

t = 0;
h = 0;
i = 0;
s[0] = 0;

e[0] = 0;
v = 0;
e[1] = 0;
n = [];

c = 0;
o[0] = 0;
u = 0;
n[0] = 0;
t
? count=1:count=0;

```
> 1 votes

---
Tags: popularity-contest
---


title: Shrink a number string

text:
# Question
Title: Shrink a number string
Given a string of `1` and `2` of any length, write some code (doesn't have to be a **function** anymore, everything will be just fine) that calculates how many steps does it need to shrink the string to a final form, following this criterion:

If your string is `112112`, this means that you have to print a 1, two 1s and a 2, like this: `1112`. When you'll perform the operation again you'll have to print a 1 and a 2. You get `12`. Then you print one 2, obtaining `2`. This is a final form, since this string is not going to change anymore. Your code will output `3`, since you needed 3 steps to get to the final form.

**Other Rules**

* If the string has uneven length, the last number remains untouched.
* Every string that cannot change anymore (like `222222`) is considered a final form.
* You cannot use any external source.
* Your code must work with every string of `1` and `2`.
* Shortest code wins, as it is code-golf.
* Your code should print every step.
* Every input method will be fine.

**Examples**

```
Input >> 122122122121212212

Your code has to print:
211222111111222
11222111222
122111222
2111222
111222
1222
222
Steps:7 (you can omit the "Steps")
---- ---- ---- ----
Input >> 22222221

Your code has to print:
22222211
2222221
2
---- ---- ---- ----
Input >> 2222

Your code has to print:
0

```

**EDIT:** Heavily edited. So sorry about that.

# Answer
# Ruby 1.9+, 73 characters

I see the no-regex rule as silly and arbitrary, so here's a spiteful regex based solution:

```
gets
($.+=1;puts$_.gsub!(/(.)(.)/){$2*$1.to_i})until~/^(22)*[12]?$/
p~-$.

```

Test run:

```
$ ruby 21.rb <<< 122122122121212212
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

```

The last line is the number of steps.

Edit: Regex restriction has been removed by Vereos.
> 7 votes

# Answer
## C - ~~156~~ 154

My first code golf here!

```
f(char*s,c){puts(s);char*a=s,*b=s,m=50,x,y;while(*a){
x=*a++;y=*a++;if(y)m&=x&y;*b++=y?:x;x-49?*b++=y:(*b=0);}
*b=*a;return m/50?printf("%i",c),c:f(s,c+1);}

```

Test:

```
char c[] = "12211122211222221";
f(c,0);

```

Output:

```
12211122211222221
21112211222221
111221222211
121122221
21222211
1122221
122221
22211
22111
2211
221
10

```
> 3 votes

# Answer
## GolfScript: 69 characters

```
0\{\)\.p.[]\{~10base{.,1>{(\(@\{''+*}++~@\+\.}{~+0.}if}do;}~.@=!}do;(

```

Every iteration of the inner loop finds the first 2 numbers in the string, and use them to form a block of the form `{num1 num2 '' + *}`. When this block is evaluated, we get the desired reading of those numbers. Repeat this until there are no more characters. Then, repeat that loop while keeping track of the number of iterations and printing.

Sample:

```
echo '12211122211222221' | ruby golfscript.rb g.gs
"12211122211222221"
"21112211222221"
"111221222211"
"121122221"
"2122221"
"1122221"
"122221"
"22211"
"22111"
"2211"
"221"
10

```
> 2 votes

# Answer
# Python - 126

```
def f(s):
 j=0
 while 1:
    n="";i=0
    for c in s:n+=c*i;i=[int(c),0][i>0]
    if i:n+=`i`
    if s==n:break
    s=n;print s;j+=1
 print j

```

This doesn't print the input value. If it needs to, then move `print s;` to right before `n="";`

Note: you said "function", so this is a function. Here is a version that is not a function (127 chars):

```
s=raw_input();j=0
while 1:
    n="";i=0
    for c in s:n+=c*i;i=[int(c),0][i>0]
    if i:n+=`i`
    if s==n:break
    s=n;print s;j+=1
print j

```

(If I can have the user paste the number in then **118** (paste data between quotes on first line)):

```
s="";j=0
while 1:
    n="";i=0
    for c in s:n+=c*i;i=[int(c),0][i>0]
    if i:n+=`i`
    if s==n:break
    s=n;print s;j+=1
print j

```

Sample run:

```
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

```

As a bonus, each of these solutions work for strings containing larger numbers (up to 9), but some strings produce larger and larger outputs (for example, `99`)
> 2 votes

# Answer
# JavaScript, 107

(requires arrow function support, e.g. as in Firefox)

```
for(p=prompt,s=p(),k=0;r=s.match(/.?.?/g).map(a=>a>2?a[1]+(a<13?'':a[1]):a).join(''),p(s),r!=s;s=r)k++;p(k)

```
* `s` is the input string
* Each round, we use the regex `.?.?` to explode `s` into an array of two-character strings, then `map` those strings into their reduced forms and glue the array back together
* `r` stores the result of the current round for comparison against the previous `s`
* `k` is the round counter
* We horribly abuse `prompt` (aliased to `p`) as both an input and output mechanism, since it can present a message to the user

---

```
for(p=prompt,s=p(),k=0;
    r=s.match(/.?.?/g).map(
        a=>
            a>2?                     // if a is more than one char
                a[1]+(a<13?'':a[1])  // double the second char if the first char is 2
               :a                    // if not two chars, return a
    ).join(''),                      // glue new array together
     p(s),                           // print s
     r!=s;                           // test if string has changed
    s=r)
        k++;
p(k)

```
> 1 votes

# Answer
**PHP, 240**

```
<?php
$s=$_GET['i'];$h=$s;for($t=1;$h!=r($h);$t++){echo$h.'<br>';$h=r($h);}echo r($s)==$s?0:$h.'<br>'.$t;function r($c){for($i=0;$i<strlen($c)-1;$i+=2){$s.=$c[$i]==1?$c[$i+1]:$c[$i+1].$c[$i+1];if($i+3==strlen($c))$s.=$c[$i+2];}return$s;}?>

```

Example: http://skyleo.de/codegolf.php?i=211222111111222

```
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

```

I'm kinda bad at codegolf .\_. Maybe I shouldn't use only Java and PHP (and I should think more complicated)
> 1 votes

# Answer
## Perl - 50 (+2) bytes

```
$a-=print while"$_"ne(s/(.)(.)/$2x$1/ge,$_);$_=-$a

```

Requires `-pl` command line switches.

Sample usage:

```
$ more in.dat
122122122121212212

$ perl -pl rev-count.pl < in.dat
211222111111222
11222111222
122111222
2111222
111222
1222
222
7

$ more in.dat
22222221

$ perl -pl rev-count.pl < in.dat
22222211
2222221
2

$ more in.dat
2222

$ perl -pl rev-count.pl < in.dat
0

```
> 1 votes

# Answer
## R, 158

```
s=utf8ToInt(scan(,""))-48;i=0;while(any(!!s-2)){t=(a<-sum(s|T))%%2;u=s[seq(a-t)];cat(s<-c(rep(u[c(F,T)],u[c(T,F)]),s[a*t]),"\n",sep="");i=i+1};cat("Steps:",i)

```

Example:

```
122122122121212212

211222111111222
11222111222
122111222
2111222
111222
1222
222
Steps: 7

```
> 0 votes

# Answer
## MATHEMATICA, 117

```
s="122122122121212212";
Grid@FixedPointList[(Partition[#,2,2,1,{}]/.{{1,1}->{1},{1,2}->{2},{2,1}->{1,1}}//Flatten)&,FromDigits/@Characters@s]

122122122121212212
211222111111222
11222111222
122111222
2111222
111222
1222
222
222

```
> 0 votes

# Answer
**POWERSHELL, 2**

Based on Vereos's response " You can use whatever input method shortens your code" to my question in the comments of the OP, the following script achieves the result:

```
$a

```

Example run for "122122122121212212":

```
# Input method is to assign answer to $a:
$a = @"
211222111111222
11222111222
122111222
2111222
111222
1222
222
Steps: 7
"@

# Execute script
$a

# Answer follows:
211222111111222
11222111222
122111222
2111222
111222
1222
222

```

Obviously this isn't a serious entry - it's purpose is to illustrate my point that allowing any input method can trivialize the actual code needed to yield the answer. Hence the input method needs to be more rigorously specified.
> 0 votes

# Answer
## J, 41 chars

As a function (ew parens! not terribly happy about them):

```
(,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:)

```
**Exploded view**
```
                _2&(            )\          NB. on non-overlapping 2-grams:
                       (      )/            NB.   insert between the two chars:
                        ".@[                NB.     read left operand ([) as a number
                            #]              NB.     and repeat right this many times,
                    <@(           )         NB.   then put it in a box
            ([:;                   )        NB. open and concatenate the boxes
           (                        ^:a:)   NB. repeat until fixpoint (keeping intermediates)
        }:@                                 NB. drop first element (the input)
(,":@#)@                                    NB. append length of array (# steps)

```
**Sample run**
```
   (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) '1121121'
1121121
11121
121
21
11
5
   (,":@#)@}:@(([:;_2&(<@((".@[#])/)\))^:a:) '122122122121212212'
122122122121212212
211222111111222
11222111222
122111222
2111222
111222
1222
7

```
> 0 votes

# Answer
# Perl, 107 chars

The other perl code clearly beats this, but for what it's worth, here it is. I used the -l switch at the cost of an extra character:

```
$_=<>;while(1){$l=$_;$_=join"",map{($a,$b)=split//;$b?$b x$a:$a}grep/./,split/(..?)/;last if$l eq$_;print}

```

A more legible version of that:

```
$x = <>; while(1) { $l = $x; $x = join "", map{ ($a,$b) = split//, $_; $b ? $b x $a: $a } grep /./, split /(..?)/, $x; last if $l eq $x; print $x}

```
> 0 votes

---
Tags: code-golf
---


# Question
Title: Creating a quine in as many characters as possible
A is not the same as a , in a Code-Bowling, you should solve the challenge in as many characters as possible. The goal of this Code-Bowling is to create a quine in as many characters as possible, but you still should try to remove redundant characters. For example, don't post a HQ9+ solution with 10,000,000 times the `+` character, because the code still works if you remove them. Also, don't use variables with a name of 100 characters long, because you could easily rename them to a name of one character. Because this is a popularity-contest, the highest-voted answer wins. With 'redundant characters', I mean characters that can be removed, but the code will still work after removing them.

# Answer
# Brainfuck: 153,191 bytes

This is probably my largest BF binary. It prints it's own source including the intro text which is the Norwegian fairy tail The three billy goats Gruff (De tre bukkene Bruse). You cannot remove the story without removing the generating code so this Quine is designed to tell a story!

`bf` (A well known interpreter on Debian based linux distros) has too few cells by default so start it with:

```
bf -c35724 billy-quine.bf

```

Since StackExchange has a 30K limit I had to put it somewhere else. Beginning of the file follows:

```
[
Once upon a time there were three billy goats, names Gruff. They were on their
way to eat on the hillside, but they had to cross a bridge. Under the bridge
lived a troll, with eyes as big as saucers, and a nose as long as a poker.

The first goat over the bridge was the youngest Billy Goat Gruff. "Trip, trap,
trip, trap!" he walked across the bridge.

"Who's that tripping over my bridge?" roared the troll.

"I am the smallest Billy Goat Gruff, and I'm going up to the hillside to make
myself fat," said the billy goat, with a tiny voice.

"I'm coming to gobble you up," said the troll.

"Oh, no! please don't eat me. I'm too little!" said the billy goat. "Wait for
the second Billy Goat Gruff. He's much bigger."

"Well, be off with you," said the troll.

A little while later, the second Billy Goat Gruff crossed the bridge. "Trip,
trap, trip, trap, trip, trap" went the bridge.

"Who's that tripping over my bridge?" roared the troll.

"I am the second Billy Goat Gruff, and I'm going up to the hillside to make
myself fat," said the billy goat, with a medium voice.

"I'm coming to gobble you up," said the troll.

"Oh, no! Don't eat me. Wait for the last Billy Goat Gruff. He's much bigger."

"Very well! Be off with you," said the troll.

Next, the big Billy Goat Gruff crossed the bridge. "Trip, trap, trip, trap,
trip, trap!" went the bridge. This billy goat was heavy and the bridge creaked
and groaned under him.

"Who's that tramping over my bridge?" roared the troll.

"I am the big Billy Goat Gruff ," said the billy goat, with a big ugly voice.

"I 'm coming to gobble you up," roared the troll.

"No, you're not!" said the biggest Billy Goat Gruff. "I am bigger than you and
I could crush you into bits and bones."

"No, you're not!" said the biggest Billy Goat Gruff. "I am bigger than you and
I could crush you into bits and bones."

And when the troll saw how big the billy goat was, the troll let him pass. After
that, the three billy goats went to the hillside. They got so fat they could
hardly walk home. And if the fat hasn't fallen off, they're still fat; and so,

Snip, snap, snout. This tale's told out.
]
->>>>++++>++>++>>++++>++>+++>++>++++>++>++>+++++>+++>++>++++++>++>++++>+>+>+++>+>+>++++>+>+++>+>+>++++>++>++++>++>+++>++>++++>++>++>+++>>++++>+>+>+++>+>+>++++>+>+++>+>+>+++++>+++>+++++>+++>++>++>>++++>++>++>+++>+++++>+>+>>+>+>+>+>>>>+>+>>+>+>+++++>+++++>+>+>+>+>+++++>+++++>+>+>++++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>>+>+>>+>+>>+>+>>>+>+>>>+>+>+>+++++>+>+>+>>+>+>+++++>+++>>>++>++++>++>++>++>++>++>>+>+>>+>+>+>+++++>+++>++>++++>>+>+>+>++++>++>>+>+++++>+++>++>++++>++>>+>+++++>+++>++++++>+>+>>++>++>++>++++>+>+>+>>++>++++++>++>++>+++++>+++>+++++>+++>>+>++++++>++++++>++++++>++++++>+++++>+>+++++>+++++>+>++++>++>++>>>>>>>>+>>>>>>+>+++++>+++>>>>>>>>>>+>++++>>++>+++++>+++>>++>++>++>++>++++++>+>++++>++>>>>>>>>>>+>+++++>+++>>>>>>+>++++>++++>++>++>+++++>+++++>+++>>>+>+++++>++++>>++>+++++>+++>+++>>++++>+++++>+++>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>>>>>>>>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>>++++++>>++++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>>>>++>++++>+>>>>>>>>++>+++++>+++>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>++++++>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>++>+++++>+++>>>>>>+>++++++>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>>>>>>>>>>++++++>>++>++++>+>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>+>++++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>+++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>++++++>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>++++++>>>>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>+++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++++++>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>++>+++++>+++>>>>>>>+>++++++>>>>++>++++>+>>>>>>>++>+++++>+++>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++++++>>>>>>>>++++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>>>>>>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>>>>>++++++>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>++>++++>+>>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++....

```
> 7 votes

# Answer
# Java 2286+

This can be expanded easily by including lowercase class names and then moving on to unicode characters. I do believe that there are no redundant characters. However, you could **replace** characters to simplify this (If this is allowed, then no solution here will win because you could simply replace every character and get the shortest quine for the language). This is a true quine, with no sort of reading code.

Redundant characters removed version:

```
class Z{String s(){char q=34;String t="class Z{String s(){char q=34;String t=;t=t.substring(0,38)+q+t+q+t.substring(38);return t;}}class Y{String s(){return new Z().s();}}class X{String s(){return new Y().s();}}class W{String s(){return new X().s();}}class V{String s(){return new W().s();}}class U{String s(){return new V().s();}}class T{String s(){return new U().s();}}class S{String s(){return new T().s();}}class R{String s(){return new S().s();}}class P{String s(){return new R().s();}}class O{String s(){return new P().s();}}class N{String s(){return new O().s();}}class M{String s(){return new N().s();}}class L{String s(){return new M().s();}}class K{String s(){return new L().s();}}class J{String s(){return new K().s();}}class I{String s(){return new J().s();}}class H{String s(){return new I().s();}}class G{String s(){return new H().s();}}class F{String s(){return new G().s();}}class E{String s(){return new F().s();}}class D{String s(){return new E().s();}}class C{String s(){return new D().s();}}class B{String s(){return new C().s();}}class A{public String toString(){return new B().s();}}public class Q{public static void main(String...a){System.out.print(new A());}}";t=t.substring(0,38)+q+t+q+t.substring(38);return t;}}class Y{String s(){return new Z().s();}}class X{String s(){return new Y().s();}}class W{String s(){return new X().s();}}class V{String s(){return new W().s();}}class U{String s(){return new V().s();}}class T{String s(){return new U().s();}}class S{String s(){return new T().s();}}class R{String s(){return new S().s();}}class P{String s(){return new R().s();}}class O{String s(){return new P().s();}}class N{String s(){return new O().s();}}class M{String s(){return new N().s();}}class L{String s(){return new M().s();}}class K{String s(){return new L().s();}}class J{String s(){return new K().s();}}class I{String s(){return new J().s();}}class H{String s(){return new I().s();}}class G{String s(){return new H().s();}}class F{String s(){return new G().s();}}class E{String s(){return new F().s();}}class D{String s(){return new E().s();}}class C{String s(){return new D().s();}}class B{String s(){return new C().s();}}class A{public String toString(){return new B().s();}}public class Q{public static void main(String...a){System.out.print(new A());}}

```

Readable version:

```
class Z{

    String s(){
        char q=34;
        String t="class Z{String s(){char q=34;String "
                + "t=;t=t.substring(0,38)+q+t+q+t.substring(38);"
                + "return t;}}class Y{String s(){return new Z().s();"
                + "}}class X{String s(){return new Y().s();}}"
                + "class W{String s(){return new X().s();}}"
                + "class V{String s(){return new W().s();}}"
                + "class U{String s(){return new V().s();}}"
                + "class T{String s(){return new U().s();}}"
                + "class S{String s(){return new T().s();}}"
                + "class R{String s(){return new S().s();}}"
                + "class P{String s(){return new R().s();}}"
                + "class O{String s(){return new P().s();}}"
                + "class N{String s(){return new O().s();}}"
                + "class M{String s(){return new N().s();}}"
                + "class L{String s(){return new M().s();}}"
                + "class K{String s(){return new L().s();}}"
                + "class J{String s(){return new K().s();}}"
                + "class I{String s(){return new J().s();}}"
                + "class H{String s(){return new I().s();}}"
                + "class G{String s(){return new H().s();}}"
                + "class F{String s(){return new G().s();}}"
                + "class E{String s(){return new F().s();}}"
                + "class D{String s(){return new E().s();}}"
                + "class C{String s(){return new D().s();}}"
                + "class B{String s(){return new C().s();}}"
                + "class A{public String toString(){return new B().s();}}"
                + "public class Q{public static void main(String...a){System.out.print(new A());}}";
        t=t.substring(0,38)+q+t+q+t.substring(38);
        return t;
    }
}
class Y{

    String s(){
        return new Z().s();
    }
}
class X{

    String s(){
        return new Y().s();
    }
}
class W{

    String s(){
        return new X().s();
    }
}
class V{

    String s(){
        return new W().s();
    }
}class U{

    String s(){
        return new V().s();
    }
}
class T{

    String s(){
        return new U().s();
    }
}
class S{

    String s(){
        return new T().s();
    }
}
class R{

    String s(){
        return new S().s();
    }
}
class P{

    String s(){
        return new R().s();
    }
}
class O{

    String s(){
        return new P().s();
    }
}
class N{

    String s(){
        return new O().s();
    }
}
class M{

    String s(){
        return new N().s();
    }
}
class L{

    String s(){
        return new M().s();
    }
}
class K{

    String s(){
        return new L().s();
    }
}
class J{

    String s(){
        return new K().s();
    }
}
class I{

    String s(){
        return new J().s();
    }
}
class H{

    String s(){
        return new I().s();
    }
}
class G{

    String s(){
        return new H().s();
    }
}
class F{

    String s(){
        return new G().s();
    }
}
class E{

    String s(){
        return new F().s();
    }
}
class D{

    String s(){
        return new E().s();
    }
}
class C{

    String s(){
        return new D().s();
    }
}
class B{
    String s(){
        return new C().s();
    }
}
class A{
    public String toString(){
        return new B().s();
    }
}
public class Q{
    public static void main(String...a){
        System.out.print(new A());
    }
}

```
> 6 votes

# Answer
## Python 2, jiggabytes.

Here's a small variant. I'd use some dataset like all the phone conversations in the world over the last 6 months, but some jackass can't figure out power to the building. Oh, and they haven't responded to my FOIA<sup>*</sup> request.

```
s='Another one got caught today, it\'s all over the papers. "Teenager Arrested in Computer Crime Scandal", "Hacker Arrested after Bank Tampering"...\n\nDamn kids. They\'re all alike.\n\nBut did you, in your three-piece psychology and 1950\'s technobrain, ever take a look behind the eyes of the hacker? Did you ever wonder what made him tick, what forces shaped him, what may have molded him?\n\nI am a hacker, enter my world...\n\nMine is a world that begins with school... I\'m smarter than most of the other kids, this crap they teach us bores me...\n\nDamn underachiever. They\'re all alike.\n\nI\'m in junior high or high school. I\'ve listened to teachers explain for the fifteenth time how to reduce a fraction. I understand it. "No, Ms. Smith, I didn\'t show my work. I did it in my head..."\n\nDamn kid. Probably copied it. They\'re all alike.\n\nI made a discovery today. I found a computer. Wait a second, this is cool. It does what I want it to. If it makes a mistake, it\'s because I screwed it up. Not because it doesn\'t like me... Or feels threatened by me.. Or thinks I\'m a smart ass.. Or doesn\'t like teaching and shouldn\'t be here...\n\nDamn kid. All he does is play games. They\'re all alike.\n\nAnd then it happened... a door opened to a world... rushing through the phone line like heroin through an addict\'s veins, an electronic pulse is sent out, a refuge from the day-to-day incompetencies is sought... a board is found. "This is it... this is where I belong..." I know everyone here... even if I\'ve never met them, never talked to them, may never hear from them again... I know you all...\n\nDamn kid. Tying up the phone line again. They\'re all alike...\n\nYou bet your ass we\'re all alike... we\'ve been spoon-fed baby food at school when we hungered for steak... the bits of meat that you did let slip through were pre-chewed and tasteless. We\'ve been dominated by sadists, or ignored by the apathetic. The few that had something to teach found us willing pupils, but those few are like drops of water in the desert.\n\nThis is our world now... the world of the electron and the switch, the beauty of the baud. We make use of a service already existing without paying for what could be dirt-cheap if it wasn\'t run by profiteering gluttons, and you call us criminals. We explore... and you call us criminals. We seek after knowledge... and you call us criminals. We exist without skin color, without nationality, without religious bias... and you call us criminals. You build atomic bombs, you wage wars, you murder, cheat, and lie to us and try to make us believe it\'s for our own good, yet we\'re the criminals.\n\nYes, I am a criminal. My crime is that of curiosity. My crime is that of judging people by what they say and think, not what they look like. My crime is that of outsmarting you, something that you will never forgive me for.\n\nI am a hacker, and this is my manifesto. You may stop this individual, but you can\'t stop us all... after all, we\'re all alike.\n;from hashlib import*;h=new("sha512");h.update(`s`);h=h.digest().encode("base64");print(%r==h)*(\'s=\'+`s`+s[2952:]%%h)';from hashlib import*;h=new("sha512");h.update(`s`);h=h.digest().encode("base64");print('25eLAyYiA1nZPZQ6u0QwdIcPdypqedXDgGtwY1E7R1cYo6amjKxOl18rmmyGBMHyzW7tQPjYziOk\nXNQd+Egpeg==\n'==h)*('s='+`s`+s[2952:]%h)

```

**How it works**

The quine starts by defining a string `s` which contains a payload followed by the quine code. You'd like to delete that junk to golf the quine. But you can't, because the quine contains a cryptographically strong hash of `s`. If the hash of `s` doesn't match that in the quine, it doesn't print.

Initially, I'd used this article for the payload but a government conspiracy<sup>\**</sup> prevented me from pasting in the 34k program. The choice of article was not random: the NSA may know how to delete characters from this quine to preserve the hash. So, I used the Hacker Manifesto. Not that I'm actually that kind of hacker... but it seemed appropriate to draw an analogy.

To really beef up security, I even included the *length of the hashed string*. As everybody knows, this makes hashes like a million million times more secure. But this is *even better than that*, because you'd have to delete some subset of the length if you've deleted some of the hashed text.

Here's the prequine.

```
s=open("anyfile").read()
t=""";from hashlib import*;h=new("sha512");h.update(`s`);h=h.digest().encode("base64");print(%%r==h)*('s='+`s`+s[%d:]%%%%h)"""%len(s)
from hashlib import*
h=new('sha512')
h.update(`s+t`)
h=h.digest().encode('base64')
print"s="+`s+t`+t%h

```

<sup>*</sup>`BTLT+JTWAQFZC3zIr29pQO6BbKSz6lNS7vqbyrLj8osjiphxgkgr9GsySFBMp0ZCor8aTVc94Xdji4KaSX543Q==`

<sup>\**</sup> Or, y'know, because it was over the site size limit for a post.
> 4 votes

# Answer
# Ruby, 2242 (I could have made it as long as I want)

```
require 'open-uri'
puts open('http://pastebin.com/raw.php?i=pQRy8Mn8').read
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

```

Learn to forbid network access ;-)
> 2 votes

# Answer
## Fortran - 1359

```
 program quine
    character(len=48)::l(16),n
    integer::i,j,k
    data l/&
       'program quine                                   ',&
       '   character(len=48)::l(16),n                   ',&
       '   integer::i,j,k                               ',&
       '   data l/&                                     ',&
       '   do i=1,4;print*,l(i);enddo                   ',&
       '   do i=1,15                                    ',&
       '      n=l(i);j=index(n,'''''''');k=0            ',&
       '      do while(j/=0)                            ',&
       '         n=n(:k+j-1)//''''''''//n(k+j:47)       ',&
       '         k=k+j+1;j=index(n(k+1:),'''''''')      ',&
       '      enddo                                     ',&
       '      print*,''      '''''',n,'''''',&''        ',&
       '   enddo                                        ',&
       '   print*,''      '''''',l(16),''''''/''        ',&
       '   do i=5,16;print*,l(i);enddo                  ',&
       'end program quine                               '/
    do i=1,4;print*,l(i);enddo
    do i=1,15
       n=l(i);j=index(n,'''');k=0
       do while(j/=0)
          n=n(:k+j-1)//''''//n(k+j:47)
          k=k+j+1;j=index(n(k+1:),'''')
       enddo
       print*,'      ''',n,''',&'
    enddo
    print*,'      ''',l(16),'''/'
    do i=5,16;print*,l(i);enddo
 end program quine

```

I might try bloating this some, but I don't think I can do that. Note that this is an adapted version of this code to satisfy the non-redundancy.
> 2 votes

# Answer
# Python - infinity

```
print(r"print(r"print(r"print ...

```

And so on and so forth...
> 2 votes

# Answer
# Pascal

source code 2479 bytes, so code is about 2300 char, too lazy to count :)

```
program as;
var
  st : array[1..18] of string;
  i,j : integer;
begin
  st[1] := #112+#114+#111+#103+#114+#97+#109+#32+#97+#115+#59;
  st[2] := #118+#97+#114;
  st[3] := #32+#32+#115+#116+#32+#58+#32+#97+#114+#114+#97+#121+#91+#49+#46+#46+#49+#56+#93+#32+#111+#102+#32+#115+#116+#114+#105+#110+#103+#59;
  st[4] := #32+#32+#105+#44+#106+#32+#58+#32+#105+#110+#116+#101+#103+#101+#114+#59;
  st[5] := #98+#101+#103+#105+#110;
  st[6] := #32+#32+#102+#111+#114+#32+#105+#32+#58+#61+#32+#49+#32+#116+#111+#32+#53+#32+#100+#111;
  st[7] := #32+#32+#32+#32+#119+#114+#105+#116+#101+#108+#110+#40+#115+#116+#91+#105+#93+#41+#59;
  st[8] := #32+#32+#102+#111+#114+#32+#105+#32+#58+#61+#32+#49+#32+#116+#111+#32+#49+#56+#32+#100+#111+#32+#98+#101+#103+#105+#110;
  st[9] := #32+#32+#32+#32+#119+#114+#105+#116+#101+#40+#39+#32+#32+#115+#116+#91+#39+#44+#32+#105+#44+#32+#39+#93+#32+#58+#61+#32+#39+#41+#59;
  st[10] := #32+#32+#32+#32+#102+#111+#114+#32+#106+#32+#58+#61+#32+#49+#32+#116+#111+#32+#108+#101+#110+#103+#116+#104+#40+#115+#116+#91+#105+#93+#41+#32+#100+#111;
  st[11] := #32+#32+#32+#32+#32+#32+#105+#102+#32+#106+#32+#60+#62+#32+#108+#101+#110+#103+#116+#104+#40+#115+#116+#91+#105+#93+#41+#32+#116+#104+#101+#110+#32+#119+#114+#105+#116+#101+#40+#39+#35+#39+#44+#32+#111+#114+#100+#40+#115+#116+#91+#105+#93+#32+#91+#106+#93+#41+#44+#32+#39+#43+#39+#41;
  st[12] := #32+#32+#32+#32+#32+#32+#101+#108+#115+#101+#32+#119+#114+#105+#116#101+#108+#110+#40+#39+#35+#39+#44+#32+#111+#114+#100+#40+#115+#116+#91+#105+#93+#32+#91+#106+#93+#41+#44+#32+#39+#59+#39+#41+#59;
  st[13] := #32+#32+#101+#110+#100+#59;
  st[14] := #32+#32+#102+#111+#114+#32+#105+#32+#58+#61+#32+#54+#32+#116+#111+#32+#49+#56+#32+#100+#111+#32+#98+#101+#103+#105+#110;
  st[15] := #32+#32+#32+#32+#105+#102+#32+#105+#32+#60+#62+#32+#49+#56+#32+#116+#104+#101+#110+#32+#119+#114+#105+#116+#101+#108+#110+#40+#115+#116+#91+#105+#93+#41;
  st[16] := #32+#32+#32+#32+#101+#108+#115+#101+#32+#119+#114+#105+#116+#101+#108+#110+#40+#39+#101+#110+#100+#46+#39+#41+#59;
  st[17] := #32+#32+#101+#110+#100+#59;
  st[18] := #101+#110+#100;
  for i := 1 to 5 do
    writeln(st[i]);
  for i := 1 to 18 do begin
    write('  st[', i, '] := ');
    for j := 1 to length(st[i]) do
      if j <> length(st[i]) then write('#', ord(st[i] [j]), '+')
      else writeln('#', ord(st[i] [j]), ';');
  end;
  for i := 6 to 18 do begin
    if i <> 18 then writeln(st[i])
    else writeln('end.');
  end;
end.

```
> 0 votes

---
Tags: popularity-contest, quine, code-bowling
---


# Question
Title: How do I convert a word document to a pdf?
Help guys my assignment says it needs to be in .pdf format but I did it in Word. I'm really stuck.

How do I take a word document in .docx format and make a .pdf that contains all the text from it? Bonus points if it also contains all the images and any formatting, but text is a bare minimum. The sample file I'll be using will be this one, though your solution should be generic.

I don't want it to go through any unnecessary processing steps - simply encoding then decoding the document in base64 or whatever is not in the spirit of the question, though creative use of `cowsay` will be an exception to this. Standard rules of code trolling apply - the solution should be technically correct, all steps should be technically necessary, the result should be technically useless. This should be more of a "Rube Goldberg" style program, than an obfuscation and obtuseness competition.

Most upvotes on answers other than my own by 5/1/14 wins.

Note: This is a question. Please do not take the question and/or answers seriously. More information here.

# Answer
> 24 votes
Ok this is a little tricky but not too bad because pdf uses the same graphics model as postscript which means that once you have postscript it is quite trivial to convert it to pdf and postscript is way to drive printers all you have to do is print to get postscript.

Now you could write a program to convert postscript to pdf, but we don't have to there is ghostscript, which was written for unix and works just fine on linux (no major differences for this project). Unfortunately word only runs on windows, so you need two computers, and to convince windows that the linux computer is a printer you need a serial cable and a null modem. If your computer(s) don't have serial ports usb to rs232 converters work just fine (I recommend ones with a fttdi chipset). Now hook up the two computers with the serial cable and the null modem and verify that you can communicate (make sure that your parameters match).

Ok now that you have them talking it is time to convince your windows box that the linux box is a printer: just install the printer driver for the applewriter II and say it is connected to the serial port. Now when you print you send postscript to the linux box. the next step is to save it as a file.

Now scoot over to your linux box and use this simple command:

```
dd -if=/dev/ttyS0 -of=- -bs=1 | ps2pdf - - | sed -e '' >tmpfile && mv tmpfile file.pdf

```

and as simple as that you are done.

---

This can actually be made to work (if you send a signal to dd when you are finished) but there are easier ways like printing to a file and running gostscript on your windows box, and although fttdi makes good quality usb to serial converters it is a royal pain to install the drivers.

# Answer
> 13 votes
These days many printers are combination printer/scanner with automatic document feeders. It will be simple.

1. Print the document.
2. Scan the print out.

# Answer
> 9 votes
# PHP

This code produces PDF files that should print out perfectly on your ticker tape machine. If you want to view the PDF files on your monitor, you might have to zoom in a bit.

**Example source document**

**PDF output (viewed in browser)**

**Source code**

```
<?php

header("Content-Type: application/pdf");

$s = docx2txt("word-file.docx"); // <-- Insert filename here!
echo txt2pdf($s);

function docx2txt($filename) {
  if (!($z=zip_open($filename))) return false; // Can't open file
  while ($r=zip_read($z)) {
    if (zip_entry_name($r)!="word/document.xml") continue;
    if (!zip_entry_open($z,$r)) return false; // Can't open XML data
    for ($s="";;) {
      $c=zip_entry_read($r);
      if ($c===false || $c=="") break;
      $s.=$c;
    }
    return trim(preg_replace('/\s+/',' ',preg_replace('/<[^>]*>/','',$s)));
  }
  return false; // Can't find XML data
}

function txt2pdf($text) {
  $width="".ceil(strlen($text)*7.2);
  $text=str_replace('(','\050',str_replace(')','\051',$text));
  $length=strlen($text);
  $wlen=strlen($width);
  $len4="".(44+$length);
  $xr3=sprintf("%010d",174+$wlen);
  $xr4=sprintf("%010d",449+$wlen);
  $xrstart=544+$wlen+strlen($len4)+$length;
  return "%PDF-1.1\n%¥±ë\n\n1 0 obj\n  << /Type /Catalog\n     /Pages 2 0 R\n" .
         "  >>\nendobj\n\n2 0 obj\n  << /Type /Pages\n     /Kids [3 0 R]\n   " .
         "  /Count 1\n     /MediaBox [0 0 $width 14]\n  >>\nendobj\n\n3 0 obj" .
         "\n  <<  /Type /Page\n      /Parent 2 0 R\n      /Resources\n       " .
         "<< /Font\n           << /F1\n               << /Type /Font\n       " .
         "           /Subtype /Type1\n                  /BaseFont /Courier\n " .
         "              >>\n           >>\n       >>\n      /Contents 4 0 R\n" .
         "  >>\nendobj\n\n4 0 obj\n  << /Length $len4 >>\nstream\n  BT\n    /" .
         "F1 12 Tf\n    0 3 Td\n    ($text) Tj\n  ET\nendstream\nendobj\n\nxr" .
         "ef\n0 5\n0000000000 65535 f \n0000000018 00000 n \n0000000077 00000" .
         " n \n$xr3 00000 n \n$xr4 00000 n \ntrailer\n  <<  /Root 1 0 R\n    " .
         "  /Size 5\n  >>\nstartxref\n$xrstart\n%%EOF";
}

?>

```

---

Note: The `txt2pdf()` function is based on a minimal PDF file made by Brendan Zagaeski.

# Answer
> 5 votes
On UNIX systems:

```
mv document.docx document.pdf && cowsay "code-trolling is cool"

```

On Windows:

```
ren document.docx document.pdf

```

# Answer
> 4 votes
I believe this shell script to be a simple and intuitive method of solving the problem. Is there a better way?

```
( echo $'<svg>\n<text y="10">';
  unzip -p ./YOUR_FILENAME_HERE.docx word/document.xml |
  sed -e 's/<[^>]\{1,\}>//g; s/[^[:print:]]\{1,\}//g';
  echo $'\n</text>\n</svg>' ) |
inkscape -f /dev/fd/0 -D -A ./OUTPUT_FILENAME_HERE.pdf

```

# Answer
> 2 votes
This link will surely gonna help you. http://javahive.in/convert-word-doc-to-pdf-file-in-java/ you just have to run this java code and your pdf will be there for you.

# Answer
> 0 votes
# Windows Batch

The easiest way to convert a file: change the extension!

```
:: convert.cmd

xcopy "%~dpnx0" "%~dpn0.pdf"

```

Spoiler/troll: (hover below to see)

> Oops...did I forget that you could convert even a file with a `.exe` extension? So much for that... ;) Also, I'm too lazy to code the guards.
> And I thought I'd add a little extra troll in this: it doesn't even touch the data inside... (doesn't parse it to make it a valid PDF)

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


title: Count occurrences of an integer

text:
# Question
Title: Count occurrences of an integer
Based on the question How many positive integers \< 1,000,000 contain the digit 2?. I'm looking for the most creative solution to count all the Integers from `X` to `Y` containing the Integer `Z`. `Z` can be from 0 to `Y`.

Every found Integer only counts once, even if the integer `Z` appears more often. For example:

```
Z = 2
123 counts 1
22222 also counts 1

```

I will start with a really simple algorithm written in Java (because it's beloved by everyone):

```
public class Count {
    public static void main(String[] args) {
        int count = 0;
        for (int i = Integer.parseInt(args[0]); i <= Integer.parseInt(args[1]); i++) {
            if (Integer.toString(i).contains(args[2])) {
                count++;
            }
        }
        System.out.println(count);
    }
}

```

if you run this with

```
java -jar Count.jar 0 1000000 2

```

you get this as the result:

```
468559

```

Because this problem is not hard to solve it's just a . Most upvoted answer posted by 28th of February wins!

# Answer
# bash (20)

```
seq $1 $2|grep -c $3

```

### Usage

```
$ bash count.sh 0 1000000 2
468559

```
> 26 votes

# Answer
# Funciton

As usual, since the line height added by StackExchange breaks up the lines, consider running `$('pre').css('line-height',1)` in your browser console to fix that.

Unlike my other Funciton answers, this one does not use any function declarations. It’s just a program. It uses a lambda expression, though — a feature I added to Funciton in December :)

Expects the input as three decimal integers (can be negative) separated by spaces (i.e. `x y z`). In fact, `z` can be any string; for example, it could be just the minus sign (, U+2212) to count the number of negative numbers in the interval :)

```
           ┌───╖
     ┌───┬─┤ ♯ ╟──────────┐
     │   │ ╘═══╝ ╔════╗ ┌─┴─╖             ┌────╖ ╔═══╗
   ┌─┴─╖ └────┐  ║ 21 ║ │ × ╟─────────────┤ >> ╟─╢   ║
 ┌─┤ ʃ ╟───┐  │  ╚══╤═╝ ╘═╤═╝             ╘═╤══╝ ╚═══╝
 │ ╘═╤═╝   │  └──┐  └─────┘   ┌───────────┐ │
 │ ╔═╧═╗ ┌─┴─╖ ┌─┴─╖ ╔════╗ ┌─┴─╖   ┌───╖ ├─┴────────┐
 │ ║   ╟─┤ · ╟─┤ ʘ ╟─╢ 32 ╟─┤ · ╟───┤ ʘ ╟─┘          │
 │ ╚═══╝ ╘═╤═╝ ╘═══╝ ╚════╝ ╘═╤═╝   ╘═╤═╝ ┌─────┐    │
 │         └───────┐  ╔═══╗ ┌─┴─╖     │ ┌─┴─╖   │    │
 │ ┌───────────┐   └──╢ 0 ╟─┤ ʃ ╟─┐   │ │ ♯ ║   │    │
 │ │   ┌───╖ ┌─┴─╖    ╚═══╝ ╘═╤═╝ │   │ ╘═╤═╝ ┌─┴─╖  │
 │ │ ┌─┤ ♯ ╟─┤   ╟─┬─┐ ╔════╗ │ ┌─┴─╖ │   │ ┌─┤ × ║  │
 │ │ │ ╘═══╝ └─┬─╜ └─┘ ║ −1 ║ └─┤ · ╟─┴───┘ │ ╘═╤═╝  │
 │ │ │    ┌────┴────┐  ╚══╤═╝   ╘═╤═╝       │ ╔═╧══╗ │
 │ │ │    │ ┌───╖ ┌─┴─╖ ┌─┴─╖ ┌───┴─────╖   │ ║ 21 ║ │
 │ │ │    └─┤ ♯ ╟─┤ ? ╟─┤ = ║ │ str→int ║   │ ╚════╝ │
 │ │ │      ╘═══╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═══════╝   │ ┌────╖ │
 │ │ │      ╔═══╗ ┌─┴─╖   └─┐ ┌─┴─╖         └─┤ >> ╟─┘
 │ │ │      ║ 0 ╟─┤ ? ╟─┐   └─┤ · ╟───┐       ╘═╤══╝
 │ │ │      ╚═══╝ ╘═╤═╝ └─┐   ╘═╤═╝   └───┐   ┌─┴─╖
 │ │ │            ┌─┴─╖   └─┐ ┌─┴─╖       └───┤ ʘ ║
 │ │ └────────────┤ · ╟─┐   └─┤ ≤ ║           ╘═╤═╝
 │ │              ╘═╤═╝ │     ╘═╤═╝ ┌─────────╖ │
 │ │        ╔═══╗ ╔═╧═╕ │       └─┬─┤ int→str ╟─┘
 │ │        ║ 0 ╟─╢   ├─┤         │ ╘═════════╝
 │ │        ╚═══╝ ╚═╤═╛ └─────────┘
 │ └────────────────┴─┐              │
 │    ┌─────────╖   ┌─┴─╖ ┌─┐   ┌────┴────╖
 └────┤ str→int ╟───┤   ╟─┴─┘   │ int→str ║
      ╘═════════╝   └─┬─╜       ╘════╤════╝
                      └──────────────┘

```
> 11 votes

# Answer
# C#

```
public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine(Enumerable.Range(Convert.ToInt32(args[0]), (Convert.ToInt32(args[1]) + 1) - Convert.ToInt32(args[0])).Count(x => x.ToString().Contains(args[2])));
    }
}

```

## Example

```
count.exe 0 1000000 2
468559

```
> 10 votes

# Answer
## APL (29)

```
{+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵}

```

This is a function that takes `Z` as the left argument and the interval `[X,Y]` as the right argument:

```
      2 {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} 0 1e6
468559
      0 {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} 0 1e6
402131
      42 {+/∨/¨(⍕⍺)∘⍷¨⍕¨⊃{⍺+0,⍳⍵-⍺}/⍵} 0 1e6
49401

```
> 5 votes

# Answer
## Python 2.7

# Need for Speed

**Explanation**

**Implementation**

```
def Count(lo,hi,key):
    if hi == 0: return 0
    # Count(lo,hi,key) = Count(0,hi,key) - Count(0,lo - 1,key)
    if lo != 0: return Count(0, hi, key) - Count(0, lo - 1, key)
    # Calculate no of digits in the number to search
    # LOG10(hi) may be a descent trick but because of float approximation
    # this would not be reliable
    n = len(str(hi)) - 1
    # find the most significant digit
    a_n = hi/10**n
    if a_n < key:
        count = a_n*(10**n - 9**n)
    elif a_n > key:
        count = (a_n - 1)*(10**n - 9**n) + 10**n
    else:
        count = a_n*(10**n - 9**n) + 1
    if hi % 10**n != 0:
        if a_n != key:
            return count + Count(0, hi%10**n, key)
        else:
            return count + hi%10**n
    else:
        return count

```

**Demo**

```
In [2]: %timeit Count(0,123456789987654321,2)
100000 loops, best of 3: 13.2 us per loop

```

**Comparison**

@Dennis

```
$ \time -f%e bash count.sh 0 1234567 2
585029
11.45

```

@arshajii

```
In [6]: %timeit count(0,1234567,2)
1 loops, best of 3: 550 ms per loop

```
> 4 votes

# Answer
# PHP

Nothing original, just celebrating my first post here.

```
<?php

    $x = $argv[1];
    $y = $argv[2];
    $z = $argv[3];
    $count = 0;

    do
    {
        if (!(strpos($x, $z) === false))
            $count++;
        $x++;
    } while ($x <= $y);

    echo $count;

?>

```

Input

```
php script.php 0 1000000 2

```

Output

```
468559

```
> 3 votes

# Answer
# bash - ~~32~~ ~~31~~ ~~17~~ 14 characters + length of X, Y and Z

Thanks to devnull for suggesting `seq`!

```
seq [X] [Y]|grep -c [Z]

```

e.g. X = 100, Y = 200, Z = 20

```
$ seq 100 200|grep -c 20
2

```

e.g. X = 100, Y = 200, Z = 10

```
$ seq 100 200|grep -c 10
11

```

e.g. X = 0, Y = 1000000, Z = 2

```
$ seq 0 1000000|grep -c 2
468559

```
> 3 votes

# Answer
## Python 2.7

A solution using regular expressions:

```
>>> from re import findall as f
>>> count=lambda x,y,z:len(f('\d*%d\d*'%z,str(range(x,y+1))))
>>>
>>> count(0,1000000,2)
468559

```
> 3 votes

# Answer
Scala:

`args(0).toInt to args(1).toInt count (_.toString contains args(2))`
> 3 votes

# Answer
# Ruby

This is a great example to use reduce!

```
puts (ARGV[0]..ARGV[1]).reduce(0) { |c, n| n.to_s.include?(ARGV[2].to_s) ? c + 1 : c }

```

Input:

```
ruby script.rb 0 1000000 2

```

Output:

```
468559

```
> 2 votes

# Answer
## Python golf - 61

```
f=lambda x,y,z:len([i for i in range(x,y)if str(z)in str(i)])

```

## Python non-golf

```
def f(x, y, z):
    c = 0
    for i in range(x, y):
        c += str(z) in str(i)
    return c

```
> 2 votes

# Answer
**R 23 ~~25~~ ~~27~~chars**

Just get the right tool for the job. Simple use of grep in R, nothing fancy.

This is what it does: `grep` all instances of `2` in the vector `0` until `10e6` and count the number of results using `length`.

~~`length(grep(2,0:100000,value=TRUE))`~~

```
length(grep(2,0:10e6))

```

Result: `[1] 468559`

---

Offcourse you can write a function that takes the numbers as an input, just like it is shown in the example.

```
count = function(x=0, y=1000000, z=2){
  length(grep(z,x:y))
}

```

Now you can call `count` with with x, y and z, if unset (that is by default), the values for x, y and z are 0, 1000000 and 2 respectively. Some examples:

```
count()
[1] 468559

```

or

```
count(20, 222, 2)
[1] 59

```

or

```
count(0, 100, 10)
[1] 2

```

Some here think time is of importance, using this function in R takes around 1 second.

```
system.time(count())
user  system elapsed
0.979   0.003   0.981

```
> 2 votes

# Answer
## Java8

Using the new IntStream stuff, this becomes essentially a one liner, if you ignore the obligatory Java Framework stuff:

```
import java.util.stream.IntStream;
public class A{
  public static void main(String[] args){
    System.out.println(IntStream.rangeClosed(Integer.parseInt(args[0], Integer.parseInt(args[1])).filter(x -> ((Integer)x).toString().contains(args[2])).count());
  }
}

```

It can be run here, although I did have to hardcode the values.
> 2 votes

# Answer
# Regular Expression

Following will count 1's digits up to 49.

```
#!/bin/bash

echo "12313451231241241111111111111111111111111111111111111"  |\
sed "s/[^1]//g;s/11111/5/g;s/1111/4/g;s/111/3/g;s/11/2/g;s/555555555/45/g;s/55555555/40/g;s/5555555/35/g;s/555555/30/g;s/55555/25/g;s/5555/20/g;s/555/15/g;s/55/10/g;s/54/9/g;s/53/8/g;s/52/7/g;s/51/6/g;s/50/5
/g;s/40/4/g;s/30/3/g;s/20/2/g;s/10/1/g"

```
> 2 votes

# Answer
## F#

This solution uses `IndexOf` to search the string, then a little bit of number fiddling to convert the result to 1 if found, and 0 if not found, then sums the result:

```
let count x y (z : string) =
    [ x .. y ] |> Seq.sumBy(fun n -> min 1 (n.ToString().IndexOf z + 1))

```

And it can be called like this:

```
count 0 1000000 "2" // 468559

```
> 2 votes

# Answer
# Javascript

```
function f(s,e,n){for(r=0;e-->s;){if(~(''+e).indexOf(n))r++}return r}

```

`f(0,1e6,2)` returns 468559

What is `-->` operator ? Not an operator
> 1 votes

# Answer
# JavaScript (ES6), 63

```
f=(i,j,n)=>{for(c=0;i<=j;!~(''+i++).indexOf(n)?0:c++);return c}

```

Usage:

```
f(0, 1e6, 2)
> 468559

```

Un-golfed:

```
f = (i,j,n) => {
  for(
    // Initialize the counter.
    c=0;
    // Iterate through all integers.
    i<=j;
    // Convert current number into string then increment it.
    // Check if the digit appears into the current number.
    !~(''+i++).indexOf(n)
      // Occurence not found.
      ? 0
      // Occurence found.
      // Add 1 to the counter.
      : c++
  );
  return c
}

```
> 1 votes

# Answer
# Ruby

Basically I took Pablo's answer and semi-golfed (38 chars if you drop unnecessary whitespace) it into a not-so-great example of using `select`.

It selects every index in the range `(x .. y)` that contains `z`. This intermediate result is unfortunately stored in an array, whose size is then returned.

```
x,y,z = $*
p (x..y).select{ |i| i[z] }.size

```

It looks pretty neat both syntactically and semantically, although the `i[z]` part doesn't really seem to make sense.

It works because `x` and `y` actually are strings, not numbers! Thus each `i` is also a string, and `i[z]` of course checks if the string `z` is contained in `i`.

```
$ ruby count-digits.rb 100 200 20
2
$ ruby count-digits.rb 0 1000000 2
468559

```
> 1 votes

# Answer
# Python 2.7, 70 signs

```
f = lambda x,y,z: sum(map(lambda x: str(z) in str(x), range(0, y+1)))

>>> f(0, 1000000, 2)
468559

```

## Shorter, 65 signs

```
g = lambda x, y, z: sum(str(z) in str(i) for i in range(0, y+1))
>>> g(0, 1000000, 2)
468559

```
> 1 votes

# Answer
Using Ruby's `Enumerable#grep`:

```
start, stop, target = $*
p (start..stop).grep(Regexp.new target).size

```
> 1 votes

# Answer
## T-SQL

*If I can assume variables `@X`, `@Y`, and `@Z` are available:*

**With an (arbitrarily large ;) existing numbers table - 65**

```
select count(*)from n where n>=@X and n<=@Y and n like '%'+@Z+'%'

```

**With a recursive CTE - 127**

```
with n(n)as(select @X union all select n+1 from n where n<@Y)select count(*)from n where n like'%'+@Z+'%'option(MAXRECURSION 0)

```

---

*If the variables need to be defined explicitly:*

**Add 58 to both answers -- Numbers table: 123, Recursive CTE: 185**

```
declare @X int=0;declare @Y int=100;declare @Z varchar(30)='2';

```

---

I have no idea how much memory the recursive CTE can use, but it's certainly not going to win any speed contests. The example of searching for 2 in 0 to 1000000 takes 8 seconds on my system.

Here's a SQL Fiddle if anyone wants to play with it. The 1000000 query takes 30+ seconds to run.
> 1 votes

# Answer
# Mathematica

## First way: strings

`x, y, z` are converted to strings. If a string-integer is not free of `z`, it is counted.

```
f[{x_,y_},z_] :=Length[Select[ToString/@Range[Max[x, z], y], !StringFreeQ[#, ToString@z] &]]

```

**Examples**

```
f[{22, 1000}, 23]
f[{0, 10^6}, 2]

```

> 20
> 468559

---

## Second way: lists of digits

```
g[{x_,y_},z_]:=(t=Sequence@@ IntegerDigits@z;Length@Cases[IntegerDigits@Range[190],
{s___,t,e___}])

```

**Examples**

```
g[{22, 1000}, 23]
g[{0, 10^6}, 2]

```

> 20
> 468559
> 1 votes

# Answer
# Rebol

```
; version 1 (simple loop counting)

count: func [x [integer!] y [integer!] z [integer!] /local total] [
    total: 0
    for n x y 1 [if found? find to-string n z [++ total]]
    total
]

; version 2 (build series/list and get length)

count: func [x [integer!] y [integer!] z [integer!]] [
    length? collect [for n x y 1 [if find to-string n z [keep true]]]
]

```

Usage example in Rebol console (REPL):

```
>> count 0 1000000 2
== 468559

```
> 1 votes

# Answer
# PowerShell

Two solutions, both 40 37 chars.

For all versions of PowerShell:

```
$a,$b,$c=$args;($a..$b-match$c).count

```

PowerShell V3 and up have the `sls` alias for `Select-String`. This requires the `@` to force an array if only one value makes it through the pipeline.

```
$a,$b,$c=$args;@($a..$b|sls $c).count

```
> 1 votes

# Answer
## Batch

```
@setLocal enableDelayedExpansion&@set a=0&@for /L %%a in (%1,1,%2) do @set b=%%a&@if "!b:%3=!" NEQ "!b!" @set/aa+=1
@echo !a!

```

```
H:\uprof>count 0 1000000 2
468559

H:\uprof>count 1 2 3
0

```

A bit more readable -

```
@setLocal enableDelayedExpansion
@set a=0
@for /L %%a in (%1,1,%2) do (
    @set b=%%a
    @if "!b:%3=!" NEQ "!b!" @set/aa+=1
)
@echo !a!

```

Nice and simple. Uses string manipulation to check if the variable `!b!` is the same as itself without the third user input, `%3` (`!b:%3=!`).
> 1 votes

# Answer
## GolfScript

I've been trying to improve my GolfScript skills so I thought I'd give it a shot with this question. Here's what I came up with:

```
`@@0\{.3$>}{.`4$?-1>@+\(}while@;;\;

```

This can be broken down like this:

```
0 1000000 2    # parameters

`@@            # convert Z to string and put at bottom of stack
0\             # init counter and swap
{.3$>}         # loop condition: Y > X
{              # loop body
  .`           # convert to string
  4$?          # search for substring
  -1>@+        # if found add to counter
  \(           # decrement Y
}              # end loop body
while          # perform loop
@;;\;          # cleanup

```

Even though it's GolfScript, by goal was more to try to make it relatively efficient rather than compact, so I'm sure that someone can point out various ways this can be improved.

**Demonstration**: Note that I've reduced Y in the demo so that it can complete in \< 5 seconds.
> 1 votes

# Answer
# PHP - 112

No visible loops, but a bit heavy on memory!

```
<?=count(array_filter(range($argv[1],$argv[2]),function($i)use($argv){return strpos($i,$argv[3].'')!==false;}));

```

Usage `php script.php 0 1000000 2`
> 1 votes

# Answer
# ECMAScript 3 to 6

(javascript, JScript, etc)

## using regex:

```
function f(x,y,z,r){for(r=0,z=RegExp(z);x<y;r+=+z.test(''+x++));return r}

```

**breakdown:**

```
function f(x,y,z,r){        // note argument `r`, eliminating the need for `var `
  for( r=0, z=RegExp(z)     // omitting `new` since ES will add it if omitted
     ; x<y                  //
     ; r+=+z.test(''+x++)   // `x++` == post increment
                            // `''+Number` == convert Number to string
                            // `test` gives true | false
                            // `+Boolean` converts boolean to 1 | 0
                            // `r+=Number` incrementing r (were Number is always 1 or 0)
     );                     // no body thus semicolon is mandatory!
  return r;                 // returning r
}

```

## using indexOf:

```
function f(x,y,z,r){for(r=0;x<y;r+=+!!~(''+x++).indexOf(z));return r}

```

**breakdown:**

```
function f(x,y,z,r){                // note argument `r`, eliminating the need for `var `
  for( r=0                          // omitting `new` since ES will add it if omitted
     ; x<y                          //
     ; r+=+!!~(''+x++).indexOf(z)   // `x++` == post increment
                                    // `''+Number` == convert Number to string
                                    // `indexOf` returns index or `-1` when not found
                                    // `!!~ indexOf` converts sentinel value to boolean
                                    // `+Boolean` converts boolean to 1 | 0
                                    // `r+=Number` incrementing r (were Number is 1 or 0)
     );                             // no body thus semicolon is mandatory!
  return r;                         // returning r
}

```

this function-body is one char less then florent's, so when using ES6 `=>` function notation the total would be 62 char

Example call: `f(0,1e6,2)`
Example use: `alert( f(0,1e6,2) );`

JSFiddle here

PS: both functions above return their *local* variable `r`.
So when leaking the result variable `r` into the global scope, one can again save 10 characters:

```
function f(x,y,z){for(r=0;i<=j;r+=+!!~(''+i++).indexOf(z));}

```

Example use: `alert( f(0,1e6,2)||r );`
> 1 votes

# Answer
### Delphi - 120

Bit to much for my taste, going to see if i can get some off.

```
var x,y,z,i,c:int16;begin readLn(x,y,z);for i:=x to y do if inttostr(i).contains(inttostr(z))then inc(c);writeln(c);end.

```
> 1 votes

# Answer
# k \[28 chars\]

```
{+/($x+!y)like"*",$:[z],"*"}

```

### Usage

```
{+/($x+!y)like"*",$:[z],"*"}[0;1000000;2]
468559

```
> 1 votes

# Answer
## Javascript - ~~55~~ 54 chars (Loop)

### (Shortest JS solution!)

Edit: 12/Feb/14 - Updated search condition - 1 char reduced

```
a=(x,y,z,c)=>{while(x<=y)c+=(x+++'').search(z)+1?1:0}

```

Using the new fat arrow notation.

**Usage:** `a(1,20,2,0),c` gives `3` (Note the fourth argument is compulsorily set to `0` and don't forget the `,c` also. Just some work to save chars ;) ).

### Javascript - ~~62~~ 61 chars (Recursive)

Edit: 12/Feb/14 - Updated search condition - 1 char reduced

```
c=0
a=(x,y,z)=>{if(x<=y)c+=(x+'').search(z)+1?1:0,a(x+1,y,z)}

```

**Usage:** `a(1,20,2),c` gives `3`

Feedback appreciated!
> 1 votes

# Answer
# Python 2.7 - 50 chars

Bit of a saving on the existing Python answers.

```
lambda x,y,z:sum(1for n in range(y-x)if`z+x`in`n`)

```

Using the following tricks:

* Sum can be applied to a generator, unlike len, so use sum(1...) instead of len(\[n...\])
* Use \`\` instead of str(), which also allows...
* Kill all spaces - see '1for' and 'if`z+x`in`n`'
* Remove the first range() arg by starting at 0 and testing the offset (actually...saves me nothing but I like the look of it better :) )

In action:

```
In [694]: (lambda x,y,z:sum(1for n in range(y-x)if`z+x`in`n`))(0,1000000,2)
Out[694]: 468559

```
> 1 votes

# Answer
# k (28)

```
{+/($x+!y-x)like,/3#"*",,$z}

```

Takes three arguments, like this:

```
  {+/($x+!y-x)like,/3#"*",,$z}[0;1000000;42]
49401

```
> 1 votes

# Answer
# Haskell (56 code, 16 import)

Thought I'd throw a little Haskell version into the mix!

```
import Data.List
c x y z=length$filter(isInfixOf(show z))$map show$[x..y]

```

It can be shorter if we are allowed to require that z be input as a string:

```
import Data.List
c x y z=length$filter(isInfixOf z)$map show$[x..y]

```

Usage:

```
> c 0 1000000 2
468559

```
> 1 votes

# Answer
# perl \[41 chars\]

```
print 0+grep/$ARGV[0]/,$ARGV[1]..$ARGV[2]

```

Run:

```
> perl -le 'print 0+grep/$ARGV[0]/,$ARGV[1]..$ARGV[2]' 2 0 1000000
468559

```
> 1 votes

# Answer
**Perl - 44 chars**

```
$x+=/$ARGV[2]/ for$ARGV[0]..$ARGV[1];print$x

```

**Usage**

```
C:\strawberry\projects>perl county.pl 0 1000000 2
468559

```

My first golf with Perl(I'm learning it currently) so I'm open for suggestions! I'd appreciate them.
> 1 votes

# Answer
# Golfscript - 18

My contribution in golfscript

```
`:i;,\>{`i?1+},,

```

Explaination:

```
`:i;        #Convert Z to string, store in i, and pop
,\>         #Generate range 0 ... Y and then remove values < X
{`i?1+},    #Filter all non-matches out of the array
,           #Count the number of values in the array

```

Try it here
> 1 votes

# Answer
## TI-BASIC

As usual, `->` represents the `STO->` arrow:

```
:0->I
:Prompt X,Y,Z
:randIntNoRep(X,Y)
:Z=Ans
:cumSum(Ans)

```

Let's try it out:

```
X=?1
Y=?10
Z=?2
               1
            Done

```
> 0 votes

---
Tags: popularity-contest, counting
---


# Question
Title: Write a program that can draw 2-D shapes using ASCII or any other method
Rules (not too restrictive; flexible):

1.Must be able to draw shapes on command (e.g., I type in "square" and a square is drawn).

Minimum completed shapes that can be drawn on command: Square, Circle, Triangle, Pentagon.

2.Must also be able to also draw shapes vertex-by-vertex, specified by a command function that gives the user an input to determine line segment lengths between points in succession.

The program has to give the option to make polygons as well, but incomplete 2-D shapes, circles, unclosed planes, and non-polygons shall be allowed.

Winner: Most votes.

# Answer
# Logo

Just install it!

Then things like triangles, squares, pentagons and circles are defined as:

```
to triangle :length
    polygon :length 3
end

to square :length
    polygon :length 4
end

to pentagon :length
    polygon :length 5
end

to circle :length
    polygon :length 360
end

to polygon :length :sides
    repeat :sides [forward :length right 360/:sides]
end

```

Easy peasy lemon squeezy...
> 2 votes

---
Tags: popularity-contest, ascii-art
---


# Question
Title: Refactor variable names in JavaScript code
Your challenge today is to refactor JavaScript code. You will take three strings as input; a JavaScript string, a old variable name, and the name you want to refactor it to. For example, an input of

```
"var x = 100; alert(x);", "x", "num"

```

Will output

```
"var num = 100; alert(num);"

```

---

Here's a more advanced test case:

```
"var gb = 1; var g = bg = 2; gb = bg = g = function(gg) { alert(gb); };
var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g
/*gb gb g g*/", "gb", "aaa"

```

It should output

```
var aaa = 1; var g = bg = 2; aaa = bg = g = function(gg) { alert(aaa); };
var str = 'g gb bg gg'; var regexp = /gb gb g g/g; //comment gb gb g g
/*gb gb g g*/

```

And the same JS input with the other arguments `"g", "aaa"` should output

```
var gb = 1; var aaa = bg = 2; gb = bg = aaa = function(gg) { alert(gb); };
var str = 'g gb bg gg'; var regexp = /gb gb gb/g; //comment gb gb g g
/*gb gb g g*/

```

---

Here is one last much more complicated test case:

```
var g = 1; "g\"g"; "g'"; g; '"g\'g"g'; /g"\/*\//g; g; "// /*"; g; "*/"

```

It should output, with other parameters `"g"` and `"a"`, this:

```
var a = 1; "g\"g"; "g'"; a; '"g\'g"g'; /g"\/*\//g; a; "// /*"; a; "*/"

```

(sidenote: I really like `/g"\/*\//g`; I think that's just evil `:D`)

---

Full specification:

* For simplicity, you may ignore scope. Ex. `"var a=1; function(){var a=2;}; var o={a: 3}", "a", "b"` can output `var b=1; function(){var b=2;}; var o={b: 3}`.
* Text in strings (`'...' and "..."`), regexps and their modifiers (`/.../...`), and comments (`//...\n` and `/*...*/`) must not be modified.
* Also for simplicity, a valid identifier is one that starts with a letter, dollar sign, or underscore, and the rest of the characters are letters, numbers, dollar signs, or underscores.
* You may assume that the input contains no syntax errors.
* This is , so the shortest code in bytes will win.
* If you use network access, all bytes downloaded from the network count towards your score.
* You must use an actual programming language. No IDE solutions, like emacs or vim keystrokes. ;)

# Answer
# Ruby, 134 (113?) characters

```
*c,o,n=*$<;puts (c*?\n).gsub(/('|")((\\?+.)*?)\1|\/\*[\s\S]*?\*\/|\/\/.*|\/(\[\g<2>\]|\g<2>)+?\/\w*|([\w$]+)/){$5==o.chop&&n.chop||$&}

```

Unicode is not supported. If Unicode identifiers are to be supported, replace `\w` with `[[:word:]]` and `[\w$]` with `([[:word:]]|\$)` (and adjust the backreferences).

If unescaped slashes inside regexp literals (such as `/[/]/`) don't need to be supported, we can handle them together with string literals (**116 characters**). This also gives us string flags:

```
*c,o,n=*$<;puts (c*?\n).gsub(/\/\*[\s\S]*?\*\/|\/\/.*|('|"|\/)((\\?+.)*?)\1\w*|([\w$]+)/){$4==o.chop&&n.chop||$&}

```

Ungolfed version:

```
*code, old, new = *$<

puts code.join("\n").gsub (/
     ('|")((\\?+.)*?)\1           #strings
   | \/\*[\s\S]*?\*\/             #multiline comments
   | \/\/.*                       #single-line comments
   | \/(\[\g<2>\]|\g<2>)+?\/\w*   #regexes
   | ([\w$]+)                     #identifiers and keywords
/x){
  if $5 == old.chop then new.chop else $& end
}

```
> 4 votes

# Answer
## Perl, 122

```
@a=<>;chomp(($y,$x)=(pop@a,pop@a));$_=join'',@a;s!//.*?\n|/\*.*?\*/|("|'|/)(\\?+.)*?\1\w*|([\w\$]+)!$3eq$x?$y:$&!sge;print

```

i.e. (semi-ungolfed)

```
@a=<>;
chomp(($y,$x)=(pop@a,pop@a));
$_=join'',@a;
s!//.*?\n|/\*.*?\*/|("|'|/)(\\?+.)*?\1\w*|([\w\$]+)!$3eq$x?$y:$&!sge;
print

```

practically the same as Ruby's short version answer (except I didn't knew about possessive quantifiers trick and my first take was slightly longer). Regexp is shorter, but 'I/O' part spoils everything (Perl can't do `(@a,$x,$y)=<>`), and my assumption (the same I see in Ruby's, if I'm not mistaken) was we feed JS string line by line through STDIN, followed by 'old name' and 'new name' on separate lines.
> 3 votes

# Answer
# ECMAScript 6, 136 bytes

```
(s,o,n)=>s.replace(/\/\/.*?\n|\/\*[\s\S]+?\*\/|('|")(\\\1|[^\1])+?\1|\/(\\u[a-f\d]{4}|\\.|[^\/])+\/[angi]*|[a-z_$][\w$]*/gi,x=>x==o?n:x)

```

*Runs fine on any recent version of Firefox/Google Chrome.*

---

It creates a function with three parameters:

1. The code
2. The old variable name
3. The new variable name

See this JSFiddle for an example.
> 1 votes

---
Tags: code-golf, javascript
---


title: 2D javascript table graphics

text:
# Question
Title: 2D javascript table graphics
# The challenge

Make a JavaScript program that can use a HTML table as a canvas, having each cell a pixel. You can either input the position and color values in a form or by using the console.

# Score calculation

* +10 points for not using JQuery
* +15 points for the cells scaling equally to keep the same table aspect ratio when the browser is scaled
* +15 points for accomplishing the last thing without using any kind of CSS
* +\[number of upvotes\]
* +20 points if you do not label the cells' tags with coordinates (it counts if you make an JavaScript array like `{"cell1-1": ..., "cell1-2": ..., "cell1-3": ...}` but it doesn't count when you label the `<td>` tag itself, like `<td id="cell-7-9">` or `<td class="cell-8-1">`)

So if you have 67 upvotes, no JQuery (+10), the cells scaling (+15) but by using CSS (no +15) and you do not label the cells (+20), then your score will be 67 + 10 + 15 + 0 + 20 = 112.

The challenge ends on **20 Feb 2014, 4:00 PM GMT+0**.

**WINNERS:**
Doorknob -\> 61 + 3 = 64 points
Victor, with 60 + 1 = 61 points
they have very close scores so I couldn't exclude Victor.

# Answer
# Score: 61

*10 (no jQuery) + 15 (scaling cells) + 15 (the scaling part uses no CSS) + 20 (no labels) + 1 (upvotes)*

When you click on a cell, it turns the current color.

## JavaScript

```
var w = h = 20, color = 'red'
function createTable() {
    var tbl = document.createElement('table')
    tbl.id = 'tbl'
    for (var i = 0; i < h; i++) {
        var tr = document.createElement('tr')
        for (var i2 = 0; i2 < w; i2++) {
            var td = document.createElement('td')
            td.addEventListener('mousedown', draw)
            tr.appendChild(td)
        }
        tbl.appendChild(tr)
    }
    document.body.appendChild(tbl)
    return tbl
}
function killTable(tbl) {
    tbl.parentNode.removeChild(tbl)
}
var tbl = createTable()

function draw(e) {
   e.preventDefault()
   this.style.backgroundColor = color
}

document.getElementById('finalize').addEventListener('click', finalize)
function finalize() {
    var tds = document.getElementsByTagName('td')
    for (var i = 0; i < tds.length; i++) {
        tds[i].style.border = 'none'
        tds[i].removeEventListener('mousedown', draw)
    }
    document.getElementById('optionsWrapper').style.display = 'none'
}

document.getElementById('changeColor').addEventListener('click', changeColor)
function changeColor() {
    color = document.getElementById('color').value
}

document.getElementById('changeDims').addEventListener('click', changeDims)
function changeDims() {
    var dims = document.getElementById('dims').value.split('x')
    w = +dims[0], h = +dims[1]

    killTable(tbl)
    tbl = createTable()
}

```

## HTML

```
<div id='optionsWrapper'>
    <button id='finalize'>Finalize</button><br/>
    <label for='color'>Color: </label><input id='color' type='text' value='red' /><button id='changeColor'>Go</button><br/>
    <label for='dims'>Change dimensions (WARNING: will erase drawing): </label><input id='dims' type='text' value='20x20' /><button id='changeDims'>Go</button>
</div>

```

# CSS

```
td {
    width: 5px;
    height: 5px;
    padding: 0;
    border: 1px solid black;
}

table {
    border-collapse: collapse;
}

```

## JSFiddle

http://jsfiddle.net/D9u2N/1/

## Screenshots

Zoomed in view (while editing, click to enlarge to full size):

>

Finalized view (zoomed out):

>
> 5 votes

# Answer
# Score: 60 + upvotes

* No jQuery used.
* No CSS.
* The rule says *\[cells scaling equally to keep the same table aspect ratio when the browser is scaled\]*, it does that by not scaling at all when the window is resized and if you do use scaling/zoom in the browser, it will keep the aspect ratio.
* No cell or row labeling used.

The code basically creates a `TableCanvas` object. This object creates a table-based canvas and using javascript's DOM API, inserts it in a DOM node. Colors are specified as strings like `"rgb(0,255,0)"` for green.

It features:

* Resizing without deleting the canvas contents (except for the pixels clipped out of the canvas in the operation).
* Zooming (not to be confused with scaling).
* Clearing area to a color.
* Pixel manipulation.
* Line, rectangle and ellipse drawing.
* Extensible API to add your own methods.
* Allows the creation of multiple independent instances at the same time in different parts of your DOM.

Fiddle

# The actual code

```
function TableCanvas(target, pp) {
  var w = -1, h = -1, zoomH = 1, zoomV = 1, defaultColor = "rgb(255,255,255)";
  var rows = {};

  var tbl     = document.createElement("table");
  var tblBody = document.createElement("tbody");

  this.remake = function(p) {
    var newW = p.w ? p.w : w, newH = p.h ? p.h : h;
    if (newW < 0 || newH < 0) newW = newH = 0;
    if (p.zoomH) zoomH = p.zoomH >= 1 ? p.zoomH : 1;
    if (p.zoomV) zoomV = p.zoomV >= 1 ? p.zoomV : 1;
    if (p.defaultColor) defaultColor = p.defaultColor;

    for (var j = 0; j < newH; j++) {
      var isNewRow = j >= h;

      if (isNewRow) {
        var tr = document.createElement("tr");
        rows[j] = {tr: tr, cells: {}};
        tblBody.appendChild(tr);
      }

      for (var i = 0; i < newW; i++) {
        var isNewCell = isNewRow || i >= w;

        if (isNewCell) {
          var td = document.createElement("td");
          td.style.background = defaultColor ? defaultColor : "rgb(255,255,255)";
          rows[j].cells[i] = {td: td};
          rows[j].tr.appendChild(td);
        }
        rows[j].cells[i].td.style.paddingLeft = (zoomH - 1) + "px";
        rows[j].cells[i].td.style.paddingTop = (zoomV - 1) + "px";
      }
    }

    for (var j = h - 1; j >= 0; j--) {
      for (var i = w - 1; i >= newW; i--) {
        rows[j].tr.removeChild(rows[j].cells[i].td);
        delete rows[j].cells[i];
      }
      if (j >= newH) {
        tblBody.removeChild(rows[j].tr);
        delete rows[j];
      }
    }

    w = newW;
    h = newH;
    return this;
  };

  tbl.appendChild(tblBody);
  target.appendChild(tbl);
  tbl.setAttribute("border", "0");
  tbl.style.borderSpacing = "0";

  this.getTd = function(p) {
    return (p.x >= 0 && p.y >= 0 && p.x < w && p.y < h) ? rows[p.y].cells[p.x].td : null;
  };

  this.getPixelColor = function(p) {
    return (p.x >= 0 && p.y >= 0 && p.x < w && p.y < h) ? rows[p.y].cells[p.x].td.style.background : null;
  };

  this.setPixelColor = function(p) {
    if (p.x >= 0 && p.y >= 0 && p.x < w && p.y < h) {
      rows[p.y].cells[p.x].td.style.background = p.color ? p.color : defaultColor ? defaultColor : "rgb(255,255,255)";
    }
    return this;
  };

  this.drawRectangle = function(p) {
    for (var a = Math.min(p.x1, p.x2); a <= Math.max(p.x1, p.x2); a++) {
      for (var b = Math.min(p.y1, p.y2); b <= Math.max(p.y1, p.y2); b++) {
        this.setPixelColor({x: a, y: b, color: p.color});
      }
    }
    return this;
  };

  this.drawLine = function(p) {
    var t, x1 = p.x1, x2 = p.x2, y1 = p.y1, y2 = p.y2;
    if (Math.abs(x2 - x1) > Math.abs(y2 - y1)) {
      if (x1 > x2) { t = x1; x1 = x2; x2 = t; t = y1; y1 = y2; y2 = t; }
      for (var a = x1; a <= x2; a++) {
        this.setPixelColor({y: y1 + (y1 === y2 ? 0 : Math.floor((a - x1) * (y2 - y1) / (x2 - x1))), x: a, color: p.color});
      }
    } else {
      if (y1 > y2) { t = x1; x1 = x2; x2 = t; t = y1; y1 = y2; y2 = t; }
      for (var a = y1; a <= y2; a++) {
        this.setPixelColor({x: x1 + (x1 === x2 ? 0 : Math.floor((a - y1) * (x2 - x1) / (y2 - y1))), y: a, color: p.color});
      }
    }
    return this;
  };

  this.drawEllipse = function(p) {
    var t, x1 = p.x1, x2 = p.x2, y1 = p.y1, y2 = p.y2;
    if (x1 > x2) { t = x1; x1 = x2; x2 = t; }
    if (y1 > y2) { t = y1; y1 = y2; y2 = t; }
    var rx = (x2 - x1 + 1) / 2, ry = (y2 - y1 + 1) / 2, cx = (x2 + x1) / 2, cy = (y2 + y1) / 2;
    for (var a = x1; a <= x2; a++) {
      for (var b = y1; b <= y2; b++) {
        if ((a - cx) * (a - cx) / (rx * rx) + (b - cy) * (b - cy) / (ry * ry) <= 1) this.setPixelColor({x: a, y: b, color: p.color});
      }
    }
    return this;
  };

  this.clear = function(c) {
    this.drawRectangle({x1: 0, y1: 0, x2: w - 1, y2: h - 1, color: c});
    return this;
  };

  this.getWidth = function() { return w; };
  this.getHeight = function() { return h; };
  this.remake(pp);
}

```

# The test code

```
var body = document.getElementsByTagName("body")[0];
var divA = document.createElement("div"), divB = document.createElement("div");
body.appendChild(divA);
body.appendChild(divB);
divA.style.cssFloat = "left";
divA.style.marginRight = "10px";
divB.style.cssFloat = "left";
var canvas, canvas2, i = 0, f, commands = [
  function() {
    console.log("Create a magenta canvas");
    canvas = new TableCanvas({target: divA, w: 50, h: 50, defaultColor: "rgb(255,0,255)"});
  },
  function() { console.log("Draw black pixel"); canvas.setPixelColor({x: 2, y: 2, color: "rgb(0,0,0)"}); },
  function() { console.log("Zoom 10x horizontal, 5x vertical"); canvas.remake({zoomH: 10, zoomV: 5}); },
  function() { console.log("Draw green pixel"); canvas.setPixelColor({x: 9, y: 16, color: "rgb(0,255,0)"}); },
  function() { console.log("Zoom to 3x"); canvas.remake({zoomH: 3, zoomV: 3}); },
  function() { console.log("Paint as yellow"); canvas.clear("rgb(255,255,0)"); },
  function() { console.log("Draw second green pixel"); canvas.setPixelColor({x: 29, y: 36, color: "rgb(0,192,0)"}); },
  function() { console.log("Resize 1"); canvas.remake({w: 50, h: 60, defaultColor: "rgb(0,0,255)"}); },
  function() { console.log("Resize 2"); canvas.remake({w: 60, h: 45}); },
  function() { console.log("Resize 3"); canvas.remake({w: 45, h: 50, defaultColor: "rgb(255,0,0)"}); },
  function() { console.log("Resize 4"); canvas.remake({w: 60, h: 60}); },
  function() {
    console.log("Create a green second canvas");
    canvas2 = new TableCanvas({target: divB, w: 50, h: 50, defaultColor: "rgb(0,255,0)"});
  },
  function() {
    console.log("Draw smiley");
    canvas2.drawEllipse({x1: 1, y1: 1, x2: 48, y2: 48, color: "rgb(255,255,0)"})
           .drawEllipse({x1: 10, y1: 10, x2: 20, y2: 20, color: "rgb(0,0,0)"})
           .drawEllipse({x1: 30, y1: 10, x2: 40, y2: 20, color: "rgb(0,0,0)"})
           .drawLine({x1: 10, y1: 30, x2: 15, y2: 35, color: "rgb(0,0,0)"})
           .drawLine({x1: 15, y1: 35, x2: 35, y2: 35, color: "rgb(0,0,0)"})
           .drawLine({x1: 35, y1: 35, x2: 40, y2: 30, color: "rgb(0,0,0)"});
  },
  function() { console.log("Draw cyan rectangle"); canvas.drawRectangle({x1: 10, y1: 10, x2: 45, y2: 45, color: "rgb(0,255,255)"}); },
  function() { console.log("Draw orange ellipse"); canvas.drawEllipse({x1: 28, y1: 14, x2: 38, y2: 49, color: "rgb(255,128,0)"}); },
  function() { console.log("Draw blue line"); canvas.drawLine({x1: 12, x2: 20, y1: 40, y2: 5, color: "rgb(0,128,255)"}); },
  function() { console.log("Zoom to 4x"); canvas2.remake({zoomH: 4, zoomV: 4, h: 80}); },
  function() { console.log("Draw black line"); canvas.drawLine({x1: 4, y1: -9, x2: 32, y2: 60, color: "rgb(0,0,0)"}); },
  function() { console.log("Zoom to 2x3"); canvas2.remake({zoomV: 3}); },
  function() { console.log("Zoom to 1x"); canvas2.remake({zoomH: 1, zoomV: 1}); },
  function() {}
];
f = function() {
  (commands[i])();
  i++;
  if (i < commands.length) setTimeout(f, 400);
};
f();

```
> 2 votes

---
Tags: code-challenge, popularity-contest, javascript
---