[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
/dpt/ daily programming thread
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: 255
Thread images: 14
File: 300px-Point_quadtree.svg.png (21 KB, 300x300) Image search: [Google]
300px-Point_quadtree.svg.png
21 KB, 300x300
CS fundamentals edition

Old: >>54236916
>>
>>54244786
How hard would it be to implement an array-backed quadtree?
>>
>>54244820
Really easy.
>>
>>54244820
not hard at all
>>
>>54244820
super hard
>>
post more shitty code
>>
>>54244786
Is fgets() the best function in C for receiving string input via stdin?
>>
>>54244826
>>54244837
>>54244846
please guys this is imporatnt
>>
binary tree vs quad tree vs octree vs ???
>>
>>54244820
You would need to store some metadata, but shouldn't be too hard
>>
>>54244858
Pretty much, at least without using non-standard stuff.
>>
>>54244862
it's easy as fuck what are you struggling with
>>
>>54244858
It's what I usually use
>>
>>54244882
>>54244893

Thanks. What is the usual instance for using scanf? Is there an advantage to either function? I just thought scanf was inappropriate for strings because it cuts off the input stream at the first space.
>>
>>54244867
Dumb question. Depends entirely on your usage.

>>54244920
Don't use scanf ever. Use fgets and sscanf and any other string processing functions you might need.
>>
>>54244920
>What is the usual instance for using scanf?
scanf is very fragile. It doesn't handle errors particularly well, and can leave the input stream in a partially read state.
I pretty much never use scanf and opt to use fgets + some other parsing functions instead. Although sscanf is still very useful.
>Is there an advantage to either function?
fgets just reads a string. *scanf tries to parse the input.
>I just thought scanf was inappropriate for strings because it cuts off the input stream at the first space.
That, as well as scanf on unbounded strings can overflow buffers.
char buf[4];
scanf("%s", buf);

with the input "12345" will overflow the buffer.
You can do
scanf("%4s", buf);
to limit the string read though.
>>
I've been refactoring and micro-optimising my application for over a week now because I can't muster the motivation to write the introduction to the academic paper about it.
>>
Anyone here play codingame?

It's quite fun, we should have /dpt/ private matches sometime
>>
>>54244977
>Dumb question. Depends entirely on your usage.
talk about the usage then fuckface
>>
File: 1461647933786.webm (2 MB, 710x540) Image search: [Google]
1461647933786.webm
2 MB, 710x540
What's the best thing to drink while programming and why is it soju
>>
>>54244867
2^n-tree, where n is the amount of dimensions you want

a binary tree for one-dimensional areas
a quadtree for two-dimensional areas
an octotree for three-dimensional areas

etc.
>>
>>54245042
Poor cat
>>
I don't really understand what a binary tree is supposed to do.
>>
>>54245017
Binary trees are good for storing data that can be easily compared and gives you O(log(n)) inserts, deletes, updates, min, max etc. so it has a good balance to the O of it's operations. If you are going to need data and will equally use all those functions use a binary tree.

n-ary trees of any n besides 2 are only to be used if whatever data you are modeling actually fits well into that, which is very very few problems. You'll never use them.
>>
>>54245055
cool but why exactly 2^n
>>
>>54245071
You're wrong. Quadtrees are very nice.
>>
>>54245042
I wish it was easier to find soju here.
>>
>>54245070
It's a tree, with two children per node. Hence 'binary'.
It's a fundamental data structure.
>>
>>54245071
>n-ary trees of any n besides 2 are only to be used if whatever data you are modeling actually fits well into that, which is very very few problems. You'll never use them.
what about 2d and 3d games environments or is there some other trick to them
>>
>>54245101
I guess my problem is that I don't really understand what is supposed to be going on or what kind of output there is to be expected from it.
>>
>>54245084
>binary : 2 child nodes
>quadtree : 4 child nodes
>octree : 8 child nodes
You tell me.

>>54245088
For what? I've only seen them used for modeling shortest paths in a 2D pixel graph.

>>54245104
Not everyone programs vidya. And outside of the people who do no one cares because that's the only case I've seen for them.
>>
>>54245145
but why do you want 8 child nodes for 3d instead of 3 or 9 or 16 or ...
>>
>>54245084
You add 2 new directions with every dimension

First one has left and right, next has up and down, third has 2 more
>>
>>54245163
oh wait it's because it's like subdividing a cube into cubes
>>
>>54245163
Are you retarded? Do you even know what a tree data structure is?
>>
>>54245137
It's just used for storing data. If a code example helps, here is how you would define a binary tree in C:
struct binary_tree {
int some_data;
struct binary_tree *left;
struct binary_tree *right;
};

There is a lot of computer science literature about binary trees. It's a very efficient data structure if implemented and used properly.
>>
>>54245163
How many sides are there on a cube?
>>
>>54245163
Even splitting with smallest possible factor.

Smallest factor for cutting line is cutting into 2 lines.
4 squares from one square
8 cubes from one cube
16 hypercubes from one hypercube, if you are well-versed in the jewish kabbalistic arts.
>>
>>54245187
6
>>
>>54245199
Shit. I'm drunk. Fuck me.
>>
>>54245185
Damn, I was already breaking my head on how to implement when C already has the necessary functions.
Anyway, thanks a lot, your example actually cleared everything up.
>>
>>54245187

What kind of cube?
>>
>>54245199
There are 8 combinations of directions in 3 axes.
>>
File: round ice cubes.jpg (136 KB, 1000x1000) Image search: [Google]
round ice cubes.jpg
136 KB, 1000x1000
>>54245229
>>
>>54244977
>>54245002

So what data types are best suited to fgets and sscanf? Or is it more to do with other factors, like memory size, what will happen with the data etc.

I always suspicious of scanf when I started learning about it because it seems so volatile and restrictive. For example, entering a character/string when it's expecting an integer or float makes the entire program execution spaz out. No failsafe whatsoever.
>>
I'm 80% sure a cube has 6 sides.
>>
>>54245319
6 faces
8 vertices
8 edges
>>
>>54245290
http://linux.die.net/man/3/fgets
>>
File: c9a.png (225 KB, 373x327) Image search: [Google]
c9a.png
225 KB, 373x327
>>54245334
FUCK

12 edges
>>
>>54245334
Wrong
>>
>>54245016
pls respond
>>
That makes sense. I've never heard someone refer to a vertex as a side before.
>>
>>54245335
Thanks for the link.

If gets() is basically just fgets with stdin, why use fgets(var, size, stdin) instead of the gets() function?
>>
>>54245394
fgets can be used with files n shit
>>
What projects on Github has /g/ contributed to? I'm looking for a good project to work on. Preferably in C/C++ or maybe even Python.
>>
>>54245394
gets will write as many characters as input to your buffer. If your buffer is 20 characters, but the user types 30, it will write past your buffer, corrupting data and whatnot.
>>
>>54245394
>Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
>>
>>54245394
>>54245425
Basically *never* use gets as any use if it will automatically introduce security vulnerabilities
>>
>>54245436
Oops. Didn't notice that. So fgets allows you to parametrize the size and gets just assumes one?

>>54245453
Gotcha. As for input again, I was told that fscanf was better for input. What's the advantage of sscanf?

>>54245425
And silly question, but is there a default size for the buffer? Is it a set value throughout an execution or a different size every time it is used depending on the scenario?
>>
File: pc.png (378 KB, 1450x1080) Image search: [Google]
pc.png
378 KB, 1450x1080
>>
>>54245042
Water.
>>
>>54245042
$0.20 have been deposited into your Korea™® Account
>>
>>54245042
That makes me want to punch that fucking chink in the face. Cruel race of mongoloids.
>>
>>54245394
gets() is so dangerous and shit, they literally removed it from the latest C standard.
>>
Ideas for a dissertation if I ever go full PhD: How to efficiently and anonymously stream HD video.
>>
>>54245817
Teledildonics with VR
>>
>>54245817
How about me and you collab together on it bae
>>
coding/prgramming special snowflake syndrome
lmao
>>
>>54245790
Understood. Pretty solid evidence of danger.

>>54245862
>can't program so projects on programming thread
Good job buddy. You're doing great.
>>
>>54245817
Develop an encrypted middle-out lossless compression algorithm
>>
>>54245790
why did they add it in the first place
>>
>>54245862
>>>/g/wdg
>>
I don't understand Java programming it makes no sense to me
>>
>>54245893
It's easier to type than scanf
>>
>>54245917
>one less letter
>>
>>54245911
pssh even pajeet understands java
>>
>>54245911
Learn OOP and it will make sense. You'll still hate Java though.
>>
>>54245656
roll
>>
>>54245893
From the C99 rationale:
>Because gets does not check for buffer overrun, it is generally unsafe to use when its input is not under the programmer’s control. This has caused some to question whether it should appear in the Standard at all. The Committee decided that gets was useful and convenient in those special circumstances when the programmer does have adequate control over the input, and as longstanding existing practice, it needed a standard specification. In general, however, the preferred function is fgets.
I guess they changed their mind in C11. They did have a bigger focus on security in that standard.
>>
>>54245937
That's what I don't understand why am I treating everything as an Object? I am in first day in programming class and professor is talking about how everything is an Object and there is an array of objects. He also told the class to ignore most of the code for Hello World but I kept asking what is static? What is main? What is Strng[] args?
>>
>>54245853

Have any experience with Cryptography, peer to peer/anonymity networks, and/or data compression techniques?
>>
>>54245995
I implemented the Cipher Encryption before
>>
File: themoreyouknow.png (808 KB, 1280x931) Image search: [Google]
themoreyouknow.png
808 KB, 1280x931
>>54245974
cool
>>
>>54245991
Have you ever programmed before?
>>
>>54245991
>but I kept asking what is static? What is main? What is Strng[] args?
and that is why Java is a terrible language for beginners. Those are all completely valid questions for a beginner to have, and Java forces you to deal with those concepts before you have a solid enough understanding in everything else.
>>
>>54246005
Did you do it correctly?
>>
>>54246010
No I have not. I understood variables and expressions then the professor lost whole class with all those million of things

>>54246018
the professor kept saying to ignore it all
>>
>>54246035
so just ignore it all
>>
>>54246035
Learn C on the side. Java is a terrible first language.
>>
>>54246035
>the professor kept saying to ignore it all
Because none of you would know enough of the fundamentals for him to be able to explain them.
>>
>>54245098
Where you live?
>>
>>54246084
>>54246094
I have never been so confused before it makes absolutely no sense to learn this way
>>
>>54246102
Tell your professor to suck less Oracle cock.
>>
>>54246102
>it makes absolutely no sense to learn this way
That's pretty much the only way you can learn Java, as it forces you to use those things.
>what is static?
I don't expect you to understand this. I'm not trying to be condescending though; you're just new.
A static method is a method which is not tied to a particular instance of an object.
>What is main?
main is the method where your program starts.
>What is Strng[] args?
Those are the arguments to main. It is an array of strings which contain the command line arguments.
>>
>>54245991
To answer those questions though, static variables or functions (methods) can be used without instantiation of the class it's in. Main is the entry point of the program, where your code starts executing. String[] args have to do with command line arguments when the program is being run. A string of input args get loaded into an array to be parsed in the program.
>>
hey guys I found the entire source code to minecraft:

http://www.ioccc.org/2015/dogon/prog.c

To be honest though the shit people pull off in the ioccc is amazing, I gotta learn how they do it
>>
>tfw the random bullshit you write actually works
    for(sum = 0, i = 0, j = 0; i < ROW_CNT; (j = ((j + 1) < COL_CNT) ? j + 1 : 0, i = (j == 0) ? i + 1 : i))
sum += array[i][j];
>>
>>54245767
You jelly that Koreans are prettier and more popular than every other race rn?
>>
>>54245551
>is there a default size for the buffer?
When you declare your buffer you must always give it a size.
gets assumes that somehow your buffer is endless and that it is OK to read any number of characters into the buffer. This introduces so many security vulnerabilities that you literally should never use gets() under any circumstance
>>
>>54246209
>j = ((j + 1) < COL_CNT) ? j + 1 : 0,
j = (j + 1) % COL_CNT,

>i = (j == 0) ? i + 1 : i
i += !j
>>
>>54246209
>>54246332
Why not just use nested for loops and save everyone time deciphering what the hell your code does, while simultaneously allowing easier compiler optimizations?
>>
>>54246326
So a "buffer" is usually a variable declared in the program itself? I'm confused, I thought it was an innate functionality of the computer.
>>
>>54246509
The "innate buffer" on your computer is your ram, which your OS dispenses in short bursts.
>>
>>54246289
The girl you posted is a pretty gross one to go with in order to try prove your point.

But to answer your question: No.
>>
>>54246509
A buffer is just a space in memory used to hold data. When inputting data from a get function you (should) tell the compiler how big the buffer should be before taking in the data.
>>
>>54246540
So what is an example of a "non-innate" buffer? I've seen variables declared as buffer, but never thought much of it. What does that mean and why is it done?
>>
>>54246550
Ahh, I see. So "buffer" is another term for a scalar variable/storage location, but is buffer used more commonly with reference to transferring data as a sort of stream?
>>
>>54246598
Pretty much. Think of it like buffering a video. You're waiting for the video to be downloaded into a buffer so it can be played back.
>>
my old-school hardware professor wanted to gauge whether or not we'd had introductory programming classes so he started asking us if we knew how to implement numerical algorithms like runge-kutta and dft

god damn i wish i'd gone to university in the 70s
>>
>>54245042
Buckfast
>>
Need a template for an apk that can install assets into a specific path on internal memory.

I want to sell my expansion packs for games

Please and thank you.
>>
>>54246709
What do you think this is, the pajeetware trading forum?
>>
>>54246659
I gotcha. Like a temporary loading bay between stops? Dunno if that's a poor metaphor.
>>
>>54246721
....yes
>>
>>54244786
Does this code calculate each element in the result matrix in a separate thread? I am trying to make it do that.


private static int endThreadsCount = 0;

/**
* matrMult - two matrix multiplication method
* @param m1 - first matrix
* @param m2 - second matrix
* @return result of matrix multiplication (also, matrix)
*/
private static int[][] matrMult(int[][] m1, int[][] m2) {
int[][] mtrxRes = new int[m1.length][m1.length];
for (int i = 0; i < m1.length; i++) {

final int finalI = i;
Thread t = new Thread(() -> {
synchronized (mtrxRes) {
int mp = 0;
for (int j = 0; j < m1.length; j++) {
mp = 0;
for (int k = 0; k < m2.length; k++) {
mp += m1[finalI][k] * m2[k][j];
}
mtrxRes[finalI][j] = mp;
}
endThreadsCount++;
if (endThreadsCount == m1.length)
mtrxRes.notify();
}
});
t.start();
}

synchronized (mtrxRes) {
try {
mtrxRes.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mtrxRes;
}
}

>>
>>54247106
You wrote the code fag, you tell us what it does.
>>
>>54247125

I didn't write the code. I just changed its inputs and incorporated it into my program to suit my purposes. It does correct matrix multiplications, and I can see that it makes new threads, but I don't know if it " calculates each element in the result matrix in a separate thread"?
>>
>>54247106
It certainly looks that way but I don't understand 1) why you would do that 2) why you would go for a procedural approach in Java. Makes no sense.
>>
>>54247187
>1) why you would do that

It's for an assignment. We are learning about operating systems and threads.

> 2) why you would go for a procedural approach in Java

