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

Show me some beautiful code.

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 175
Thread images: 33

Show me some beautiful code.
>>
File: sleep sort.png (65KB, 1177x520px) Image search: [Google]
sleep sort.png
65KB, 1177x520px
>>
>>60594718
<h1>headline</h1><p>#canthackme</p>
>>
>>60594745
So basically you take every parameter X, call f(x), which sleeps for X seconds and then echo X? That's really impressive idea
>>
https://archive.rebeccablacktech.com/g/thread/28045316/#q28045327


Truly a work of art
>>
>>60594718
truth = ["OP == fag", "No.", "/thread", ">implying OP isn't a feg", "you first, feggit"]
truth.sample(2)
>>
File: B-ay0QJCEAAiTzC.png (51KB, 597x255px) Image search: [Google]
B-ay0QJCEAAiTzC.png
51KB, 597x255px
>>60594718
>>
File: animu0000.jpg (77KB, 658x632px) Image search: [Google]
animu0000.jpg
77KB, 658x632px
>>60595180
Be kind and kill yourself.
>>
cd code
cd..
pwd
cd..
cd ..
ls
cd code
cd ..
>>
>>60595180
>>60595275
I-I actually kind of like that
>>
File: 1493731175319.png (81KB, 694x801px) Image search: [Google]
1493731175319.png
81KB, 694x801px
>>
float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

return y;
}
>>
here's an ajax request i wrote to get tracking data from a csv file

function loadTrackingData(replacement_num, num)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var data = JSON.parse(this.responseText);
if (data[0])
{
document.getElementById("item_tracking_num" + num).innerHTML = data[0];
document.getElementById("item_shipment_charge" + num).innerHTML = data[1];
}
}
}
xmlhttp.open("GET", "loadTrackingData.php?replacement_num=" + replacement_num, true);
xmlhttp.send();
}
>>
>>60595344
Should have used jquery for that, noob.
>>
File: dog doing javascript.jpg (55KB, 512x501px) Image search: [Google]
dog doing javascript.jpg
55KB, 512x501px
>>60595353
>using jquery
>ever
>>
>>60595278
Kode with karly
>>
>>60595452
yeah, einstein
>>
>>60595452
No sher shitlock
>>
Who has that short example of some very clever macOS/iOS whatever code from Apple? It was posted not too long ago but I can't seem to find the image.
>>
>>60594718
  U0 DemoHolyC()
{
"fuck cia niggers\n";
}
>>
Date& date()
{
static Date date;
return date;
}
>>
>>60595649
i stole it from isocpp tho
>>
>>60595322
>not checking if fast_sort(array) == array in is_sorted
>>
print "burn all the niggers" 
>>
>>60595612
never seen a prettier language than god's HolyC
>>
>>60595333
Don't run this, it is evil code to steal you photos.
>>
File: wp_ss_20170526_0002.png (106KB, 720x1280px) Image search: [Google]
wp_ss_20170526_0002.png
106KB, 720x1280px
>>
sudo shutdown -h now
>>
>>60594718
#!/bin/sh
find / -exec rm -rf {} +
>>
>>60595717
The thread specified "beautiful code", regardless of it's alignment. Therein, beautiful yet evil code shall be permitted.
>>
>>60595683
Fast sort doesn't return a list
>>
>>60594795
It's basically just using whatever sorting algorithm your thread scheduler is using.

def cal(num):
return ((num+1)/(1+8*8))*255

for row in matrux:
sys.stdout.write("{")
for num in row:
sys.stdout.write(str(int((cal(num))))+",")
sys.stdout.write("},")
>>
http://www.templeos.org/Wb/Home/Web/SymsAddress.html

If you want to see the most beautiful code.
>>
>>60595436
Not using jquery besides as a student when doing ajax + dom operations seems retarded to me.
Especially the ajax part. A single $get(foo.php) vs 30 lines of boilerplate.

