/dpt/ - Daily Programming Thread

old thread: What are you working on, Sup Forums?

Other urls found in this thread:

preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers/
en.wikipedia.org/wiki/Dependency_injection
en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants
ideone.com/lJdnsz
hashcode.withgoogle.com/
inventwithpython.com/chapter10.html
twitter.com/NSFWRedditGif

trying to make a JSON parser for school

I love this meme.

Sup Forums working on things?

:3333

No, the skirts.

haven't done much programming because my job is obsessed with the docker meme lately

What's the easiest way to make an inner class object aware of an outer class member in C++?

I figured out the solution.

So, to generate a psuedorandom sequence of unique pairs, we need to make an assumption: the range of x and y in the tuple (x,y) are the same, meaning that they both go from 0 to n.

Literally all you have to do is generate a psuedorandom unique integer sequence with a maximum value of n*n, and then x = f[i] / n, y = f[i] % n.
The psuedorandom unique sequence generator would be written according to the blogpost: preshing.com/20121224/how-to-generate-a-sequence-of-unique-random-integers/
Boy, that was easier than I thought it would have been.

dependency injection by passing the outer class into the inner class

en.wikipedia.org/wiki/Dependency_injection

This solution is O(1) in time AND memory complexity by the way.

Rate my tic tac toe made in python 3
pls be gentle senpai
# Tic Tac Toe Try 2
#Define space object
class Space:
def __init__(self,x,y,S=0):
self.x = x
self.y = y
self.S = S
def __str__(self):
if self.S == 1:
return "X"
elif self.S == 0:
return " "
elif self.S == -1:
return "O"
else:
return "Error"
def update(self,n):
self.S = n
#Lists with the 9 spaces
SPACE1L = [Space(1,1),Space(1,2),Space(1,3)]
SPACE2L = [Space(2,1),Space(2,2),Space(2,3)]
SPACE3L = [Space(3,1),Space(3,2),Space(3,3)]
#Board printing function
def printboard():
board = '''
y
|
|3|%s|%s|%s|
|2|%s|%s|%s|
|1|%s|%s|%s|
|1|2|3|--x ''' % (SPACE3L[0],SPACE3L[1],SPACE3L[2],SPACE2L[0],SPACE2L[1],SPACE2L[2],SPACE1L[0],SPACE1L[1],SPACE1L[2])
print(board)
#Function that checks for line of three
Statuzer = lambda x: x.S
def checker():
S1L = [Statuzer(x) for x in SPACE1L]
S2L = [Statuzer(x) for x in SPACE2L]
S3L = [Statuzer(x) for x in SPACE3L]
D1L = [Statuzer(x) for x in [SPACE1L[0],SPACE2L[0],SPACE3L[0]]]
D2L = [Statuzer(x) for x in [SPACE1L[1],SPACE2L[1],SPACE3L[1]]]
D3L = [Statuzer(x) for x in [SPACE1L[2],SPACE2L[2],SPACE3L[2]]]
DiaRL = [Statuzer(x) for x in [SPACE1L[2],SPACE2L[1],SPACE3L[0]]]
DiaLR = [Statuzer(x) for x in [SPACE1L[0],SPACE2L[1],SPACE3L[2]]]
for a in [S1L,S2L,S3L,D1L,D2L,D3L,DiaRL,DiaLR]:
global PWON
if sum(a) == 3:
PWON = P1NAME
return True
if sum(a) == -3:
PWON = P2NAME
return True
else:
pass
#Winner function
def winner():
if k == 0:
print("Congratulations %s you won!" % (PWON))
else:
return

cont
#Get Coordinates from Input Function
k = 0
def askcord(ps):
global k
checker()
if checker():
winner()
k = 1
else:
avail = ["1","2","3"]
if ps == 1: det = P1NAME
elif ps == -1: det = P2NAME
print("Please enter a coordinate (Player %s) (x,y):" % (det))
rawcord = list(input("> "))
cord1s = [n for n in rawcord if n in avail]
if len(cord1s) != 2: askcord(ps)
cord1s = [int(x) for x in cord1s]
if cord1s[1] == 1:
if SPACE1L[cord1s[0]-1].S == 0:
SPACE1L[cord1s[0]-1].update(ps)
printboard()
else:
askcord(ps)
elif cord1s[1] == 2:
if SPACE2L[cord1s[0]-1].S == 0:
SPACE2L[cord1s[0]-1].update(ps)
printboard()
else:
askcord(ps)
elif cord1s[1] == 3:
if SPACE3L[cord1s[0]-1].S == 0:
SPACE3L[cord1s[0]-1].update(ps)
printboard()
else:
askcord(ps)
else: askcord(ps)