Not sure what you mean by this.
>>
>>54245991
quality bait
>>
>>54247206
>It's for an assignment
>learning about operating systems and threads
>copy paste code with no understanding of what it does
>does not know what procedural is
>can't even google
Fucking Javafags.
>>
File: 80640695.jpg (50 KB, 400x572) Image search: [Google]
80640695.jpg
50 KB, 400x572
Anyone know a good book/tutorial series on data structures? Perferably in python or something generic. Please not java.

Do TAOCP or another algorithm book cover them well?
>>
>>54247269
At least he can get a job when he's done.
>>
>>54247327
Thus another Pajeet joins the industry.
>>
Some Google programmer just open sourced a modern text editor for osx with its back end written I pure rust. How do you feel bout rust now faggots?
>>
Is it recommended to always use properties in C# just in the off chance you need get/set logic at some point later?
>>
>>54245353
I'll join you
>>
File: 1457647829631.png (57 KB, 292x219) Image search: [Google]
1457647829631.png
57 KB, 292x219
>>54247206
>Not sure what you mean by this.

If you want OOP you need to do it like this:

public Matrix multiply(Matrix other) { ... }


or in-place:

public void multiply(Matrix other) { ... }


Basically you need a Matrix class.
>>
Hay guys im gonna learn generics and adts, what am i in for?
>>
>>54245656
>multiply 2 random 100-digit numbers, display the result
>medium
wut
>>
I'm learning Ruby with RubyMonk, and I don't quite get the solution to this problem they gave me.

