[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: 17
File: trap programmer.png (1 MB, 1702x2471) Image search: [Google]
trap programmer.png
1 MB, 1702x2471
Old /dpt/: >>51488679

What are you working on, /g/?
>>
Rate my strrev implementation.
char *strrev(char *str)
{
int length = strlen(str) - 1; /* omit \0 */
char *tmp = malloc(length);
int a = length;
int b = 0;
while (a >= 0 && b <= length)
{
strncpy(tmp+b, str+a, sizeof(char));
a--;
b++;
}
return tmp;
}
>>
ITT: millenials get BTFO by basic CS question.
LMAO
LOL
KEK
>>
>>51491633
What is the basic CS question?
>inb4 "do you wear a skirt while programming?"
>>
File: beyond-fizzbuzz.jpg (33 KB, 381x499) Image search: [Google]
beyond-fizzbuzz.jpg
33 KB, 381x499
Are you ready for round 2, /g/?

>protip: you aren't
>>
>>51491650
averaging two integers on C
>>
>>51491633
>>51491681
samefag

please get out and stop trolling this thread
>>
>>51491681
what is that, like
int avg(int a, int b)
{
return (a * b) / 2;
}


??????
>>
>>51491691
>muh animu
>muh traps
>muh degeneracy
>muh jerking off to kids
pedo...
>>
Studying java for a year, and this problem beats me

Given a M * N matrix, print the minimum value for each row and each column, but this has to be a separate method, to which you pass a matrix of integers

eg: minValues(m) and the output would be

-min for row 1: 5
-min for column 1: 3
-min for row 2: .... Etc

How do i do this?
>>
>>51491716
yes
>>
>>51491564
FAAAAAAAAAAAAAAAAAAAGGGGGGGGGGGGGGGGGGOTS
>>
>>51491564
>What are you working on, /g/?
Averaging two ints in C

>>51491716
>*
No, average would be (a + b) / 2

Also, if a or b or both are high values, (a + b) might overflow causing undefined behaviour in C.
>>
>>51491737
Please be joking.
>>
>>51491747

It sounds easy but it's not. Go ahead and try
>>
>>51491744
oh ok
just use size_t and return a size_t.
Why is this an issue.
You'd be more hard pressed to find people who can make a function that can take a variable argument list and create a function that isn't limited to 2 ints.
>>
>>51491767
>Go
TRIGGERED
>>
>>51491744
>>51491724
>>51491681
>>51491633
samefag
>>
>>51491771
>Why is this an issue.
Because negative numbers exist.
>>
>>51491780
>animooooooooooooo
degenerate, please return to your /a/
>>
>>51491771
>just use size_t and return a size_t
size_t can't represent negative integers
>>
>>51491747
>>51491737

That is not as easy as it sounds.
>>
File: princess.jpg (60 KB, 602x824) Image search: [Google]
princess.jpg
60 KB, 602x824
So, /g/, what should someone too smart for programming do?
>>
ITT: anime faggots and trap lovers get triggered over basic CS discussion so they want to derail the thread again to anime and traps.

LOL
>>
File: image.jpg (769 KB, 1252x1252) Image search: [Google]
image.jpg
769 KB, 1252x1252
>>51491747
>>51491737

Tried that but if i pass a matrix that is not square, it throws an exception
>>
need to write a java app 1 week to impress some people for a job interview.

What should i write?

using Java and Hibernate
>>
>>51491863

Probably go back to fapping to ponies
>>
>>51491863
Get into finance.
>>
>>51491771
>just use size_t and return a size_t.
size_t can't represent negative integers

>Why is this an issue.
It's really not, just your average /g/ autism

>You'd be more hard pressed to find people who can make a function that can take a variable argument list and create a function that isn't limited to 2 ints.
I agree, but if you are asked that question in an interview you should say "oh, you can do (a + b) / 2 but you should be aware that this might overflow" or something similar.
>>
>>51491911
>there's a correct way and a simple and shitty way
>I only know the simple and shitty
>I can't write reliable code
really, /g/?
>>
>>51491911
>It's really not
>oh, you can do (a + b) / 2
looks like it's an issue for you
>>
File: image.png (708 KB, 2048x1536) Image search: [Google]
image.png
708 KB, 2048x1536
>>51491737
>>51491737
>>51491737
>>51491737

Ideas please
>>
>>51491946
The correct way would be to cast to double, since the question in no way implies that you need to store/truncate the result into an int.

But I guess this too tickles your autism, doesn't it? And you're going to reply with a bunch of new shitposts too, aren't you?
>>
>>51491771
>just use size_t and return a size_t
orly? and how would that work with 1 and SIZE_MAX? is the average 0?
fucking moron
>>
>>51491964
>only quotes half of the sentence
Also, see >>51491982

>inb4 autistic shitstorm
>>
>>51491982
>I don't know how to do it with ints
>I need muh dublez!
fucking webdev amateur
>>
>>51492000
>using webdev as an insult
ok kid

You do know that floor(avg) is not actually the average, right?
>>
>>51491965
is this your homework? how can you be this lazy?
>>
>>51492016

Its for work. And i am not lazy, i just cant do it
>>
>>51491600
>>51491591

destructive version
void strrev(char *str) {
size_t length = strlen(str);
char *a = str,
*b = str + length,
tmp;
while (a < --b) {
tmp = *a;
*(a++) = *b;
*b = tmp;
}
}
>>
>>51492000
>doesn't care about precision
Found the NEET
>>
>>51491982
>in no way implies that you need to store/truncate the result into an int.
>what is gmp
>what is mpz_add
>what is mpz_tdiv
anon, can you even bigint?
>>
>>51492014
>floor(avg)
>average
webcuks actually believe this!
>>
>>51492032
>>51491737
>print the minimum value
>has to be a separate method to which you pass a matrix of integers

your job would not require you to do something like have a separate method. this is for your class.
>>
>>51492037
>cares about precision of integers when he needs to determine an integer between two other integers
how's that css coming along, boy?
>>
File: puketan.jpg (53 KB, 386x460) Image search: [Google]
puketan.jpg
53 KB, 386x460
>>51492040
>GNU extensions
Do you even know C?
>>
>>51492081
>extensions
this ain't CSS, webfag!
>>
>>51492073
>an integer between two integers
That's not the average, anon

That can be calculated in this way:
int between = MIN(a, b) + MAX(a, b) - MIN(a, b); // yes this overflows too, I'm doing this on purpose
>>
>>51492111
GNU aint C kid, good luck trying to get that shit into the Linux kernel
>>
>>51492112
You're a moron. That's just MAX(a, b).
>>
What the fuck is going on here
>>
>>51492129
Good luck trying to get CSS and JavaScript in the Linux kernel, webfag.
>>
>>51492136
Found the web developer

It's actually potential demons flying out your nose.
>>
>>51492141
Just webfags getting rekt by a big-dick-C-god.
>>
>>51491600
if you're not allocating space for the null terminator, aren't you returning a pointer to an unterminated string?
>>
>>51492141
millenials and webdevs getting BTFO by C kun
>>
>>51492081
>GNU extensions

GMP is a library
>>
File: she.jpg (63 KB, 609x772) Image search: [Google]
she.jpg
63 KB, 609x772
What is the stack in C, anons?
>>
>>51492060
>this is for your class.
Well yes, he did say it was in Java after all.
>>
>>51492169
>>51492182
samefag
>>
Has anyone ever purchased international versions of textbooks? Are there any real differences?
The US version of a book I'm looking at is $160. The international version is less than $20.
>>
>>51492212
that's even worse
>>
Hi, I don't want to open a new thread for a stupid question.
So, I'm already a programmer (C++,Java,PHP) and I want to learn Python.
What is the fastest way?
>>
>>51492229
you cannot buy the international versions of those books because they weren't made for FREEDOM
http://yro.slashdot.org/story/12/04/16/1843257/student-charged-for-re-selling-textbooks
>>
>>51491879
need some help fuckers.

thx in advance
>>
>>51492229
If you don't intend to keep the book, as is the case with most college texts, it's fine.
They're usually black and white and have shittier quality paper stock, but the content is the same.
Just make sure they're brand new, the price difference is often negligible.

If you're looking to buy international editions of meme programming books you intend to keep on your shelf, please don't.
I bought an indian copy of K&R once and the paper smell was so unbearable I had to throw it away.
>>
>>51492239
>I didn't know, I'm just a webdev
>>
is Perl good?
>>
>>51492350
>I use GNU libraries because I'm too stupid to average two integers in pure C
I'm not the one who need a third-party library to average two numbers.
>>
>>51491879
can't you research what you employer bussiness is and do a small app that would help him in his business domain?
>>
>>51492390
>libraries
>extensions
>they are the same thing to me because I only know HTML
ishyggydiggy
>>
>>51491564
LINK TO THE NEW THREAD FROM THE OLD ONE FUCKING RETARDED FAGGOT
>>
>>51492416
>>51491580
>>
>>51492314
>I bought an indian copy of K&R once and the paper smell was so unbearable I had to throw it away.
That's terrible. I tend to buy the textbooks for that are part of my major courses to keep as reference; so if they are shit quality, then I won't bother.
>>
>>51492409
>literally extending your application with additional libraries
>not extensions

>needs libraries to average two integers
>thinks "web development" is HTML and CSS
Found the NEET
>>
>>51492431
IT DIDN'T HAVE AN ANIME IMAGE. HOW WAS HE SUPPOSED TO SEE THAT? FUCK YOU NIGGER
>>
File: 1420317518446.png (152 KB, 1948x858) Image search: [Google]
1420317518446.png
152 KB, 1948x858
I see you're still arguing over C, maybe some of you (doubt it tá Žbá Žh) can tell me what's wrong with this C code. Some anon said it's unreliable:
void copy_stream(FILE *in, FILE *out)
{
int c;
while ((c = fgetc(in)) != EOF) {
fputc(c, out);
}
}
>>
>>51492431
DON'T POST A NEW THREAD BEFORE THE BUMP LIMIT FUCKING RETARDED FAGGOT

THE BUMP LIMIT IS 310
>>
>>51492450
>>thinks "web development" is HTML and CSS
he's right tho
>>
>>51492477
>that pic
literally not an oop problem

two fucking integers or one being used as two
>>
>>51492443
>to keep as reference
What's your major?

Also, if you want to avoid the smell thing, make sure they're brand new.
They come sealed in plastic.
That K&R was $4 shipped, and I didn't notice it said used.
>>
>>51492390
>My language of choice coerces all numbers to doubles anyway

>>51492450
extension means a different thing in c

libraries are portable. compiler extensions are not (necessarily).
>>
>>51492478
this desu
you can make a thread early if you've got a new epic OP pic
>>
>>51492493
>"he"
lol

>thinking HTML and CSS is programming
lol
>>
>>51492477
c is not initialized
>>
>>51492521
>thinking web development is programming
anon...
>>
>>51491875
> protip: read the exception, figure out why it gets thrown and what you can do about it, then either adapt or completely change your code. In brief be a big boy stop crying, and do real programming

Or if you are a trans woman of color, we'll help you, we promise, but POST YOUR FUCKING METHOD, A MATRIX THAT CAUSES THE EXCEPTION, AND THE DETAILS OF THE EXCEPTION BLOODY HELL!!!!
>>
>>51492477
honestly idk but what would happen if in and out are the same file? infinite writing?
>>
>>51492521
kill yourself
>>
>>51492506
>My language of choice coerces all numbers to doubles anyway
It doesn't, which is why you need to cast it to two doubles in order to get the average.

>extension means a different thing in c
Wrong. I didn't say "compiler extensions", I simply said extensions.

The library web page even use that exact same word about itself (and about the more complete library, MPFR).

>libraries are portable
Not necessarily
>>
>>51492555
>infinite writing?
no
>>
>>51491737
>Studying java for a year
for like 1 hour once a month?
>>
>>51492541
>>51492565
>hurr durr HTML is programming
>herp derp oh wait i didn't say it was durrr
>>
>codeeval asks you to efficiently get all the prime numbers up to a certain integer
>your code wastes time calculating the largest one first so you know where to stop putting commas in the output
>all because you're too lazy to dynamically allocate a string buffer and replace spaces with commas.
Should I even bother?
>>
>>51492569
webcuk detected
>>
>>51492582
>animu
m8...
>>
>>51492585
Always bother unless it's not worth bothering
>>
>>51492496
friendly reminder that you handled a book that had been used by people who don't poo in the loo and who wipe themselves with their bare hands
>>
>>51492587
>needs a third-party library to get the average of two numbers
>doesn't give a fuck about portability
>doesn't give a fuck about performance
>doesn't give a fuck about ease of maintenance, ease of deployment etc
>doesn't give a fuck about memory or disk usage
I'm fairly sure you're the "webkek" here, who else in their right mind would include a library to do basic arithmetic?
>>
>>51492477
Too soon, anon, too soon!
Stream IO is a far too advanced topic for /dpt/, these retards can't even average 2 numbers nor do they know how to use memcpy. Maybe in 3-4 years, at the rate they learn.
>>
>>51492626
don't fucking remind me
>>
>>51492525
>c = fgetc(in)
>>
>>51492585
Do the first one, then do every other one putting a comma before them
>>
>>51492628
>muh grunt and gulp are standard tools
>muh nodejs is webscale
>muh madness
>I'm a htmlcá Žuck
>>
>>51492477
Jesus Christ, no one called it yet?

You don't write the terminating EOF to the stream you're copying to.
>>
>>51492676
>no one called it yet?
this is the level of /g/
>>
>>51492654
>knowing about webtools
>"I'm a htmlcá Žuck"
Glad you admit it.
>>
>>51492683
>proud about not knowing
anon, I hate to break it to you, but you're an ignorant moron
>>
>>51492697
At least I know how to average two ints without having to rely on large third-party libraries
>>
>>51492697
>proud of being a web code monkey and showing off his "knowledge" about the latest hipster frameworks
>>
>>51492676
You don't write EOF to a file. You fclose it and that's that.

>>51492680
Shut the fuck up.
>>
>>51492758
Okay, he doesn't close/flush the stream then.
>>
>>51492797
Why would a function, given an open stream as input, be expected to close it?
>>
>>51492797
that's the responsibility of the caller of the function really
>>
Can somebody help me understand why C's bsearch() works this way? Pic shows the function definition

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

int dumbcmp(char **, char **);

#define NUM sizeof(wlist)/sizeof(char *)
#define WIDTH sizeof(char *)
int main()
{
char *wlist[] = {
"aids", "crud", "evil", "gall", "idiot", "kick",
"moon", "oval", "quod", "sulk", "under", "west",
"year"
};
char *word = "evil";

int found;
/* why doesn't this work... */
found = (bsearch(word, *wlist, NUM, WIDTH, strcmp) != NULL);
printf("%d\n", found);

/* ...but this does? */
found = (bsearch(&word, wlist, NUM, WIDTH, dumbcmp) != NULL);
printf("%d\n", found);
}

int dumbcmp(char **a, char **b)
{
return strcmp(*a, *b);
}
>>
>>51492676
It won't, it exits the loop as soon as it reads EOF
>>
>>51492797
But what if copy_stream() isn't meant to close a file after writing to it? What if it's to be designed to allow one fopen(), multiple copy_stream()s and one and one fclose()?

I don't think there's anything wrong with his function, but that's just me.
>>
>>51492817
>>51492814
It would be expected to flush it.
>>
>>51492840
Why?
>>
>>51492847
Because of how I/O streams work
>>
>>51492858
Flushes are expensive. Why do one if it's not strictly necessary?
>>
>>51492871
>not strictly necessary
Consistency is strictly necessary

But the real question is if you think flushes are expensive, why would you read and write single bytes rather than reading a whole chunk into memory and writing that chunk to the stream?
>>
>>51492840
Not necessarily. printf() does not always flush (it only completely flushes if the last character you pass to it is a '\n', or if the number of bytes it has to write to stdout exceeds the size of its internal buffer).

The problem in his implementation lies on whether or not in == out, I believe. If that is the case, then reading half of the file + writing it to itself will cause the cursor to reach the end of the file, meaning that the last half of your file gets destroyed. Depending on whether the number of bytes in your steam is even or odd, you might also go on trying to write in junk memory.
>>
>>51492904
Beats me.
>>
who /java/ here?
>>
>>51492917
>The problem in his implementation lies on whether or not in == out, I believe.
Well, reading and writing to the same file simultaneously is no problem as long as you do open it with the rw modifier (and not r+)
>>
>>51492958
I was working under the assumption that the file was opened for rw. I believe that rw keeps one single cursor though, so a read increases the same cursor a write this, and not separate ones (e.g. fgets followed by fputs places your character at offset 1 instead of offset 0). I don't know if this is implementation-defined though, but that's how I think it works for 64 bit linux.
>>
>>51492951
>
>>
>>51492951
Most people actually enjoy programming
>>
>>51492951
this.
who the fucks cares about autistic C garbage like averaging integers.

most employeers don't need library programmers.
>>
>>51493034
What's wrong with Java?
>>
>>51492904
>But the real question is if you think flushes are expensive, why would you read and write single bytes rather than reading a whole chunk into memory and writing that chunk to the stream?
I've limited knowledge of C but doesn't fgetc work with streams underneath? Which means while you're reading it char-by-char it's actually buffered internally.
>>
>>51493000
>>51493000
Actually, rw is non-standard.
a (a+) allows reading from start and writing from end.
>>
>>51492822
>string literal to char*
you are one step away from breaking the universe
>>
there is nothing wrong with java it's literally the best language along with C++
>>
>>51493045
it is shit
>>
>>51493057
Yes, from an I/O perspective you're quite right, but doing two function calls per bytes is in-efficient if you're copying a lot of bytes, and you're also totally at the mercy of the stream implementation (which is free to do a syscall for every call to fputc for example).
>>
>>51493058
Well then, aside from the case where in == out and the file pointer has permission to both write to and read from itself, I believe anon's function holds up.

Oh, there's also the case where he leaves old characters on a file if he copies an amount of bytes lesser than the target's size, but I believe that's expected to be taken care of by the caller.
>>
>>51492711
>know how to average
last two threads prove otherwise, webshit
>>
File: 1434597174467.jpg (8 KB, 204x204) Image search: [Google]
1434597174467.jpg
8 KB, 204x204
>>51492222
underrated
>>
>>51492822
pretty obvious actually
>>
when should i pass by reference vs pass by value in C?

if i'm not going to modify the variable, why pass it by reference?
>>
>>51493096
>last two threads prove otherwise, webshit
I didn't post in the last two threads.

>failing to tell completely different people apart
lol
>>
>>51493045
no unsigned integers
Shitty generics
No easy way to box primitives. (have to deal with bullshit like int and Integer types)
no pointers
painful native code interop
the most verbose language in popular use by far
Currently developed by Oracle.

probably loads of other shit i can;t remember
>>
>>51493118
>if i'm not going to modify the variable, why pass it by reference?
Because it is "cheaper" for compound types.

Lets say you have a struct with many members. It's easier to pass it as a const struct something* than as a value-type.
>>
>>51493118
Passing a large object by value can incur an expensive copy. A good rule of thumb is to pass by const reference if you're not going to modify it.
>>
>>51493118
There's no "pass by reference" in C. You always pass by value. What might be the case is that your value is a pointer.

All arguments must be put on the stack. Passing a pointer means you must put an address on the stack. Passing whatever it points to means you have to put that entire thing on the struct. This matters for huge unions and structs, mostly.
>>
>>51493124
>pretending
back to reddit, csstard
>>
so what is actually the correct way to get an average of two ints in C?
>>
>>51493124
> I am not anon, I am anon, DUH!
>>
>>51493131
It really is verbose. I've started learning it few months ago, and even the simplest shit that I want to make takes lines and lines of code.
>>
>>51493147
>All arguments must be put on the stack
No, they can be put in registers.
>>
>>51493131
boohoo
>>
>>51493149
>still going at it
you lost, go include some bloated library for adding two integers
>>
>>51493131
pretty good list. I would add forced pass by value and inability allocate objects without references (Object o; in C++)
>>
>>51493151
apparently nobody on this shit vietnamese blog knows
>>
>>51493142
Explain that...

A const reference? Does that mean I can't change the variable?

Can you give me an example?
>>
>>51493151
http://ideone.com/qXPpZQ

int avg(const int a, const int b) {
long long difference = (long long) b - a;
if(b < a) {
difference += difference & 1;
}
return a + difference / 2;
}
>>
>>51493159
>assuming anyone would spend three /dpt/s arguing with a sperglord
>>
>>51493176
>pls no bully
>I can't take any more ass raping from your big dick
>>
>>51493168
also this, retarded user base
>>
>>51493131
>no unsigned integers
Not really a problem.

>Shitty generics
This is true.

>No easy way to box primitives. (have to deal with bullshit like int and Integer types)
Well, it's pretty easy to make your own holder type, but this is a fair enough complaint.

>no pointers
Not a problem.

>painful native code interop
This is a true complaint, but not really valid (it's not what java was meant to do).

>the most verbose language in popular use by far
Annoying, but not really a huge problem (I don't mind it, especially considering that an IDE makes it relatively effortless to write java)

>Currently developed by Oracle.
Irrelevant
>>
>>51493195
or

int avg(const int a, const int b) {
long long difference = (long long) b - a;
difference += difference & (b < a);
return a + difference / 2;
}
>>
>>51492646
This works, thanks.

Also, I noticed it runs much faster if you stop checking for divisibility at sqrt of the number of you're checking.

Why is that?
>>
>>51493195
implementation defined as fuck
>>
>>51493147
>All arguments must be put on the stack
that is implementation defined. It can be easily optimized by a compiler

Also C has pointers, so pass by reference is not really a necessity.
>>
>>51493193
Since you're talking about C you have to use a const pointer.
typedef struct Big {
int stuff[1024];
} Big;

// makes a copy even if it's not strictly necessary since you're not modifying it
passByValue(Big big);

// doesn't make a copy, retains semantics of immutability
passByConstPointer(const Big *big);
>>
>>51493193
>Does that mean I can't change the variable?
Yes

>Can you give me an example?
void print_string(const char* str)
{
// i can read str here, but I'm not allowed to write to it
while (*str != '\0') {
char c = *str; // this is allowed
*str = c; // this is not allowed [it is undefined behaviour]
str++;
}
}
>>
>>51493225
incorrect
>>
Is it possible to go more enterprise than this: https://en.wikipedia.org/wiki/Dependency_inversion_principle
>>
>>51493166
You're right, but if the thing you're referencing is big enough for this to matter, it's probably not going to completely fit on the registers.
>>
>>51493232
>>51493251
no FOR FUCK'S SAKE RETARD

>Long long signed integer type. Capable of containing at least the [−9223372036854775807, +9223372036854775807] range;[3] thus, it is at least 64 bits in size. Specified since the C99 version of the standard.
>>
>>51493211
You can take some more anon, my dick isn't that big.
>>
>>51493195
what if int and long long have the same representation

i'll admit i don't think such a thing can actually happen right now but the standard doesn't disallow it
>>
>>51493252
It's just an over engineered as fuck example of "program to an interface, not an implementation".
>>
>>51493252
starship tier enterprise
>>
>>51493252
>Is it possible to go more enterprise than this:
Yes

Including a bigint library in order to calculate the average of two integers, for example.
>>
>>51493251
http://ideone.com/HhYyR9

these two are perfectly equivalent FUCKING RETARD
>>51493195
>>51493225
>>
https://github.com/woky/chrome-mouse-wheel-tab-scroll
>>
>>51493061
The original function where this problem arose used a passed char* as the key instead of a string literal. I'm just simulating it here.

>>51493107
pls explain. It looks like bsearch() is passing strcmp() a pointer to each array element (char**), instead of the element itself (char*) which strcmp expects. Is that the expected behavior? If so, why?
>>
>>51493306
>equivalent
Yes, correct, no?

How is truncating the average into an integer value "the average of two integers"?
>>
>>51493227
It should be obvious why it's faster, you're only doing "sqrt n" iterations instead of "n".

It works because as soon as you go past the square root, any factor you find would be the counterpart of a factor that you've already checked. If you haven't found any factors yet, there cannot be any more.
>>
>>51493283
then you use stdint with int32 and int64. or an arbitrary size integer representation for a-b. it's just a toy example and you know it works in practice because no one expects ints to have more than 32 bits
>>
>>51493324
autism fuck you i hope you die in a fire

the average of two integers is a truncated integer unless otherwise specified FUCKING AUTIST I SERIOUSLY HOPE YOU DIE
>>
>>51493330
What if you use C89/90 where there's no such thing as stdint.h?
>>
>>51493346
A U T I S M
U
T
I
S
M

>or an arbitrary size integer representation for a-b
>>
>>51493330
>then you use stdint with int32 and int64.

but then you're deviating from the spec of the average of 2 ints :^)
>>
>>51493324
oh, didn't notice that you have autism. my bad
>>
>>51493343
>the average of two integers is a truncated integer unless otherwise specified
Wrong

https://en.wikipedia.org/wiki/Average

>In colloquial language, an average is the sum of a list of numbers divided by the number of numbers in the list. In mathematics and statistics, this would be called the arithmetic mean.

https://en.wikipedia.org/wiki/Arithmetic_mean

Do you define PI as 3 as well, because it wasn't specified as something else than an integer?
>>
>>51493365
how would you write an average function anon?
>>
>>51493364
>>51493357
>>51493343
>webcuk defines PI as 3 because precision wasn't specified
>>
>>51493365
why are you in a programming thread
>>
>>51493299
>producing code with rounding errors
repugnant desu senpai
>>
>>51493384
if you knew anything about this subject you would know that all numbers that most webcuks use are double-precision floats
>>
>>51493382
double average(int a, int b)
{
return ((double) a + (double) b) / 2.0;
}
>>
>>51493384
>autistic defines PI as a rational number
>>
>>51493084
>doing two function calls per bytes is in-efficient if you're copying a lot of bytes
Function call overhead is negligible compared to the cost of IO
>you're also totally at the mercy of the stream implementation (which is free to do a syscall for every call to fputc for example)
Same thing applies to fread/fwrite. fread/fwrite are usually implemented in terms of of fputc/fgetc rather than the other way around.
>>
>2015
>not storing all your data in Pi
have fun worrying about disk space
>>
>>51493396
>truncating a fraction into an integer =not rounding error
>using floating point precision = rounding error

>>51493385
>programming = incorrect math
wut

>>51493406
>no u
lame comeback, anon
>>
>>51491737
lol this is so your homework. and this is easy homework kid
>>
>>51493438
Let's see how you would do it anon
>>
>>51493414
what if double can't hold all integers?
>>
>>51493420
>Function call overhead is negligible compared to the cost of IO
Yes, but that doesn't mean that it's cost free. If you're on the track of doing performant code, you should think about this.

>Same thing applies to fread/fwrite. fread/fwrite are usually implemented in terms of of fputc/fgetc rather than the other way around.
Yes, but there's a vast difference between doing a syscall per X bytes and doing a syscall per byte.
>>
>>51493438
>average two ints
>no further specification
>autistically assume for no valid reason that a function that takes ints as input should return a float
>>
>>51493438
not an error if you do it on purpose
>>
>>51493414
AUTIST fucking kill yourself i'm dead serious
>>
>>51493454
See >>51493414

>>51493458
Then you implement your own number representation using strings.
>>
File: 18211.png (98 KB, 400x300) Image search: [Google]
18211.png
98 KB, 400x300
>>51493489
kill yourself
>>
>>51493267
int can be 64 bits too, it's also specified in the standard
>>
>>51493469
>calculate average
>average
>autistic to assume that a function that calculates the FUCKING AVERAGE would return a floating point number
lolwat

>>51493486
I'm sorry you failed the job interview.
>>
>>51493489
So your answer gives wrong answers? lol what a retard.
>>
>>51493514
then >>51493414 is also wrong. CHECK MATE AUTISTS
>>
>>51493531
doubles can be 128 bit
>>
>>51493531
It is.
>>
>>51493518
kill yourself
it's a function that averages two ints. my function returns the average of the two ints with full integer accuracy. there is no reason to assume that it should return a double. YOU FAIL

kill yourself
>>
oh yeah well I got some doubles for you right here
>>
>>51493546
int can be 256 bit
>>
>>51493555
>my function returns the average of the two ints with full integer accuracy
That's not the average though.

>there is no reason to assume that it should return a double
Yes, it's the fucking average, not the average rounded down to the nearest integer.

Do you think the square root of an integer should also be returned as an integer?
>>
>>51493567
your mom can be googolplex bit
>>
>>51493166
>>51493147

> What might be the case is that your value is a pointer.

You mean by value is a memory address basically?

> All arguments must be put on the stack.

Stack?


Question:

What's a better practice, keeping a global extern variable to store data, or passing around a reference in the arguments?
>>
guys calm down, i got this

bool average(int a, int b)
{
return ((a & 1) != (b & 1));
}
>>
>>51493414
I'm pretty sure a bunch of people did this last thread and you told them they were wrong
>>
File: 3mLydMU.png (70 KB, 243x200) Image search: [Google]
3mLydMU.png
70 KB, 243x200
>>51493577
>Yes, it's the fucking average, not the average rounded down to the nearest integer.
your answer is also rounded.

>Do you think the square root of an integer should also be returned as an integer?
yes.
>>
>>51493584
yes; bottom line, the code is wrong and nobody presented a good solution for averaging 2 ints
>>
>>51493595
>keeping a global extern variable to store data
Never ever use a global mutable variable.
>>
>>51493555
>calculating the average as a double is autism
>you should rather include a third-party library to handle bigints

ITT: webdevelopers programming in C for the first time
>>
>>51493599
it returns true if there will be a rounding error
false if there won't

problem solved
>>
>>51493607
STUPID ASS TROLL GO FUCK YOURSELF
>>
>>51493601
>you
I'm not that guy, see the replies to >>51491982


>>51493602
>your answer is also rounded.
True, but it's not truncated entirely. But yes, there will be precision errors for some values.

>>Do you think the square root of an integer should also be returned as an integer?
>yes.
Okay then.
>>
>>51493607
LOL
>>
I see everyone is busy showing their broken average implementation and ignore telling >>51492477 why the code is not correct.
That code is not guaranteed to copy the entire input stream because it stops at EOF instead of stopping when end-of-file or an error is encountered. Use feof() and ferror() to detect those cases. The function should also return an error code to signal those errors.
>>
>>51493607
NO IT'S THE EXACT OPPOSITE OF WHAT YOU'RE SAYING

WEB DEVS AND STUPID ASS KIDS LIKE YOU WITH NO PROGRAMMING EXPERIENCE WOULD ASSUME THAT IT'S FINE TO RETURN A DOUBLE WHEN THE SPEC CLEARLY IMPLES AN INT.
>>
>>51491681
For unsigned: small + (big - small) / 2
Parity of (big - small) tells you if the average can be represented accurately as an integer. Adding half the difference rather than dividing the sum by two avoids overflow.

For signed: if both are on same side of 0, use unsigned procedure, else use (a+b)/2 and parity of (a+b).

You can probably avoid the branches if you rely on the twos complement representation.

Easier, fine for most purposes: convert to double, (a+b)/2

If you aren't using your largest integer size: convert to i64, (a+b)/2.

Seems like there should be a better way to do signed, still without relying on larger types, floats, or twos complement representation.
>>
>>51493644
but truncated errors are also precision errors.
>>
>>51493467
It fread/fwrite are calling fgetc/fputc in a loop anyways (they probably are) there is not going to be a measurable difference.

>If you're on the track of doing performant code, you should think about this.
Right, and you should know that it doesn't matter when your code is IO bound. And in general, you should profile before you even think about complicating your code to improve performance.

>there's a vast difference between doing a syscall per X bytes and doing a syscall per byte.
At the end of the day, you just have to hope that your libc devs aren't retarded. If you're that concerned about it, you should be using read/write directly.
>>
>>51493666
>WEB DEVS AND STUPID ASS KIDS LIKE YOU WITH NO PROGRAMMING EXPERIENCE WOULD ASSUME THAT IT'S FINE TO RETURN A DOUBLE WHEN THE SPEC CLEARLY IMPLES AN INT.

>clearly
>implied
lolwat

>calculate the average of two integers
Clearly that implies calculating the arithmetic mean of two integer values, which is not floor(mean(x, y))

Why would you assume that a function must have the same return type as its parameters?

Do you think strlen returns a char pointer? Do you think sqrt returns an int?
>>
what's wrong with

int avg(int a, int b) {
return (a/2 + b/2) + (a & 1 || b & 1);
}
>>
>>51491982
this is what normies actually believe
>>
>>51493667
>if you rely on the twos complement
>fine for most purposes: convert to double
>convert to i64
implementation-defined/10
>>
>>51493041
>averaging integers.
>library programmers.
Is this what programming has come to?
>>
>>51493696
>which is not floor(mean(x, y))
right, it's trunc(mean(x, y))
>>
>>51493696
REEEEEEEEEEEEEEEEEEEEEEEEEEEEETAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARD

if the spec was to calculate the average of two doubles you'd return a double unless otherwise specified
if the spec was to calculate the average of two floats you'd return a float unless otherwise specified
if the spec was to calculate the average of two intsyou'd return a int unless otherwise specified
>>
int average(int a, int b)
{
return (a + b);
// shr to get truncated
// &1 to determine if .5
}


nobody will notice one missing bit
>>
>>51493718
The first two procedures aren't implementation defined, they use branches to avoid relying on twos complement.

I just mentioned some other ways for completeness.
>>
>>51493707
it doesn't always work
>>
>>51493691
>It fread/fwrite are calling fgetc/fputc in a loop anyways (they probably are) there is not going to be a measurable difference.
But they're not (unless you have an retarded implementation of fread/fwrite).

>Right, and you should know that it doesn't matter when your code is IO bound.

Not doing a syscall every byte anymore = no longer IO bound
Then it starts to matter.

>And in general, you should profile before you even think about complicating your code to improve performance.
Doing an fread into a buffer is not "complicated code" anon.

>At the end of the day, you just have to hope that your libc devs aren't retarded.
Yes, of course, but even if they're not, calling a function (or in this case, two functions) for every single byte should raise some eyebrows.

>If you're that concerned about it, you should be using read/write directly.
Not necessarily, calling a function for every byte should be a huge red flag for any developer.

>>51493675
One is more accurate than the other though.
>>
>>51493763
one is more true to the spec though
>>
>>51493746
that's a sum, anon
>>
So /dpt/, did you learn a functional language yet or are you still only have limited skills as a developer?
>>
>>51491681
Here's some solutions

int avg2(int x, int y) {
int sum = (x / 2) + (y / 2);
int mod = (x % 2) + (y % 2);
sum -= (sum > 0) * (mod == -1);
sum += (sum < 0) * (mod == 1);
return sum + mod/2;
}

int avg(int x, int y) {
int sum = (x / 2) + (y / 2);
int mod = (x % 2) + (y % 2);
int nsig = (sum < 0) - (sum > 0);
return sum + nsig * (nsig == mod) + mod / 2;
}


int32_t avg3(int32_t x, int32_t y) {
return (((int64_t)x)+y)/2;
}

int avg4(int x, int y) {
return (x / 2) + (y / 2) + (((x / 2) + (y / 2) < 0) - ((x / 2) + (y / 2) > 0)) * (((x / 2) + (y / 2) < 0) - ((x / 2) + (y / 2) > 0) == (x % 2) + (y % 2)) + ((x % 2) + (y % 2)) / 2;
}


avg3 is by far the fastest but not supported on all architectures.
the other ones are more or less the equivalent.\
didn't write these myself, but you can use them if you need a solution for this.
>>
>>51493778
>can't read
>>
>>51493784
oh and they're branchless.
>>
>>51493775
>the spec
The spec says
>calculate the average of two integers
One calculates the average (albeit with less than ideal precision), the other adds two integers and then does long division.

Which one is the most "true to the spec"

>>51493741
See above.
>>
>>51493763
>One is more accurate than the other though.
implementation-defined, what if integers are a thousand bit while double mantissa is only 10 bit

only correct solution is returning a struct that contains truncated value of average in int and a bool to store if it is 0.5 or not
>>
>>51493696
>Do you think sqrt returns an int?
sqrt returns the same type that's input into it

sqrt takes a double, returns a double
sqrtf takes a float, returns a float
sqrtl takes a long double, returns a long double

don't think c has at square root function that takes an int but if there was one i'd expect it to return an int

>>51493760
when
Thread replies: 255
Thread images: 17

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.