printboard()
#Ask for names
P1NAME = str(input("Player 1 Name: "))
P2NAME = str(input("Player 2 Name: "))
askcord(1)
askcord(-1)
askcord(1)
askcord(-1)
askcord(1)
askcord(-1)
askcord(1)
askcord(-1)
askcord(1)
if not checker():
print("Game end, Nobody won")

Is posting broken

Clearly.

professional python programmer here.

- work on your variable names. things like S1L and S2L don't make any sense. good code doesn't need comments because you can tell what it does from variable names and control flow
- proper scoping of data. stay away from the global keyword
- lot's of if/else statements is a kind of code smell; there is most likely a simpler way of doing things
- you have lot's of "magic numbers" (eg. sum(a) == 3)in your code; stay away from them or make constants for them to show they are special

en.wikipedia.org/wiki/Magic_number_(programming)#Unnamed_numerical_constants
- lot's of repetitive code like [Statuzer(x) for x in blah]

BIP 44 Derivation paths for our product

I'm getting the impression the rust devs are synthetically targeting the benchmarks game programs to make it look faster than they do in the real world.

Everybody does that tho.

Your x row comment is triggering my autism, it doesn't line up.

But how can I reduce the quantity of if/else?
Was thinking on defining a function but I would prefer to read what would you do

#include
#include
#include

class Foo
{
public:
Foo() {
arry[0] = "foo";
arry[1] = "bar";
arry[2] = "baz";
arry[3] = "qux";
}

// template
// void each(T func)
// void each(const std::function &func)
void each(std::string (* func)(std::string ele))
{
for(int i = 0; i < size; i++) {
func(arry[i]);
}
}

int size = 4;
std::string arry[4];
};