def sort_string(string) string.split(' ').sort{|x, y| x.length <=> 
y.length}.join(' ')
end


It's a method to order words in a sentence in ascending order, but I have no idea what most of the parts beyond .split actually do in the function.
>>
Lets say I had a struct like this
typedef struct {
char* title;
char* text;
} data;


and you had a function that looked like this


data* new_data(char* title, char* text){
data retval;
retval->title = title;
retval->text = text;
return retval;
}


why would calling something like:
data* item = malloc(sizeof(data));
item = new_data("Foo","Bar");


result in the following error?
 warning: assignment makes pointer from integer without a cast


I am new to C and if it's not clear I have no idea what I'm doing.
>>
>>54247324
TAOCP is pretty advanced, and it's mostly an algorithms book. I'd recommend this since you know C++.
http://www.amazon.com/Data-Structures-Algorithm-Analysis-C/dp/013284737X
>>
>>54247348
Thanks for linking it... retard

Just because google used it doesn't mean it's good.

https://github.com/gchp/iota
>>
>>54247485
Hold on, that can't work. You can't just create a data inside a function and then return it. You need to malloc it too.
>>
>>54247481
Overflow errors
>>
>>54247485
You can make new_data's return type just data and use retval.title, etc.
>>
>>54247485
1. You are mallocing space for a data item, but then overwriting the pointer leading to a memory leak
2. The function you wrote returns a data, while the return type of the function is data*
3. You cant return a pointer to a stack alloced object from a function.
>>
>>54247592
>>54247485
To resolve these issues you can either return a malloced pointer from the function (A) or just return a copy of the struct (B) (you can return aggregate types from functions in C).

