title: Play the "bzzt" game

text:
# Question
Title: Play the "bzzt" game
# Winner: Aditsu's CJam answer! A whopping 25 bytes! Nice!

You may continue to submit your answer, however you can no longer win. Original post kept for posterity:

---

The "Bzzt" game is a game where you must count to a number (in this case 500). However, if the number has a 3 in it, or is divisible by 3, you don't say the number. Instead, you say "Bzzt".

Rules:

* You can't hard-code the numbers.
* The number only has to satisfy at least 1 of the following requirements
    + Divisible by 3
    + Number contains a 3
* Some type of separator is mandatory (12bzzt14 doesn't count)
* Score is measured in bytes.
* You must count exactly to 500, starting at 1 or 0 (you chose).
* The numbers must be output, but it doesn't matter how (e.g., stdout, writing to a text file, etc.).
* 0 can be divisible by 3 or not divisible. You can choose.
* You can output the numbers one at a time (ex, output 1, then 2, then bzzt, then 4, etc) or all at once (e.g., output 1 2 bzzt 4 5).
* You must replace the letter 3 with the word "bzzt". This is not case sensitive (bZzt, Bzzt, bzzt are all okay).

---

* This is a challenge, so the shortest code wins.
* This contest ends June 30th 2014 (7 days from posting).

# Answer
> 33 votes
# CJam - 25

```
501{3sI3%<Is-I"bzzt"?N}fI

```

Thanks Howard :)

Try it at http://cjam.aditsu.net/

**Explanation:**

`501{…}fI` is basically `for(int I=0; I<501; ++I) {…}`
`3s` converts 3 to string, i.e. "3"
`I3%` is `I` % 3
`<` gets the left substring - `"3".substring(0, I % 3)` \- which is "" for `I` % 3 == 0 and "3" otherwise
`Is` converts `I` to string
`-` with 2 strings does a set difference, resulting in an empty string iff `I` % 3 == 0 (the first string was empty) or `I` has a 3 digit in it
`…I"bzzt"?` is like `… ? I : "bzzt"`; the previous string is treated as a boolean value, where "" is false and any other string is true
`N` adds a newline

# Answer
> 30 votes
## Ruby, 43

```
501.times{|a|puts"#{a}"[?3]||a%3<1?:Bzzt:a}

```

Pretty straightforward.

Edit: Saved one byte, thanks Howard!

# Answer
> 25 votes
# seq and GNU sed - 42 33 31 30

Works directly in dash, some other shells might need to have history expansion disabled, e.g. with bash `set +H`:

```
seq 500|sed 0~3!{/3/!b}\;cbzzt

```

# Answer
> 18 votes
# x86 machine code on DOS (.com file) - 71 bytes

```
00000000  31 c9 68 20 24 89 e5 89  c8 bb 03 00 31 d2 f7 f3  |1.h $.......1...|
00000010  85 d2 74 1a 89 c8 b3 0a  31 d2 f7 f3 80 fa 03 74  |..t.....1......t|
00000020  0d 80 c2 30 86 d6 52 44  85 c0 75 ea eb 08 89 ec  |...0..RD..u.....|
00000030  68 7a 74 68 62 7a 89 e2  b4 09 cd 21 89 ec 41 81  |hzthbz.....!..A.|
00000040  f9 f4 01 7e c2 59 c3                              |...~.Y.|

```

Prints the required output to stdout with space as a delimiter; can be run without problems in DosBox.

Commented assembly:

```
    org 100h

start:
    ; 0 - 500 counter
    xor cx,cx
    ; we'll use the stack as scratch space to build the strings to print
    ; first of all, push ' $' on the stack (in reverse order); this will be
    ; the end of each string we'll print
    push 2420h
    ; save the stack pointer, to get back to this position after each print
    mov bp,sp
mainloop:
    ; first try to divide by three
    mov ax,cx
    mov bx,3
    xor dx,dx
    div bx
    test dx,dx
    ; no remainder => bzzt
    jz bzzt
    ; otherwise, go into the decimal-print loop
    mov ax,cx
divloop:
    ; bh is already at zero due to the mov bx,3 above
    mov bl,10
    xor dx,dx
    ; divide by 10
    div bx
    ; remainder is 3 => bzzt
    cmp dl,3
    je bzzt
    ; convert number to digit
    add dl,'0'
    ; trick: we move the digit to the upper byte of dx: this allows us to
    ; push the whole dx (you cannot do push dl) but to easily kill the
    ; undesidered byte by touching the stack pointer (it will be overwritten
    ; by the next stack operation/ignored by the print)
    xchg dl,dh
    push dx
    inc sp
    ; check is there anything left to print, rinse & repeat
    test ax,ax
    jnz divloop
    ; skip straight to print
    jmp print
bzzt:
    ; since we may be here from inside divloop, reset the stack pointer to
    ; where we left ' $'
    mov sp,bp
    ; push 'bzzt'
    push 747ah
    push 7a62h
print:
    ; print what is on the stack
    mov dx,sp
    mov ah,9h
    int 21h
    ; move us back to ' $'
    mov sp,bp

    ; increment cx and repeat while we are <=500
    inc cx
    cmp cx,500
    jle mainloop
end:
    ; fix back the stack pointer to the original value (=kill the first push)
    pop cx
    ; quit
    ret

```

# Answer
> 17 votes
# Perl - 35 ~~40~~ ~~42~~

```
print$_*!/3/%3?$_:bzzt,$/for 1..500

```

# Answer
> 16 votes
# PHP, no separator - 62, 61,59,58,52,49 47

It doesn't say there should be a space/newline/separator between them, without:

```
while(++$i<501)echo$i%3*!strpbrk($i,3)?$i:bzzt;

```

**With the separator, 68,67,65,64,58/55,53/52 51/50**

```
while(++$i<501)echo$i%3*!strpbrk($i,3)?$i:bzzt,' '; // 51
while(++$i<501)echo$i%3*!strpbrk($i,3)?$i:bzzt,~õ; // 50

```
* Just found a small 'cheat', don't need a space after `echo`, saved me a bit.
* The  creates a newline
* Another small 'cheat', the bzzt doesn't need quotes (tested it). Not the way to go, but it works.

---

# Javascript - 54,51 50

Same principle, but javascript functions:

```
for(i=0;i++<500;)alert(i%3<1|/3/.test(i)?'bzzt':i)

```

# Answer
> 15 votes
# Javascript 50 49

-1 byte thanks to core1024

```
for(i=0;i++<500;)alert(i%3*!/3/.test(i)?i:'bzzt')

```

# Answer
> 11 votes
### GolfScript, 30 29 characters

```
501,{:^`3`^3%<?)'bzzt'^if n}/

```

Not so straightforward implementation in GolfScript, can be tested here.

# Answer
> 10 votes
## Perl, 36

```
print$_%3&&!/3/?$_:Bzzt,$/for 1..500

```

Edit: I'm not a Perl monk, so core1024 seems to have managed to golf another byte out of this in his answer.

# Answer
> 10 votes
## C# (71)

Can be directly executed in LinqPad.

```
for(var i=0;++i<501;)(i%3<1|(i+"").Contains("3")?"buzz":i+"").Dump();

```

# Answer
> 9 votes
# Python (52)

Thanks grc!

```
for i in range(501):print[i,'Bzzt'][i%3<1or'3'in`i`]

```

Old version:

```
print['Bzzt'if'3'in`i`or i%3<1 else`i`for i in range(501)]

```

# Answer
> 7 votes
# Haskell: ~~88~~ ~~82~~ ~~80~~ 79

```
main=mapM_ f[1..500]
f n|n`mod`3<1||'3'`elem`show n=putStrLn"bzzt"
f n=print n

```

# Answer
> 6 votes
# Cobra - 70

```
class P
    def main
        for i in 501,print if('3'in'[i]'or i%3<1,'Bzzt',i)

```

# Batch - 222

Because I genuinely love this language... for some reason...

```
SETLOCAL ENABLEDELAYEDEXPANSION
for /l %%n in (1,1,500) do (
    set a=%%n&set /ai=!a!%%3
    if "!a:~0,1!"=="3" set a=Bzzt
    if "!a:~1,2!"=="3" set a=Bzzt
    if "!a:~2,3!"=="3" set a=Bzzt
    if !i!==0 set a=Bzzt
    echo !a!>>x)

```

# Answer
> 6 votes
# JavaScript ~~66~~ ~~63~~ 60

```
for(a=i=[];i<500;)a[i++]=i%3&&!/3/.test(i)?i:'bzzt';alert(a)

```

Thanks to edc65 for the suggestion to use array. The output will now be comma-separated.

---

## Old versions

### Version 1a - 66

Print from 1 to 500 in an alert box according to the rule. The output is space-separated.

```
a="";for(i=1;i<501;i++)a+=i%3&&!/3/.test(i)?i+" ":"bzzt ";alert(a)

```

### Version 1b - 65

If we consider 0 to be not divisible by 3, we can shorten the solution to 65 character:

```
a=0;for(i=1;i<501;i++)a+=i%3&&!/3/.test(i)?" "+i:" bzzt";alert(a)

```

### Version 2 - 63

```
for(a=i="";i<501;)a+=++i%3&&!/3/.test(i)?i+" ":"bzzt ";alert(a)

```

Thanks to grc for the suggestion to reduce the length.

# Answer
> 6 votes
## PowerShell, 42

```
1..500|%{($_,'bzzt')[$_-match3-or!($_%3)]}

```

Mostly Ventero's work, with a little help on syntax by me ;-)

# Answer
> 6 votes
## R, 49 characters

```
a=1:500;b='bzzt';a[!a%%3]=b;a[grep(3,a)]=b;cat(a)

```

Explained:

```
a=1:500 #Creates a vector with all integers from 1 to 500
b='bzzt'
a[!a%%3]=b #Replace all multiples of 3 by 'bzzt', thus coercing all other integers to character strings
a[grep(3,a)]=b #Replaces the character strings containing 3 by 'bzzt'
cat(a) #Print to stdout

```

Usage:

```
> a=1:500;b='bzzt';a[!a%%3]=b;a[grep(3,a)]=b;cat(a)
1 2 bzzt 4 5 bzzt 7 8 bzzt 10 11 bzzt bzzt 14 bzzt 16 17 bzzt 19 20 bzzt 22 bzzt bzzt 25 26 bzzt 28 29 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 40 41 bzzt bzzt 44 bzzt 46 47 bzzt 49 50 bzzt 52 bzzt bzzt 55 56 bzzt 58 59 bzzt 61 62 bzzt 64 65 bzzt 67 68 bzzt 70 71 bzzt bzzt 74 bzzt 76 77 bzzt 79 80 bzzt 82 bzzt bzzt 85 86 bzzt 88 89 bzzt 91 92 bzzt 94 95 bzzt 97 98 bzzt 100 101 bzzt bzzt 104 bzzt 106 107 bzzt 109 110 bzzt 112 bzzt bzzt 115 116 bzzt 118 119 bzzt 121 122 bzzt 124 125 bzzt 127 128 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 140 bzzt 142 bzzt bzzt 145 146 bzzt 148 149 bzzt 151 152 bzzt 154 155 bzzt 157 158 bzzt 160 161 bzzt bzzt 164 bzzt 166 167 bzzt 169 170 bzzt 172 bzzt bzzt 175 176 bzzt 178 179 bzzt 181 182 bzzt 184 185 bzzt 187 188 bzzt 190 191 bzzt bzzt 194 bzzt 196 197 bzzt 199 200 bzzt 202 bzzt bzzt 205 206 bzzt 208 209 bzzt 211 212 bzzt 214 215 bzzt 217 218 bzzt 220 221 bzzt bzzt 224 bzzt 226 227 bzzt 229 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 241 242 bzzt 244 245 bzzt 247 248 bzzt 250 251 bzzt bzzt 254 bzzt 256 257 bzzt 259 260 bzzt 262 bzzt bzzt 265 266 bzzt 268 269 bzzt 271 272 bzzt 274 275 bzzt 277 278 bzzt 280 281 bzzt bzzt 284 bzzt 286 287 bzzt 289 290 bzzt 292 bzzt bzzt 295 296 bzzt 298 299 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 400 401 bzzt bzzt 404 bzzt 406 407 bzzt 409 410 bzzt 412 bzzt bzzt 415 416 bzzt 418 419 bzzt 421 422 bzzt 424 425 bzzt 427 428 bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt bzzt 440 bzzt 442 bzzt bzzt 445 446 bzzt 448 449 bzzt 451 452 bzzt 454 455 bzzt 457 458 bzzt 460 461 bzzt bzzt 464 bzzt 466 467 bzzt 469 470 bzzt 472 bzzt bzzt 475 476 bzzt 478 479 bzzt 481 482 bzzt 484 485 bzzt 487 488 bzzt 490 491 bzzt bzzt 494 bzzt 496 497 bzzt 499 500

```

