/r/codegolf
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
import pyperclip as c,secrets as s
while 1:c.copy(p:='%c'*(l:=int(input('Length of new password: ')))%(*map(s.choice,[range(32,127)]*l),));print('Copied',p,'to clipboard.')
I am responsible for managing an online social community for Splunk users and devs and thought CodeGold challenges would be a fun thing to do. I tried FizzBuzz and it works out pretty well in SPL! But I dont know what the best way to score might be. I was thinking either time, resource load, or some way to measure the size of the SPL
Is runDuration (in the job inspector) reliable? Or is it prone to flucutation based on whether the search heads are running good?
Is number of characters just the simpliest way to score CodeGold in SPL?
Is there anyway to measure how many "bytes" a block of SPL has, or how many resources it takes up (even just one acpest of resource load, like CPU or RAM, would be fine so long as it is the same load everytime you run the code)
Thank y'all so much and it was rather fun writing the SPL to solve that!
Background, I have zero programming knowledge. I’m a creative and I make wacky stunts like the above idea work. Just seeing if this one has legs.
I have contacts at a company which is partnered with PGA and also hires a lot of programmers/ developers so I think this would be a dope way to find new talent.
If there’s enough interest, I’ll try and make it real.
can anyone suggest any suitable platforms to host a code golf contest right now, ik about code.golf and anarchygolf
A function that sorts an array of positive integers using radix sort with radix = 2. My first version was 112 bytes long, then I shortened it to 84 bytes:
l=>{for(b=1;b<<=1;)for(i in k=0,l)l[i]&b||l.splice(k++,0,l.splice(i,1)[0]);return l}
Later it was shortened to 81 bytes by a guy from a chat (he added recursion to remove for and return):
l=>(f=b=>b?f(b<<=1,k=0,l.map((x,i)=>x&b||l.splice(k++,0,l.splice(i,1)[0]))):l)(1)
Then I shortened the 84 version to 75 bytes, however, this version does not return the array, but modifies the source array:
l=>{for(b=1;k=0,b<<=1;)l.map((x,i)=>x&b||l.splice(k++,0,...l.splice(i,1)))}
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?
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!!!
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.
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!
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?
A logic game, similar to “Regex Golf”, that is designed to teach you authorization principles by completing permissions with as few objects as possible.
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!
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)
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
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:
isPrime
function is not definedLet'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:
if
with &&
again.isPrime
function right after declaration.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.
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
from random import*
while 1:print(''.join(map(chr,choices(range(32,127),k=int(input())))))
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)