A)
data* new_data(char* title, char* text) {
data* retval = malloc(sizeof(data));
data->title = title;
data->text = text;
return retval;
}

Make sure to free the pointer once you are done with the data.

B)
data new_data(char* title, char* text) {
data retval;
data.title = title;
data.text = text;
return retval;
}
>>
>>54245656
r-r-r-r-r-r-r-r-r-r-r-rollin
>>
>>54247467
I'm not too concerned about OOP. More about threads.
>>
>>54245656
roll
>>
>>54247673
>no error checking
>no memory assert
>not strdup'ing strings
>accessing data as if it was a variable
>accessing data* as if it was a variable and not even dereferencing

Someone make a CS.jp out of this please.
>>
>>54247750
Can't blame a beginner for making beginner mistakes.
>>
>>54247750
Doesn't fit the meme, because while they are blatant errors, they are things I'm sure I did back when I was learning C. Deleting /usr was not one of those things, though.
>>
>>54247544
Can't you just use your language's arbitrary precision number type and be done with it?
>>
>>54247750
>>accessing data as if it was a variable
>>accessing data* as if it was a variable and not even dereferencing
Shit I didn't even realize that. Thank god for compiler errors.
>>
>>54247750
>implying people in CS write in C
lad...
>>
>>54247509
That's not it faggot. It's this:

https://github.com/google/xi-editor
>>
>>54247840
Harvard's CS course begins with a year of C.
>>
>>54247851
>mac os only
>need xcode to build
>rust
>google
>
>
>

LMAO
>>
>>54247851
Well it definitely looks like a text editor. Dunno what's different about it from the native OSX text editor. It literally looks the same.
>>
>>54247858
In pretty much every ECE course I've seen starts with an intro to programming in C.
>>
>>54247858

No it doesn't. CS50 uses c, PHP, JS etc. 61 uses C but 51 uses OCAML.
>>
File: AI.webm (679 KB, 800x600) Image search: [Google]
AI.webm
679 KB, 800x600
are u impressed by my hacker skills?
;^)
>>
>>54247993
>out of all listed, C is used primarily and is the only language with a recommended reading list on the course

