r/codegolf • • Jul 03 '21

2 player tictactoe-hosting TCP server in 650 bytes of JavaScript

Thumbnail
github.com
14 Upvotes

r/codegolf • • Apr 09 '21

some code golf challenges ive done

14 Upvotes

1: palindrome checker

grep -Ei `rev`

2: ascii H made of H without H in source code

basenc --z85 -d<<<nfyCgnjVnUnfyC6

3: 99 bottles of beer

c,a='on the wall ',' bottles of beer 'for i=100,1,-1 do print(i,a,c,"\n",i,a,"\ntake one down, pass it around,",i-1,a,c)end

(or `` (empty) in vitsy)

4: convert to ordinal numbers

tail -c1|sed 's/[0456789]/th/g;s/1/st/g;s/3/rd/g;s/2/nd/g'

fails on 11-19 though

5: get screen dimensions

xdpyinfo|grep dim

6: generate a UUID

head /dev/random -c16|xxd -p

head /dev/urandom -c16|xxd -p

bc<<<'ibase=A;obase=G;'$RANDOM

head /dev/random -c8|xxd -p

7: tic tac toe

a=(- - - - - - - - -);while :;do read p;[ ${a[$p]} = - ]&&a[$p]=x;[ ${a[$((RANDOM%8))]} = - ]&&a[$p]=o;echo ${a[@]};case ${a[@]} in xxx******|***xxx***|******xxx|x**x**x**|*x**x**x*|**x**x**x|x***x***x|**x*x*x**)exit;;esac;done

r/codegolf • • Aug 14 '20

FizzBuzz in R

14 Upvotes

So I made a 66 character FizzBuzz in R the other week as my first code golf experiment. Feedback would be appreciated.

for(i in 1:100)write(max(i,paste0("Fizz"[!i%%3],"Buzz"[!i%%5])),1)

write(..., 1) was used instead of print() to fit with the rules of the FizzBuzz challenge on the code golf Stack Exchange here: https://codegolf.stackexchange.com/questions/58615/1-2-fizz-4-buzz?page=1&tab=votes#tab-top.


r/codegolf • • Aug 04 '19

cellular automata in 66 bytes of (pure) bash

14 Upvotes

i posted something similar a while ago on r/tinycode but had some success making it a bit shorter in the mean time, so i thought you guys may be interested too

code :