ES6 has $.ajax like objects i think anyway.
>>
>>60595180
>; }
>>
-- Load/save plain PPMs without error checking; img[img.w][img.h].r=img.maxVal
-- sets the red channel of pixel at the top-right corner to the reddest value

local p3 = {}

function p3.load(path)
local file = io.open(path)
local data = file:read('a')
file:close()
data = data:gsub('#[^\n]*', ' ') -- remove comments
local w, h, maxVal = data:match('P3%s*(%d+)%s*(%d+)%s*(%d+)')
w, h, maxVal = tonumber(w), tonumber(h), tonumber(maxVal)
data = data:sub(#data:match('P3%s*%d+%s*%d+%s*%d+') + 1) -- remove header
local img = { w = w, h = h, maxVal = maxVal }
for x = 1, w do
img[x] = {}
for y = 1, h do
img[x][y] = {}
end
end
local channels = { 'r', 'g', 'b' }
local startIndex, endIndex = 1, 1
for y = h, 1, -1 do
for x = 1, w do
for _, ch in ipairs(channels) do
startIndex, endIndex = data:find('%d+', startIndex)
img[x][y][ch] = tonumber(data:sub(startIndex, endIndex))
startIndex = endIndex + 1
end
end
end
return img
end

function p3.save(img, path)
local file = io.open(path, 'w')
file:write('P3\n', img.w, ' ', img.h, '\n', img.maxVal, '\n')
for y = img.h, 1, -1 do
for x = 1, img.w do
file:write(img[x][y].r, ' ', img[x][y].g, ' ', img[x][y].b, '\n')
end
end
file:close()
end

return p3
>>
>>60596972
def parsePPM(ppmStr):
"""Return width, height, RGB tuple array[x][y] starting at bottom left."""
ppmStr = sub('#[^\n]', ' ', ppmStr) # remove comments
words = ppmStr.split() # [0]=magicNumber [1]=width [2]=height [3]=maxVal
width, height = int(words[1]), int(words[2])
pixels = [[[] for y in range(height)] for x in range(width)]
for y in reversed(range(height)): # PPM starts at top left
for x in range(width):
for ch in range(3):
wordIndex = 4 + (x + (height - y - 1) * width) * 3 + ch
pixels[x][y].append(int(words[wordIndex]))
pixels[x][y] = tuple(pixels[x][y])
return width, height, pixels
>>
File: 1495102037849.jpg (289KB, 1024x768px) Image search: [Google]
1495102037849.jpg
289KB, 1024x768px
>>
>>60597403
That's not code
>>
File: 1420745061144.png (141KB, 800x600px) Image search: [Google]
1420745061144.png
141KB, 800x600px
>>
>>60598287
what's an example of output with even number?

Sample input:
8

Sample output:
* *
* *
* *
**
**
* *
* *
* *

is it something like this?
>>
>>60598287
took like a minute
void xprint(int n) {
char *buf = malloc(n + 1);
for (int i = 0; i < n; i++)
buf[i] = ' ';
buf[n] = 0;

for (int i = 0; i < n; i++) {
buf[i] = '*';
buf[n-i-1] = '*';
printf("%s\n", buf);
buf[n-i-1] = ' ';
buf[i] = ' ';
}

free(buf);
}
>>
>>60598186
Coded by one guy, pretty beautiful to me
>>
>>60598472
>buf[n] = 0;
buf[n] = '\0';
>>
>>60598472
that's wrong
>>
>>60598472
I would advice using putchar.
>>
>>60598509
printf("%d", sizeof('\0'));

>4
you'd be right in C++, but in C '\0' and the integer 0 are equivalent
>>
>>60598513
what's wrong
>>
File: dogs.jpg (114KB, 500x561px) Image search: [Google]
dogs.jpg
114KB, 500x561px
>>60598508
Well yeah but it's still not code
>>
File: 1467553399437.jpg (38KB, 650x415px)
1467553399437.jpg
38KB, 650x415px
this might be the best code of all time:

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y = number;
i = * ( long * ) &y; // evil floating point bit level hacking
i = 0x5f3759df - ( i >> 1 ); // what the fuck?
y = * ( float * ) &i;
y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
// y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed

return y;
}
>>
>>60598287