I'm taking the course, you silly sausage.
>>
>>54248026
bruh set a wider range so it stops shaking like that
>>
>>54248042
http://gamedevelopment.tutsplus.com/tutorials/understanding-steering-behaviors-seek--gamedev-849
I've spent the last three hours trying this to get to work.
chill down.
jesus
>>
>>54248026
What is this supposed to be?
>>
>>54248075
a seek behaviour implementation.
>>
>>54248054
It was a suggestion, not a criticism, fak
>>
>>54246908
Pretty much, although often you'd allocate a buffer from the operating system, and then use it long-term within your program; it doesn't have to be temporary at all. In general, a buffer is just a chunk of memory.

For example, in a game engine I wrote, all game objects such as walls, the player, enemies, etc. are represented by smallish chunks of data arranged contiguously in a buffer that exists for the duration of the program.
>>
>>54248026
What language did you do this in and can you post the source code?
>>
>>54248026
Sexual harassment.
>>
>>54248181
How do you allocate a buffer from the operating system?

And what data structure did you use for your videogame buffer?
>>
>>54248203
java.

float n_speed = warrior_speed * 1.8f;

s_mage = new Vector2(v_mage.x - mage.pos.x, v_mage.y - mage.pos.y).nor().scl(warrior_speed)
.sub(velocity).nor().scl(n_speed/4)
;
mage.pos.add(s_mage);
>>
>>54248241
With C, malloc typically invokes a system call to map a chunk of memory retrieved by the operating system into the program's address space.
>>
>>54245042
What a strange way to treat your food.
>>
>>54248241
I wrote it in C, so I used malloc(); you call malloc with the size of the buffer, and if successful it returns a pointer to the start of the newly allocated region of memory. You then use that pointer to read/write data.

If you mean game entities, each one contains a unique integer id, its name (well, its hash), a pointer to another buffer containing entity components (things like position, velocity, sprites for rendering, scripts for AI, etc. are stored there), and a reference to an entity archetype.

Most game state processing then occurs through the components; e.g. every frame, the physics system will go over the buffers containing position and velocity component data, and move entities around a little, then the graphics system will iterate over everything with a sprite and a position, and draw it at the right position on the screen, etc. etc.
>>
>>54248376
Typically? No. Under typical usage kernel calls are avoided for obvious reasons.

>>54248241
In Linux (and most Unixes, probably Windows too) malloc only does a syscall when it runs out of heap space (or out of contiguous heap space large enough for the demand) or if the requested allocation size is large (like MB range). Look into the syscalls sbrk and mmap. How malloc works isn't super complicated, read the wiki page on malloc.
>>
>>54247993
damn, didnt realize schools were teaching intro classes in OCaml
>>
>>54247158
Thank the heavens for Stack Overflow.
>>
I had a look at glMatrix and am confused what this is doing.
mat2d.rotate = function (out, a, rad) {
var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5],
s = Math.sin(rad),
c = Math.cos(rad);
out[0] = a0 * c + a2 * s;
out[1] = a1 * c + a3 * s;
out[2] = a0 * -s + a2 * c;
out[3] = a1 * -s + a3 * c;
out[4] = a4;
out[5] = a5;
return out;
};


I know it's creating a rotation matrix but which elements of the array are these supposed to be? I've seen matrixes labelled like this
a b tx
c d ty
0 0 1
and this
a b 0
c d 0
tx ty 1
and even this
a c tx
b d ty
0 0 1

Surely there's a difference? I'll be the first to admit my maths is shit.
>>
>>54248527
Also it says the matrix is
[a, c, tx,
b, d, ty]
0, 0, 1
^^^^^^^Unneeded for 2D matrix

But in the setter it sets it like this
mat2d.fromValues = function(a, b, c, d, tx, ty) {
var out = new glMatrix.ARRAY_TYPE(6);
out[0] = a;
out[1] = b;
out[2] = c;
out[3] = d;
out[4] = tx;
out[5] = ty;
return out;
};


What the fuck.
>>
>>54248527
Looks like out is a 2x3 or 3x2 matrix; you should first find out which of the two it is and how the memory is laid out, row-major or column-major. I remember a lot of GL fuckery with transposing matrices
>>
>>54248447
Yeah, typically. And it also depends on the implementation present in whichever runtime being used.
>>
>>54248562
Maybe I should use something else to learn matrix manipulation.
>>
>>54244786
What am I doing wrong here?

/*

b. Implement a program in another file, which:
i. Receives a string from the user as an argument;
ii. Stores the characters of your student number one by one in a char array variable;
iii. Prints the above two variables and length of strings (from i and ii), using one printf() statement; and
iv. Includes examples to test the above 3 functions, with proper assignments and printf() statements.

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char s;
char arr[9];

char* receiveInput()
{
char *s = (char*) malloc( 100 );
printf("Please input a string.\n");
scanf("%s",s);
return s;
}

char getStudentNumber()
{
printf("Please input your student number.\n");
int c; /* int */
int count;
char arr[9];
c = getchar();
count = 0;
while (count < 9 && (c != EOF)) /* don't go over the array size! */
{
arr[count] = c;
++count;
c = getchar(); /* get *another* character */
}

return arr;

}

void printVariables()
{


printf("The string is %s and the student number is %s.\n", s, arr);


}