echo $2;for((;${#2}-i;)){ 0$20
p+=$[1&$1>>2#${_:i++:3}];};$0 $1 $p

usage :

./<script>.sh <rule> <strip of 0s and 1s> 2> /dev/null

examples :

~ ./automaton.sh 110 0000000000000001000000000000000 2> /dev/null | head -n 15 | tr 01 ' #'
               #
              ##
             ###
            ## #
           #####
          ##   #
         ###  ##
        ## # ###
       ####### #
      ##     ###
     ###    ## #
    ## #   #####
   #####  ##   #
  ##   # ###  ##
 ###  #### # ###
~ ./automaton.sh 30 0000000000000001000000000000000 2> /dev/null | head -n 15 | tr 01 ' #'
               #
              ###
             ##  #
            ## ####
           ##  #   #
          ## #### ###
         ##  #    #  #
        ## ####  ######
       ##  #   ###     #
      ## #### ##  #   ###
     ##  #    # #### ##  #
    ## ####  ## #    # ####
   ##  #   ###  ##  ## #   #
  ## #### ##  ### ###  ## ###
 ##  #    # ###   #  ###  #  #

r/codegolf • • Nov 01 '22

mandelbrot in python 322 bytes

13 Upvotes

made it a bit smaller it's now 319 bytes

import numba,numpy
from PIL import Image
@numba.njit
def m(w,h):
 i=100;o=numpy.full((h,w),0,numpy.bool8)
 for p in range(w*h):
  c=complex(p%w/(w-1)*3-2,p//w/(h-1)*3-1.5);z,n=c,0
  while abs(z)<=2and n<i:z=z*z+c;n+=1
  o[p//w][p%w]=n==i
 return o
Image.fromarray(m(2048,2048)).save('frctl.png',optimize=True)

r/codegolf • • Sep 23 '22

A quine in Befunge (no, it's not a specialized golfing language). 22 bytes

13 Upvotes

0:0g:84*-!#@_,1+037*-


r/codegolf • • Sep 19 '20

Rainy window effect with sound in 32 bytes

Thumbnail
pouet.net
13 Upvotes

r/codegolf • • Aug 27 '20

Brainfuck interpreter in 304 (or 312) bytes in C [First codegolf]

13 Upvotes
#define c case
#define b ;break;
#define a 3000
char z[a],f[a],*m=z,*p=f;main(o){read(0,p,a);while(*p){switch(*p){c 91:if(!(*m))for(o=1;o;o+=(*p==91))o-=(*(p++)==93)b c 93:if(*m)for(o=1;o;o+=(*p==93))o-=(*(p--)==91)b c'+':(*m)++b c'-':(*m)--b c'>':m++b c'<':m--b c'.':write(2,m,1)b c',':read(0,m,1)b}p++;}}

This was fun to work on and I’m surprised I got it working the first try (I was sure I was gonna trip up on nested loops), and I thought it would take longer than 10 minutes

I did realize that it expects standard input and therefore ‘,’ doesn’t work properly, but since I’m afk for a while, I hacked together one that should work but idk

#define c case
#define b ;break;
#define a 3000
char z[a],f[a],*m=z,*p=f;main(o){read(open("-"),p,a);while(*p){switch(*p){c 91:if(!(*m))for(o=1;o;o+=(*p==91))o-=(*(p++)==93)b c 93:if(*m)for(o=1;o;o+=(*p==93))o-=(*(p--)==91)b c'+':(*m)++b c'-':(*m)--b c'>':m++b c'<':m--b c'.':write(2,m,1)b c',':read(0,m,1)b}p++;}}

r/codegolf • • May 21 '19

Mandelbrot Set in 138 bytes of C

13 Upvotes

main(k){for(float x,y,u,v,z;++y<40;puts(""))for(x=-2;x+=.03,x<1;putchar(k+32))for(u=v=0,k=27;z=v*v,--k&&u*u+z<4;u=u*u-z+x)v=2*u*v+y/20-1;}

This is already golfed about as much as it'll go before affecting the character set used to output

I wrote this program for an email signature and business card.


r/codegolf • • Sep 09 '18

Interactive 3D Raycaster in 64 bytes (msdos)

13 Upvotes

Youtube

Youtube (Interactive)

Download/Comment

Since 2013, i tried a lot of approaches in tiny intros for MSDOS, with the exception of : 3D raycasting. As a computer scientist with specialisation "computer graphics" i simply was not interested enough in manually asm-coding a brute force raycaster, with regard to already existing, excellent examples like "Spongy" (128b, TBC, 2009) and "Wolf128" (128b, Baudsurfer, 2014). However, i coded several "2,5D" effects like "Lucy" (64b, 2014) and recently "Projektbeschreibung" (32b, DESIRE, 2018). So naturally, at some point i asked myself, what is the smallest 3D raycaster which is perceived as one, being centered, having decent textures and colors, and runs on all common systems (MSDOS, FreeDos, WinXP Dos, Dosbox) while being totally smooth at least on real hardware? The (my) answer is :

49 bytes

That "pure" version is included in the archive - as well as a *43* bytes version which lacks all the criteria above. Going lower in size means that you abandon the "3D" and "raycasting" at some point, leading to something like "Floorcast" (32b, DESiRE, 2018) ... Anyway! So what to do with the "rest" of space to reach the next 2^x category - 64b?

A) "INTO A NEW ERA"

The 64b intro shown at function 2018, it has 64 gray custom colors and softclipping, trying to somewhat imitate the look of "Spongy". I had a hard time to decide between this and a dithered 85(!) shades version that flickers a bit, but shows a full tunnel (no clip)

B) "INTERACTIVE / "Wolf64"

Mouse controlled, escapable version for both real systems (FreeDos, MSDOS, WinXP Dos) and DosBox, 64b and 63b, in the spirit of "Wolf128", just in half the size ;) Don't forget to load a mouse driver on real systems! Note : these haven't been fully optimized

C) "COLORS!"

Custom Color Palettes in Blueish, Purplelish, Greenish, Yellowish, Redish, inverted, whatever, you name it. All of them are 64b or smaller. Some of them look REALLY good, but may flicker noticeably or maybe too dark which is why the released intro itself comes with safe anticodercolors ;)

mov al,13h
int 10h
push 0x9FF6
mov dx,0x3c9
pop es
P out dx,al
out dx,al
out dx,al
cmp al,63
jz F
inc ax
F loop P
pop ds
X mov cl,-9
L mov bl,cl
mov ax,0xcccd
mul di
lea ax,[bx-80]
add al,dh
imul bl
xchg ax,dx   
imul bl
mov al,dh
xor al,ah
sub bl,[0x46c]
add al,4
and al,bl
test al,24
loopz L
or al,252
sub al,cl
stosb      
loop X

r/codegolf • • Jul 18 '18

Standing up for CodeGolf, abusing the language you love, to learn more about it

Thumbnail
itnext.io
13 Upvotes

r/codegolf • • Jan 05 '26

Brainf**k interpreter in JS in 326 bytes

12 Upvotes

This is very compact interpreter written in ES6, no obfuscation or any tools used. Code:

r=_=>{for(p=a.value,d=new Uint8Array(512),e=i=0,h=[];i<p.length;i++){k=d[e];({'>':_=>e++,'<':_=>e--,'+':_=>d[e]++,'-':_=>d[e]--,'[':_=>{if(!k)for(g=1;g;)g+=(p[++i]=='[')-(p[i]==']');else h.push(i)},']':_=>k&&(i=h.pop()-1),'.':_=>b.innerHTML+=String.fromCharCode(k)})[p[i]]?.()}}

EDIT 1/16/2025: Now 278 bytes

Demo at: http://eymenwinneryt.42web.io/bf.htm


r/codegolf • • Nov 22 '24

Prompt Golf - code golf but where you write the shortest AI prompt

12 Upvotes

I've created a variant to code golf called "prompt golf" (promptgolf.app) where the aim is to write the shortest prompt for an LLM to get a desired output.

It has a global leaderboard on each challenge so you can compete with others.

Would really appreciate if anyone here could check it out and provide any feedback!


r/codegolf • • Aug 19 '20

(C++, 105 byte) Printing all unsigned 64-bit Fibonacci numbers

12 Upvotes

This 105-byte C++ code prints all unsigned 64-bit Fibonacci numbers, separated by spaces.

(Note: It's predicated on size_t and unsigned long being 64 bits wide, so old hardware is not supported. When compiled with Clang++ trunk it produces a series starting with 0 while on gcc trunk it starts with 1. Also, 4 bytes could be shaved off on gcc by omitting the main function's return type, but this will trigger compilation warnings.)

https://godbolt.org/z/7KE4sW (demo)

#include<cstdio>
int main(){size_t n[]{0,1};for(int i;n[i]<~0ul>>1;printf("%lu ",n[i=!i]),n[!i]+=n[i]);}

Or a less fun but shorter one (89 bytes) compiled with Clang++:

https://godbolt.org/z/jcacx4 (demo)

#include<cstdio>
int main(){for(size_t a,b,c=1,d=95;--d;a=b+c,b=c,c=a)printf("%lu ",b);}

Or 87 bytes if we compile with GCC and init b to 0 and omit the return type:

https://godbolt.org/z/8sPPEK (demo):

#include<cstdio>
main(){for(size_t a,b=0,c=1,d=95;--d;a=b+c,b=c,c=a)printf("%lu ",b);}

r/codegolf • • Aug 06 '18

Data URI which plays happy birthday tune using javascript and fits in a tweet.

Thumbnail
twitter.com
12 Upvotes

r/codegolf • • Aug 02 '17

The shortest "FizzBuzz" I could make on codepen

Thumbnail
codepen.io
12 Upvotes

r/codegolf • • Jan 15 '25

I made world's smallest text editor

11 Upvotes

https://www.youtube.com/watch?v=FVpl8cGJO-g

#!/bin/python3
i=' if ';e=' elif z==';exec(f"""import curses as u,sys;s=u.initscr()
s.nodelay(1);u.noecho();u.raw();s.keypad(1);b=[];n='o.txt';x,y,r,c=[0]*4
if len(sys.argv)==2:n=sys.argv[1]\ntry:\n with open(sys.argv[1]) as f:
  w=f.read().split('\\n')[:-1]\n  for Y in w:\n   b.append([ord(c) for c in Y])
  r=len(b)-1;c=len(b[r])\nexcept:b.append([])\nwhile True:\n R,C=s.getmaxyx()
 s.move(0,0)\n{i}r<y:y=r\n{i}r>=y+R:y=r-R+1\n{i}c<x:x=c\n{i}c>=x+C:x=c-C+1
 for Y in range(R):\n  for X in range(C):\n   try:s.addch(Y,X,b[Y+y][X+x])
   except:pass\n  s.clrtoeol()\n  try:s.addch('\\n')\n  except:pass
 u.curs_set(0);s.move(r-y,c-x);u.curs_set(1);s.refresh();z=-1\n while z==-1:\
z=s.getch()\n if z!=z&31 and z<128:b[r].insert(c,z);c+=1\n{e}10:l=b[r][c:];b[
r]=b[r][:c];r+=1;c=0;b.insert(r,[]+l)\n{e}263 and c==0 and r:l=b[r][c:];del b[
r];r-=1;c=len(b[r]);b[r]+=l\n{e}263 and c:c-=1;del b[r][c]\n{e}260 and c!=0:\
c-=1\n{e}261 and c<len(b[r]):c+=1\n{e}259 and r!=0:r-=1;c=0\n{e}258 and r<len(
b)-1:r+=1;c=0\n{i}z==17:break\n{e}19:\n  w=''\n  for l in b:w+=''.join([chr(c)\
 for c in l])+'\\n'\n  with open(n,'w') as f:f.write(w)\nu.endwin()""")

r/codegolf • • Sep 19 '22

[Unity/C#] Movement system with jumping and ground detection in 307 bytes (or 288)

11 Upvotes
namespace UnityEngine{using V=Vector3;using static Input;class C:MonoBehaviour{public Rigidbody r;void Update()=>r.velocity=new V(GetAxis("Horizontal"),0,GetAxis("Vertical"))*9+V.up*(GetAxis("Jump")>0&&Physics.Raycast(new(transform.position-V.up*transform.localScale.y/2.05f,V.down),.05f)?8:r.velocity.y);}}

An extended (and a bit different) version, with comments:

using UnityEngine;

class C : MonoBehaviour
{
    public Rigidbody r;

    public float speed = 9f;
    public float jumpForce = 8f;

    void Update()
    {
        var inputVector = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
        var xzAxisMovement = inputVector * speed;

        // calculates the position of the ray so that it is just below the player
        var isOnGround = Physics.Raycast(new Ray(transform.position - Vector3.up * transform.localScale.y / 2.05f, Vector3.down), 0.05f);
        var shouldJump = Input.GetAxis("Jump") > 0f && isOnGround;

        // changes the player's y velocity if they should jump, otherwise keeps gravity
        var yAxisMovement = new Vector3
        {
            y = shouldJump ? jumpForce : r.velocity.y
        };

        r.velocity = xzAxisMovement + yAxisMovement;
    }
}

Here are a few compromises made to make the code smaller:

  • The whole thing happens in Update, including things that involve physics, which should be in FixedUpdate.

  • It doesn't use Time.deltaTime, making this framerate dependent.

  • The input is caught using GetAxis, and not GetAxisRaw, since it's 3 characters shorter. However, the easing makes the movement look weird in my opinion.

  • Speed and jump force (9 and 8 respectively) are hardcoded, since I didn't put any variables for them.

  • It uses Physics.Raycast for ground detection, which isn't really a good way to do it, but is probably the shortest one that somewhat works.

  • It doesn't normalize the input vector, making the player go faster when moving diagonally.

Another problem is that, since this controller directly sets the player's velocity, any velocity that was applied before the execution of this script's Update is lost. This is kinda done on purpose, since I don't want velocity to start pilling up, making the player look like they're walking on ice. A possible way of solving this would be to have your own velocity variable, and add that to the velocity calculations. That's a bit of a bodge, and can cause bugs, though.

I wanted this to work without having to change any configuration inside of Unity, so I kept the axis' names as the default ones. However, one could make this 288 bytes by changing each axis to be only one character long. Like this:

namespace UnityEngine{using V=Vector3;using static Input;class C:MonoBehaviour{public Rigidbody r;void Update()=>r.velocity=new V(GetAxis("H"),0,GetAxis("V"))*9+V.up*(GetAxis("J")>0&&Physics.Raycast(new(transform.position-V.up*transform.localScale.y/2.05f,V.down),.05f)?8:r.velocity.y);}}

Also, in newer versions of C#, it should be possible to save another byte using file scoped namespaces.


r/codegolf • • Feb 25 '21

Become Love - A 256 byte story about fear and love, written in X86 assembler

Thumbnail
pouet.net
11 Upvotes

r/codegolf • • Jan 16 '21

I made a Python code golfer in web browser

11 Upvotes

When you play Codingame's Clash of Code, sometimes you have to solve a problem in a given amount of time, but with the shortest possible code! Sometimes the code becomes completely unreadable, but it's bad for good if the code gets shorter.

Concerning Python, it is possible to encode the UTF-8 characters of the code into UTF-16 and then execute them. This has the effect of halving the size of the code, because one character of UTF-16 represents 2 of UTF-8.

Here's how to change a code to UTF-16:

>>> a="""print('Hello!')"""

>>> print(a.encode().decode('utf-16'))

牰湩⡴䠧汥潬✡


And this code can be executed with:

>>> exec(bytes('牰湩⡴䠧汥潬✡ ','u16')[2:])

Hello!

In this case, the code becomes longer because it is pretty short already, but if your code is 60+ chars, you actually shorten it!

The process of converting is pretty simple, but since Clash of code games can last around only one or two minutes, it's sometimes redundant to have to do the same thing over and over again.

So I've created a site, which will, using Python, generate this code for us.

Here is what it produces when given a longer input code than in the previous example:

(The used code prints the indice N (input) of the Copeland-Erdos' constant)

The site is accessible at https://clemg.github.io/pythongolfer/

The sources are available on my Github at https://github.com/clemg/pythongolfer/

Let me know what you think, and if you have any remarks and/or advice for improvement (or even want to do a pull-request) don't hesitate!


r/codegolf • • Oct 18 '20

Simple calculator in 161 bytes of Ruby.

11 Upvotes
def t s,o
s=~/(\d+)\s*([#{o}])\s*(\d+)/&&$`+($1.to_i.method($2).call($3.to_i)).to_s+$'||[s,1]
end
$<.each_line{|l|l,q=t l,"*/"until q;l,r=t l,"-+"until r;$><<l}

Features:

  • 4 basic arithmetic operations

  • order of operations

  • line buffering

Limitations:

  • only integers

  • no parenthesis


r/codegolf • • Sep 21 '20

Kharon - An audio visual trip to the underworld in only 256 bytes! (Demoscene)

11 Upvotes

Straight from the demoscene, hope you guys like it (more info, sourcecode and youtube-video at the link below)

https://www.pouet.net/prod.php?which=86939

It is named after Kharon. The ferryman of Hades who carries souls of the newly deceased across the river Styx that divided the world of the living from the world of the dead. This intro is represents a modernistic version of that trip to the underworld.

For more of our work / intro's , check out: https://www.pouet.net/groups.php?which=14389

- Enjoy!


r/codegolf • • Oct 29 '14

SE is codegolfing the top 100 movie quotes, each program writing a different quote, and with one less character than the last quote. It's beautiful.

Thumbnail
codegolf.stackexchange.com
11 Upvotes

r/codegolf • • Apr 21 '26

Pipes2K - Pipes Screensaver demo in about 2k of JS

10 Upvotes

As the title says. Above GIF is footage of it running in Chrome. No libraries like Three.js or trig functions were used. Due to the small footprint the "Camera" features only 1 Isometric perspective.

Could get golfed down slightly more probably... but not much. I'll release the un-golfed source once I clean it up a bit and add comments. Enjoy!

Gist of the golfed code can be found here: https://gist.github.com/edev90/00dd40e8424740358bf9b7d5d482d30a