# Answer
> 6 votes
# TI-BASIC - 31 ~~(32)(34)(35)(36)(43)~~

```
:While X<500
:X+1→X
:If not(fPart(X/3
:"bzzt
:Disp Ans
:End

Total: 25 + 6 lines = 31

```

Note that most commands on TI-BASIC are represented as single-byte entities.

The code requires X to be initialized to 0 beforehand (otherwise, it's an extra 3 bytes).

I've made several attempts to shave several bytes, so I'm not detailing everything I've done here, as to not clutter the post. They have mostly been directed at shortening the loop, which I've done in this version by a While loop and by shortening the If condition with the help of the `Ans` variable.

# Answer
> 5 votes
# groovy - 51

```
500.times{println"$it".find('3')||it%3<1?'bzzt':it}

```

edit: using `times` the printing version is now as short as the "displaying". thanks @will-p

# Answer
> 5 votes
# C, 93

Just for the hell of it...

```
main(i){char s[9]="bzzt";while(i<498+sprintf(s+5,"%d",i))puts(s+5*(i++%3&&!strchr(s+5,51)));}

```

# Answer
> 5 votes
# Julia 64 bytes

```
map(x->x%3==0||contains(string(x),"3")?"Bzzt":string(x),[1:500])

```

# Answer
> 5 votes
# k4 ~~(37)~~ (35)

```
{$(x;`bzzt)(|/51=$x)|~"."in$x%3}'!501