int main()
{

receiveInput();
getStudentNumber();
printVariables();
return 0;

}


This is the output.

Please input a string.
string
Please input your student number.
T
0
0
1
2
The string is (null) and the student number is .


For some reason the variables aren't getting modified and it's not letting me put in 9 characters for the student number.
>>
>>54248660
printVariables doesn't know what s or arr are. They don't exist outside of the function scope so you need to pass them around somehow.
>>
>>54248660
You shouldn't be returning addresses to locally defined variables from functions, like you are with arr in getStudentNumber(). You'll have to pass the array as a parameter instead and have the information be passed that way
>>
>>54248695
>>54248660
I just noticed you declared then outside of the functions. That's fucking stupid because you're doing it twice and making them different things. Why isn't your compiler yelling at you?
>>
File: 1403901198841.gif (742 KB, 245x172) Image search: [Google]
1403901198841.gif
742 KB, 245x172
Lads, I have a question

I took Data structures with C++ with a teacher last semester, and now I'm taking Data Structures with java with the same teacher

It turned out that one project he gave was the exact same one that he gave last semester, but in Java

Do you think he'll give a damn if my program is the same as my C++ one plus his correction, but in java?

Will he accuse me of plagiarizing his correction and reusing code or something?
Like, he said he didnt much of a damn and wasn't playing cop and trying to get students cheating, but idk if he'll fuck my shit up for this
>>
>>54248721
If your teacher is lazy enough to give the same project for 2 classes then whatever, you already did it once

You really have two choices, try to do it again in a different way, or just save your time and do something else, I can't really say but I don't think he'll care since it's obvious you took his class before and you already know the theory behind the project

If he really cared about that he'd have made different projects for both classes
>>
>>54248721
>correction
It's called "feedback" and when applied shows you've learned from your previous mistakes.
>>
What should I program this week, /dpt/?
>>
>>54248925
what language would you use?
>>
>>54248925
Torrent client
>>
>>54248939
Depends on what gets suggested. Probably C or Python.
>>
>>54248721
why are you taking two data structure classes? you can take another class in java this semester?

its pretty much the same things you are learning
>>
>>54248947
do a Chip-8 interpreter if you haven't made one yet
>>
>>54248660
What these guys said
>>54248695
>>54248697
And scanf() has an address as a second parameter so in your receiveInput function, your scanf should be:
scanf("%s", &s);
>>
>>54248941
I imagine unless I use a library that does all the interesting stuff for me that would be a much larger project than something I could reasonably do in a week. I just want something I can tinker with and get reasonable complete over my time off this week.

>>54248973
I have already made one.
>>
>>54249009
a forth or lisp could be fun to make quickly, you could turn it into a library to embed in your programs
>>
>>54249009
oh, also if you want something graphics related try maybe a text renderer with opengl
>>
>>54248925
huffman tree generator
jpeg decoder
graph processor that spits out tree decompositions in linear time
graph processor that uses that to find hamiltonian paths in linear time
constraint solver
>>
>>54249036
That seems like a fun idea, thanks anon.
>>
>>54245991
Java is a shit first language
>>
>>54244867
See
>>54245055
It's completely about the dimensions of your data.
>>
I'm trying to dump a file from a URL to a txt file. I can manage to retrieve the file and print it out in the terminal, however when I try dumping it to the file, the file comes out empty.

import json, urllib.request

url = "https://api.myjson.com/bins/4rpaa"
print("Fetching data...")
response = urllib.request.urlopen(url)
print("Analyzing JSON...")
str_response = response.readall().decode('utf-8')
data = json.loads(str_response)
print("Dumping data...")
print(data)
print("Writing to file...")
f = open("datadump.txt", "w")
json.dumps(data, f)
print("Success!")
>>
>>54249315
I'm pretty sure json.dumps works as:
json_str = json.dumps(data)

not the way you're using it.

Also use requests instead of urllib.
>>
We should all program a captcha solver in C
>>
>>54246022
No
>>
>>54245656
Roll
>>
Been programming a 3D Game Library for a while now. Made some great progress, but I've decided to code the physics engine completely from scratch as a learning experience. I've made good progress, but am I just wasting my time not using someone else's physics library and trying to learn it all myself?
>>
Have a shitty CS1 professor, she (yes, she) has this for our final exam:

We are in groups of 3, and have three hours to make three games (cli) from these 5:
hangman
connect 4
roulette
blackjack
concentration (matching)

Absolutely retarded. 90% of the students in my class are absolutely retarded ("Will you give us the character array for a word for hangman? I don't know how to make character arrays" - a girl 2 days before the 'exam'), some are okay. I'm tempted to just write every game the night before, and just tell my team members I did everything already. I don't know who's supposed to be on my team, but I know I'd hate working with almost all of them.

/blog
>>
just implementing some generic data structures in C for fun to pass the time until my next exam
>>
Just finished my last project for my Computer Architecture class. Made a branch predictor within our CPU simulator we've been adding onto over the semester.
>>
>>54249738
Sounds neato
>>
>>54249711
Do it anyway. It's good practice.
>>
My teacher wants my whole class to write a programme that calculates the inverse matrix of one given, IN VB.
Have you ever had to code somethint similar?