int main(void)
{
Foo foo;

foo.each(
[](std::string str) -> std::string {
std::cout

>C++
Why on earth would you use that shit?
Also, I doubt that a C++ lambda is compatible with a function pointer.

Maybe the maintainers of jruby or some trash, but the previous top 3 have been consistent for years but in two weeks rust jumps from #4 to #2? I'm dubious.

it usually means you need to come up with a better algorithm. you built a program around an algorithm that handled a few cases, but now you have to use a bunch of if/else statements to handle everything else.

>>C++
>Why on earth would you use that shit?
cause I wanna make money

>for years
Rust has been stable for less than two years, it takes some time for people to come up with implementations that are competitive with benchmarks for languages that have been around for decades. There's no reason for Rust to be slower.

so let me give you an idea of where you could take this...

instead of seeing tic-tac-toe as a cartesian graph that has X's and O's in it what if we saw it as a matrix of just 0's and 1's? what if we had a matrix for player 1 and matrix for player 2? could we use matrix math to compute intersections and so on?

>matrix operations
>in python

socialism doesn't work, neither does gpl
forcing people to do a certain thing never works
it's why there's barely any contributions to open source

> The one that is not commented out causes a runtime error.
It works just fine - ideone.com/lJdnsz . What compiler/version do you use?

Which is better for fibonacci.

Number 1:

#include

using namespace std;

int main() {

int r, ft = 0, s = 1, f = 0;

cout r;
cout

Both are retardedly over complex for fibo.

So they came up with a more efficient code, it doesn't mean there's some sort of conspiracy. Rust is a compiled language without GC with LLVM backend, there is no inherent reason it shouldn't be on par with C/C++.

you should learn haskell, which is objectively the #1 lang for writing fibonacci

the win condition checker makes me sad.
i suggest you make one that can test n in a row in an x*y grid and just set them all to 3 in the beginning so you can easily make the game more customizable

The two weeks part is the interesting part. It wasn't incremental increases over months.

no this one is
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

Any of you faggots signed up for hashcode.withgoogle.com/ ?

You do compete, don't you?

No.

Nice exponential solution you have ther.e

Holy fuck, your code is hideous.

>he doesn't compete

>unironically doing Google's work for free

That's because they updated the regex library used in regex-dna to a newer and faster version and replaced the standard library (unordered) hashmap in k-nucleotide with a insertion-order preserving hashmap (Literally a drop-in replacement). These two small changes made Rust first in both benchmarks.

>void each(std::string (* func)(std::string ele))

Why is the function parameter returning a string? Unless I'm missing some functionality you're looking for in returning a string (and it doesn't look like it looking at the way you're calling it), just make it a void function:
#include
#include
#include

class Foo
{
public:
Foo() {
arry[0] = "foo";
arry[1] = "bar";
arry[2] = "baz";
arry[3] = "qux";
}

// template
// void each(T func)
// void each(const std::function &func)
void each(void (* func)(std::string ele))
{
for(int i = 0; i < size; i++) {
func(arry[i]);
}
}

int size = 4;
std::string arry[4];
};

int main(void)
{
Foo foo = Foo();

foo.each(
[](std::string str) -> void {
std::cout

Hey tic tac toe guy. Check this link out and compare it your own program. See how you can improve.

inventwithpython.com/chapter10.html

That is fucking awful. It's overcomplicated as fuck.

That because it is a tutorial you retard. It is supposed to be complicated for teaching certain concepts. Doesn't mean the implementation of certain functions are bad. If you don't compare your code with others good or bad, you will never learn.

>It is supposed to be complicated for teaching certain concepts
That's fucking ass-backwards. Teaching materials should be simple and well-written.
You're going to give the impression that this is how you should write code.

>It works just fine - ideone.com/lJdnsz . What compiler/version do you use?
g++ 5.4.0 was crashing for me after printing foo. I compiled using VS2013 on another computer and it ran fine. Go figure.

>Why is the function parameter returning a string? Unless I'm missing some functionality you're looking for in returning a string (and it doesn't look like it looking at the way you're calling it), just make it a void function:
I originally had the returned string getting assigned to something, but I removed it for clarity. Was the original code crashing for you at all using gcc or clang?

What's the easiest way of implementing a fully-functional binary search tree? With a collection of structs?

It's not my code. It's code from a github project. I was just asking lol.

It is over complicated for a tic tac toe program but the logic and design steps are sound. Of course these steps are meant for more complex programs but they use tic tac toe as an example because it is a tutorial and people understand the concept of tic tac toe.

Yes.
struct bst {
int data;
struct bst *left;
struct bst *right;
};
is literally all you need.
The actual trick to it is height-balancing.

PYTHON HELP
so I have
if "good" or "great" in choice:
print("Glad to hear that!")
start()
elif "bad" in choice:
print("Sorry to hear that "+username+"...")
start()
else:
print("Sorry I didn't recognize that")
start()

but it wont output Sorry to hear that "+username+"..." when I put bad been happening since I added if "good" or "great" in choice:

did I retard it up? what did I do wrong?

Yeah, crashed when I compiled with gcc but ran fine with clang.

I wonder if it would crash using a primary type rather than a string. It didn't crash with void

Also worth asking is why we're passing std::string by value and not by const reference.

When I use fork() in C/C++, does the kernel allow me to take advantage of multiprocessing without any additional effort on my part?

Just skimming over the code, I'm seeing all sorts of travesties.
Duplicated code.
Not taking advantage of loops in some situation.
Using poinless loops in other situations.
Using strings when some sort of enumerated type is more appropriate.
Pointless functions.
Being written in memesnek.
And so on.

>without any additional effort
No. Now you have IPC to deal with, which is not a trivial thing to do.

elif means else if
If good or great has been detected it will skip lines with else

Convince me that using void pointers as numbers is wrong (example below)

#include
#include

typedef struct VectorList
{
int size;
int count;
void **data;
} VectorList;

VectorList *Vector_create(void)
{
VectorList *vector = malloc(sizeof(VectorList));
vector->count = 0;
vector->size = 0;
vector->data = NULL;
return vector;
}

void Vector_add(VectorList *vector, void *element)
{
if(vector->size == 0)
{
vector->size = 8;
vector->data = malloc(sizeof(void*) * vector->size);
}
if(vector->size == vector->count)
{
vector->size *= 2;
vector->data = realloc(vector->data, sizeof(void*) * vector->size);
}
vector->data[vector->count] = element;
vector->count++;
}

int main(void)
{
VectorList *vector = Vector_create();
int i;
Vector_add(vector, (void*)5);
Vector_add(vector, (void*)44);
Vector_add(vector, (void*)3);
Vector_add(vector, (void*)50);
Vector_add(vector, (void*)5);
for(i = 0; i < vector->count; i++)
{
printf("Element %d is the number %d\n",i,vector->data[i]);
}
}

Can someone explain this stupid meme?

How does python development work?
For my job I said, "yeah learning python should be easy," because purely from a programming perspective it shouldn't be that difficult to pick up.
but then I was like
>fucking packages
>fucking fragmented versioning system
>fucking shitty IDEs
>fucking having to use Python 2 and 3 at the same time
What masochist uses this language for actual software engineering and how do they do it?

tried changing the elif to an if and it still has the same problem, have i misunderstood you?

Well you won't lock or run into concurrency errors or anything (assuming you're only accessing local variables), but unless you have a clever way of dividing up the problem in a fundamentally parallel way, you're probably just running a bunch of duplicate threads doing duplicate things. Which isn't exactly what I would call "taking advantage of multiprocessing."

Pycharm is fine. Legacy code is always cancer and because it is my job.

Do any of you dudes have an interesting project idea for a multilayer system? Need to pick a semester long project for school

Yes, the kernel tries to distribute the load evenly on all cores, so it will schedule the new process on an idle core if it has one.

fork() creates a second process that is an exact copy of its parent. The kernel should allow both processes to be scheduled simultaneously if need be. However, since they are both different processes, they cannot share the same address space. They will need to communicate through some other means, such as IPC sockets, pipes, etc...

>but it wont output Sorry to hear that "+username+"..." when I put bad been happening since I added if "good" or "great" in choice:

Explain this sentence again since I get the impression you want bad to happen if good or great are also present in choice.

>exponential
lmao fucking idiot

no I want it to say "Glad to hear that user" if the user inputs a sentence containing good or great so like "doing good" or "I'm doing great" or any variants containing good or great, but if the user puts bad in the sentence it says "sorry to hear that user..."

I'd tell you ``Just use MPI'', but then I realized you're probably a student.
Good luck fgt you're gonna need it

>but if the user puts bad in the sentence it says "sorry to hear that user..."
should say I want it to say "sorry to hear that user"

Ah I see. Easy.
Here if what you think is happening:
If (good or great) in choice
What is really happening:
If (good) or (great in choice)

Or is for two conditionals
Not for combining 2 conditions

cause you'll be wasting space in a 64-bit environment

and also the practice is horrid unless you have an explicit reason why you need to do it

It's inelegant, cast-heavy shit.

formatting like this solved it
>If (good or great) in choice
thanks user

Why don't you just use C++, this shit is easier, safer and more efficient with templates.

Ruby senpai, I really love D lang. Please say some good things about it.

>market share
I never care about it, I dualboot Linux and FreeBSD

>sepples
>ever
go away nobody likes you.

You can also use the find method to make it clearer. So

if choice.find("good") or choice.find("great):

>I don't want my code to be cleaner, safer and more efficient because memes
Whatever you say, bud.

>template mess makes you code cleaner
Were you always retarded or did programming in sepples turn your into one?

if you think templates obfuscate code, git gud

thats really all there is to it

Well, if I wanted to use that data structure for say, a list of numbers, then my alternative is to either modify it to use macro templates, or malloc(sizeof(int))

Or, more relevant was using a struct that was basically a generic action:
typedef struct
{
void (*callback)(void *data);
void *data;
} Generic action;

that had a function pointer and then a void data pointer that could be anything, and the function pointer would have to interpret it. So I was thinking I could skip allocating more RAM for the integer and use the void pointer.

Sometimes I think that would be nice but I'm in a strange situation where C++ might be slow (working on 486)

(Sorry for bad formatting I'm phoneposting right now)

Post acknowledged.
Opinion discarded.

>That spacing and formatting
It's no surprise that the fucking sepplesfag is a redditor.
Piss off.

Haskell polymorphism is much better than C++ templates

>templates make ur code messy

>"hurr its much cleaner in 's situation to use either function pointers or a whole mess of macros"
C autists everybody

>C
Why isn't C banned yet? Why are idiots circlejerking about retro trash language like C?

t. Rust code artisan

For instance

template
vector map(std::function, vector);
//n.b. i am ignoring qualifiers, enable_if and other stuff necessary to use non-std::functions, etc

haskell:
(t -> r, Vector t) -> Vector r

t. turbo expert super secret kernel hacker of 4chen

I prefer the term 'code cuckold', thank you very much

How to trigger /dpt/ and simultaneously show that you're capable of earning money, unlike the /dpt/ autists: the image

get on my level faggot

I'm born in the wrong generation. I wish more of my generation would appreciate C. 80's was the best XD

>not in java