```

`k4` lacks a built-in modulo command, and using the `q` one would take an extra character; this version (ab)uses the built-in output format to check if the string of the result of dividing `x` by 3 has a decimal point in it.

EDIT:

```
{$(x;`bzzt)(|/51=$x)|x=3*_x%3}'!501

```

Clever as matching the decimal point may be, I can shave two bytes by checking that `3*floor x%3` is still `x`.

# Answer
> 5 votes
# cmd.exe - 91

```
for /l %x in (1,1,500)do @set/a %x%3|find "0">nul&&echo bzzt||echo %x|find/v"3"||echo bzzt

```

...because why use a batch file when a perfectly straightforward one-liner exists...:-)

# Answer
> 4 votes
## Mathematica, 54 Characters

This feels too straightforward. Shorter solutions must be possible.

```
If[DigitCount[#][[3]] > 0 || #~Mod~3 < 1, Bzzt, #] & /@ Range@500

```

# Answer
> 4 votes
# T-SQL 2008 - 80

Not going to win or anything but fun none the less: Tweaked thanks to @domager:

```
declare @ int=0t:if(@)like'%3%'or @%3=0print'bzzt'print @;set @+=1if @<501goto t

```

A little known fact, @ is a valid name for a variable. It feels weird as the set based code is the more SQL variant, but shorter is shorter! This version works on any database. Edit: I was able to remove two of the semis as they were not needed. I'm pretty sure this is as optimal as it gets.

Edit2: Never say never. Here it's now even grosser using goto, but it allows us to avoid the block. We can Replace while,begin,end with the shorter if,t:,goto saving 6 characters. We also rearrange statement by rewriting the loop as a pseudo do-while,semantically equivalent. Edit3: Yeah, somehow if is now shorter. Original:

```
select top 501iif(number like'%3%'or number%3=0,'bzzt',str(number))from spt_values where'p'=type

```

Must be run on the master database. I love T-SQL despite its noisy and ugly ways. There might be a way to make this simpler, but unfortunately, the `iif` built-in requires both sides agree on types. Sql servers precedence rules give int higher precedence than strings. Number is also really long, but aliasing is more characters than it is worth. There might be a better way to turn number in to a string. Edit: str works too. 2 less characters than ltrim

# Answer
> 4 votes
# C, 80

Using spaces as separators instead of line breaks.

```
n;main(){for(;n++<500;)printf(n%10^3&&n/10%10^3&&n/100^3&&n%3?"%d ":"bzzt ",n);}

```

# Answer
> 4 votes
# VBA: 54

```
for x=0to 500:?iif(x/3=x\3=instr(1,x,3),x,"Bzzt"):next

```

Open up your favorite Office program, hit alt+F11 to open the VBA IDE and paste the code into the immediate pane and press enter.

In VBA, : is the line separator, ? is shorthand for print, iif means inline if (think x?"Y":"N"), x/3 does floating point division and x\3 does integer division, instr returns the position of a char in a string, or 0 otherwise, true=-1 and false=0.

The code basically increments x and outputs x if x/3=x\3=instr(1,x,3) is true and "Bzzt" otherwise. x/3=x\3 compares (float)(x/3) to (int)(x/3) and returns a boolean (0 is false and -1 is true). instr(1,x,3) returns 0 if "3" is not in the number, and a positive integer otherwise. The only time the expression returns true is when (x/3=x\3) is false (0) and instr(1,x,3) is 0, or in other words, when x is not divisible by 3 and does not contain the digit "3", which is exactly what we are looking for.

# Answer
> 3 votes
# Bash, ~~53 52 48~~ 46

```
seq 500|factor|sed '/3.*:\| 3 */cBzzt
s/:.*//'

```

Requires GNU sed (uses the `c` extension).

# Answer
> 3 votes
**Java, 142 131** thank to WozzeC suggestion

```
public class a{public static void main(String[]a){for(int i=1;i<501;i++)System.out.println(i%3>0&(""+i).indexOf(51)<0?i:"bzzt");}}

```

# Answer
> 3 votes
# R (40) (36)

*This is basically plannapus answer a little bit shortened, but I can not comment yet*

*Update: -4 characters (see plannapus's comment)*

```
a=1:500;a[grepl(3,a)|!a%%3]='bzzt';a

```

Output:

```
  [1] "1"    "2"    "bzzt" "4"    "5"    "bzzt" "7"    "8"    "bzzt" "10"   "11"   "bzzt" "bzzt" "14"   "bzzt" "16"   "17"   "bzzt" "19"   "20"   "bzzt" "22"   "bzzt" "bzzt" "25"   "26"   "bzzt" "28"   "29"   "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "40"   "41"   "bzzt" "bzzt" "44"   "bzzt" "46"   "47"   "bzzt" "49"   "50"   "bzzt" "52"   "bzzt" "bzzt" "55"   "56"   "bzzt" "58"   "59"   "bzzt" "61"   "62"   "bzzt" "64"   "65"   "bzzt" "67"   "68"   "bzzt" "70"   "71"   "bzzt" "bzzt" "74"   "bzzt" "76"   "77"   "bzzt" "79"   "80"   "bzzt" "82"   "bzzt" "bzzt" "85"   "86"   "bzzt" "88"   "89"   "bzzt" "91"   "92"   "bzzt" "94"   "95"   "bzzt" "97"   "98"   "bzzt" "100"  "101"  "bzzt" "bzzt" "104"  "bzzt" "106"  "107"  "bzzt" "109"  "110"  "bzzt" "112"  "bzzt" "bzzt" "115"  "116"  "bzzt" "118"  "119"  "bzzt" "121"  "122"  "bzzt" "124"  "125"  "bzzt" "127"  "128"  "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "140"  "bzzt" "142"  "bzzt" "bzzt" "145"  "146"  "bzzt" "148"  "149"  "bzzt" "151"  "152"  "bzzt" "154"  "155"  "bzzt" "157"  "158"  "bzzt" "160"  "161"  "bzzt" "bzzt" "164"  "bzzt" "166"  "167"  "bzzt" "169"  "170"  "bzzt" "172"  "bzzt" "bzzt" "175"  "176"  "bzzt" "178"  "179"  "bzzt" "181"  "182"  "bzzt" "184"  "185"  "bzzt" "187"  "188"  "bzzt" "190"  "191"  "bzzt" "bzzt" "194"  "bzzt" "196"  "197"  "bzzt" "199"  "200"  "bzzt" "202"  "bzzt" "bzzt" "205"  "206"  "bzzt" "208"  "209"  "bzzt" "211"  "212"  "bzzt" "214"  "215"  "bzzt" "217"  "218"  "bzzt" "220"  "221"  "bzzt" "bzzt" "224"  "bzzt" "226"  "227"  "bzzt" "229"  "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "241"  "242"  "bzzt" "244"  "245"  "bzzt" "247"  "248"  "bzzt" "250"  "251"  "bzzt" "bzzt" "254"  "bzzt" "256"  "257"  "bzzt" "259"  "260"  "bzzt" "262"  "bzzt" "bzzt" "265"  "266"  "bzzt" "268"  "269"  "bzzt" "271"  "272"  "bzzt" "274"  "275"  "bzzt" "277"  "278"  "bzzt" "280"  "281"  "bzzt" "bzzt" "284"  "bzzt" "286"  "287"  "bzzt" "289"  "290"  "bzzt" "292"  "bzzt" "bzzt" "295"  "296"  "bzzt" "298"  "299"  "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "400"  "401"  "bzzt" "bzzt" "404"  "bzzt" "406"  "407"  "bzzt" "409"  "410"  "bzzt" "412"  "bzzt" "bzzt" "415"  "416"  "bzzt" "418"  "419"  "bzzt" "421"  "422"  "bzzt" "424"  "425"  "bzzt" "427"  "428"  "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "bzzt" "440"  "bzzt" "442"  "bzzt" "bzzt" "445"  "446"  "bzzt" "448"  "449"  "bzzt" "451"  "452"  "bzzt" "454"  "455"  "bzzt" "457"  "458"  "bzzt" "460"  "461"  "bzzt" "bzzt" "464"  "bzzt" "466"  "467"  "bzzt" "469"  "470"  "bzzt" "472"  "bzzt" "bzzt" "475"  "476"  "bzzt" "478"  "479"  "bzzt" "481"  "482"  "bzzt" "484"  "485"  "bzzt" "487"  "488"  "bzzt" "490"  "491"  "bzzt" "bzzt" "494"  "bzzt" "496"  "497"  "bzzt" "499"  "500"

```

# Answer
> 3 votes
# Fortran - ~~118 114~~ 111

A hopelessly unlikely candidate, though originally developed to fit on punch cards. Using all the obscure constructs from the past, some short code may still be written:

```
do3 i=1,500
j=i
if(mod(i,3))2,1,2
1 print*,'bzzt'
cycle
2 goto(1)mod(j,10)-2
j=j/10
if(j>0)goto2
3 print*,i
end

```

The "computed goto" `goto(L1,L2,...,Ln) x` branches to one of the labels L if and only if 1 \<= x \<= n.

**Edit:** Managed to shave off 4 bytes by rearranging the loop that checks for the digit 3. As a bonus, the code now also contains the arithmetic if-statement `if(x) a,b,c`, which always branches to one of three labels: a if x \< 0, b if x == 0 or c if x \> 0.

Unfortunately, the first two versions did not produce the correct output. The digit-3 loop now works correctly, and the code now also includes a modern logical if-statement. Three more bytes are gone, because who needs an `enddo` statement? The output may be verified here.

# Answer
> 3 votes
# Scala, 70

## Code

```
1 to 500 map(x=>if(x%3<1||(""+x).contains(51))"bzzt"else x)map println

```

## Usage

```
scala -e '1 to 500 map(x=>if(x%3<1||(""+x).contains(51))"bzzt"else x)map println'

```

## Demo

http://ideone.com/KfcO1M

## Explanations

* `1 to 500`: produces values from 0 to 500
* `map`: function which takes iterable argument at the left, and applies the function given at the right
* `x=>...`: lambda expression
* `if(condition) value_if_condition_is_true else value_if_condition_is_false`: returns a value (functional behavior) which can be either a `java.lang.String` or a `scala.Int`. The expression type is `scala.Any` in this case, because this is the lower type the two types can coerce to (see the Scala Class Hierarchy)
* `map println`: takes each object (`java.lang.String` or `scala.Int`) and prints it with line feeds

# Answer
> 3 votes
### Swift - 74

```
for i in 0..501 {println(i%3<1||"\(i)".rangeOfString("3") ?"bzzt":"\(i)")}

```

# Answer
> 3 votes
# 05AB1E, ~~26~~ ~~23~~ 21 bytes (non-competing)

```
501FND3ÖN3å~i"bzzt"},

```

Try it online!

# Answer
> 2 votes
# JavaScript - 57

Another JavaScript example:

```
for(i=0;i<500;)alert((++i+'').indexOf(3)<0&&i%3?i:'bzzt')

```

# Answer
> 2 votes
## Microsoft Small Basic (115 chars, 127 bytes)

```
For i = 1 To 500
j=i
If(Math.Remainder(i,3)=0 Or Text.IsSubText(i,"3"))then
j="bzzt"
EndIf
TextWindow.Write(j+" ")
EndFor

```

# Answer
> 2 votes
## PROLOG (144)

```
b:-b(R,1),print([0|R]).
b([500],500).
b([bzzt|R],N):-((0is N mod 3);(name(N,C),member(51,C))),N1 is N+1,b(R,N1).
b([N|R],N):-N1 is N+1,b(R,N1).

```

Usage:

```
b.

```

# Answer
> 2 votes
## Ruby, 57

Not a competitive Ruby answer, but I like it because it's weird.

```
i=-1;([b=:bzzt,p,p]*167).map{|a|puts"#{i+=1}"[?3]?b:a||i}

```

# Answer
> 2 votes
# Python2 (59)

Simple case of list comprehension

```
print[n if n%3or '3'in str(n)else"bzzt"for n in range(501)]

```

# Answer
> 2 votes
# Haskell 78

```
main=mapM(putStrLn.f)[0..500];f x|x`mod`3<1||'3'`elem`show x="bzzt";f x=show x

```

# Answer
> 2 votes
**Python - 53**

```
for i in range(1,501):print[i,'Bzzt']['3'[:i%3]in`i`]

```

Can't add comments to above answer so posting down here. Starting range at 0 produces Bzzt at 0, need to start at 1.

# Answer
> 2 votes
# Mouse-2002, 34 bytes

I'm proud that lil' ol' Mouse, first implemented in 1979 and the most recent iteration updated Aug '07 (excluding the one by me), can do so well! :')

```
(x.501<^x.d\[x.!J!'|"bzzt!"]x.1+x:)

```

Explained:

```
(             ~ while true
  x. 501 < ^  ~ push x; push 1 if less than 501 and break if 0
  x. d \      ~ push x mod 3
  [           ~ if 0; then
    x. ! J!'  ~ push x and print, push the ascii code 9 and print
  |           ~ else
    "bzzt!"   ~ print this string
  ]           ~ endif
  x. b+ x:    ~ push x, increment by 1
)             ~ endwhile
$             ~ (implicit for scripts) end prog

```

Sample run:

```
$ mouse bzzt.mou | head
bzzt
1       2       bzzt
4       5       bzzt
7       8       bzzt
10      11      bzzt
13      14      bzzt
16      17      bzzt
19      20      bzzt
22      23      bzzt
25      26      bzzt

```

Tab chars because I say so.

My reboot of this language's legacy can do this exact thing in **27 bytes**:

```
(x501<^xd\[x.|"bzzt".]1!x+)

```

And I'm not even aiming for it to be a golfing lang, just a small syntax! No interpreter *yet*.

# Answer
> 2 votes
# MathGolf, ~~19~~ 18 bytes

```
♪½{î3╧î3÷+î╕▄┴_ß§p

```

Try it online!

## Explanation

```
♪                     push 1000
 ½                    divide by 2, making 500
  {                   start for loop
   î                  index of current loop (1-based)
    3                 push 3
     ╧                pop a, b, a.contains(b)
      î               index of current loop (1-based)
       3              push 3
        ÷             is divisible
         +            pop a, b : push(a+b)
          î           index of current loop (1-based)
           ╕▄┴        decompress "bzzt"
              _       duplicate TOS
               ß      wrap last three elements in array (makes [<index>, "bzzt", "bzzt"])
                §     get from array
                 p    print with newline

```

# Answer
> 2 votes
# Vyxal `Hj`, ~~21~~ ~~16~~ 14 bytes

```
5*ƛ:3₌cḊ∨ß«⊍β«

```

Try it Online!

### Explained

```
5*ƛ:3₌cḊ∨ß«⊍β«

5*             # The H flag pushes 100 to stack so 5*100=500
  ƛ:3₌cḊ∨ß     # check divisibility by 3 or if it has a 3
          «⊍β« # compressed string of "bzzt"
               # j flag joins with newlines

```

# Answer
> 1 votes
# Delpi - 128

```
procedure x;var I: integer;begin for I:=0to 500do writeln(iif((IntToStr(i).Contains('3')or(i mod 3=0)),'bzzt',inttostr(i)));end;

```

# Answer
> 1 votes
# seq and awk 48 38

```
seq 500|awk '!($1%3)||/3/{$1="bzzt"}1'

```

# Answer
> 1 votes
# LiveScript (54)

```
for n to 500=>alert if n%3==0||/3/test n=>\bzzt else n

```

# Answer
> 1 votes
# bash – 74

I know it won't win anything, not even within bash, but thought I'd submit one where *500* or *501* is not in the solution.

```
seq 0 166|awk '{print"bzzt\n"($1)*3+1"\n"($1)*3+2;}'|sed 's/.*3.*/bzzt/g'

```

# Answer
> 1 votes
# Java, ~~127~~ ~~124~~ 95 bytes

```
class B{static{for(int i=0;i++<500;System.out.println(i%3<1||(i+"").contains("3")?"Bzzt":i));}}

```

It throws an exception at the beginning but it works, at least for me (Java version `1.7.0_60-b19` on Mac OS X `10.8.5`).

# Answer
> 1 votes
# C# (110)

```
Enumerable.Range(1,500).All(x =>{Console.Write((x%3==0)||(x + "").Contains("3")?"Bzzt ":x+" ");return true;});

```

# Answer
> 1 votes
# F# - 86

```
for i in 0..500 do if(string i).Contains"3"||i%3=0 then printfn"Bzzt"else printfn"%i"i

```

# Answer
> 1 votes
**PHP, no seperator - 53**

```
while(++$i<501)echo$i%3<1||strpos(-$i,'3')?'bzzt':$i;

```

It's a improved version of @Martijn's code. I would like to add comment to his answer, but I haven't enough reputation to do that...

# Answer
> 1 votes
# Python2 (63)

Corrected version of @idiot.py's code (I don't have enough reputation to comment on his post).

```
print[n if n%3and'3'not in str(n)else"bzzt"for n in range(501)]

```

or, equivalently,

```
print["bzzt"if not n%3or'3'in str(n)else n for n in range(501)]

```

You have to negate the second condition, otherwise it gives incorrect output.

output:

```
['bzzt', 1, 2, 'bzzt', 4, 5, 'bzzt', 7, 8, 'bzzt', 10, 11, 'bzzt', 'bzzt', 14, 'bzzt', 16, 17, 'bzzt', 19, 20, 'bzzt', 22, 'bzzt', 'bzzt', 25, 26, 'bzzt', 28, 29, 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 40, 41, 'bzzt', 'bzzt', 44, 'bzzt', 46, 47, 'bzzt', 49, 50, 'bzzt', 52, 'bzzt', 'bzzt', 55, 56, 'bzzt', 58, 59, 'bzzt', 61, 62, 'bzzt', 64, 65, 'bzzt', 67, 68, 'bzzt', 70, 71, 'bzzt', 'bzzt', 74, 'bzzt', 76, 77, 'bzzt', 79, 80, 'bzzt', 82, 'bzzt', 'bzzt', 85, 86, 'bzzt', 88, 89, 'bzzt', 91, 92, 'bzzt', 94, 95, 'bzzt', 97, 98, 'bzzt', 100, 101, 'bzzt', 'bzzt', 104, 'bzzt', 106, 107, 'bzzt', 109, 110, 'bzzt', 112, 'bzzt', 'bzzt', 115, 116, 'bzzt', 118, 119, 'bzzt', 121, 122, 'bzzt', 124, 125, 'bzzt', 127, 128, 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 140, 'bzzt', 142, 'bzzt', 'bzzt', 145, 146, 'bzzt', 148, 149, 'bzzt', 151, 152, 'bzzt', 154, 155, 'bzzt', 157, 158, 'bzzt', 160, 161, 'bzzt', 'bzzt', 164, 'bzzt', 166, 167, 'bzzt', 169, 170, 'bzzt', 172, 'bzzt', 'bzzt', 175, 176, 'bzzt', 178, 179, 'bzzt', 181, 182, 'bzzt', 184, 185, 'bzzt', 187, 188, 'bzzt', 190, 191, 'bzzt', 'bzzt', 194, 'bzzt', 196, 197, 'bzzt', 199, 200, 'bzzt', 202, 'bzzt', 'bzzt', 205, 206, 'bzzt', 208, 209, 'bzzt', 211, 212, 'bzzt', 214, 215, 'bzzt', 217, 218, 'bzzt', 220, 221, 'bzzt', 'bzzt', 224, 'bzzt', 226, 227, 'bzzt', 229, 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 241, 242, 'bzzt', 244, 245, 'bzzt', 247, 248, 'bzzt', 250, 251, 'bzzt', 'bzzt', 254, 'bzzt', 256, 257, 'bzzt', 259, 260, 'bzzt', 262, 'bzzt', 'bzzt', 265, 266, 'bzzt', 268, 269, 'bzzt', 271, 272, 'bzzt', 274, 275, 'bzzt', 277, 278, 'bzzt', 280, 281, 'bzzt', 'bzzt', 284, 'bzzt', 286, 287, 'bzzt', 289, 290, 'bzzt', 292, 'bzzt', 'bzzt', 295, 296, 'bzzt', 298, 299, 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 400, 401, 'bzzt', 'bzzt', 404, 'bzzt', 406, 407, 'bzzt', 409, 410, 'bzzt', 412, 'bzzt', 'bzzt', 415, 416, 'bzzt', 418, 419, 'bzzt', 421, 422, 'bzzt', 424, 425, 'bzzt', 427, 428, 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 'bzzt', 440, 'bzzt', 442, 'bzzt', 'bzzt', 445, 446, 'bzzt', 448, 449, 'bzzt', 451, 452, 'bzzt', 454, 455, 'bzzt', 457, 458, 'bzzt', 460, 461, 'bzzt', 'bzzt', 464, 'bzzt', 466, 467, 'bzzt', 469, 470, 'bzzt', 472, 'bzzt', 'bzzt', 475, 476, 'bzzt', 478, 479, 'bzzt', 481, 482, 'bzzt', 484, 485, 'bzzt', 487, 488, 'bzzt', 490, 491, 'bzzt', 'bzzt', 494, 'bzzt', 496, 497, 'bzzt', 499, 500]

```

# Answer
> 1 votes
# C, ~~90~~ ~~86~~ 81

```
i,s;main(){while(++i<501)sprintf(&s,"%d",i),puts(i%3&&!strchr(&s,51)?&s:"bzzt");}

```

Not a serious contender. This is essentially bacchusbeale's answer golfed better, as I suggested in comments to his answer. As well as those changes, I used `strchr` as a shorter test than a `for` loop to see if the string version of the integer contains the character `3` (character 51 in ASCII).

Edit: down to 81 characters incorporating edc65's sick trick from the comments (assumes `int` is at least 32 bits). Thanks!

# Answer
> 1 votes
# **Tcl 90**

```
set i 0;while {$i < 501} {if {[regexp 3 $i]||($i %3)<1} {puts "bzzt"} {puts "$i"};incr i}

```

I'm sure other tclers could make this more terse, but the interpreter is funny about whitespaces.

# Answer
> 1 votes
## C, 79

```
i;main(s){while(++i<498+sprintf(&s,"%d",i))puts(i%3*!strchr(&s,51)?&s:"bzzt");}

```

Improved version of squeamish ossifrage's solution. Now it's the shortest C solution.

# Answer
> 1 votes
# JavaScript, 70

First entry into a code golf

```
i=0;while(i<501)console.log(((""+i).match(/3/g)||i%3==0)?'bzzt':i),i++

```

Can probably be made shorter, but this one doesn't do alert and make you want to kill the developer.

# Answer
> 1 votes
# *C#*

Code can be executed directly in LinQPad.

## Number is divisible by 3 (49)

```
var i=0;while(i++<501)(i%3<1?"bzzt":i+"").Dump();

```

This one should count as the question stated:

> *The number only has to satisfy at least 1 of the following requirements.*

---

## Number contains 3 (64)

```
var i=0;while(i++<501)((i+"").Contains("3")?"bzzt":i+"").Dump();

```

---

## Both conditions apply (70)

```
var i=0;while(i++<501)(i%3<1|(i+"").Contains("3")?"buzz":i+"").Dump();

```

# Answer
> 1 votes
## Delphi - 119

```
repeat ShowMessage(IfThen((Tag mod 3=0) or (pos('3',IntToStr(Tag))>0),'bzzt',IntToStr(Tag))); Tag:=Tag+1 until Tag=500

```

Uses the fact that "self" is assumed so the form's Tag property can be accessed directly without actually declaring a variable. I had critiqued another Delphi answer here a few minutes ago so I thought it was only fair I posted one too.

# Answer
> 1 votes
# JAGL V1.0 - 35

```
1 501r{ddg@3%nSg51e|"bzzt"SnI32+p}/

```

Probably could have done better. May try to revise it.

Explaination:

```
1 501r                                     Make a range of 1 to 500 inclusive
      {ddg                                 Duplicate twice and convert top to string
          @3%n                             Rotate top 3 on stack, and push not(top mod 3)
              Sg                           Swap top two values, and convert top to string
                51e                        Check if 51 (3) is in the string rep
                   |"bzzt"                 Take the logical "or", and push "bzzt"
                          SnI              Swap, reverse, and if not divisible, drop "bzzt"
                             32+p          Add a space, and print
                                 }/        End block, and map over range

```

# Answer
> 1 votes
## Java, 139 132 128 127 bytes

```
class A{public static void main(String[] a){for(int i=0;i++<500;)System.out.print(i%3==0|(i+"").contains("3")?"bzzt ":i+" ");}}

```

# Answer
> 1 votes
# jq: 59 bytes

(56 characters code + 3 characters command line option.)

```
range(501)|select(.%3<1or("\(.)"|test("3"))|not)//"bzzt"

```

Sample run:

```
bash-4.3$ jq -n -r 'range(501)|select(.%3<1or("\(.)"|test("3"))|not)//"bzzt"' | head
bzzt
1
2
bzzt
4
5
bzzt
7
8
bzzt

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)

# Answer
> 1 votes
# beeswax, 148 bytes

beeswax was created after the challenge, but why shouldn’t I give the challenge a try anyway? ;)

Not golfed to death yet, but it satisfies both requirements:

```
 ;pK~gFP{?gp'           <      <
>F B~6-!P~2 .Pfz1~h#>@-"d~9P~:Fd
4 N     >@f>F9P~%~3Kd`bzzt`g?Pp
*0>F3~%'d`bzzt`@Pp
  dN             <            <

```

Output:

```
julia> beeswax("bzzt.bswx")
bzzt
1
2
bzzt
4
5
bzzt
7
8
bzzt
10
11
bzzt
bzzt
14
bzzt
16
...
29
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
40
41
...
296
bzzt
298
299
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
bzzt
...
bzzt
bzzt
bzzt
bzzt
400
401
bzzt
bzzt
404
...
494
bzzt
496
497
bzzt
499
500
Program finished!

```

You can clone my beeswax interpreter (written in Julia) from my GitHub repository.

# Answer
> 1 votes
## Groovy, ~~46~~ 45 bytes

```
{(0..500).collect{x->x%3<1||x=~/3/?'bzzt':x}}

```

This is an unnamed closure. Try it Online!

# Answer
> 1 votes
# Japt, 21 bytes

```
501Ç%3«/3/tZ ?Z:"bzzt

```

Try it online!

Almost direct translation of nderscore's JS submission.

### Unpacked & How it works

```
501oZ{Z%3&&!/3/tZ ?Z:"bzzt

501oZ{                      Map range(501) to a function...
      Z%3&&!/3/tZ             If Z is not a multiple of 3 and Z doesn't have digit 3
                  ?Z          Return Z
                    :"bzzt    Otherwise, return "bzzt"

```

# Answer
> 1 votes
# Brachylog, 23 bytes (posted *way* after the end of the challenge)

```
500⟦{{f|}∋3∧"bzzt"|}ᵐẉᵐ

```

Try it online!

```
    {              }ᵐ      For every
500⟦                       number from 0 to 500,
            "bzzt"         the string "bzzt"
         ∋3∧               if 3 is an element of
     {f }                  the input's factors
       |                   or the input itself,
                  |        the input if neither condition is satisfied.
                     ẉᵐ    Write that all with one line per item.

```

# Answer
> 1 votes
# Python 3, 56 bytes (Non-Competing)

```
for x in range(501):print([x,'bzzt']['3'[:x%3]in'%s'%x])

```

Try it online!

Shortest I could get it in Python 3. Can't yet comment on the existing Python 3 solution so posting as a separate answer.

# Answer
> 1 votes
# APL (Dyalog Unicode), 30 bytes

```
{(0=3|⍵)∨'3'∊⍕⍵:'bzzt'⋄⍵}¨⍳500

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 19 bytes

```
₄;END3ÖN3å~i.•è‰•},

```

Try it online!

```
₄;                   # push 500
  E                  # for N in [0, 1, 2, ..., 500]...
   ND3ÖN3å~          # push N and 1 if either 3 is in N or N is divisible by 3, else 0
           i         # if top of stack is truthy:
            .•è‰•}   # push "bzzt"
                  ,  # output top of stack to STDOUT

```

# Answer
> 1 votes
# Vyxal 3 `j`, 14 bytes

```
500ƛ3∦cḊa["ġ/„

```

Try it Online!

-9 bytes thanks to @lyxal

-1 byte thanks to @Aaroneous Miller

### Explanation (outdated):

```
500ɾ(nD3c$K3c∨["bzzt",|,
500ɾ                      ## push [1..500]
    (                     ## loop every number
     nD                   ## push the loop variable three times
       3c                 ## Contains 3?
         $   ∨            ## or
          K3c             ## it's divisible by 3?
              ["bzzt",    ## If so, print "bzzt"
                      |,  ## else print the loop variable

```

Created with the help of Luminespire.

# Answer
> 0 votes
# Javascript - ~~109~~ 97

Compressed:

```
function b(m,c,z){for(i=1;i<=m;i++){if((i+'').indexOf(c)>-1||i%c==0){alert(z);continue}alert(i)}}

```

Replaced `console.log` with `alert`

Uncompressed:

```
function bzzt(max, contains, z) {
    for(i=1;i<=max;i++) {
        if((i+'').indexOf(contains)>-1||i%contains==0) {
            console.log(z);
            continue;
        }
        console.log(i); // console.log instead of alert for testing purposes
    }
}

```

> max is the number to count to, contains is the number it contains and is divisible by, z is the message, so 'bzzt'

```
b(500, 3, 'bzzt');

```

# Answer
> 0 votes
## C 174

```
int i,j,k;char n[3];
int main(){
while(i++<501){k=0;sprintf(n,"%d",i);
for(j=0;j<3;j++){if(n[j]=='3'){k=1;break;}}
(i%3==0||k)?puts("Bzzt"):printf("%d\n",i);}
return 0;}

```

# Answer
> 0 votes
## JavaScript, 65

OK, longer than others so far, but I've never tried this before and felt compelled to post...

```
a='';for(i=0;i-->-500;)a+=(i%3?i:-3);a.replace(/\d*3\d*/g,'bzzt')

```

### Usage:

From a node repl paste the code. Output is by returned value

### Output:

```
'-1-2-bzzt-4-5-bzzt-7-8-bzzt-10-11-bzzt-bzzt-14-bzzt-16-17-bzzt-19-20-bzzt-22-bzzt-bzzt-25-26-bzzt-28-29-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-40-41-bzzt-bzzt-44-bzzt-46-47-bzzt-49-50-bzzt-52-bzzt-bzzt-55-56-bzzt-58-59-bzzt-61-62-bzzt-64-65-bzzt-67-68-bzzt-70-71-bzzt-bzzt-74-bzzt-76-77-bzzt-79-80-bzzt-82-bzzt-bzzt-85-86-bzzt-88-89-bzzt-91-92-bzzt-94-95-bzzt-97-98-bzzt-100-101-bzzt-bzzt-104-bzzt-106-107-bzzt-109-110-bzzt-112-bzzt-bzzt-115-116-bzzt-118-119-bzzt-121-122-bzzt-124-125-bzzt-127-128-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-140-bzzt-142-bzzt-bzzt-145-146-bzzt-148-149-bzzt-151-152-bzzt-154-155-bzzt-157-158-bzzt-160-161-bzzt-bzzt-164-bzzt-166-167-bzzt-169-170-bzzt-172-bzzt-bzzt-175-176-bzzt-178-179-bzzt-181-182-bzzt-184-185-bzzt-187-188-bzzt-190-191-bzzt-bzzt-194-bzzt-196-197-bzzt-199-200-bzzt-202-bzzt-bzzt-205-206-bzzt-208-209-bzzt-211-212-bzzt-214-215-bzzt-217-218-bzzt-220-221-bzzt-bzzt-224-bzzt-226-227-bzzt-229-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-241-242-bzzt-244-245-bzzt-247-248-bzzt-250-251-bzzt-bzzt-254-bzzt-256-257-bzzt-259-260-bzzt-262-bzzt-bzzt-265-266-bzzt-268-269-bzzt-271-272-bzzt-274-275-bzzt-277-278-bzzt-280-281-bzzt-bzzt-284-bzzt-286-287-bzzt-289-290-bzzt-292-bzzt-bzzt-295-296-bzzt-298-299-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-400-401-bzzt-bzzt-404-bzzt-406-407-bzzt-409-410-bzzt-412-bzzt-bzzt-415-416-bzzt-418-419-bzzt-421-422-bzzt-424-425-bzzt-427-428-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-bzzt-440-bzzt-442-bzzt-bzzt-445-446-bzzt-448-449-bzzt-451-452-bzzt-454-455-bzzt-457-458-bzzt-460-461-bzzt-bzzt-464-bzzt-466-467-bzzt-469-470-bzzt-472-bzzt-bzzt-475-476-bzzt-478-479-bzzt-481-482-bzzt-484-485-bzzt-487-488-bzzt-490-491-bzzt-bzzt-494-bzzt-496-497-bzzt-499-500'

```

# Answer
> 0 votes
# Python3, 62

```
for i in range(501):print('bzzt'if'3'in str(i) or i%3<1 else i)

```

# Answer
> 0 votes
**VB.net (~100c)**

1)

```
Function t()
For c=0 To 500:t+=If(CStr(c).Contains("3")Or(c Mod 3)=0,"Bzzt",c)+" ":Next
End Function
Function t()

```

2) I'd forgotten about `Like` operator in vb.

```
Function t()
For c = 0To 500:t &=If(CStr(c)Like"*3*"Or(c Mod 3)=0,"Bzzt",c)&" ":Next
End Function

```

The result is *output* as the return value of the function.

> The numbers must be output, **but it doesn't matter how** (e.g., stdout, writing to a text file, etc.).

# Answer
> 0 votes
# Scala – 62

```
for(x<-1 to 501)println(if(x%3<1||(x+""toSet 51))"Bzzt"else x)

```

`toSet` is a nice shorthand for `contains`.

# Answer
> 0 votes
# Haskell - 73

```
b n|mod n 3<1||'3'`elem`show n="bzzt"|1<2=show n
main=print$map b[0..500]

```

# Answer
> 0 votes
## Racket 80

```
(for/list([i 501])(if(or(=(modulo i 3)0)(memv #\3(string->list(~a i))))'bzzt i))

```

# Answer
> 0 votes
# Pyth, 20

```
V501?N&%N3-`3`N"bzzt

```

Explanation:

```
V501            for N in range(501):
?               _ if _ else _
 N              print(N)
 &              _ and _
  %N3           N mod 3
  -`3`N         Assymetric difference of str(3) and str(N)
 "bzzt          "bzzt" (Final " is implicit)

```

Essentially, the test is the logical and of `N%3`, which is only 0, and thus interpreted as false iff `N` is divisible by 3, with

```
-`3`N

```

which is the empty list iff 3 is present in str(N). Setwise minus removes all appearances of characters in the second string from the first string.

If this and returns true, we print `N`, otherwise we print `"bzzt"`. Having `"bzzt"` in the else clause saves a character, because there is no need to end-quote the string.

# Answer
> 0 votes
## Clojure - 82 chars

Newbie solution: plain and simple. Golfed:

```
(dotimes[n 501](if(or(.contains(str n)"3")(= 0(mod n 3)))(println "bzzt")(prn n)))

```

Ungolfed:

```
(dotimes [n 501] (if (or (.contains (str n) "3") (= 0 (mod n 3)))
                  (println "bzzt")
                  (prn n)))

```

# Answer
> 0 votes
# Note: This answer is invalid, because Pyth is too new a language.

## Pyth, 20

```
V501?N&%N3-\3`N"bzzt

```

Explanation:

```
V501              for N in range(501):
    ?N                                print(N if
      &%N3                                       N % 3 and
      -\3`N                                      "3" - repr(N)
     "bzzt                                    else "bzzt")

```

Try it here.

# Answer
> 0 votes
# Swift 2.0, 71

```
(0...500).map{print($0%3<1||"\($0)".utf8.contains(51) ?"bzzt":"\($0)")}

```

# Answer
> 0 votes
# Swift 3, 62

`(0...500).map{print($0%3<1||"\($0)".contains("3") ?"bzzt":$0)}`

or

`for n in 0...500{print(n%3<1||"\(n)".contains("3") ?"bzzt":n)}`

---
Tags: code-golf
---


title: One-dimensional map colouring

text:
# Question
Title: One-dimensional map colouring
It is a well-known fact that you can colour a two-dimensional map with four colours in such a way that two countries with a common border always have different colours. There have already been enough challenges on this topic.

However, the prerequisite for this is that there must be no enclaves, i.e. non-contiguous areas that must be coloured in the same colour (otherwise, in the worst case, you would always need as many colours as countries, because each one could have an enclave in every other one).

In this task there is only one dimension, so without enclaves, you would get by with two colours. But, alas, the world and this challenge allow enclaves.

**The task**: Colour a one-dimensional map with as few colours as possible, so that adjacent countries always have different colours, but enclaves have the same colour as the rest of the country. Of course, there can be more than one optimal solution, but output only one.

**Input**: A list of whatever, e.g. a character string in which a certain character stands for a country.

**Output**: The corresponding "coloured" list, e.g. the corresponding character string in which a certain character stands for a certain colour.

**Test data**:

```
abcdddeefghhhi x2x222xx2x222x
abcdddeefgahhi 12122211231221
abcdadcbaaaeb1 12321232111321
#Aa#Bb#Ccabc#  1231321243241
#Aa#Bb#CcabC#  1231321323231

```

**Test data for languages that do not support strings, but lists**:

```
[5,6,3,8,8,8,9,9,1,12,2,2,2,17]   [9,2,9,2,2,2,9,9,2,9,2,2,2,9]
[5,6,3,8,8,8,9,9,1,12,5,2,2,17]   [1,2,1,2,2,2,1,1,2,3,1,2,2,1]
[5,6,3,8,5,8,3,6,5,5,5,9,6,1]     [1,2,3,2,1,2,3,2,1,1,1,3,2,1]
[1,2,3,1,4,5,1,6,7,3,5,7,1]       [1,2,3,1,3,2,1,2,4,3,2,4,1]
[1,2,3,1,4,5,1,6,7,3,5,6,1]       [1,2,3,1,3,2,1,3,2,3,2,3,1]

```

# Answer
# JavaScript (ES6), 121 bytes

Expects an array of characters, returns a string of digits.

```
f=(a,x)=>(g=([v,...b],m,p,o)=>v?(h=j=>j?h(j-1)||!(m[v]-j)&&p==v|j^m[p]&&g(b,{...m,[v]:j},v,[o]+j):0)(x):o)(a,g)||f(a,-~x)

```

Try it online!

### Commented

```
f = (                 // f is a recursive function taking:
  a,                  //   a[] = input array
  x                   //   x = maximum color index, initially undefined
) =>                  //
( g = (               // g is a recursive function taking:
    [v,               //   v = next value from a[]
        ...b],        //   b[] = remaining values
    m, p, o           //   m = mapping, p = previous value, o = output
  ) =>                //
  v ?                 // if v is defined:
    ( h =             //   h is yet another recursive function taking:
      j =>            //     j = color index candidate
      j ?             //   if j is not 0:
        h(j - 1) ||   //     try a recursive call with j - 1
        !(            //     if either m[v] is undefined
          m[v] - j    //     or m[v] is equal to j
        ) &&          //     and
        p == v |      //     either p = v
        j ^ m[p] &&   //     or j is not equal to m[p],
        g(            //     then do a recursive call to g:
          b,          //       pass the remaining values
          { ...m,     //       build a new object m' with all properties
            [v]: j }, //       of m and a new property m'[v] = j
          v,          //       set the previous value to v
          [o] + j     //       append j to the output
        )             //     end of recursive call
      :               //   else:
        0             //     failure: return 0
    )(x)              //   initial call to h with j = x
  :                   // else:
    o                 //   success: return the output
)(a, g) ||            // initial call to g, using m = g
f(a, -~x)             // if it failed, try again with one more color

```
> 3 votes

# Answer
# Charcoal, ~~33~~ 30 bytes

```
⊞υθＦυＦιＦΦ⁻ικ¬№⁺ι⮌ι⁺κλ⊞υ⪫⪪ιλκ⊟υ

```

Try it online! Link is to verbose version of code. Exponentially slow, as it generates multiple copies of all legal colourings and then outputs one with the fewest colours, so test case is pretty short. Uses the input character set as the colour characters. Explanation:

```
⊞υθＦυ

```

Start a breadth-first search for legal colourings.

```
ＦιＦΦ⁻ικ¬№⁺ι⮌ι⁺κλ

```

Loop over all possible parings of countries that could be coloured with the same colour.

```
⊞υ⪫⪪ιλκ

```

Generate the resulting colouring and add it to the search list.

```
⊟υ

```

Output one of the colourings that uses the fewest colours.

~~41~~ 38 bytes for a somewhat faster version that saves fewer duplicate colourings and can therefore handle one of the provided test cases:

```
⊞υθＦυＦιＦＥΦι›‹κλ№⁺ι⮌ι⁺κλ⪫⪪ιλκＦ¬№υλ⊞υλ⊟υ

```

Try it online! Link is to verbose version of code.
> 2 votes

# Answer
# Python, 111 bytes

```
f=lambda s:min([f(s.replace(x,y))for x in s for y in s if y<x<x+y not in s+s[::-1]]+[s],key=lambda t:len({*t}))

```

Attempt This Online!

Takes and returns a string.

## How?

Recursively replaces one colour a time for a non neighbouring one. Of all possible such replacements returns the best one as found recursively.

This would be very slow, so in the footer I inject the Python standard lib magic memoiser which doesn't change the outcome of a function but very much its speed.
> 2 votes

# Answer
# Python3, 318 bytes:

```
def f(s):
 q,F,T=[(s,'','',{})],0,''
 while q:
  s,S,L,d=q.pop(0)
  if''==s:
   if(T==''or len({*S})<F):F,T=len({*S}),S
   continue
  K=[*{*sum(d.values(),[])}]
  for i in d.get(s[0],K+[max(K+[0])+1]):
   if(''==S or S[-1]!=str(i)or s[0]==L)and(T==''or len({*S})<F):q=[(s[1:],S+str(i),s[0],{**d,s[0]:[i]})]+q
 return T

```

Try it online!
> 1 votes

# Answer
# Haskell, 138 bytes

```
import Data.List
f x|b<-nub x,y<-[elemIndices j b!!0|j<-x]=[v|n<-[1..],t<-mapM id$[1..n]<$b,v<-[map(t!!)y],z y==z v]!!0
z=map length.group

```

Attempt This Online!
> 1 votes

# Answer
# Jelly, ~~20~~ 19 bytes

```
QŒcw@ÐḟŒBy€)Ẏ
WÇƬẎṪ

```

Try it online!

A pair of links called as a monad and taking a string and returning a string. Uses a subset of the input characters for output. In brief this iteratively finds all possible merges of characters in a breadth-first search. The last remaining group of possibilities will be the ones with most characters merged. Slow for the first two test cases as written so TIO link uses slightly shorter versions.

## Explanation

```
QŒcw@Ðḟ;U$y€)Ẏ  # Helper link: takes a list of strings and for each one generates a list of strings with one pair of valid characters merged before joining these outer lists
            )   # For each string:
Q               # - Uniquify
 Œc             # - Combinations length 2
   w@Ðḟ         # - Filter out those which are a substring of:
       ŒB       #   - The string palindomised
          y€    # - Use each of the remaining combinations to ‘translate’ the string
             Ẏ  # Join outer lists

WÇƬẎṪ           # Main link: takes a string and returns the simplified string
W               # Wrap in a list
 ÇƬ             # Call the helper link until no further changes, collecting up intermediates
   Ẏ            # Join outer lists
    Ṫ           # Tail

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Perl 5, 150 bytes

```
sub{$_=pop;sub L{pop=~s/(.)\1*/X.length$&/egr}@c=/./g;for$n(1..@c){for$t(0..$n**@c){$c{$_}=$t%$n,$t/=$n for@c;L($s=s/./$c{$&}/gr)eq L($_)&&return$s}}}

```

Try it online!
> 0 votes

# Answer
# Scala

I was trying to rewrite @Ajax1234's Python answer in scala.

**But the scala code fails on some cases. Any help would be appreciated.**

Try it online!

```
object Main {
  def f(s: String): String = {
    var queue = List((s, "", ' ', Map[Char, List[Int]]()))
    var F = 0
    var T = ""

    while (queue.nonEmpty) {
      val (currentString, prevS, lastChar, dictionary) = queue.head
      queue = queue.tail

      if (currentString.isEmpty) {
        if (T.isEmpty || prevS.toSet.size < F) {
          F = prevS.toSet.size
          T = prevS
        }
      } else {
        val K = dictionary.values.flatten.toSet.toList
        for (i <- dictionary.getOrElse(currentString.head, K :+ (if (K.isEmpty) 0 else K.max + 1))) {
          if (prevS.isEmpty || prevS.last.toString != i.toString || currentString.head == lastChar) {
            if (T.isEmpty || prevS.toSet.size < F) {
              queue = (currentString.tail, prevS + i.toString, currentString.head, dictionary.updated(currentString.head, dictionary.getOrElse(currentString.head, List()) :+ i)) :: queue
            }
          }
        }
      }
    }

    T.split("").map(_.toInt+1).map(_.toString).mkString
  }

  def main(args: Array[String]): Unit = {
    println(f("abcdddeefghhhi"))
    //println(f("abcdddeefgahhi"))
    //println(f("abcdadcbaaaeb1"))
    println(f("#Aa#Bb#Ccabc#"))
    //println(f("#Aa#Bb#CcabC#"))
  }
}

```
> 0 votes

---
Tags: code-golf, string, array
---


title: A "cheating" quine

text:
# Question
Title: A "cheating" quine
Long-time lurker, first-time poster. So here goes.

In the Wikipedia page for quine, it says that "a quine is considered to be 'cheating' if it looks at its own source code." Your task is to make one of these "cheating quines" that reads its own source code.

This is , so the shortest code in bytes - *in each language* \- wins. This means that a 5-byte Pyth script would not beat a 21-byte Python script - but a 15-byte Python script would.

You must use file I/O to read the source code, so the following JavaScript code, taken from the official Wikipedia page, is invalid:

```
function a() {
    document.write(a, "a()");
}
a()

```

It must access the source code of the file *on disk*.

**You are not allowed to specify the file name. You must make it detect the filename itself.**

Everyone clear? Go!

# Answer
# Zsh, 4 bytes

```
<$0

```

The Z shell has feline functionalities built in. The fourth character is a linefeed.

Try it online!

The code does not depend in any way on the file name; it works even if the file name contains special character, such as spaces or newlines.

### Test run

```
$ cat "my quine.sh"
<$0
$ zsh "my quine.sh"
<$0
$ diff -s <(zsh "my quine.sh") <(cat "my quine.sh")
Files /dev/fd/63 and /dev/fd/62 are identical

```
> 66 votes

# Answer
# Bash, 6 bytes

```
cat $0

```

Basically.
> 49 votes

# Answer
# UNIX executable loader, 10 bytes

```
#!/bin/cat

```

If you don't care about spam on standard error, you can make it one byte shorter:

```
#!/bin/dd

```
> 38 votes

# Answer
# C, 52

```
s[99];main(){read(open(__FILE__,0),s,99);printf(s);}

```

Of course, this reads the source code and not the compiled program - I assume that's within spec.
> 25 votes

# Answer
# Vyxal 2.4.0, 50 bytes

```
`\");VY_print(chr(96)+code.split('\n')[3][15:-4])#

```

Vyxal doesn't have a way to read files, but in v2.4.0 and prior, there was an ACE exploit that allowed for arbitrary python to be executed.

---

### The ACE:

Vyxal is a transpiled language, meaning that every command in a program is converted to some python code, and then all of the python code is combined together and executed.

When pushing a string, all that was done to the string in transpilation was changing `"` to `\\\"`, then appending it to the stack. This meant that a string `\"); #` would become `\\");#`. On its own, this means nothing, but when considered in the transpiled code, it is much more useful.

When viewing the transpiled code (which you can do for any Vyxal program using the `c` flag), you can see that the snippet ``\\"); #` is transpiled to the following python code:

```
stack.append("\\"); #\n")

```

Instead of pushing the string that we told it to, it simply pushed `\`, followed by a comment. In theory, we could put any python code between the `;` and the `#`, which is what we do in this program.

---

### The program:

In this program, the payload (the python code that we actually care about) is the following:

```
VY_print(chr(96)+code.split('\n')[3][15:-4])

```

This has several parts to it, so lets pick it apart bit by bit.

`VY_print` is the printing function that is defined internally in Vyxal. I used this function instead of `print` because it disables the implicit output that Vyxal normally has. This prints the final string, which will hopefully be the same as the program.

When the program is transpiled, the transpiled code is saved in the `code` variable. This variable is used in the program to read the source code, which makes this a cheating quine.

However, the `code` variable also contains a header that initializes a few variables, such as the stack. To combat this, we `split` the code on newlines and get only the fourth line, which is where our code is.

Unfortunately, this line also has the `stack.append...`, and the comment at the end, neither of which are part of our quine. Because of this, we need to take only the 16th through 5th-to-last characters in the string, which we do with `[15:-4]`.

Finally, our code has a backtick at the beginning to start the string, so we add one to the beginning of the output with `chr(96)`, since the ASCII value of ``` is 96.
> 23 votes

# Answer
## Perl, 15 bytes

```
open 0;print<0>

```

Saved 3 bytes thanks to @ThisSuitIsBlackNot!
> 14 votes

# Answer
# PHP, 21 Bytes

```
<?=file(__FILE__)[0];

```

`file` reads a file line by line into an array and the file only has one line. This saves a byte in comparison to `readfile(__FILE__)`.
> 13 votes

# Answer
# Perl 6, 20 bytes

```
print slurp $?FILE

```

I haven't worked with Perl 6 very long so I'm not sure if there are any tricks to make this shorter.
> 13 votes

# Answer
# Python 2, 32 bytes

There's a newline at the end of the file.

```
print open(__file__).readline()

```

# Python 3, 33 bytes

There's a newline at the end of the file.

```
print(open(__file__).readline())

```

Thanks to feersum for catching a problem and supplying `__file__`, Loovjo for a new approach to the Python 2 solution that saved 17 bytes, and Skyler for a solution that saved yet another byte and worked in both Python 2 and 3 (pending `print` being a function in Python 3)!

Doc link for `readline`
> 12 votes

# Answer
# osascript (AppleScript from the command line), ~~40~~ ~~33~~ 32 bytes

```
(read path to me)'s paragraph 1

```

Executing on a file called a with `osascript a`.

Gets the first paragraph (line) of the file and prints it to STDOUT with a trailing newline, therefore the newline in the code.
> 12 votes

# Answer
# Python 2.7, 30 bytes

```
print open(__file__).read(29)

```

Edit: Just to be clear, the code above is supposed to have a newline at the end as the 30th byte. I'm not familiar with markdown enough to figure out how to display it in the code block.

I'm using the same trick here as the one in my C submission. This reads the whole source file excluding the trailing newline to account for the additional newline which `print` will append to the output.
> 12 votes

# Answer
# Batch, ~~9~~ 8 Bytes

```
@type %0

```

Saved a byte thanks to @Joshua
> 11 votes

# Answer
# AutoIt, 34 bytes

Outputs itself to the clipboard:

```
ClipPut(FileRead(@ScriptFullPath))

```
> 9 votes

# Answer
# Ruby, 14

```
$>.<<IO.read$0

```
> 9 votes

# Answer
# Go, ~~111~~ 105 bytes

```
package main
import("io"
."os"
."runtime")
func main(){_,p,_,_:=Caller(0)
f,_:=Open(p)
io.Copy(Stdout,f)}

```

My first code-golf in Go – just a few tricks you can use here I guess.
> 8 votes

# Answer
# C, 49 bytes

```
s[];main(){read(open(__FILE__,0),s,48);puts(s);}

```

Edit: To clarify, the 49th byte is a newline.

This reads the source code minus the newline at the end to account for the newline which `puts` will append to the end of the output.
> 7 votes

# Answer
# PowerShell, 39 36 31 25 Bytes

About as tight as I can get it:

`gc $MyInvocation.MyCommand.Path | oh`

Backed by popular demand this has been changed to:

```
gc $PSCommandPath|echo -n

```

prints to host shell current standard output.
> 7 votes

# Answer
## C, 31 bytes

```
main(){system("cat "__FILE__);}

```

The bash solution is so short, so why not base a C solution on it?
> 7 votes

# Answer
# Ruby, 15 bytes

```
$><<IO.read($0)

```

Source: https://stackoverflow.com/questions/2474861/shortest-ruby-quine
> 5 votes

# Answer
# Pyth, 25 bytes

```
$import sys$h'e$sys.argv

```

This reads its file name. Essentially, it looks up argv, opens the file corresponding to its last argument, and prints its first line.
> 5 votes

# Answer
# Mathematica, 16 bytes

```
FilePrint@$Input

```

Run it in script mode.
> 5 votes

# Answer
## \>\<\>, 13 Bytes

```
0:0go:c=?;1+!

```

Tested both on the online and offline interpreters. The `g` command is the closest to being able to read from the source file and if it doesn't count for the purpose of this challenge I'll mark my entry non-competing; I do believe it normally considered "cheating" for quines.

Try it online.
> 5 votes

# Answer
# Haskell, 63 bytes

For science!

```
import System.Environment
main=getProgName>>=readFile>>=putStr

```
> 5 votes

# Answer
# Haskell, 49 bytes

```
{-#LANGUAGE CPP#-}main=putStr=<<readFile __FILE__

```

Try it online!

(GHC) Haskell has an extension to use the C preprocessor (commonly used for portability between versions and architectures.) Hopefully self-explanatory.
> 5 votes

# Answer
# Rust, 45 bytes

```
fn main(){print!("{}",include_str!(file!()))}

```

Try it online!

The file macro expands to the file it's invoked in's file path, the include\_str macro expands to a string literal containing the contents of the file at the specified path, and the print macro prints.
> 5 votes

# Answer
# Go, 133 Bytes

> Everyone clear? Go!

```
package main
import("fmt"
"io/ioutil"
"runtime")
func main(){_,f,_,_:=runtime.Caller(0)
s,_:=ioutil.ReadFile(f)
fmt.Print(string(s))}

```
> 4 votes

# Answer
# , 2 chars / 6 bytes

```
ℹ⬮

```

`Try it here (Firefox only).`

The ℹ function both returns and pushes to the stack the source code. There is automatic outputting, so the contents of the stack will be outputted. Therefore, the source code will be outputted.
> 4 votes

# Answer
# HTML with JavaScript, 115 bytes (doesn't really count)

```
<!DOCTYPE html><html><title>x</title><script>alert(new XMLSerializer().serializeToString(document))</script></html>

```

Does this count? I don't mind, it was fun :)

Technically it doesn't open a file. It's also a well-formed HTML5 document. The XMLSerializer was the only tool which also returned the DOCTYPE portion, but is non-standard. Still, it works on chrome and firefox, and I bet other browsers.

And as a bonus:

# JavaScript, 41 bytes

```
alert(document.currentScript.textContent)

```
> 4 votes

# Answer
# Node.js, ~~66~~ 63 bytes

```
p=process;p.stdout.write(require('fs').readFileSync(p.argv[1]))

```

Doesn't use `console.log`, which appends a newline.
> 4 votes

# Answer
# Java 8, ~~133~~ 125 Bytes (or ~~150~~ 142 slightly cleaner)

Based on @VoteToClose's answer but choosing Files.copy and thus avoiding the intermediate String creation needed to call System.out:

```
import java.nio.file.*;interface A{static void main(String[]a) throws Exception{Files.copy(Paths.get(A.class.getName()+".java"),System.out);}}

```

or hard-coding the class-name even more:

```
import java.nio.file.*;interface A{static void main(String[] a)throws Exception{Files.copy(Paths.get("A.java"),System.out);}}

```

Cleaned up:

```
import java.nio.file.*;

class A {
    public static void main(String[] a) throws Exception {
        Files.copy(Paths.get("A.java"), System.out);
    }
}

```
> 4 votes

# Answer
# F#, 54 Bytes

```
printf"%s"(System.IO.File.ReadAllText __SOURCE_FILE__)

```

Usage:

```
fsi --exec a.fsx

```
> 3 votes

# Answer
# Perl 5, 15 13 bytes

Credit to the Bash solution for inspiring this:

```
print`cat $0`

```

EDIT: Don't need the semi-colon or first space.
> 3 votes

# Answer
# Scala(2.10), 101 bytes

```
import scala.reflect.io.File;object A extends App{print(File(getClass.getName.head+".scala").slurp)}

```

Similar to the Java and C# answers. The only "interesting" parts here are the `.head` to drop the `$` from the class name and the `slurp` method (which I'd never seen before) to read the file in as a String.
> 3 votes

# Answer
# Python 2, 27 bytes

```
print next(open(__file__))

```

# Python 3, 28 bytes

```
print(next(open(__file__)))

```

Byte count includes new line.
> 3 votes

# Answer
# Raku, 17 bytes

```
$?LANG.orig.print

```

Try it online!

This relies on some compiler internals.
> 3 votes

# Answer
## Java - ~~214~~ 194

```
import java.io.*;class Q{Q(){try{System.out.print(new BufferedReader(new FileReader(getClass().getName()+".java")).readLine());}catch(Exception e){}}public static void main(String[]a){new Q();}}

```

Reduced a lot with using @VoteToClose method of finding the filename for java.

Readable version:

```
import java.io.*;

class Q {
        Q() {
                try {
                        System.out.print(new BufferedReader(new FileReader(getClass().getName()+".java")).readLine());
                } catch(Exception e) {}
        }
        public static void main(String[] a) {
                new Q();
        }
}

```

NOTE: The readable version doesn't actually work, it just reads the first line. Just to show what the code is doing
> 2 votes

# Answer
# C#, 153 bytes

`class A{static void Main(){new A();}A([System.Runtime.CompilerServices.CallerFilePath]string s=""){System.Console.Write(System.IO.File.ReadAllText(s));}}`

Readable version:

```
class A
{
    static void Main()
    {
        new A();
    }

    A([System.Runtime.CompilerServices.CallerFilePath] string s = "")
    {
        System.Console.Write(System.IO.File.ReadAllText(s));
    }
}

```

Thanks to @Johnbot for the idea to use `CallerFilePathAttribute`, which avoids any kind of name hardcoding!
> 2 votes

# Answer
# JavaScript (node.js), 65

```
with(process)require('fs').createReadStream(argv[1]).pipe(stdout)

```
> 2 votes

# Answer
# Perl, 9 bytes

```
#!/bin/dd

```

Perl allows you to change the parser while the file's being read. One thing you can do is to change the program that parses the file entirely via the use of `#!` on the first line; this feature was intended to allow the use of Perl to fix a system on which shebangs didn't work correctly. `dd` with no parameters copies standard input to standard output (followed by some statistics on standard error which shouldn't matter), thus is a suitable program to use for a cheating-quine (because Perl reloads the file from disk to give to `dd`.)
> 2 votes

# Answer
# Python 3, ~~28~~ ~~35~~ ~~32~~ ~~29~~ 21 bytes

```
lambda:open(__file__)

```

Try it online! File objects are iterable, and output in a singleton iterable is allowed.

```
lambda:open(__file__)  # full program
lambda:                # define function taking no arguments which returns...
       open(        )  # file at path...
            __file__   # current script path

```
> 2 votes

# Answer
# Javascript (Babel Node), ~~74~~ 72 bytes

Thanks to Kyle Slattery for posting his answer about `__filename`.

Also, thanks to Makonede for saving 2 bytes and making my answer correct.

```
require('fs').readFile(__filename,'utf8',(e,d)=>process.stdout.write(d))

```
> 2 votes

# Answer
# Python, 22 bytes

```
input(*open(__file__))
```

Attempt This Online!
> 2 votes

# Answer
# Shell + `xargs`, 27 bytes

```
xargs -0a/proc/self/cmdline
```

Attempt This Online!

On Linux, the file `/proc/self/cmdline` contains the arguments provided to the current command, including the command's name itself, separated by null bytes. In this case, the command is `xargs`, and the argument is `-0a/proc/self/cmdline`.

`xargs -0` splits its input on null bytes, and passes them to another command. When a second command isn't specified, it defaults to `echo`. The `-a` option makes `xargs` read from a file instead of STDIN.

I'm not 100% sure if this is valid, because strictly speaking the source code of the shell script itself isn't in `/proc/self/cmdline`, but it certainly isn't a proper quine, so I think it morally ought to be allowed.
> 2 votes

# Answer
# \*nix interpreter directive, 10 bytes

```
#!/bin/cat

```

Shebang (`#!`) abuse. The shebang causes the "code" to be "interpreted" using `cat`, which prints out the content of the file.

EDIT: Someone else came up with it before me.
> 2 votes

# Answer
# JavaScript (Node.js), 56 bytes

```
with(require('fs'))writeSync(1,readFileSync(__filename))

```

Try it online!
> 2 votes

# Answer
## VBScript, 67 bytes

```
CreateObject("WScript.Shell").Run "cmd /K type "&Wscript.ScriptName

```
> 1 votes

# Answer
# C (Win32), 36 bytes

```
main(){CopyFileA(__FILE__,"CON",0);}

```

CopyFile makes the challenge easier in Win32 than in POSIX or ISO C, that's for sure. You however need to call the compiler with stdcall as its default calling convention.
> 1 votes

# Answer
## Aubergine, 22 bytes, noncompeting

The tab character at the end signals end of file, and the interpreters all crash without it. It's cool that this challenge showed up on my radar this week since I just finished golfing this for the wiki.

```
-a1+a1=oA=Bi-BA:bB=ia

```

I'll explain how it works later. It does not use file I/O but it very much does read its listing, and it is definitely cheating.
> 1 votes

# Answer
# Groovy 92 bytes

Shorter than the other groovy answer, in addition to being filename agnostic.

```
print new Error().stackTrace*.fileName.collect{it?new File(it):null}.find{it?.exists()}.text

```

No newline at end of file.
> 1 votes

# Answer
# Vitsy, 4 bytes

This language feature is newer than this question, but not made for this question.

```
iG`Z

i     Grab input. Since there is no input, it pushes -1 to the stack.
 G    Get the class name of the referenced class. -1 refers to the current class.
  `   Read the file under the name of the stack's contents and push all of it to the stack.
   Z  Output everything in the stack.
```

As of November 24, class commands allow for referencing other programs accessible by disk, or 'classes'. Normally, it'd be used something like this:

```
00k

;u someothervitsyfile
```

Where I execute the 0th line (the first line) of the 0th index of the uses list ('someothervitsyfile'). I can get its name with `G` like so:

```
0GZ

;u someothervitsyfile
```

And, if I have the name, I can get its contents like so:

```
0G`Z

;u someothervitsyfile
```

But the special cases of this are `-2` and `-1`, where `-2` references the superclass (as defined by ;e) and `-1` references the current class.

So, to get the name of the current class, I use `-1`, get its name, and, with its name being the only thing in the stack, I pull its contents with \`.

Very fancy.

You cannot try this online, as it has been disabled to prevent reading server files.
> 1 votes

# Answer
# Mouse-2002, 8 bytes

Expects to be put in a file called `MOUSE.001`. (Files with the names MOUSE.nnn are the only files Mouse knows how to perform I/O on. I didn't write the interpreter.)

If the EOF char at the end of the file, which is printed to the terminal, crashes your terminal, it's not my fault and I consider this a feature, not a bug.

```
(1 &F!')

```

Additionally, technically this is undefined behaviour (though most of Mouse is *undefined* except in practice) because it promises that the file's length is at least as long as the `while(true)`. If this hangs your system because it's a loop, save your work, run `git commit && git push`, and don't say I didn't warn you.
> 1 votes

# Answer
## Lua, 31 Bytes

```
print(io.open(arg[1]):read'*a')

```

The Arg table contains the following in lua.

{Filename, Command Line Argument1, Command Line Argument 2, ...}
> 1 votes

# Answer
## SmileBASIC, ~~69~~ 68 bytes

```
LOAD"PRG1:"+PRGNAME$(0),FALSE
PRGEDIT 1
FOR I=0 TO 3?PRGGET$();
NEXT

```

Load the program into slot 0 (the default slot), and run!

### Explanation

```
LOAD"PRG1:"+PRGNAME$(0),FALSE  load the source code into program slot 1
PRGEDIT 1                      open program slot 1 for editing
FOR I=0 TO 3                   loop 3 times { (no newline here)
?PRGGET$();                      print line, supressing extra newline
NEXT                           }

```

The `,FALSE` on `LOAD` is required to supress a confirmation dialogue. I wasn't sure if this was required so I threw it in anyways (seems like it should be).

The extra setup of loading the source code into the neighbouring slot is required as SmileBASIC can't read or write from the currently loaded source code for some reason (it clearly reads it to load it into the other slot, but whatever).

As the output format isn't specified, you might be able to get away with just using the first line and claiming the output is found on slot one (which is one tap away) for 29 bytes.
> 1 votes

# Answer
# SmileBASIC, 26 bytes (newline at end)

Saw @redstarcoder 's answer and wanted to out-golf it. I'm not sorry.

```
?LOAD("TXT:"+PRGNAME$());

```

This exploits the fact that PRG is just a resource subtype of TXT (it's literally the same file format with a different icon) and loads the source file into a string. It's then simply printed.

I removed unneeded whitespace wherever the parser would let me, and put it all on one line for show. `?` is just a shorthand for `PRINT`. The `;` at the end ensures the `PRINT` doesn't add an extra newline. This one also doesn't disable the load dialog popup, but whatever.

If you remove the newline using a program that deletes the last character (since SB automatically adds a LF whenever you save through the editor) you can also remove the semicolon, bringing the answer down to 24 bytes. I didn't do this though, because I consider it kinda underhanded.
> 1 votes

# Answer
# Node.js, 63 bytes

Uses the `__filename` global to obtain its file path as opposed to `process.argv[1]`, which can be flawed:

```
require('fs').createReadStream(__filename).pipe(process.stdout)

```
> 1 votes

# Answer
# GW-BASIC / Applesoft BASIC / IBM BASIC / Commodore BASIC, 6 bytes

```
1 LIST

```

Pretty simple. No matter where you loaded the program from or how much is in it, it will *always* print everything in the program buffer, including itself.
> 1 votes

# Answer
# , 44 bytes

```
cat(scan(sub(".*=","",commandArgs()[4]),""))

```

Prints to `stderr` as well. If that's not allowed this works for 46 bytes:

```
cat(readLines(sub(".*=","",commandArgs()[4])))

```

Run these from the command line using `Rscript`.
> 1 votes

# Answer
## Burlesque - 25 bytes

***With-IO***

```
,%____FILE?rfQ

```

**Disclaimer**: I've just added `____FILE` because I/O support is still very rudimentary and there was no way of detecting the name of the file. Otherwise this would have been impossible. I/O built-ins aren't available in default builds but can be activated by using `ghc ... -DHAVE_IO_UNSAFE ...`.

***Without-IO:***

```
,#Q2 SH ~- ",#Q" \/ .+ sh

```

*Explanation:* Burlesque is nasty.

**Actual explanation**: `#Q` looks at its own source code and pushes the code that is left in the "execution pipeline" onto the stack. In otherwords: `#Q` pushes all the code that is to the right to the stack. However, `#Q` does not look at ALL the source code just what is left in the "execution pipeline of the current execution context":

```
blsq ) 2ro{#Qj}m[
{1 {j} 2 {j}}

```

The `#Q` here is only able to see the `j` due to the execution context.

On a side-note: Burlesque has other modifiers that allow you to modify code such as for example `#q` which allows you to overwrite the remaining code in the execution pipeline of the current execution context:

```
blsq ) 3 4 {?*}#q?+
12

```

`{?*}#q` overwrites the `?+` with `?*`. With `#J` we can inject/delay a piece of code by appending it to the execution pipeline:

```
blsq ) 3 4 {J?*}#J?+
49

```

The `#J` here appends `J?*` to the `?+`.
> 1 votes

# Answer
# Racket, 63 bytes

```
#lang racket
(display(file->string(find-system-path'run-file)))

```

Try it online!

Pretty straightforward - just finds the current file, reads it, and prints it back out.
> 1 votes

# Answer
# Knight (C/AST, \*nix), ~~50~~ 49 bytes

`\t` represents a raw tab.

```
O`"cat `tr '\0' '`\t`'</proc/$PPID/cmdline|cut -f3`"
```

Doesn't work in the golfed interpreter for some reason, so no TIO.

Abuses the shell command built-in `<backtick>` and the standardized command line args for Knight, which is `knight -f file.kn`

`/proc/$PPID/cmdline` obtains the `\0`-separated command line arguments of the parent process (which is the knight interpreter itself), `tr '\0' '\t'` replaces `\0` with `\t`, and `cut -f3` takes the third tab-delimited argument. Then, we just `cat` the file and output the result.

A similar result can be done using the `-e` flag, but that doesn't read the source file from the disk (unless you count the `cmdline` file)

-1 byte using a raw tab over `\t`
> 1 votes

# Answer
# PARI/GP, 18 bytes

```
print1(readstr[1])
```

Attempt This Online!

The function `readstr` reads every lines as strings form a file. When `readstr` takes no input, it reads the source file.
> 1 votes

# Answer
# C (clang), 47 (46?) bytes

```
main(s){write(!!read(open(__FILE__,0),&s,47));}

```

Try it online!

This **will** corrupt the stack and segfault, but not before printing the correct output.

If executing in a terminal we can do 46 bytes printing to `stdin`:

```
main(s){write(!read(open(__FILE__,0),&s,46));}

```
> 1 votes

# Answer
# Bash, 18 Bytes

```
history|tail -c18

```

**Note:** *Technically* this is not allowed because it gets history from memory, and not from disk.

## Bytes:

```
echo 'history|tail -c18' > quine
wc -c quine
18 quine

```

18 bytes (including the newline)

## Explanation:

`history` gets the bash history from memory and `tail` grabs the last 18 characters. This is a more proper quine than `cat $0` and `#!/bin/cat` because it includes the newline.

`echo "$BASH_COMMAND"` can be used to do the same thing for an extra 1 character.
> 1 votes

# Answer
## Tcl, 37 bytes

```
chan copy [open [info script]] stdout

```

The older, more self explanatory version (43 bytes):

```
puts -nonewline [read [open [info script]]]

```
> 0 votes

# Answer
# Lua, 59 characters

```
print(io.open(debug.getinfo(1,'S').source:sub(2)):read'*a')

```

Sample run:

```
bash-4.3$ lua quine.lua
print(io.open(debug.getinfo(1,'S').source:sub(2)):read'*a')

```
> 0 votes

# Answer
# C++, 93 bytes

```
#include <iostream>
#include <fstream>
main(){std::fstream f(__FILE__);std::cout<<f.rdbuf();}

```

I wanted to do a “pure” C++ version…and I have to say that it doesn't do too badly: it's down to 54 bytes if I can do without including the headers.
> 0 votes

# Answer
# A Groovy ~~103~~ 100 bytes!

<sub>Yes I know I'm evil</sub>

I stay in line with the other JVM answers (Java, Scala) to make this answer.

```
class X{static def main(String[]a){new X()}
def X(){print new File(getClass().name+'.groovy').text}}

```
> 0 votes

# Answer
# Emacs Lisp (93 Bytes)

```
:; emacs -Q -script $0; exit
(find-file (nth 2 command-line-args))
(message (buffer-string))

```

The first line calls the program in your normal shell and exits (to prevent the rest also being evaluated). `command-line-args` will be a list of three strings, `"emacs"`, `"-scriptload"` and the name of your file. `find-file` will open that file and make it the current buffer, so that `(message (buffer-string))` will write it to `stdout` as `-script` redirects messages there.

It should be noted, that `-Q` may not be necessary if your Emacs doesn't print other messages during startup, so that the first line could be shortened to `#!emacs -script`, shortening this to 81 bytes, but as it is highly unlikely that init and site-lisp files produce 0 messages at all, this cannot be assumed.
> 0 votes

# Answer
# APL, 8 bytes (non-competing)

APL does not use source files for single functions, rather a whole workspace (a machine-readable collection of token-representations) is saved and loaded, so I guess this is not allowed:

```
f
⎕CR'f'

```

(`⎕CR` is Character Representation) as the program reads its current definition in memory (the loaded workspace), which may have been modified from the source in the file.
> 0 votes

# Answer
# Matlab, 32 bytes

```
disp(fileread([mfilename,'.m']))

```
> 0 votes

# Answer
# stacked, 11 bytes

```
program put

```

Try it here!

Outputs the program stored in the `program` variable. Simple!
> 0 votes

# Answer
# HTML and Javascript, 88 Bytes

```
<head></head><body><svg onload="alert(document.documentElement.innerHTML)"></svg></body>

```

Had to add `<head></head><body></svg></body>` because that's what the browser outputs regardless of the original file.
> 0 votes

# Answer
# Lua, ~~32~~ 29 bytes

*3 bytes saved thanks to Jonathan Frech*

```
print(io.open(arg[0]):read())

```

### Try it online!

## How?

Lua uses the `arg` table to store it's arguments, the script name is always stored at index `0` of this table despite the fact there are no further arguments. After using this table to get the name of the file, printing it was as easy as opening the file and reading its content.
> 0 votes

# Answer
# Perl 6 / POSIX shell, 16 bytes

```
run 'cat',$?FILE

```

Try it online!
> 0 votes

# Answer
## CopyPasta Language, 32 bytes

But I think this is interesting enough to compete here.

```
CopyFile
TheFuckingCode
Pasta!

```

Copy the source code, display the clipboard, and stop the program.
> 0 votes

# Answer
# Jelly `u`, 26 bytes

```
“open(sys.argv[2])”ŒV

```

Try it online!

*Not* encoded in Jelly's SBCS, because 1. by meta consensus on flags Jelly `u` is a different language from Jelly (so it's not like I'm handicapping myself or anything), 2. I'm having some difficulties deciding on what form of output would be valid for an SBCS Jelly cheating quine, and 3. I'm having some difficulties actually executing on the methods I've considered (note that that's not even shorter than this).

```
“open(sys.argv[2])”ŒV    Evaluate "open(sys.argv[2])" as Python, within Jelly's interpreter.py.

      sys.argv           Get the arguments with which this was invoked on the command line.
                         (jelly fu [whatever the file's called])
              [2]        Take the third argument,
 open(           )       and open the file at that location.

                   ŒV    Iterate through the file object, obtaining a Jelly string of its contents.

```
> 0 votes

# Answer
# 05AB1E (legacy), ~~43~~ ~~39~~ ~~30~~ 27 bytes

```
’ƒÛ(__£Ø__('Ë‚').Òœv[1])’.E

```

Try it online! I would've used the rewrite, if only I knew Elixir… Output doesn't contain the program, however it is the program in a singleton iterable object (a file). This is allowed.

```
’ƒÛ(__£Ø__('Ë‚').Òœv[1])’.E  # full program
’ƒÛ(__£Ø__('Ë‚').Òœv[1])’    # push "open(__import__('sys').argv[1])"...
                         .E  # evaluated as Python code
                             # implicit output

============================================================================

open(__import__('sys').argv[1])  # full Python program
open(                         )  # return file at path...
                           [1]   # second...
     __import__('sys').argv      # command-line argument

```

**Note:** This program assumes no command-line flags or extra arguments are passed. If this assumption is not allowed, it can be fixed at a cost of 1 byte by adding a `-` before the `1`.
> 0 votes

# Answer
# Julia 1.0, ~~29~~ 26 bytes

```
print(readline(@__FILE__))

```

Try it online!
> 0 votes

# Answer
# Processing, 48 bytes

```
print(loadStrings(getClass().getName()+".pde"));

```
> 0 votes

# Answer
# Nim, 43 bytes

```
import os
echo readFile(paramStr(0)&".nim")

```
> 0 votes

# Answer
# JavaScript (Deno), ~~49~~ 47 bytes

```
console.log(Deno.readFileSync(import.meta.url))

```
> 0 votes

# Answer
# C, 31 bytes

```
main(){system("cat "__FILE__);}

```

Works perfectly...
> 0 votes

# Answer
# Nim, 39 bytes

```
stdout.write currentSourcePath.readFile

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, quine
---