***Reminder For Faggots***
Inverse Matrix =/= Transposed Matrix
>>
>>54249745
Of course I'm going to do it anyway, it's a grade, and I don't have a 100 because I skipped 10 times and she takes attendance. I mean, I'd love to do this 'exam' on my own, just sitting and making little cli games for a couple hours sounds like some good innocent fun, but having my final exam grade depend on two other people is a bit ridiculous
>>
>>54249764
I'm actually doing matrix shit right now.
https://github.com/toji/gl-matrix/blob/master/src/gl-matrix/mat3.js

Most of the operations will be basic maths so it doesn't really matter about the language.

>>54249776
I meant make the games at home the night before. If your team looks shit whip out your massive C cock but if things look fine then just type away with them for a couple hours.
>>
>>54248560
Welcome to the world of column and row-major faggotry.
>>
>>54249793
Ah, I gotcha. Yeah that sounds like a good plan. I have all day off tomorrow so it works out nicely.
>>
>>54247485
int new_data( struct data *d, char * title, char * text ) {
if (!d) return 1;
d->title = title;
d->text = text;
return 0;
}


call

struct data d;
int result = new_data( &d, "Foo", "Bar");
if (result)// null ptr
>>
>>54249793
It will work for 3X3 matrix. That's the Sarrus determinant if I am right.
But this guys want me to do something more generic with a nXn matrix. My idea was to use the pivot column method, but this fucking language doesn't know what a condition is.
I may a bit of the code after
>>
>>54249812

So... there is a problem with this. Namely, you're letting the fields of the struct point to string literals that are going to be sitting in read only memory. Not only will you have problems with any sort of generic destructor function for the struct (you may or may not be allowed to free memory on it), but you also made it so that someone may choose to mutate the struct's values unwittingly and thus cause a segmentation fault.

Honestly, I'd make those char* arguments const, and also use something like strdup.

int new_data(struct data *d, const char *title, const char *text)
{
if (!d) return 1;

// You can just use strdup for all of this if in a POSIX environment
size_t ti_len = strlen(title);
size_t tx_len = strlen(text);

d->title = malloc(ti_len + 1);
if (!(d->title)) return 1;
strcpy(d->title, title);

d->text = malloc(tx_len + 1);
if (!(d->text)) {
free(d->title);
return 1;
}
strcpy(d->text, text);

return 0;
}


You may think it is wasteful to create a new buffer just for holding strings. In a small enough program, this is true. You probably could be able to make sure that the fields of that struct aren't being free'd or written to or anything like that. As the program size becomes larger, you start to realize that bugs will find their way easy into your programs if you don't have some proper structure. It should be reasonable to argue that the functions which manage a struct should manage the memory pointed to by its members.
>>
>>54245656
roolllin
>>
rate my silly vector /dpt/

#include <stdio.h>

#include "vector.h"

CREATE_VECTOR_CLASS(int);
CREATE_VECTOR_CLASS(double);

int main(void) {
Vector(int) *v = New_Vector(int);
Vector(double) *u = New_Vector(double);

// appending elems
for (int i = 0; i < 10; i++) {
Vector_PushBack(v, i * 3);
}

// pop from end of v
int val1 = Vector_PopBack(v);
double val2 = Vector_PopBack(u);

// the 'raw' arrays
int *vdata = Vector_Data(v);
double *udata = Vector_Data(u);

// print the raw array's elems ofc
int size = Vector_Size(v);
for (int i = 0; i < size; i++) {
printf("%d: %d\n", i, vdata[i]);
}

// check emptiness of vector
puts(Vector_Empty(u) ? "u is empty" : "u is not empty");
puts(Vector_Empty(v) ? "v is empty" : "v is not empty");

// clear elems from v
puts("Clearing v...");
Vector_Clear(v);
puts(Vector_Empty(v) ? "v is now empty" : "v still isn't empty");


// free em up
Delete_Vector(v);
Delete_Vector(u);

return 0;
}


They say don't reinvent the wheel, but it's fun
>>
>>54245656
rawl
>>
>>54250085
output of course
0: 0
1: 3
2: 6
3: 9
4: 12
5: 15
6: 18
7: 21
8: 24
u is empty
v is not empty
Clearing v...
v is now empty
>>
>>54244858
If you can't determine the answer to that question yourself you shouldn't be using C
>>
>>54250085
wut
>>
>>54250118
it's just a generic vector famalam
works with user-created types too (of course)
>>
>>54248721
>I took Data structures with C++ last semester, and now I'm taking Data Structures with java
I have no idea why your school would offer both of those and why you would choose to take both of them.

But anyway, just ask the teacher. I had a similar situation. 95% chance he'll say it's fine, but asking is better than risking it.
>>
GUYS QUICK

how do i make the else statment loop the program??

