[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
What's the most brilliant snippet of code you've ever
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 125
Thread images: 15
File: magic.png (2 KB, 335x147) Image search: [Google]
magic.png
2 KB, 335x147
What's the most brilliant snippet of code you've ever come across?
>>
>>53540325
>inverted square root
What the fuck...?
>>
>>53540439
>>53540325
Fuck off Carmack, you didn't even write it
>>
>>53540439
power of 2?
>>
printf("hello world");
>>
File: 1451007318607.png (111 KB, 415x353) Image search: [Google]
1451007318607.png
111 KB, 415x353
>>53540325
>0x5f3759df
what the fuck?
>>
>>53540439
Extremely useful in 3D graphics programming

>>53540487
Fuck off retard
>>
>>53540496
https://en.wikipedia.org/wiki/Fast_inverse_square_root#A_worked_example
>>
I wrote a paper on it. Pretty interesting example of the application of calculus in computing
>>
>>53540521

Number from hell
>>
File: 1430271650135.jpg (63 KB, 572x497) Image search: [Google]
1430271650135.jpg
63 KB, 572x497
>>53540497
>>
>>53540325
My own:
void DrawCircle(Point p, int diameter, Color color)
{
if (diameter < 3)
{
color.A = (byte)(color.A * 0.7854f);
FillRectangle(new Rectangle(p.X, p.Y, diameter, diameter), color);
return;
}

...
}
>>
>>53541036
epic my man, simply epic.
>>
>>53541036
>return
>void
ayy
>>
>>53541084
What's wrong with either?
>>
>>53541084
fucking retarded
>>
>>53540325
Just so you know, now that SSE is so common the rsqrtss instruction is a better choice because it's a lot faster. (I think even sqrtss is on newer chips.)
>>
>>53541144
>>53541186
>return illigal with all void type
>return illigal with all void type
>return illigal with all void type
learn programming
>>
>>53541084
goddamn, you're dumb
>>
>>53541245
It's not illegal in C# :^)
>>
>>53541245
Hahahahahaha
>>
>>53541262
>>53541255
it's illogical, so not correct. why should you return if you can't.
>>
>>53541245
In what language m8? Return can usually be used as a short circuit in void functions.
>>
>>53541299
I have to return so it doesn't draw the circle normally afterwards
>>
>>53541323
just ignore, he's baiting
>>
>>53541307
mainly C, but it's a illogical things to this. there are other function for exiting a function like exit();

>>53541323
find a better way
>>
>>53541299
Why do you bother to do this? Are you trying to act retarded or are you really this retarded? Or are you just this desperate for attention?
>>
File: when_girls_code.jpg (226 KB, 869x1776) Image search: [Google]
when_girls_code.jpg
226 KB, 869x1776
Shitty man-code.
>>
>>53541299
Actually to add to >>53541307: the original use of return (and current use in most assembly) was to return to where a procedure had been called, not return a value. So it isn't illogical.
>>
>>53541343
i am this retarded, anon. i like my code to be logical

>>53541353
if this is true i have to say thet you are right BUT i don't know if this is true
>>
>>53541333
>exit
>Terminates the process normally, performing the regular cleanup for terminating programs.

How dumb are you?
>>
>>53541299
to break out of the function?
idiot
>>
>>53541403
i said like exit() not "hurr durr use exit"

try not to be a fucktard, anon
>>
>>53541352
>else if(a > b && b < a)

what
>>
>>53541381
>https://courses.engr.illinois.edu/ece390/archive/spr2002/books/labmanual/inst-ref-ret.html
You'll have to look in a reference document from Intel for the official definition, but this explains it.
>>
>>53541452
>like exit()
That's the first thing that comes to your mind when thinking about a structure that lets you do one thing if a condition is true, and something else otherwise?
>>
>>53541468
okay, you are right

but i still won't use return with void type
>>
>>53541352

>max(0, 0)
>5
>>
>>53541528
so random XD
>>
>>53540325

I don't think there are many things in this world that are more brilliant than fast inverse square root. However, one of the more brilliant pieces of code that I have come across was written by a certain hacker named Bisqwit. He's got a youtube channel focused on programming, and he's done some INTERESTING techniques to make an emulator whose codebase can be shown off entirely in 15 minutes.

http://bisqwit.iki.fi/jutut/kuvat/programming_examples/nesemu1/nesemu1.cc

Observe the instruction Ins()

He explains it a bit in this video
https://www.youtube.com/watch?v=QIUVSD3yqqE

>>53540439

1 / sqrt(n), or n ^ -0.5

>>53540663

I have seen several papers on the subject of this one function. Mind linking to yours if it's publicly available? It's a goddamn interesting topic.

>>53541189

If it's in SSE2, then every x86-64 CPU supports it out of the box. But the inverse square root function may nonetheless be a decent backup if used on a non-x86 CPU.
>>
>>53541557
// NES NTSC modulator (square wave between up to four voltage levels):
int b = 40 + s[(c > 12*((c+8+p)%12 < 6)) + 2*!(0451326 >> p/2*3 & e) + l];

Jesus fuck.
>>
>>53541557
This is extremely interesting, I'm actually working on an NES homebrew, thanks anon
>>
looking thru GROMACS and seeing how astoundingly plain it was

i was blown away at its boringness
>>
>>53541084
hey I just covered void functions in my csce intro class too! except I paid enough attention to notice that returns in voids have their uses.
>>
>>53541403
>>53541333
>>53541299
>>53541084

Cringing sooo hard atm
YOU SHOUD return in a void function
IT IS PREFERED behaviour

you just return nothing
>>
>>53541457
top kek
>>
>>53540439
inverse
>>
>>53542067

He's actually done two NES emulators, one in C++, and another in QuickBasic. I'd recommend watching a few of his videos if you want some ideas.

>>53541084
>>53541245
>>53541299
>>53541333

It is neither illegal nor illogical in C to return from a void function. The only thing that void means is that the return value of that function is unusable. It is preferred to use return in a void function to terminate early to avoid undesirable side effects if certain conditions are met. The alternative is this:

void foo(int bar) {
if (bar == some_value) {
goto EndOfFunction;
}

some_side_effect(bar);
EndOfFunction:

}
>>
>>53541457
>else if(a > b && b < a)
for javascript compatibility
>>
>>53541352
Kek
>>
The first time I saw NaN boxing/tagging.
>>
>>53543666
Satan, thanks for making fuckwits go away.
>>
File: gl62.jpg (34 KB, 480x360) Image search: [Google]
gl62.jpg
34 KB, 480x360
>>53541352
>that image
>>
File: 1349217226441.jpg (47 KB, 720x439) Image search: [Google]
1349217226441.jpg
47 KB, 720x439
>>53543807
Underrated post
>>
i never understood why OP's pic is so relevant

i just dont get it

what does it actually do for 3D rendering?

every time i ask this question i get "well its impressive because no one knows why it works" but no one ever explained what it did to me
>>
>>53540439
fuck off carmack
>>
>>53541352
has to be fake
>>
>>53544211
It finds the inverse square root of the input, which is 1/sqrt(x). It's good because it's fairly accurate and extremely fast. It works via some magic bit level shifts and a magic number constant. Inverse squares are used a lot for calculating simple lighting in 3d rendering.
>>
File: what the fuck am i reading.png (57 KB, 523x288) Image search: [Google]
what the fuck am i reading.png
57 KB, 523x288
>>53540495
What the fuck does this do?
>>
>>53541457
lmao wtf

>>53543807
I don't get it
>>
>>53541557
I was just watching his channel.

How the fuck can this guy be a bus driver.

https://www.youtube.com/watch?v=HQYsFshbkYw
>>
>>53544513
He hated professional software development.

It's understandable.
>>
File: 1457666404482.gif (988 KB, 294x224) Image search: [Google]
1457666404482.gif
988 KB, 294x224
I learned not to overcomplicate shit
>>
File: 1457423708952.gif (427 KB, 266x200) Image search: [Google]
1457423708952.gif
427 KB, 266x200
>>53544286
Women is what ya reading don't make any sense
>>
File: 1382673877214.gif (2 MB, 200x200) Image search: [Google]
1382673877214.gif
2 MB, 200x200
>>53541864
to be fair though, i don't think the guy saw the problem and then wrote that down. the original solution was likely many lines of code that he iteratively whittled down to the single, elegant(?) line that you see there.

doesn't make it any less impressive imo.
>>
File: 1457983420090.jpg (28 KB, 390x310) Image search: [Google]
1457983420090.jpg
28 KB, 390x310
My most brilliant piece of code is
When I fucked my sister friend and hacked his computer everything he typed in Google it redirected him to a website that said
#print f I fucked your sister
I used the DNS file and redirected to website a simple spoof
>>
>>53543666

>What is "else"?
>>
>>53540325
public int main(){
return 0;
}


this is the "am I running a computer test"
>>
>>53541352
John Carmack v. Model
>>
>>53541084
>everyone falling for this b8
>>
>>53541352
fake and gay
>>
File: Screenshot_2016-03-18-03-41-36.png (585 KB, 720x1280) Image search: [Google]
Screenshot_2016-03-18-03-41-36.png
585 KB, 720x1280
>>53544638
>Image 9 out of 11
Mah nigga
>>
    total = df.count().values[0]
grouped = df.groupby([target])
e = 0.0
for name, g in grouped:
g_total = g.count().values[0]
p = Counter(g[against].tolist())
r = [(-x/g_total * math.log(x/g_total, 2)) for x in p.values()]
e += g_total/total * sum(r)
return e


Shannon entropy, I was actually surprised it worked.
>>
random shuffling (use swapping)

permutation (use swapping)
>>
â–²
â–² â–²
>>
The metacircular evaluator. https://youtu.be/0m6hoOelZH8
I think anyone and everyone who wants to into language design should see this lecture.
>>
File: 1456009687236.jpg (143 KB, 900x585) Image search: [Google]
1456009687236.jpg
143 KB, 900x585
>>53540325
Daily reminder just because code is clever doesn't mean it's good code.

The readability of that code is garbage, but it is very clever.

inb4 butthurt script kiddies or people who have never been employed
>>
>>53547568
That code is good code because it's fast.
It's also short, so as a black box it doesn't matter that it isn't readable.
>>
>>53547626

What if I told you it can be both fast and readable? I bet you enjoy unmastered music too, pleb.
>>
>>53547672
What if I told you that making variable names longer doesn't necessarily imply readability
>>
>>53547568

that was good code when it was written because it literally was the entire reason why the game was playable on PCs at the time without spending $100k on a purpose made workstation. it was all software rendered and not every CPU had an FPU built in.
>>
>>53547672
Go ahead, make it more readable.
>>
>>53547697

Because no comments and a random magic number can't be improved upon at all right?
>>
>>53547708
>not every CPU had an FPU

that was for Q3 in 1999, mate.
the minimum requirements were ~300MHz Pentium II or K6-2.
the last chips to not include an x87 FPU was the 486SX in the early '90s.
>>
>>53547726
Nope.
Do you think lifting the single constant into a variable, that only appears once in the entire codebase, would make it more readable?
>>
.flip
{
transform: scaleY(-1);
}

it's css...
>>
/* type punning bitcast */
template <typename T, typename U>
inline U bitcast (const T& x)
{
return *(U*) &x;
}
/* iteration of newton's method */
inline float isqrt_newton (float x, float y)
{
float half_x = x * .5f;
return y * (1.5f - half_x * y * y);
}
float invSqrt (float x)
{
const int INV_SQRT_CONSTANT = 0x5f3759df;

/* perform magic */
int x_int = bitcast<float, int>(x);
int y_int = INV_SQRT_CONSTANT - (x_int >> 1);
float y = bitcast<int, float>(y_int);

/* improve accuracy */
y = isqrt_newton(x, y);
// y = isqrt_newton(x, y);

return y;
}
>>
>>53540325
>0x5f3759df
>// what the fuck?
>>
>>53540325
Dunno about come across, but the best one i've written was my entity attachment system. Only about 10 lines, no redundant computation, no slow recursion, and could do pretty much an infinite attachment chain in O(n) time.
>>
While(2>1)
>>
>>53548113
>what are local constants
>what are comments
>what is explaining how or why
>why have I never read a single book on how to code properly
>>
>>53548382
>in theory, you should do all this shit, comment every line and put every integer into a constant

>in practice, spend a lot of time fine tuning your magic constant for optimal performance, shove it into a tiny function and continue actually getting work done on your engine
>>
>>53547726
there are comments in the original code. Not good ones though.
>>
>>53548457
>I have never worked on a large project or been paid to program
>>
Not brilliant, but beautiful:
:(){ :|: & };:
>>
>>53548781
>write only code is "beautiful"

Kill yourself my man!
>>
>>53547672
>I bet you enjoy unmastered music too, pleb.

i don't get it
>>
>>53541557
Bisqwit is based as fuck. He currently works as a bus driver and teaches jewish folk dances as one of his hobbies.
>>
>>53541352
Thats such a simple function, why do you need comments every 2 lines?
>>
>>53544513
If you look at his CV on his website you can see that that he worked as a software dev for ~10 years.

http://bisqwit.iki.fi/cv.html
>>
>>53544914

Say your "else" clause becomes excessively long. Do you really want that entire section of the function to be unnecessarily indented? Why not use an early return when they were clearly designed to be used?
>>
        program=\
"
import socket
import ctypes
import struct
import sys
row = ctypes.create_string_buffer(struct.pack('IIIII',
12,
struct.unpack('<I', socket.inet_aton('$sip'))[0],
socket.ntohs($sport),
struct.unpack('<I', socket.inet_aton('$dip'))[0],
socket.ntohs($dport)
))
sys.exit( ctypes.cdll.iphlpapi.SetTcpEntry(ctypes.byref(row)) ) #yolo
"
python -c "$program" || echo "Failed ($?)"
>>
>>53547672
It's readable. The name of the function describes everything you need to know. This function itself will very unlikely need any modifications.
>>
>>53540325
sed 'h;s/[14]/    /g;s/[0-9]/ _  /g;G;s/0/| | /g;y/24569/38228/;G;s/[068]/|_| /g;s/[147]/  | /g;s/2/|_  /g;s/[359]/ _| /g'


Example usage:
echo "$(date +%H%M)" | sed 'h;s/[14]/    /g;s/[0-9]/ _  /g;G;s/0/| | /g;y/24569/38228/;G;s/[068]/|_| /g;s/[147]/  | /g;s/2/|_  /g;s/[359]/ _| /g'
>>
>>53541245
Returning on a void is only illegal if you return something other than void.

The function will automatically return once it completes anyway, calling a return is just jumping out manually.
>>
<p>hello world</p>
>>
>>53540325
>*(int*)&x
>>
File: 1447647282299.jpg (4 KB, 344x226) Image search: [Google]
1447647282299.jpg
4 KB, 344x226
>>53543807
>>else if(a > b && b < a)
>for javascript compatibility
>>
This one's useful.

// Fast, high-quality RNG (Xorshift)
unsigned long long xor64() {
static unsigned long long x = 88172645463325252ULL;
x ^= (x << 13);
x ^= (x >> 7);
x ^= (x << 17);
return x;
}
>>
>>53541557
> /* Decode address operand */
Baaaasssedd
>>
cube_t *create_cube(unsigned x, unsigned y, unsigned z)
{
cube_t *ptr = malloc(sizeof(cube_t));
ptr->size.x = x;
ptr->size.y = y;
ptr->size.z = z;
unsigned i, j; /* make 3D cube */
ptr->cube = malloc(sizeof(unsigned char **) * x);
for (i = 0; i < x; i++)
ptr->cube[i] = malloc(sizeof(unsigned char *) * y);
for (i = 0; i < x; i++)
for (j = 0; j < y; j++)
ptr->cube[i][j] = malloc(sizeof(unsigned char) * z);
return ptr;
}
>>
ITT: unreadable code that can't be maintained is seen as brilliant by NEETs
>>
/* write length as 28-bit unsigned integer */
char *location = (char *) start;
const unsigned BIT_LENGTH = 7;
const unsigned WORD_SIZE = 4;
int i, j;
unsigned k = 0; /* length integer bit index */
for (i = WORD_SIZE - 1; i >= 0; i--)
{
for (j = 0; j < BIT_LENGTH; j++)
{
if (length & (1 << k++))
location[i] |= (1 << j);
}
}
>>
>>53550921
christ
how do you seed it tho?
>>
/* outputs 8 kHz 8-bit unsigned pcm to stdout */
/* gcc -lm sig.c;./a.out>/dev/dsp */

#include <math.h>
main(v,i,z,n,u,t){for(v=-1;;)for(n=pow(
1.06,"`cW`g[`cgcg[eYcb^bV^eW^be^bVecb^"[++v&31]+(v&64)/21),i=999;i;putchar
(
128+((8191&u)>i?0:i/8)-((8191&(z+=n))*i-->>16)))u+=v&1?t/2: (t=v&6?t:n/4);}
>>
>>53547490
>34:35
Classic.
>>
>>53540325
private int[] SortThreeInts(int a, int b, int c)
{
return new int[]
{
Math.Max(a, Math.Max(b, c)),
Math.Min(Math.Min(Math.Max(a, b), Math.Max(b, c)), Math.Max(a, c)),
Math.Min(a, Math.Min(b, c))
};
}
>>
>>53540325
Prints odd numbers to 100:

static void PrintOddNumbersVerifiedByMicrosoftSQLServer2012()
{
SqlConnection thisConnection = new SqlConnection(@"Data Source=localhost;
Initial Catalog=default;
Persist Security Info=True;
User ID=user;
Password=B1GT1tti3z");
thisConnection.Open();

string Get_Data =
@"DECLARE @start INT = 1;
DECLARE @end INT = 100;

WITH numbers AS (
SELECT @start AS number
UNION ALL
SELECT number + 1
FROM numbers
WHERE number < @end
)
SELECT *
FROM numbers
WHERE number % 2 <> 0
OPTION (MAXRECURSION 0);";

SqlCommand cmd = thisConnection.CreateCommand();
cmd.CommandText = Get_Data;

SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
var ayy = dt.AsEnumerable().ToList();

foreach (var number in ayy)
{
Console.WriteLine(number.ItemArray[0]);
}
}
>>
File: 1455593431284.png (251 KB, 346x427) Image search: [Google]
1455593431284.png
251 KB, 346x427
>>53543807
Good lord my sides
>>
>>53541521
What if you need to exit the function early in case of a serious error?
>>
>>53541557
Man I still dont get how his opcode decode function works after 3 years of occasionally looking at it haha.
>>
>>53547708
Pretty sure quake 3 required a hardware accelerated hardware rasterizer.
The invsqrt was used for per-vertex lighting. Graphics cards back before 2000 didnt have hardware t&l, so that had to be done on cpu.
>>
I wish I was able to understand this thread
>>
>>53540325
>brilliant
no way I'd allow that jerkoff garbage into production. It's incomprehensible for one thing.
>>
>i = 0x5f3759df - ( i >> 1 ); // what the fuck?

ebin
Thread replies: 125
Thread images: 15

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.