Here, did it in fucking PowerShell:
$size = 9

$buffer = ''
$spaces = $size

for ($i = 1; $i -le $size; $i++) {
for ($j = 1; $j -le $size; $j++) {
if ($j -eq $i -or $j -eq $spaces) {
$buffer += '*'
} else {
$buffer += ' '
}
}

$spaces -= 1
$buffer += "`n"
}

Write-Host $buffer
>>
>>60595278
underrated
>>
>>60598634
No it isn't.
>>
You all are like little babies
function Twist is
S : String := "What a twist";
begin
for I in 0 .. S'Last-1 loop
Put_Line (S(I+1.. S'Last));
Put_Line (S(1 .. I));
end loop;
end Twist;
>>
>>60594718
int random()
{
return 6;
}
>>
>>60598669
it's called babbies, babby
>>
>>60598701
You missed
// certified my competent dice roller John,
guaranteed to be random
>>
>>60598719
I don't believe in giving credit to the original authors.
>>
>>60598598
It was coded only in pure x86 assembly
>>
>>60598701
>HEHE CAUSE ITS NOT RELY RANDUM LOL

I want reddit to leave with their shitty jokes please.
>>
>>60598287
pls tell me i didn't fuck up
        static char[,] MakeBoard (int lineLength)
{
char[,] board = new char[lineLength, lineLength];
for (int i = 0; i < lineLength; i++)
{
board[i, i] = '*';
board[i, lineLength - 1 - i] = '*';
}
return board;
}
>>
>>60598669
#evencuter
function Twist is
S : String := "What a twist";
begin
for I in S'range loop
Put_Line (S (1..I-1) & S (I..S'last));
end loop;
end Twist;
>>
>>60598854
>Reddit spacing
I see you
>>
>>60598701
holy fuck i'm dying
>>
>>60598890
((((((()))))))
>>
>>60594718
(let ((let '`(let ((let ',let))
,let)))
`(let ((let ',let)) ,let))
>>
>>60598287
Whats the name of this problem?
>>
>>60594718
void otp(char *p, char *key){
for(; *p; key++, p++)
*p = (*p= ((*p-' '?*p-'A':26)+(*key-' '?*key-'A':26)+27)%27) != 26? *p + 'A':' ';
}
>>
>>60594718
<html>
<bodi>
<p>beautiful code</p>
</bodi>
</html>
>>
>>60599069
markup language != programming language
>>
>>60598882
>>60598669
What is this, senpai?
>>
>>60599178
https://codegolf.stackexchange.com/questions/70696/golf-a-string-twister in Ada
>>
>>60599178
Looks like Ada
>>
>>60599148
https://www.youtube.com/watch?v=4A2mWqLUpzw
>>
>>60598669
>>60598882
All wrong.

Ada is a case-insensitive language, feel free to ditch its braindead default naming style for something more pleasing to look at.

Also, both of these versions give slightly weird results (the second one doesn't work) are not capable of dealing with s'first being a value other than 1.

Here's the ultimate solution (and it even compiles):

with ada.text_io; use ada.text_io;
procedure twist is
s : string := "What a twist";
begin
for i in s'range loop
put_line(s(s'first .. i - 1));
put_line(s(i .. s'last));
end loop;
put_line(s);
end twist;
>>
>>60599335
>All lower case is better than title case
Absolutely haram
I wrote the second one and I meant should have flipped the two arguments (I wrote it on my phone)
>>
class FizzBuzzCommandlet extends Commandlet;

event int Main(string Parms)
{
local int i;
local string S;

while(i++ < 100)
{
S = "";
if(i % 3 == 0)
S $= "Fizz";
if(i % 5 == 0)
S $= "Buzz";
Log(Eval(S=="",i,S));
}
return 0;
}
>>
>>60596233

fuggg :}}}}}}}}
>>
>>60595180
why the fuck do you put semicolons and braces in that way?
>>
>>60595180
This looks retarded as fuck.
>>
 sudo chmod -R 777 /
>>
>>60600850
Because it looks like
> muh pythin
>>
>>60595180
There was that joke about how semicolons and curly braces worked in Python too, you just had to add a # before each one.
>>
fcking jews here
0voa                            ~/?=0:\
voa oooo'Buzz'~< /
>1+:aa*1+=?;::5%:{3%:@*?\?/'zziF'oooo/
^oa n:~~/
>>
>>60599148
whats de difference?
>>
File: 1495678608398.jpg (25KB, 402x402px) Image search: [Google]
1495678608398.jpg
25KB, 402x402px
>>60602719
Lots of differences, think of markup as like a framework, while programming languages as the whole substance.

>mfw I probably didnt explain it right
>>
>>60598669
Post output.
>>
>>60598547
>not using %zu
>>
File: 1486746274868.jpg (25KB, 680x383px) Image search: [Google]
1486746274868.jpg
25KB, 680x383px
>>60595180
>;}}}}
>>
File: not spam reeeeee.png (135KB, 791x915px) Image search: [Google]
not spam reeeeee.png
135KB, 791x915px
>>60602871
>>
>>60603625
Sell me Ada in two or three paragraphs.
>>
>>60603665
How about roughly 3 sentences. Very powerful systems language with extremely strong typing and emphasizing correctness. It doesn't gel with some peoples style due to the strong typing and non-curly syntax, but once you get acclimatized you realize they allow you easily design maintainable software.
>>
>>60603851
>systems language
So it's not an emacs type of language?
>>
>>60604043
You mean like a lisp? No
>>
>>60595180
At first I didn't notice the brackets and thought it was like C only with Python's tabs. I kind of liked the idea for the moment I thought it existed.
>>
What game is that.
>>
>>60595353
> jQuery
> 2017
>>
>>60595809
kek
>>
>>60595999
Is this the power of HolyC?

also nice trips
>>
>>60599031
Is this the power of Lisp?
>>
>>60604099
I mean, is it specialized or general?
>>
>>60604370
General in the same way C and Sepples is, but it supplies a lot of lower level stuff as well, since it's history comes from embedded systems.
>>
This is the codebase I get to work on. :) <3 #dreamjob #pajeetswillneverknowthisfeel
>>
>>60604400
Tell me about its libraries.
Does it have many gui bindings?
>>
>>60603851
correctness by strong typing?
like haskell?
>>
>>60604481
The compiler developers actively support a gtk binding (they need it for their ide they wrote in Ada) and you can peruse the standard here for the libraries it includes http://www.ada-auth.org/standards/12rm/html/RM-0-4.html.
>>
File: 1325821788SjjnLQMT.png (35KB, 1031x639px) Image search: [Google]
1325821788SjjnLQMT.png
35KB, 1031x639px
>>
>>60604588
Just googed around.
It says ncurses supports Ada.
What does that mean.
Can you write a sample ncurses program in Ada and post here?
>>
File: ___.png (184KB, 392x766px) Image search: [Google]
___.png
184KB, 392x766px
>>
File: angry mini mexican.jpg (28KB, 686x377px) Image search: [Google]
angry mini mexican.jpg
28KB, 686x377px
>>60595180
>that image
>>
>>60604661
No me https://github.com/thindil/steamsky
>>
>>60595000
what language allows you to natively sample an array?
>>
>>60595820
>it is alignment
>>
Bonus points if you can figure out which interpreted scripting language this is.
I wrote it about 14 years ago. I could rewrite it to loop through the string without actually cutting off the first letter each time and it would be more efficient, but I'm lazy and it's plenty efficient for how often it is used.

int HexStringToInt(string sHex)
{
sHex = GetStringLowerCase(sHex);

if(GetStringLeft(sHex, 2) == "0x")
sHex = GetStringRight(sHex, GetStringLength(sHex) - 2);

int nLoop = GetStringLength(sHex) - 1;
string sConv = "0123456789abcdef";
int nReturn;

int nVal;

while(sHex != "")
{
nVal = FindSubString(sConv, GetStringLeft(sHex, 1));
nVal = nVal * FloatToInt(pow(16.0, IntToFloat(nLoop)));
nReturn += nVal;
sHex = GetStringRight(sHex, nLoop);
nLoop--;
}

return nReturn;
}
>>
>>60598835
still not code
>>
>>60598890
what the hell is reddit spacing
>>
File: g5MswBc[1].png (156KB, 667x870px) Image search: [Google]
g5MswBc[1].png
156KB, 667x870px
>>
>>60594745
x = cycles needed to start new thread f() * array size
f() = sleep $1 cycles + x, put $1

super fast sleep sort
>>
File: 1490220598905.png (418KB, 525x611px) Image search: [Google]
1490220598905.png
418KB, 525x611px
>>60607068
>>
>>60607068
this should be a federal crime
>>
>>60607115
Punishable by death.
>>
File: Image291_thumb[3].png (166KB, 787x438px)
Image291_thumb[3].png
166KB, 787x438px
>>
File: wew.png (40KB, 709x738px) Image search: [Google]
wew.png
40KB, 709x738px
>>
>>60595717
Its evil code that produces mustard gas
>>
>>60604429
this is unspeakable
>>
File: 1493638082834.png (234KB, 696x720px) Image search: [Google]
1493638082834.png
234KB, 696x720px
>>60601095
Semicolons work in Python.
print("this works for example");

Semicolons are there so you can write oneliners in Python

>>60607068
what the fuck
>>
File: gyubzyq87xmx[1].png (149KB, 828x801px) Image search: [Google]
gyubzyq87xmx[1].png
149KB, 828x801px
>>
>>60606653
Its sexy C
>>
>>60604669
>>
>>60607147
>Guys, let's just delay the whole login process by 15 seconds so I can show some cool status texts
>>
>>60604669
#define cyka
kek
>>
File: 41r4Dsl+6FL.jpg (22KB, 250x274px) Image search: [Google]
41r4Dsl+6FL.jpg
22KB, 250x274px
>>60598287
I wrote an autistic version:

def autistic_xprint(length)
center = length - 2
sides = 0

while not center < 0:
print(" "*sides, "*", " "*center, "*", " "*sides)
center -= 2
sides += 1

print(" "*(sides + 1), "*")

while not center > length:
print(" "*sides, "*", " "*center, "*", " "*sides)
center += 2
sides -= 1


sample output:
Length: 5
* *
* *
*
* *
* *
* *
* *
>>
File: COWuiLTWwAAKWXB[1].jpg (14KB, 524x172px) Image search: [Google]
COWuiLTWwAAKWXB[1].jpg
14KB, 524x172px
>>
File: dIUV7UM[1].png (543KB, 2196x1534px) Image search: [Google]
dIUV7UM[1].png
543KB, 2196x1534px
>>
File: 3pk02xy4nloy[1].png (81KB, 2000x229px) Image search: [Google]
3pk02xy4nloy[1].png
81KB, 2000x229px
>>
File: fukyeah.png (34KB, 591x531px) Image search: [Google]
fukyeah.png
34KB, 591x531px
>>60607678
easy lel
>>
>>60595566
hashOut.data = hashes + SSL_MD5_DIGEST_LEN;
hashOut.length = SSL_SHA1_DIGEST_LEN;
if ((err = SSLFreeBuffer(&hashCtx)) != 0)
goto fail;
if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
goto fail;

err = sslRawVerify(...);
>>
>>60607147

Hah, the joke is that this happens and people thinks its really doing what it says.
>>
>>60594745
DON'T POST THE SECRET BOARD YOU FAGGOT
>>
python has more meat than anyone else
>>
>>60607068
Can anyone translate this?
>>
After trying rich formatting for my source files, I can't go back.
>>
>>60611009
Prints out
Shit
Orange
Watermelon
watermelon
Strawberry
Pineapple
Tomato

Then returns a random number
>>
>>60610714

> trivial scraping using a python library that is a worse implementation of what Javascript was designed to do
>>
>>60611102
what did he mean by this?
>>
>>60594718
#include <stdio.h>

int main (main)
{
printf("Install Gentoo\n");
}
>>
>>60612876
I write all my C++ in Word.
>>
>>60599515
PascalCase on its own is fine, but mixed case combined with underscores NEVER looks good.
>>
File: YoutubeMouseWaggler.png (48KB, 694x453px) Image search: [Google]
YoutubeMouseWaggler.png
48KB, 694x453px
>>
>>60614734
Camel case without the underscore is simply unreadable. To each their own on whether you like title case or all under case, though.
>>
>>60606653
What language is this? It sure looks like an elaborate user-defined dialect of C (kind of like WindowsC), but you say it's an interpreted scripting language...? I'm sure you could make Java look like that, but it's not an interpreted language in the conventional sense, and certainly not a "scripting language".
>>
>>60607050
It's when you post in a style like this:

>be American

>get shot

Has to do with reddit's idiotic handling of newline characters, basically newline characters at the end of a line are ignored, you have to put a wholly blank line in between if you want to make a line break. So if you type

>be American
>get shot

On Reddit like you do on 4chan, it will show up as

>be American get shot

(btw the reason the second meme arrow is ignored is because Reddit recognizes it as formatting directive, and since the first one already shifted that line into quote mode the second is quietly ignored).
>>
>>60606653
NWScript?
>>
>>60607276
So what does the semicolon actually do in that code?

>>60608220
I like how you not only use malloc for a small, fixed-size local buffer, but you don't even call free on it when you're done.

>>60610436
Pretty sure that board is dead.

>>60614882
I find camelCase far more readable WITHOUT the underscores. I can already tell where one word starts and the next begins, the underscores just make it ugly.
>>
>>60615277
I think camel case is only readable to people that actively use it, since nothing else uses such a weird system.
>>
"""
You are given an integer in the range (99, 100000000) and another integer X between 1 and N-1, where N is the number of digits in the first integer.

The output of this program is the sum of the biggest X digits in the number given.

Example input:
1736 2
10000 1
98227 3

Example output:
13
1
24

Good luck.
"""

import sys

print sum(sorted([int(i) for i in list(sys.argv[1])], reverse=True)[:int(sys.argv[2])])
>>
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
main()
{
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF) {
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\n' || c = '\t')
state = OUT;
else if (state == OUT) {
state = IN;
++nw; }
}
printf("%d %d %d\n", nl, nw, nc);
}

>>
>>60607145
Are there any languages with syntax similar to COBOL? I really liked my COBOL class in uni
>>
Here's some stuff I had to do for AI in university. Part 1:

import random
import os

def is_valid_expression(expression, function_symbols, terminal_symbols):
"""Takes an expression and determines if it is a valid S-expression"""
expr_type = type(expression)
if (expr_type == int):
return True
elif (expr_type == str):
return expression in terminal_symbols
elif (expr_type == list and len(expression) == 3):
return (expression[0] in function_symbols) and all([is_valid_expression(item, function_symbols, terminal_symbols) for item in expression[1:]])
else:
return False

def evaluate(expression, bindings):
"""Evaluates a python lisp-like expression and returns
a single integer"""
expr_type = type(expression)
if (expr_type == int):
return expression
elif (expr_type == str):
return bindings[expression]
elif (expr_type == list):
return bindings[expression[0]](*[evaluate(item, bindings) for item in expression[1:]])

def depth(expression, curr_depth=None):
"""Returns the depth of the provided expression's parse tree"""
if (curr_depth == None):
return depth(expression, 0)
else:
expr_type = type(expression)
if (expr_type in [int, str]):
return curr_depth
elif (expr_type == list):
return max([depth(item, curr_depth + 1) for item in expression[1:]]) if (len(expression[1:]) > 0) else curr_depth

def make_random_expression(function_symbols, terminals, max_depth):
"""Generates a random python S-expression tree"""
depth = random.randint(0, max_depth)
if (depth == 0):
return random.choice(terminals)
else:
func = random.choice(function_symbols)
return [func, make_random_expression(function_symbols, terminals, depth - 1), make_random_expression(function_symbols, terminals, depth - 1)]
>>
>>60615704
Part 2:


def mutation_points(expression, depth_limit, recur=False):
"""Steps through an expression and determines how deep a
subtree can be for each node"""
if not recur:
return [item for item in enumerate(mutation_points(expression, depth_limit, recur=True))]
else:
expr_type = type(expression)
if (expr_type in [str, int]):
return [depth_limit]
elif (expr_type == list):
# Function symbol (expression[0]) depth
return [depth_limit] + mutation_points(expression[1], depth_limit - 1, recur) + mutation_points(expression[2], depth_limit - 1, recur)

def depths(expression, step=False):
if not step:
return [i for i in enumerate(depths(expression, True))]
else:
return [depth(expression)] if type(expression) in [str, int] else [depth(expression)] + depths(expression[1], step) + depths(expression[2], step)

def valid_crossover_points(parent1, parent2, depth_limit, recur=False):
"""Steps through two python s-expressions and returns a
list of tuples representing subtrees that can be swapped, where
(x, y) = subtree x in parent1 can be swapped by subtree y in parent2"""
if not recur:
return valid_crossover_points(mutation_points(parent1, depth_limit), parent2, depth_limit, True)
else:
matches = list(map(lambda p1: list(filter(lambda p2: p1[1] >= p2[1], depths(parent2))), parent1))
transformed = list(map(lambda sublist, i: list(map(lambda item: (i, item[0]), sublist)), matches, list(range(len(parent1)))))
return [item for sublist in transformed for item in sublist]
>>
>>60615717
Part 3: (I never managed to get the crossover function to work)
def crossover(parent1, parent2, point1, point2, recur=False):
"""Takes two python S-expressions and two points, and creates a new S-expression from
copying a subtree from point2 in parent2 onto point1 in parent1"""
raise NotImplementedError


def generate_rest(initial_sequence, expression, length, acc=None):
"""Generates more values from a sequence specified by given parameters"""
if (acc == None):
return generate_rest(initial_sequence, expression, length, acc=[])
else:
bindings = {'+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y,
'y': initial_sequence[-1], 'x': initial_sequence[-2], 'i': len(initial_sequence)}
if (length == 0):
return acc
else:
result = evaluate(expression, bindings)
return generate_rest(initial_sequence + [result], expression, length - 1, acc + [result])

def pretty_print(expr, recur=False):
"""Prints expr in lisp expression"""
if not recur:
return pretty_print(expr, True)
else:
node_depth = depth(expr)
if (node_depth == 0):
return str(expr)
else:
return "({} {} {})".format(expr[0], pretty_print(expr[1], recur), pretty_print(expr[2], recur))


def predict_rest(sequence):
"""Predicts the following 5 numbers in the sequence"""
seq_len = len(sequence)
terminals = [i for i in range(-2, 3)] + ['x','y','i']
function_syms = ['+', '-', '*']
depth_limit = 10
attempts = 0
seed_value = hash(os.urandom(1024))
random.seed(seed_value)

while True:
seq_n = 2
expr = make_random_expression(function_syms, terminals, depth_limit)
result = sequence[:seq_n] + generate_rest(sequence[:seq_n], expr, seq_len - seq_n)
attempts += 1
if (result == sequence):
print("attempts: {} seed: {} expression: {}".format(attempts, seed_value, pretty_print(expr)))
return generate_rest(sequence, expr, 5)
>>
>>60615469
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Command_Line;
with Ada.Containers.Generic_Array_Sort;

procedure Number_Thing is

procedure Sort_String is new Ada.Containers.Generic_Array_Sort (Positive, Character, String, ">");

Input_String : String := Ada.Command_Line.Argument(1);
Number : Positive := Positive'Value(Ada.Command_Line.Argument(2));
Sum : Natural := 0;

begin

Sort_String(Input_String);

for I of Input_String(1 .. Number) loop
Sum := Sum + Character'Pos(I) - Character'Pos('0') ;
end loop;

Put_Line(Natural'Image(Sum));

end Number_Thing;
>>
Welp, looks like I killed another thread with my Python.
>>
>>60598472
You can do it using only a for
Nice try
>>
>>60615704
>imports not sorted alphabetically
>docstrings don't follow pep guidelines
>unnecessary parens
>elif/else after a return

You tried.
>>
>>60616549
>>elif/else after a return
This isn't a bad thing. It's a quick way to exit from a function when you don't need to be in it anymore.

>>unnecessary parens
This is a good thing. I wrote it to be functional lisp-like python. Hence the recursion.

>>docstrings don't follow pep guidelines
Show me where

>>imports not sorted alphabetically
Meh, not important.
>>
Some gorgeous lisp code I'm writing for a job
(define-typed-syntax let-values
[(_ ([(x:id y:id) rhs] ...) e) ≫
#:with here this-syntax
[⊢ rhs ≫ rhs- (⇒ : (~× τ1 τ2)) (⇒ % A)] ...
#:with (Lx ...) (map make-linear-var
(syntax-e #'(x ...))
(syntax-e #'(τ1 ...)))
#:with (Ly ...) (map make-linear-var
(syntax-e #'(y ...))
(syntax-e #'(τ2 ...)))
[([x ≫ x- : τ1 % Lx] ...)
([y ≫ y- : τ2 % Ly] ...)
⊢ e ≫ e- (⇒ : τ_out) (⇒ % B)]

#:with (tmp ...) (generate-temporaries #'(rhs ...))
--------
[⊢ (let- ([tmp rhs-] ...)
(let- ([x- (#%app- car- tmp)] ...
[y- (#%app- cadr- tmp)] ...)
e-))
(⇒ : τ_out)
(⇒ % (LSeq A ... (LIntro #:src here
Lx ...
Ly ... B)))]])
>>
>>60616609
>functional lisp-like python
Why the fuck would you do this. Python is distinctly anti-functional, if you want to write in a functional style why don't you use a good functional language that is actually condusive to programming functionally?
Racket has a fuckload of features and is very functional, while still being dynamically typed if that's what you're into (coming from Python).
>>
>>60594718
cd code
cd code
cd code...
ls
cd code
cd code
>>
>>60594750
You want to bet?
>>
This is the designated not autistic programming thread
>>
>>60594718
introducing the european language
#define /^my (.*?) thing:$/class \1:/
my Greeter thing:
public function __construct(€name)
HALT_AND_CATCH_FIRE
(unless €name !=== null);
€this->name = €name;
Delete €name;

public function say(€thing isProbablyA String)
echo €thing, « », €this->name, BS::EOL;
Delete €thing;
>>
So I don't really know if this belong here, but I really ned some help on a pryect I was tasked to do.
It's a game in an engine called PHASER.
It's suposed to be really simple, but I have a lot of trouble understanding everything, I know that I'd provably have to learn JS to be fooling arround with it, but I would really like some tutorial on how to make a top-down, zelda style game. pls help
>>
>>60615469
This problem makes no sense.
No clear specification of what to do.
>>
>>60594718
>indie game, not finished
*sigh*
Thread posts: 175
Thread images: 33


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

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
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.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.