public static void main(String[] args) {
Stack<String> words = new Stack<>();
Scanner scan = new Scanner(System.in);

System.out.println("Enter a word or 'end' to quit:");
words.push(scan.nextLine());
if(words.peek()=="end"){
words.pop();
System.out.printf("%nYou entered (in reverse):%n",words);
}else{
System.out.println("Enter a word or 'end' to quit:");
}
>>
>>54250184
My Uni does it a bit funny:
>Introduction to OOP in Java
the sequel to which is:
>Processes for OOP Development in C++
lol
>>
>>54250193
wrap it with 'while (words.peek() != end)' instead
>>
>>54250206
mind blown


i should stop rushing everything in last min
>>
>>54250242
fuck i forgot =
>>
>>54250107
He should use gets() instead.
>>
I wrote an interpreter and all possible commands are stored in a flat lookup table which is an array of structs that includes the token string and it's corresponding function pointer.

How bad of an idea is this?
int interpreter(const char *token)
{
int i;
for (i = 0; i < SUPPORTED_COMMANDS; i++)
{
if (!strcmp(token, LOOKUP[i].token))
return i;
}
return -1;
}
>>
>>54250368
you could:
- use a binary search tree for the tokens
- use a dictionary for the tokens -> function pointers
- anything else that isn't a linear search through every fucking token

I wrote a shitty interpreter a while ago and did exactly what you did
>>
File: 91i328.jpg (142 KB, 740x740) Image search: [Google]
91i328.jpg
142 KB, 740x740
>>54250368
>-1 for not found
>>
>>54250420
nothing wrong with it
>>
>>54250428
Why not just throw an exception?
>>
File: 1412872778070.gif (929 KB, 540x642) Image search: [Google]
1412872778070.gif
929 KB, 540x642
My compiler is coming along excruciatingly slowly and I'm starting to lose patience.
It doesn't even do type inference yet, I'm still getting it to create all the functions and types (without the need for forward declarations, of course).
>>
>>54250441
I think you should leave.
>>
>>54250428
i assume the proper way is to throw errors for a problem
>>
>>54245656
rolling you get me power
>>
>>54250428
Use 0 instead
>>
>>54250459
0 is a valid index.
>>
>>54250451
shit desu
again
>>
>>54250459
arrays are 0 based lol
>>
>>54250441
because exceptions are slow, and should be used to handle actually exceptional situations, not program logic
>>
>>54250428
>>54250459
Also, the int should be unsigned
>>
>>54250466
>>54250470
Yes, I know.
You should return 0 for not found and i+1 for found.

a 0 check is faster and -1 is a lot less indicative
>>
>>54250473
if 2 billion + elements isn't enough to fit all the tokens of your interpreted language, it might be a bit too hard to learn for the average person
>>
>>54250486
>i+1 for found
That's fucking stupid.
Also, most POSIX functions return -1 for failure, so it's not like he's doing something obscure.
>>
>>54250368
Usually you write an interpreter in multiple "passes"
First pass:
parse text into tokens
Second pass:
parse tokens into syntax
Optional pass:
desugaring
type checking etc.
Third pass:
interpret

For example, let's say we're writing a calculator (much more difficult than it sounds)
The text we're interpreting is: "1 + 3 * (4 + 1)"
First pass we turn the text into
INT(1)
PLUS
INT(3)
TIMES
LPAREN
INT(4)
PLUS
INT(1)
RPAREN

The actual code representation for this would vary based on language and on design.

Second pass we have to do order of operations and we convert it to a form easier for the computer to understand
PUSH(1)
PUSH(3)
PUSH(4)
PUSH(1)
ADD
MULTIPLY
ADD
HALT

These commands could be stored as just integers, e.g. PUSH=1,ADD=2,MULTIPLY=3,etc., place some space for the optional data in the push commands.

We have no syntax sugar and there are no types so we just interpret it.
stack      next command
PUSH(1)
1 PUSH(3)
1 3 PUSH(4)
1 3 4 PUSH(1)
1 3 4 1 ADD
1 3 5 MULTIPLY
1 15 ADD
16 HALT

Thus the result is 16.
>>
>>54250490


>>54250495
Yeah, but an alternative way of doing it is to have the first token in the array simply be a placeholder (alt. you can decrement the pointer) and then there's no need to do i+1 and you can still do stuff like if (!i) ; // not found
>>
>>54250509
Oh, and the unsigned thing isn't about size, it's about type information and general safety
>>
>>54248527
it's a 2x3 matrix
a b
c d
tx ty

which is equivalent to the 3x3 matrix
a b 0
c d 0
tx ty 1

matrices with the transform on the right are row-major instead of column-major (or is is the other way around?) openGL matrices always have the transform on the bottom
>>
>>54250508
The point of all that is that you want to convert your commands into simple non-text structures in a way that becomes simple for the computer to interpret.
The interpreting becomes something like this

typedef struct cmd {
int op;
int data;
} cmd;

#define PUSH 1
#define ADD 2
#define MULTIPLY 3
#define HALT 4

int interpret (const cmd* prgm) {
int stack[256]; // warning: buffer overflows
int sp = 0;
int i;
for (i = 0; prgm[i].op != HALT; i++) {
switch (prgm[i]) {
case PUSH:
stack[sp++] = prgm[i].data;
break;
case ADD:
// ...
}
}
return stack[0];
}

The large switch statement should probably be refactored, and could also be made into a table of function pointers if you want to get really fancy. But this is much faster than a string lookup table.
>>
So is Go or Rust going to win the c-replacement language war?
>>
>>54250575
Neither, for different reasons each. C might be replaced for a lot of applications but will take an exceptionally long time to be replaced entirely (e.g. drivers and kernals and microprocessors)
Thread replies: 255
Thread images: 14

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.