/r/codegolf

Photograph via snooOG

Challenges to test your code shortening skills. Not necessarily practical, but fun!

Challenges to test your code shortening skills. Not necessarily practical, but fun!

 

Other programming subreddits:

/r/codegolf

2,617 Subscribers

2

Challenge with fully functional game with 30 Python lines of code. Line by line source code at the top of the video

0 Comments
2024/02/25
17:52 UTC

3

Countdown to Lovebyte 2024 Tiny Code Demoparty ( https://lovebyte.party ) - 3 Days left (Atari Lynx)

0 Comments
2024/02/06
12:31 UTC

1

Countdown to Lovebyte 2024 Sizecoding Demoparty ( https://lovebyte.party ) - 4 Days left

0 Comments
2024/02/05
15:55 UTC

3

Countdown to Lovebyte demoparty ( https://lovebyte.party) - 5 Days left

0 Comments
2024/02/04
16:44 UTC

7

Any program in one line of python

Hello team. I think I can prove that any program at any level of complexity can be written in one line of python code. For example, here is advent of code day 7 problem 1:

with open("problem.txt", "r") as tf:(lambda fi, pd: (lambda m, sf2, lf, f: print(sum([int(x.split()[1]) * (i + 1) for i, x in enumerate(sorted(tf.read().split("\n"), key=lambda ct: sf2([int(x) if x.isnumeric() else m[x] for x in ct.split()[0]], f(lf(ct.split()[0])))))])))({"A": 14, "K": 13, "Q": 12, "J": 11, "T": 10}, (lambda h1, hp1: int(fi(hp1) + fi(h1))), (lambda t: [i for i in range(1, len(t) + 1) if (sorted(t) + ["z"])[i] != (sorted(t) + ["z"])[i - 1]]), (lambda tu: pd(sorted([x if i == 0 else x - tu[i - 1] for i, x in enumerate(tu)], reverse=True)))))((lambda ns: "".join([f"{n:02d}" for n in ns])),(lambda n: n + ([0] * (5 - len(n)))))

I actually wrote an article on my personal website to show how any program can be written in one line of python. I'd love for you to read it if it sounds interesting to you!

https://rebug.dev/post/TWCPgeW6ILJOa2WdR3U4

What do you think? Is my conjecture proven?

2 Comments
2024/02/01
01:12 UTC

0

Elegant js or Python memory game implementation?

Hi.

My kid is slowly getting into programming. I don't want to get too involved as I want him to be self taught like I was, however I had a look at the memory game he wrote and well he is my kid but that was one of the worst spaghetti code I've seen recently.

So I googled some top solutions on Google and to be honest it's not too good either, there's a lot of repeated code or HTML fragment, clearly violating the DRY rule.

Can anyone point me to an elegant, readable implementation of a memory game?

I appreciate that I'm not exactly looking for the leanest, shortest implementation however I'm sure at least one of you can point me to an elegant repo please.

Thank you very much in advance!!!

3 Comments
2024/01/29
13:58 UTC

6

Jugly.io: a minimalist JavaScript code golfing plateform

Hello fellow golfers!

I've recently made Jugly, a free web app designed for JavaScript code golfing. My goal was to create a place where simplicity meets challenge, allowing to focus on what we love most: crafting the shortest, least elegant code possible.

  • Pure JavaScript Challenges
  • Integrated monaco editor
  • Leaderboards

I built Jugly because I love code golfing in JS and thought it'd be cool to have a spot where we can all share that. It's a laid-back place for anyone who wants to play around with code, learn a bit, and maybe show off some.

Fancy a round of golf? Swing by https://jugly.io and see how few characters you can get away with!

It's a little project I whipped up in my spare time, nothing too fancy. I'm really looking forward to hear your feedback and see your names shining on the Jugly leaderboards!

13 Comments
2024/01/04
22:14 UTC

6

The 40 day countdown to the Lovebyte sizecoding/codegolfing demoparty ( https://lovebyte.party ) on February 9-11th 2024, starts now!

1 Comment
2024/01/02
11:35 UTC

5

What features do you wish golfing languages have?

I decided to take on the project of creating a golfing language (stack based is really easy to program). What features are golfing languages lacking that you wish they had?

5 Comments
2023/12/05
23:41 UTC

4

9 code golf challenges: authorization

A logic game, similar to “Regex Golf”, that is designed to teach you authorization principles by completing permissions with as few objects as possible.

https://oso-golf.netlify.app/

0 Comments
2023/11/15
15:19 UTC

3

A free to enter, 240 character maximum, open-source iterated prisoner's dilemma tournament

I'm running an iterated prisoner's dilemma tournament for computer programs. All programs get access to their opponent's source code, and restricted to 240 characters maximum. The exact rules are posted at this link. You don't need an account on that website to participate, you can just put your program in the comments on Reddit or PM me. Have fun!

1 Comment
2023/11/09
16:58 UTC

5

Someone manage to squeeze out one more byte from this Fizzbuzz?

The shortest fizzbuzz for JS (that I know of) is this one:

for(i=0;i<100;)console.log((++i%3?'':'fizz')+(i%5?'':'buzz')||i)

I tried a different approach. Haven't seen it anywhere else, but it's probably done before. I managed to get it down to one character away from the shortest one. Have I overlooked anything? Can you squeeze the last bit out of it? :)

for(i=0;i<100;)console.log("fizzbuzz".slice(++i%3&&4,i%5?4:8)||i)
0 Comments
2023/10/24
17:06 UTC

6

List of Primes up to n in Python

Was playing around with some stuff and came across that black box of primes post. Decided to take a crack at it for fun. Came across a few components here and kinda threw it all together. Not original by any means, but still cool to look at.

f=lambda n:[]if n<2 else([n,*f(n-1)]if(n>1)&(n//1==n)&all(n%k for k in range(2,n))else f(n-1))

Credit to u/FreakCERS for the primality checker. I think there's room for improvement. Beyond me though. I don't usually do this sort of thing

1 Comment
2023/09/26
21:59 UTC

85

Explanation of "Black Box of Primes"

Black Box of Primes

Explanation

So, the task is to find all the prime numbers up to N.

There are multiple approaches. One of the simplest approach is using recursion: to find all prime numbers up to N, first find all prime numbers up to N-1, and if N is prime, add it to the list.

function findPrimesUpTo(n) {
    const primes = findPrimesUpTo(n-1);
    if (isPrime(n)) {
        primes.push(n);
    }
    return primes;
}

Simple, but doesn't work for 2 reasons:

  1. infinite recursion
  2. isPrime function is not defined

Let's first fix the first issue. We know, that the smallest prime number is 2, so the list of prime numbers prior to 2 is empty.

    if (n<2) {
        return [];
    }

Now let's defined isPrime. There are a lot of different approaches. The easiest one (but definitely not the optimal) is to check divisibility by every number up to N-1. I know, it's super bad idea. So we can improve it a bit: divide not by every number, but by prime numbers only. We have a list, remember?

function isPrime(n, primes) {
    return primes.all((prime) => n % prime !== 0);
}

Just don't forget to pass this extra argument.

Can we do that without fancy fashioned functional methods? Sure, we can rewrite it with old-school loop:

function isPrime(n, primes) {
    let i = 0;
    while (i < primes.length) {
        if (n % primes[i] === 0) {
            return false;
        }
        i++;
    }
    return true;
}

That looks much longer, less fancy and absolutely out-fashioned. Another cool way to do that is with recursion again. We just take this loop and convert it to recursion:

function isPrime(n, prime, i = 0) {
    if (i < primes.length) {
        if (n % primes[i] === 0) {
            return false;
        } 
        return isPrime(n, primes, i+1);
    }
    return true;
}

Now let's start a dark codegolf magic.

Trick one: we can replace if with &&.

function isPrime(n, primes, i = 0) {
    if (i < primes.length) {
        return n % primes[i] && isPrime(n, primes, i+1);
    } 
    return true;
}

Trick two: JS doesn't complain when you get out of array bounds. It just returns undefined, and as we know that all items in array are non-zero, we can replace proper condition i < primes.length with a hacky primes[i].

function isPrime(n, primes, i = 0) { 
    if (primes[i]) {
        return n % primes[i] && isPrime(n, primes, i+1);
    } 
    return true;
}

Finally, let's turn it into arrow function to get rid of all that return's. Also replace if with ternary operator.

const isPrime = (n, primes, i = 0) => 
    primes[i] ? (n % primes[i] && isPrime(n, primes, i+1)) : true;

Good old one-liner. Like the one we started with (the fancy functional, remember?), but much more cryptic and jedi-ish.

Let's put it into our initial function:

function findPrimesUpTo(n) {
    if (n<2) {
        return [];
    }
    const primes = findPrimesUpTo(n-1);

    const isPrime = (n, primes, i) => 
        primes[i] ? (n % primes[i] && isPrime(n, primes, i+1)) : true;
    
    if (isPrime(n, primes, 0)) {
        primes.push(n);
    }
    return primes;
}

As it's nested function now, we can get rid of extra arguments, it can just access it from the context.

function findPrimesUpTo(n) {
    if (n<2) {
        return [];
    }
    const primes = findPrimesUpTo(n-1);

    const isPrime = (i) => 
        primes[i] ? (n%primes[i] && isPrime(i+1)) : true;
    
    if (isPrime(0)) {
        primes.push(n);
    }
    return primes;
}

console.log(findPrimesUpTo(1000));

It works!

Now let's apply some forbidden practices, to make it shorter. Warning! Never do this in production code!

First thing to change: basically, we do primes.push only when isPrime returns true. So let's just put it there. That's absolutely not what you gonna do in production code.

function findPrimesUpTo(n) {
    if (n<2) {
        return [];
    }
    const primes = findPrimesUpTo(n-1);

    const isPrime = (i) => 
        primes[i] ? (n % primes[i] && isPrime(i+1)) : primes.push(n);
    
    isPrime(0);

    return primes;
}

Now we can get rid of push at all: if i reached the end of list, we can just save n there:

 const isPrime = (i) => 
    primes[i] ? (n % primes[i] && isPrime(i+1)) : primes[i] = n;

There are too many primes[i] here. Let's join them all together:

 const isPrime = (i) => 
    n % (primes[i] ??= n) ? isPrime(i+1) : true;

What's going on here??? ??= operator assigns new value only if previous value was undefined. So if we reached the end of array, the new value is added to the end, if not, nothing happens.

Now, if we didn't reach the end of list, we calculate n % primes[i] as usual, but if we reached, then it becomes n % n, which is always zero, and we skip recursion and return true.

Beautiful? Yeah!

Whole picture now:

function findPrimesUpTo(n) {
    if (n<2) {
        return [];
    }
    const primes = findPrimesUpTo(n-1);

    const isPrime = (i) => 
        n % (primes[i] ??= n) ? isPrime(i+1) : true;
    
    isPrime(0);

    return primes;
}

console.log(findPrimesUpTo(1000));

It still works!

Next stupid jedi thing we do, is to join last two lines: isPrime(0); and return primes;. Now isPrime function returns array instead of boolean, but who cares?

function findPrimesUpTo(n) {
    if (n<2) {
        return [];
    }
    const primes = findPrimesUpTo(n-1);

    const isPrime = (i) => 
        n % (primes[i] ??= n) ? isPrime(i+1) : primes;
    
    return isPrime(0);
}

console.log(findPrimesUpTo(1000));

Now let's make primes a global variable. Just because that's what you must never do in real life.

const primes = [];

function findPrimesUpTo(n) {
    if (n>2) {
        findPrimesUpTo(n-1);
    }

    const isPrime = (i) => 
        n % (primes[i] ??= n) ? isPrime(i+1) : primes;
    
    return isPrime(0);
}

console.log(findPrimesUpTo(1000));

Now we do 3 tricks:

  1. replace if with && again.
  2. call isPrime function right after declaration.
  3. turn findPrimesUpTo into arrow function.

const primes = [];

const findPrimesUpTo = (n) => (
    n>2 && findPrimesUpTo(n-1),

    (isPrime = (i) => 
        n % (primes[i] ??= n) ? isPrime(i+1) : primes)(0)
)

console.log(findPrimesUpTo(1000));

Now, let's get rid of numbers. Why? Because why not. n-1 can be replaced with ~-n i+1 can be replaced with -~i

n>2 is trickier, but basically it's like n-2>0, which is almost the same as n-2, and that can be replaced with ~-~-n.

const primes = [];

const findPrimesUpTo = (n) => (
    ~-~-n && findPrimesUpTo(~-n),

    (isPrime = (i) => 
        n % (primes[i] ??= n) ? isPrime(-~i) : primes)(0)
)

console.log(findPrimesUpTo(1000));

How to hide 1000?

Thanks to JavaScript advanced math '' + 1 + 0 + 0 + 0 == "1000"

And did you know that -[] in JS equals to zero?

And -~[] equals to 1.

And if we add [] to a number, it will be converted to empty line ''.

So, to get it together: 1000 can be replaced with [] + -~[] + -[] + -[] + -[].

Actually, it will be a string "1000", not a number, but thanks to our bitwise operations, it will be automatically converted to a number during computations.

console.log(...findPrimesUpTo([]+-~[]+-[]+-[]+-[]));

There's still a zero left when we call isPrime.

You know what? Instead of disguising it, let's just remove it! undefined is almost the same stuff as zero. Though, not exactly the same, so we need to add some bitwise converter: ~~.

const primes = [];

const findPrimesUpTo = (n) => (
    ~-~-n && findPrimesUpTo(~-n),

    (isPrime = (i) => 
        n % (primes[~~i] ??= n) ? isPrime(-~i) : primes)()
)

console.log(...findPrimesUpTo([]+-~[]+-[]+-[]+-[]));

No more silly numbers. Now let's get of letters.

Rename n to $.

Rename primes to _.

Rename findPrimesUpTo to $$.

Rname isPrime to _$.

Rname i to $_.

And const - let's just get rid of them.

_ = [];

$$ = ($) => (
    ~-~-$ && $$(~-$),

    (_$ = ($_) => 
        $ % (_[~~$_] ??= $) ? _$(-~$_) : _)()
)

console.log(...$$([]+-~[]+-[]+-[]+-[]));

This pretty obfuscated code still works nice.

Now some optimization: you see, that we use a lot of []'s?

And totally accidentally our _ variable is initialized to []. So...

$$ = ($) => (
    ~-~-$ && $$(~-$),

    (_$ = ($_) => 
        $ % (_[~~$_] ??= $) ? _$(-~$_) : _)()
)

console.log(...$$((_ = [])+-~_+-_+-_+-_));

Now let's call $$ right after initialization:

console.log(...($$ = ($) => (
    ~-~-$ && $$(~-$),
    (_$ = ($_) => $ % (_[~~$_] ??= $) ? _$(-~$_) : _)()
))((_ = [])+-~_+-_+-_+-_));

And get rid of all that spaces and some brackets:

console.log(...($$=$=>(~-~-$&&$$(~-$),(_$=$_=>$%(_[~~$_]??=$)?_$(-~$_):_)()))((_=[])+-~_+-_+-_+-_))

Here we go!

Wait, what about console.log,

In interactive environment (like browser console), you can just run the code without console.log and still get output.

For non-interactive environment... Well... Actually, it is possible to get rid of it, but it will make code way bigger and require a lot of effort, so let's just keep it.

4 Comments
2023/04/17
16:31 UTC

7

Lovebyte 2023 - Only 5 days left until the biggest online codegolf/sizecoding party is about to start!

Lovebyte 2023 : 10-12 February 2023 ( https://lovebyte.party )

Join us in a celebration of the smallest with a dedicated sizecoding demoparty, held on the weekend of 10-12th February 2023 on Discord and Twitch ( https://www.twitch.tv/lovebytedemoparty )

This year we will take it to the next level with intro competitions in different size categories from 16 bytes to 1024 bytes. From our Tiny Executable Graphics and Nanogame competitions to Tiny CGA Pixel Graphics and Bytebeat Music competitions.

Or what about cool size-coded related seminars to get you started? Or otherwise our Bytejam, Introshows, DJ Sets and the many other events we have lined up for you. We welcome everyone from newcomers to veterans and are open to all platforms. From Pldschool 6502 and Z80 platforms like the Atari, Commodore, Amstrad & ZX Spectrum to High-end X86/ARM/RISC platforms and Fantasy Console platforms.

And for those that would like to join the fun and get creative: We have our party system ready to receive your entries at https://wuhu.lovebyte.party/. Contact us via the Lovebyte discord or socials to request your vote/registration key.

This is the one event where size does matter! Don't miss it!

Website: https://lovebyte.party/
Twitch: https://www.twitch.tv/lovebytedemoparty
Youtube: https://www.youtube.com/@Lovebytedemoparty
Discord: https://discord.gg/pUS5kCJTzp
Mastodon: https://graphics.social/@lovebyteparty
Twitter: https://twitter.com/lovebyteparty
Instagram: https://www.instagram.com/lovebyteparty

1 Comment
2023/02/05
09:14 UTC

5

91 byte password generator

from random import*
while 1:print(''.join(map(chr,choices(range(32,127),k=int(input())))))
3 Comments
2023/01/16
03:01 UTC

13

mandelbrot in python 322 bytes

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)
7 Comments
2022/11/01
17:22 UTC

10

[Python] Prime number checker (97 bytes)

import decimal as d
f=lambda n:n*f(n-1)if n>1else d.Decimal(1)
p=lambda n:n>1and(f(n-1)+1)/n%1==0

p takes a Decimal as an argument and returns a bool telling whether or not the input is a prime number. f calculates the factorial of a Decimal. I tried implementing this way of calculating the factorial of a number for Decimals, but I kept getting a InvalidOperation error, so for now this is the smallest code I could manage.

If you used floats for this instead of Decimals, you would notice that the function would start spitting out wrong answers very quickly because of floating-point errors. So yeah, that's why I used Decimals.

Here's some code-golfed code (275 bytes) that prints out all prime numbers from 0 to n:

import sys,decimal as d
n=100
f=lambda n:n*f(n-1)if n>1else d.Decimal(1)
p=lambda n:n>1and(f(n-1)+1)/n%1==0
sys.setrecursionlimit(n+3)
d.getcontext().prec=len(v)if'E+'not in(v:=str(f(d.Decimal(n))))else int(v[v.find('E+')+2:])
print(', '.join(str(i)for i in range(n)if p(i)))

Note that the code also changes the recursion limit, because there would be a RecursionError for values above 997. It also changes the precision of Decimals, since a DivisionImpossible exception would be thrown for values whose factorial has 28 (the default precision of Decimals) or more decimal places. As such, the code does some stuff with strings to find out what the precision should be to accommodate for the maximum value whose factorial we will have to calculate — and then use in a division —, in this case being n.

For some reason, on my machine, the code stops working for values above 1994, with no errors being shown.

Also, if you don't change the precision of Decimals and call p with 28 as the argument, it'll return True, even though 28 is obviously not a prime number. It also won't throw an exception, even though the factorial of 28 has more than 28 decimal places (with 29 as the argument, however, it'll actually throw the exception). No clue why.

6 Comments
2022/10/12
16:39 UTC

9

[Python] My take on the dogAgeYears thingy (82 bytes)

Here's my take on trying to make the code from this post as small as possible!

c=lambda n:['0 - 15',15,24,28][n]if n<5else n*5+12if n<15else"That's a long life!"

This code doesn't exactly match the original implementation because negative numbers are indexed into that list, and since Python supports negative indexing, the function simply returns the value that was indexed. Unless of course, that negative number is smaller than -4, at which case it throws an IndexError.

What should happen (based only off of the code in that post, so assuming that negative numbers are a possibility) is that the default case should run, so the function should return "That's a long life!".

btw i originally saw that post in this crosspost

0 Comments
2022/10/11
01:59 UTC

10

Code golfing American Psycho's new business card

1 Comment
2022/10/03
14:48 UTC

12

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

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

1 Comment
2022/09/23
17:08 UTC

Back To Top