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

>ask interviewee to write a program that calculates the average

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

Thread replies: 317
Thread images: 20

File: Vqr4p1E.png (116KB, 1515x663px) Image search: [Google]
Vqr4p1E.png
116KB, 1515x663px
>ask interviewee to write a program that calculates the average of a list of integers
>he fails
holy shit the CS major meme is real
>>
>average(list);
Boom, done.
>>
>>55272438
>average
>doesn't specify mean or median
>doesn't specify geometric, arithmetic, harmonic mean
>>
>>55272472
Boom, rejected.
>>
>>55272479
then dont complain about shit programmers working with you next time
>>
>>55272476
>implying it isn't the job of the candidate to ensure they have a proper understanding of the requirements
>>
>>55272438
would it be:
>use an array to get all the list of integers
>use the sum of array/ the count of whatever is in the array( getting the count with a for loop for the lengthof the array).
can I have job please.
>>
File: code.png (274KB, 3000x3000px) Image search: [Google]
code.png
274KB, 3000x3000px
>>55272479
Why?
>>
>>55272491
Overflow
>>
>>55272491
>use an array to get all the list of integers
You're clearly given a list though.

You'd want to get the length of the list, initialize a sum variable with 0, iterate through the list and adding to the sum, and return the sum divided by the length
>>
>>55272494
The question is asked to check if you understand basic logic as well as the issue of integer overflow

It's like saying you'd look for a project on github doing that when asked to implekent fizzbuzz: beside the point
>>
>>55272517
Doesn't consider arithmetic overflow or truncation.
>>
>>55272517
oh. thanks.Just curious.
>>
>>55272438
Given most of /g/ can't average two integers, it's understandable they would struggle to average n integers
>>
File: trump2.gif (3MB, 300x232px) Image search: [Google]
trump2.gif
3MB, 300x232px
>>55272527
>implekent
Boom, thrown out of the country
>>
Yeah, the answer should be approximately this, right? Lists don't really exist in C, so I used an array instead but whatever, same idea


#define LIST_LENGTH 50

int average(int someList*) {
int sum = 0;
for (int i = 0; i < LIST_LENGTH; i++) {
sum += someList[i];
}
return sum;
}

int main() {
int someList[LIST_LENGTH] = {...};

average(someList);
}

>>
>>55272540
>implying an interview test program doesn't use all Ints.
>>
>>55272527
>implekent
Pajeet identified.
>>
>>55272579
Oh whoops, and divide by length

return sum / LIST_LENGTH;
>>
>>55272479
what of these answers would be enough?
var avg = average(list) //assuming the language can do that


var avg = list.reduce(function(a, b) { return a + b; }, 0) / list.length


var a = 0;
for (var i = 0; i < list.length; i++) {
a += list[i];
}
var avg = a/i;
>>
>>55272438
int avg_list(int n, int *arr)
{
float result = 0.0f;
unsigned i;
for (i = 0; i < n; i++)
result += (float) arr[i] / n;
return (int) result;
}


Can I have job now?
>>
>>55272586
That's what I am implying and that's why you need to consider these two things in addition to "summating the numbers and dividing by the length".
>>
>>55272485
ok anon, please demonstrate how to harmonically integrate the tallywobble with less than 3 integers or you won't get the job
Remember: You have to understand what I just said and can't ask me anything as per your own words
>>
>>55272579
Fired for wasting company time when a much simpler solution exists
>>
>>55272579
Not OP, but if the function is returning the sum, and not the average directly, you shouldn't call it average(). Besides, that still doesn't do what was asked, since you only added everything on the list, it never did the average.
>>
>>55272624
such as..?
>>
>>55272603
>>55272632
Just saw that post, but point still stands, don't call it average if you don't actually average inside of it.

>>55272609
Found the JS cuck
>>
>>55272632
Yeah, I'm aware, I forgot to divide by LIST_LENGTH, as I said in

>>55272603
>>
ARITHMETIC OVERFLOW YA NIGGERS

What's the average of
int list[] = {1, 2, INT_MAX - 2, 1};
>>
>>55272616
then how do you get around integer overflow?
>>
>>55272527
Really? So you want new employees to waste time reinventing the wheel just to show off the fact that they "understand basic logic"?
>>
>>55272650
js can be used in browser, in server, in desktop, everywhere
can your language be used in browser and in desktop?
>>
>>55272659
Yea, never mind, I just realized you actually did the average in the return, my bad.

You should probably not return an integer if you're doing an average though, but I guess that would depend on what is being asked.
>>
>>55272619
Ensure they have a proper understanding by asking questions, you retard
>>
File: fizzbuzz.jpg (174KB, 854x853px) Image search: [Google]
fizzbuzz.jpg
174KB, 854x853px
>>55272527
Good answer, thanks.
>>
>>55272662
Yeah cool, I'm aware of overflows, but what can you do about it?

Switching to a larger data type only moves the problem slightly. I'm assuming you're not allowed to use a "bignum"-esque type.

And what could you do if that was c? Check for overflows in the for loop, and then what? Return -1? call exit()?
>>
>>55272673
>I shouldn't have to prove anything
>never mind that most people coming out of CS aren't worth what we're looking to pay
>>
>>55272579
overflow error
>>55272609
overflow error

Don't call us, we'll call you!
>>
>>55272673
>waste one minute reinventing the wheel makes anon a crybaby
It lets me throw a lot of candidates away immediately saving a lot of my time
>>
>>55272696
>Yeah cool, I'm aware of overflows, but what can you do about it?
You can avoid them, ya dingus.

>Switching to a larger data type only moves the problem slightly. I'm assuming you're not allowed to use a "bignum"-esque type.
That's only one solution. The obvious solution is to calculate a running mean so you don't risk overflow.

>And what could you do if that was c? Check for overflows in the for loop, and then what? Return -1? call exit()?
See above.
>>
>>55272662
Uncaught ReferenceError: INT_MAX is not defined(…)
>>55272711
Can JS even have overflow errors
>>
>>55272733
Oh fuck of course, you do the dividing inside the loop instead of at the end. Good call
>>
>>55272696
You can encode numbers as dynamic strings, for instance
>>
>>55272672
use a long if you expect your data to get that big.
i just described 99% of use cases
>>
>>55272672
Just store the answer in a double, then.
>>
>>55272672
See >>55272733
>>
>>55272438
Do you want the return value as an integer?
Do you want integer average, or floating point average that gets flattened back to an integer?
>>
>>55272751
yeah, that's what I mean with bignum, it's stupidly overkill
>>
>>55272438
some can't even invert a binary tree wtf?
>>
int res = 0;
for(int x : list) {
res += x/list.size();
}
return res
>>
>>55272769
gotcha. thanks.
>>
>>55272609
>javascript
this interview is over
>>
>>55272609
>he didn't do it in scheme or haskell
>>
>>55272579
nice pointer nigger
>>
stop using archaic languages with overflow errors everywhere
god gave you rust, javascript and many other languages with sane variables, but you choose to eat shit
>>
int64 sum = 0;
foreach(int i in list)
{
sum += i;
}
int avg = sum / list.Length;
>>
>>55272733
>The obvious solution is to calculate a running mean
I feel like I should have gotten this, then again, I'm studying EE and not CS.
>>
>>55272438
>Average
>integers

u wot m8 is this sum b8

also
>HR
>being useful
>>
>>55272790
oops, should use double, perhaps long, for res. also the calculation in the loop should cast to double/long ofc.
>>
>>55272438
what if i type iüğğööıııı
>>
>>55272874
Overflow happens regardless of what language you use.
>>
>>55272790
try that with a list of 50 integers that all have a value of 1
>>
>>55272438
The code I would write depends on whether the ints are at risk of overflowing or not.
>>
>>55272501
for i in list:
sum += i
return sum/len(i)

how can this cause an overflow?
>>
>>55272961
>how can this cause an overflow
if you need to ask, you're too dumb to program
>>
>>55272961
my job is secure, for now
>>
>>55272961
what if list would be 2 int_max's? sum would be larger than maximum number => overflow
>>
>>55272961
What happens if you neither have enough RAM or swap? Make it run on a distributed system.
>>
>>55272716
And how many hours are you going to waste trying to convince a young hotshot who thinks he knows everything that he doesn't actually know everything? Yeah, good luck with that.
>>
>>55273027
If my interviewer asks me to program a distributed system to average insanely large lists of integers I will kindly ask him to give me the time to find out how to do that, while being paid for my time spent, or look for someone else.
>>
>>55272956
Do a try catch.
>>
>>55273033
I have a red button under my desk which will alert security to have him escorted out
>>
>>55273062
I've seen this happen before.
They basically want to squeeze free work out of you.

just stop working abruptly and tell them that they have to hire you if they want more.
>>
>>55272978
>>55272993
>>55273000
but it's working
~% cat bla.py
import sys

list = [ sys.maxsize, sys.maxsize ]

sum = 0
for i in list:
sum += i

print(sum/len(list))
~% python bla.py
9.223372036854776e+18
>>
>>55272579
Anon why doesnt your code output anything?
>>
int vars[] = {INT_MAX, INT_MAX, INT_MAX, 1,2};

int main() {
double res = 0;
for (int x : vars) {
res += (double) x / (sizeof(vars)/4);
}
cout << res << endl;
cin.get();
}
>>
>>55273094
>of integers
nice reading comprehension there bud
>>
>>55272438
>take a random sample of 1 and binomial test it
kys
>>
>>55273094
is python like javascript where integers don't exist and all numbers are 64-bit floats?
>>
>>55273119
>assuming things about tthe distribution of numbers
>>
>>55273123
js has parseInt()
>>
>>55273098
I will fire my interviewer if he asks that
>>
>>55273073
>try catch
“programmers” need not apply

Anyway, this is how I would write it if I had to code defensively against integer overflow

int average(int *a, size_t n)
{
int err = 0;
int avg = 0;

for (int i = 0; i < n; i++) {
int x = a[i] / n;
avg += x;
err += a[i] - x * n;
}

return avg + err / n;
}
>>
>>55273142
>assuming irrealistic things
>>
>>55273123
No, Python uses longs, 64-bit numbers to store numbers, but it has a mechanism in place where if you go over sys.maxint (which is 2^63-1), it will automatically convert into a bignum type number, js actually has a maximum value, python doesn't really
>>
>>55273123
Nope, but Python has long integers that can basically be as big as your system memory allows
>>
>>55273110

>sys.maxsize
> The largest positive integer supported by the platform’s Py_ssize_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
>>
Easy. I dont know why you all need the length of the list
Pseudo code:
mean = head(list)
for i in list {
mean += i
mean /= 2
}
>>
>>55272527
>The question is asked to check if you understand basic logic as well as the issue of integer overflow
Should have said that then instead of "write a program that calculates the average of a list of integers".

I'm not going to do things in a round-about way unless I am given a reason. If there are prebuilt functions that will do what is required then I am going to use them.
>>
What the fuck is worng with people in this thread? Everything you guys posted is utter shit and pajeet tier.
Also, since when a list is a fucking array?
>>
>>55273167
so what is the probability a random element is a number if the list is not a word?
>>
>>55273179
>Easy. I dont know why you all need the length of the list

Because that code does not give the mean.
>>
>>55272438
sum(x)/len(x)
>>
>>55273183
even average(list)?
>>
>>55273157
And this if I had to code *really, really* defensively against integer overflow

int average(int *a, size_t n)
{
int err = 0;
int avg = 0;

for (int i = 0; i < n; i++) {
int x = a[i] / n;
avg += x;
err += a[i] - x * n;

if (err > INT_MAX / 2) {
int y = err / n;
avg += y;
err -= y * n;
}
}

return avg + err / n;
}
>>
>>55273203
Fails on circularly linked lists
>>
just use rust or python
>>
>>55273216
This ends the interview.
>>
>>55273217
I aint got told shit about linked lists
>>
>>55273157

Lol, you're treating integers as if they're floats or doubles.
>>
>>55272882
ok so how's this?

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

int main(){
unsigned char i;
int list[] = {1, 2, INT_MAX - 2, 1};
int mean, avg;

while(i<sizeof(&list)){
mean = (list[i] + list[i+1])/2;
avg = avg + mean;
i = i + 2;
}

avg = avg/(i/2);
printf("%i\n",avg);
return 0;
}
>>
>>55273236
Oh, right. How silly of me. I forgot that C truncates towards 0, not -infinity, so ‘err’ could actually underflow if you feed it a long enough array of negative integers. (For example, INT_MAX many of them)
>>
>>55273157
I'd just use floats/doubles internally instead of that err thingy. Probably it'd hurt performance a bit, but who cares.
>>
>>55273217
>Do x for a
>B-but it fails for b
No shit
>>
>>55273275
Not the proper mean (increase number of numbers, and you lose precision), also wtf are you doing with
sizeof(&list)
??
>>
>>55273275
crap I meant

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

int main(){
unsigned char i;
int list[] = {1, 2, INT_MAX - 2, 1};
float mean, avg;

while(i<sizeof(&list)){
mean = (list[i] + list[i+1])/2;
avg = avg + mean;
i = i + 2;
}

avg = avg/(i/2);
printf("%f\n",avg);
return 0;
}
>>
>>55273264
I get the feeling you don't even understand my code. Go ahead, try running it.

>>55273295
Floating point is not just bad for performance, it's also bad for accuracy.

But you're right in that nobody cares about either of these concerns in practice since this is a meaningless, contrived artificial test. In reality, when you want an average of something, there's a good chance you want the average as a floating point number and not an integer.
>>
>>55273320
>Not the proper mean (increase number of numbers, and you lose precision)
I noticed. How would you fix that?
>also wtf are you doing withsizeof(&list)??
Figured I'd make it expandable for longer longer lists.
>>
>>55273157
>>55273216
>>55273275
>>55273288
>>55273324
and this is why an employer prefers and hires >>55273094
>>
>>55273264
read that code more carefully retard
>>55273275
this one is broken af
>>
If you interview a CS student, you should ask him something that a CS student should typically know. If he doesn't know it, you know he's a retard.
For example ask him to use Dijkstra algorithm on some problem.

Note: this could weed out bootcampers
>>
>>55273216
What if n is greater than INT_MAX?
>>
>>55273374
That's fine by me. Employers can keep on hiring pajeets shitting out CS graduate-tier python garbage with zero understanding of the device they're sitting on front of. if they want to.
>>
>>55273382
You're the one who's retarded.

int x = a[i] / n;
>>
>>55272674
Yes, silverlight :)
>>
>>55272936
lmao
>>
>>55272711
>overflow error
why?
>>
>>55273432
What programming language can handle all numbers?
>>
 
if text = text ("Yes, correct") else {
"wrong"
}
>>
>>55272476
nice meme statkike, median is never an average
>>
>>55273400
In this case, pajeets' code would likely be more trustworthy and stable.
>>
>>55273459
this could be valid if e and x are cyrillic e and х in one of the variables
>>
>>55273484
>median is never an average

1, 1, 1, 1, 1, 1, 1, 1, 1, 1
>>
>>55272438
what did he write? it isn't that hard.
>>
File: dib.jpg (38KB, 550x404px) Image search: [Google]
dib.jpg
38KB, 550x404px
array=list()
x=str

while x != "n":
num=int(input("Enter number : "))
array.append(num)
x=input("Press anything else than 'n' to continue adding numbers : ")

avg = sum(array)/len(array)
print(avg)

#dunno how to post code
>>
>>55273389
Undefined behavior. Well fuck. At this point, working around it would be so difficult that I doubt it's worth the effort no matter what the context.

Anyway, this is how an overflow-safe floating point averaging function could look like:

double average(int a[], size_t n)
{
double sum = 0, err = 0;

for (size_t i = 0; i < n; i++) {
double x = a[i] - err;
double new = sum + n;
err = (new - sum) - n;
sum = new;
}

return (sum - err) / n;
}


Not sure if it's better to sum first and then divide, or vice versa. (But you could easily swap it by just doing
a[i] / (double)n
in the inner loop instead of at the return)
>>
>tfw almost everyone is out by default
>tfw list != array
This is trully depressing, I really hope none of you are actually employed, if you can't write a small, secure and fast average function
in your main language, you should consider a new job with less qualifications.
>>
>>55273406
err += a[i] - x * n
...
return avg + err / n

Do you know any math whatsoever?
>>
>>55273457
Haskell's Integer function is unbounded in theory (assuming you don't run out of RAM)
>>
>>55273532
>he took the bait
>>
>>55273177
So what happens when you have an integer with a value that's "as big as your system memory allows" and you add 1 to it?
>>
>>55273527
Sorry, I meant:

        double new = sum + x;
err = (new - sum) - x;
>>
>>55273579
system crash
>>
>>55273579
My money's on SIGABRT. (Or possibly SIGSEGV, but I'm going with the former.)
>>
#include <iostream>
#include <algorithm>

template <typename T, std::size_t N>
constexpr std::size_t countof(const T(&)[N]) noexcept
{
return N;
}

template <class T>
std::size_t countof(const T& container)
{
return container.size();
}

template <class T, class Iterable>
T average(const Iterable& iterable)
{
return std::accumulate(std::begin(iterable), std::end(iterable), T()) / countof(iterable);
}

int main()
{
auto numbers = { 1, 2, 3, 4, 5, 6 };
std::cout << average<double>(numbers) << std::endl;
}
>>
>>55273181
If you're asked this in an interview then they're looking for you to ask important questions like "Do we know how large the list can be? Do we know how large the largest number can be?" Any person that passed their first programming class should be able to write a solution to this problem. But they want you to be able to look at something that seems simple and be able see these potential issues.

Problems like this aren't to see if you can calculate an average. They're to see how you problem solve.
>>
>>55272438
'I would just ask stack overflow'
>>
File: n8umjWj.png (3KB, 698x1284px) Image search: [Google]
n8umjWj.png
3KB, 698x1284px
>>55273553
Full damage control now?
>>
>>55273614
I'd solve the problem once there was a problem. I'm not going to go out of my way to make a problem out of nothing just to write a solution to it to try and make myself look smarter.
>>
>>55273614
this

In the real world, most of the challenging aspects of programming (i.e. not code monkey boilerplate) are trying to connect the problem space with the solution space. This requires understanding and predicting the limitations of each approach and brainstorming ways around them, without even writing a single line of code (because having your code monkeys write the code costs $$$).

A good engineer needs to design a working system *before* it's built, rather than trying to monkey-patch the failures later.
>>
#include <vector>
#include <iostream>

double calc_mean(std::vector<int> nums)
{
double sum = 0.0;
for (int i : nums) {
sum += i;
}
return sum / nums.size();
}


int main()
{
std::vector<int> nums = { 3, 4, 1, 6, 7, 9, 2 };
std::cout << calc_mean(nums) << '\n';
return 0;
}


rate my version. I'm a girl btw ;)
>>
>>55273457
Common lisp is extremely good with numbers
>>
>>55273457
any language with bignum support, like lisp
>>
>>55272438
for(int i=1;i<list.size();i++){
list[i]+=list[i-1];
}
return list[i];

QED
>>
>>55273685
Writing an algorithm that accounts for all cases isn't "making yourself look smarter".
>>
File: 1435891907005.gif (2MB, 162x191px) Image search: [Google]
1435891907005.gif
2MB, 162x191px
>>55273194
>>ask interviewee to write a program that calculates the average of a list of integers
>>he fails
>holy shit the CS major meme is real

how many interviewees we have?
n = 1

how many of them passed the test?
P(+) = 0

how many of them failed the test?
P(-) = 1

What is the p-value of this hypothesis?
p = 0

Gee! p <= 0.05
therefore we should reject that there are more CS majors that can pass the test!
>>
>>55273830
>What is the p-value of this hypothesis testing?
>>
>>55273453
you didn't check for overflow, cuck
>>
>>55273786
None of the solutions I have seen posted have accounted for non-integer values.
>>
>>55273708
This will produce wrong results with an error rate bounded by sqrt(n).

(For an example of a worst case that triggers it, consider the list
n, BIG, -BIG
(substitute ‘BIG’ for sufficiently many repetitions of MAX_INT if necessary).

This should average out to 1, but your code can round it down to 0 instead.
>>
>>55273860
cuck
>>
>>55273932
uck
>>
>>55273870

def avItSon(listOfInts):
return sum([i for i in listOfInts])/float(len([j for j in listOfInts]))
>>
>>55273946
The correct version isn't the implementation, but consulting with the customer before doing anything.
>>
import numpy

numpy.mean([1,2,3])

don't reinvent the wheel.
>>
>>55273946
The point of this thread is that the correct version depends on your requirements

There is no single correct version.
>>
>>55273946
The correct version is the one that works with the sample data they give you.
>>
>>55273946
something that manipulate lists and not array?
retard off yourself right now.
>>
>>55273941
ck
>>
>>55273990
k
>>
>>55272438
let avg list =
let s = List.fold_right (fun e acc -> acc + e) list 0 in
s/(List.len list)
;;
>>
>>55273860
isn't that something you just kind of see when you see the list?
>>
>>55272438
>>55272476
>implying you can't easily make it generic

#include <cmath>
#include <limits>

template <template<class> class ADT, class NUM>
double average(ADT<NUM> list, double n=1){
if(n==0){
NUM product=1;
for(NUM data : list){
product*=data;
}
return pow(product, double(1)/list.size());
}
if(n==std::numeric_limits<double>::infinity()){
double max=-numeric_limits<double>::infinity();
for(NUM data : list){
if(data>max)
max=data;
}
return max;
}
if(n==-std::numeric_limits<double>::infinity()){
double min=numeric_limits<double>::infinity();
for(NUM data : list){
if(data<min)
min=data;
}
return min;
}
NUM sum=0;
for(NUM data : list){
sum+=pow(data,n);
}
sum/=list.size();
return pow(sum, double(1)/n);
}
>>
>>55273484
The median is a better indicator of the average of a distribution because it's immune to Kurtosis, silly pleb
>>
>>55273870
(defn avg [seq]
(/ (reduce + seq) (count seq)))

It is morally wrong to write anything in C that doesn't absolutely need to be.
>>
>>55274031
>inputting a list of numbers by hand
what the fuck is wrong with you what kind of worthless programs do you write
>>
>>55273999
>>
>>55273870
>given a list of integers
>I better account for non-integers
:^)
>>
>>55274063
>>
File: 1465085392970.jpg (494KB, 1280x720px) Image search: [Google]
1465085392970.jpg
494KB, 1280x720px
>>55272438
Uhh,

int IntMean(int *list, int size){
long a=0;
for(int i=0; i<size; i++) a+=(long)list[i];
return (int)a;
}


Are graduates just getting dumber because so many are shoveled through the meat grinder nowadays?
>>
>>55274097
you're trying to be smart but that won't work properly

really, the correct answer to op's question is to disregard overflows (like 99% of languages do). only if he pressed on with that question would it be worthwhile to bother preventing them.
>>
>>55274097
lol, forgot to check size!=0 and divide by size.

You could add error checking like if a=NULL and size>0, and look for overflow, but really that depends on your problem. If you can make guarantees about the data, less error checking is needed.
>>
>>55274097
>no overflow check
Your resume got thrown into the trash right after the interviewer told you that they would call you at a later date.
>>
>>55274097
>iterating using int instead of size_t
dropped right there
>>
>>55272611
>float
>>
>>55273431
Your Microsoft shilling points have been deposited to your account. Thank you for your service
>>
>>55274097
long isn't guaranteed to be bigger than int
>>
You're all fucking retarded.
var list = [1, 2]
var string = list.toString()pi&appid=XXXX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var avg = xhr.responseText;
}
}
xhr.open('GET', 'http://api.wolframalpha.com/v2/query?input=average(' + string + ')', true);
xhr.send(null);


very easy
>>
>>55273870

I guess you overlooked some then.
>>
>>55274185
nothing is guaranteed in life
the list of the numbers might randomly contain letters
did you think of that, huh smart guy?
>>
>>55274203
oh fuck forgot to remove pi&appid=XXXX when copypasting
>>
>>55274213
>the list of the numbers might randomly contain letters
no it wont, the type declaration means you're treating the bits as integers

doesn't matter fuck all what's in there, they're ints to your code..
>>
>>55274223
you're going to get a wrong answer then, you silly faggot
>>
>>55274248
“wrong” is subjective

the point is that it will return the average
>>
>>55273094
import sys
print(sys.maxsize + sys.maxsize)

hmm...
>>
>>55272619
You're a fucking retard. Reread what that guy said
>>
>>55274262
treating letters like numbers when you are only supposed to average the numbers will most certainly give you a wrong answer

otherwise why not just print a random number? it's all subjective, after all
>>
>>55274054
that's not what I meant
>>
>>55274295
The logic you are trying to defend is “it's okay to implement add(x,y) as (x - y) because the user could have accidentally negated ‘y’, thus making the code right”

Seriously, just piss off. You aren't being funny or clever
>>
>>55274144
>>55274126
>>55274125
>>55274118
lolx2. None of you even caught that I returned an int.

Really though, if an interviewer were to ask to "write a program to average integers", the correct course of action would be to force him to be more specific about his demands.

If the list is internal to a program and it is known that the list can't overflow when summed, then the appropriate solution is the shortest.

If the list can overflow, you need to ask the interviewer what he expects the error to be: a special code? a signal? exit()? Correctly sum numbers that overflow?

If he specifies special code, then the function needs to indicate this with a global or parameter list return value, because using clever shit like NaN could obscure NaNs being present in the list for other reasons. This makes the code more complicated.

If he specifies it should return the right result, then you need to work with bignums. And with bignums you have to deal with the chance you run out of memory. So you'd have to test for that.

I think talking about what is expected and agreeing upon what is needed is over 9000 times more important for good software engineering than being good at guessing at what someone whats.

>>55274144
>size_t
valid, but *sigh*
>>
>>55274313
Not at all, I'm trying to cover for every case, so that the code is always right, whereas you're trying to cover for your specific non-guaranteed case.

So in the example you give, that line of thinking is much closer to your argument than mine.
>>
>>55273946
this one >>55274203

name at least one circumstance where it doesn't work (assuming valid appid) and that he copy-pasted normally
>>
>>55274353
>I'm trying to cover for every case, so that the code is always right
Then why does your piece of shit code produce undefined behavior?

I'll tell you what you're trying to do: You're trying desperately to save face from the embarrassing revelation of the fact that you don't understand what ‘int’ and ‘long’ mean in C.
>>
>>55274367
>name at least one circumstance where it doesn't work
Averaging together 50,000 integers.
>>
File: 1330547432045.jpg (14KB, 315x329px) Image search: [Google]
1330547432045.jpg
14KB, 315x329px
>>55274386
I never posted any code, I was just arguing with you for fun.
>>
File: 1357078513050.jpg (125KB, 763x639px) Image search: [Google]
1357078513050.jpg
125KB, 763x639px
template<class T> double average(T* list, long long length){
double out = 0.;
for (int i = 0; i < length; i++){
out += static_cast<double>(list[i]) / length;
}
return out;
}


Learn to program you filthy stains on society
>>
>>55274410
Then why the fuck are you trying to defend >>55274097 (in response to >>55274185)
>>
>>55274418
that shit doesn't even compile you pleb
>>
>>55274437
Wasn't really defending, just noting that there are a high amount of things to check for given the vague problem statement.
>>
dumb softwareonly babbies
>>
>>55274418
>template
Guess where your resume is going?
>>
File: .png (69KB, 743x721px) Image search: [Google]
.png
69KB, 743x721px
>>55274401
Oh wow. """""computational""""" knowledge engine
>>
>>55274418
If my T has overrided +, then the division operator doesn't necessarily make sense __all the time__ in this context.

This is the problem with C++.
>>
>>55274462
Yes but my point is that >>55274097 was specifically using long for the running sum instead of int *as if* that would somehow prevent overflows, which it absolutely doesn't.

(int and long are just minimum size guarantees. relying on long > int is undefined behavior)

The programmer clearly thought they were being clever, and I was pointing out that their thinking was flawed.
>>
>>55273946
/g/ won't tell you because /g/ can't do it. :P
>>
File: u w0t m8.png (9KB, 505x312px) Image search: [Google]
u w0t m8.png
9KB, 505x312px
>>55274449
Try harder
>>
>>55274516
>>55274048
>>
>>55273000
Except that's not a possibility in Python, which he's obviously using.

Maybe you're the retard.
>>
>>55274521
oh so you add the main function after.

top kek.

so, the code you posted earlier didn't compile, because it didn't have the main function.

kys
>>
>>55274554
anon, it was obvious it needed a main function. Don't be a retard.
>>
File: 1406651673977.png (31KB, 138x132px) Image search: [Google]
1406651673977.png
31KB, 138x132px
>>55274484
template<class T> void inTheTrashItGoes(T& urPost){
delete urPost;
}
>>
>>55273389
It's not like he has to use size_t.
>>
>>55272638
sudo apt-get install python
>>
File: 1354484636662.gif (2MB, 448x252px) Image search: [Google]
1354484636662.gif
2MB, 448x252px
>>55274585
>using apt-get
>>
>>55274484
>Guess where your resume is going?
why? people don't like templates?
>>
>>55272501
Neither Dennis or Ken needed overflow checks when they wrote the finest OS to ever bless silicon slabs.
>>
File: u9fag.jpg (26KB, 349x642px) Image search: [Google]
u9fag.jpg
26KB, 349x642px
>>55274554
>>
>>55273513
Fuck you.
>>
>>55274038
what the fuck, at least TRY to make it more legible.
And even ignoring the spacing between operators, what's up with that indentation? First if block has no indentation. Last for block has 8 characters indented when the rest of the code uses 4.
>>
>>55274554
>so, the code you posted earlier didn't compile, because it didn't have the main function.
you're a fucking idiot

$ cat test.cpp
template<class T> double average(T* list, long long length){
double out = 0.;
for (int i = 0; i < length; i++){
out += static_cast<double>(list[i]) / length;
}
return out;
}
$ g++ -c test.cpp
$ file test.o
test.o: ELF 64-bit LSB relocatable, x86-64, version 1 (SYSV), not stripped
$
>>
>>55274729
> -c
> file
> muh special flags
top kek

kys already
>>
>>55274796
-c is how you compile a c++ source file

I'm beginning to think you don't even know the slightest thing about c++ (or c for that matter)
>>
>>55274922
>-c is how you compile a c++ source file

you don't the -c flag to comiple a C++ program retard.

if you write a *normal* program (with main) you can just do
 g++ your_program_name.cpp 


retard
>>
File: 1464396698489.png (176KB, 433x422px) Image search: [Google]
1464396698489.png
176KB, 433x422px
>>55272579
No, it should be this.
#include <stdio.h>
#include <stdlib.h>
#define CHAR_MX 256
unsigned int arrSize = 0;
void printArr(int *arr)
{
for(register unsigned int x = 0;x<arrSize;x++)
printf("%d ",arr[x]);
}
void popArr(int *arr)
{
for(register unsigned int x = 0;x<arrSize;x++)
arr[x] = rand() % 10;
}
float avgArr(int *arr)
{
unsigned int sumArr = 0;
for(register unsigned int x = 0;x<arrSize;x++)
sumArr+=arr[x];
return sumArr/(float)arrSize;
}
int main(void)
{
char inputBuff[CHAR_MX] = {0};
printf("Array size: ");
fgets(inputBuff,CHAR_MX,stdin);
sscanf(inputBuff,"%d",&arrSize);
int *array = calloc(arrSize,sizeof(int));
popArr(array);
puts("Array: ");
printArr(array);
printf("\nAverage: %.2f\n",avgArr(array));
return 0;
}

>>
>>55274941
>he had no main
If you don't use -c, you'll get
>
undefined reference to `main'
collect2: error: ld returned 1 exit status

Maybe you're the retard.
>>
>>55274585
die
>>
>>55274987
>using special flags when you should have written a normal program (with the main function)

retard
>>
>>55275017
>including a main in things that have no need for a main
My claim still holds.
>>
>>55274941
If you had ever written a program larger in scope than fizzbuzz in your life you would know that the normal procedure for compiling C++ programs is to compile all the source files with -c and then link them together at the end (using a linker) to form the actual binary or shared library.
>>
>>55272609
>i isn't local to the for
What sorcery is this?
>>
Just get a job as a farmer

You cant eat code or warm your home with programs
>>
>>55275017
>when you should have written a normal program (with the main function)
Not in the specification
>>
>>55272438
>>ask interviewee to write a program that calculates the average of a list of integers
int main()
{
return 0;
}


This calculates the average of a list of integers. (For example, the list
[1,2,3,-6]
)

You didn't specify that the list had to be read from stdin or otherwise supplied by the environment. All you asked for was a program that calculates the average of *a* list of integers.

I take that to mean I can choose the list. Feel free to hire me.
>>
>>55275071
int main(){
int i;
while (true){
i = i/5+12;
}
return 0;
}

I can warm my house with ease, ya dip
>>
>ask interviewee to write some code
>he starts rambling about this slash-gee-slash website
>>
>>55275206
>ask interviewee to average a list of integers
>starts rambling about being a big dick c playa and calling me a webcuck
>>
File: 1415660146380.jpg (36KB, 743x697px) Image search: [Google]
1415660146380.jpg
36KB, 743x697px
>>55275107
hired on the spot. Welcome to the company!
>>
Never was asked to code when doing my interviews.

How do you do it, verbally or on paper?
>>
>people missing the point of the thread and posting their own shitty solutions
Holy shit. This is like JizzCuzz all over again.
>>
>>55275226
>ask interviewee to average a list of inters
>he starts mumbling about pajeet stealing his job
>decide to pass him up and hire a highly skilled foreign worker from India.
>>
>>55275635
depends on the company. I've had one where they brought a laptop and I would write the code on there and others where I could use a whiteboard.
>>
>>55274695
congratulations, you have autism
>>
>>55272573
kek
>>
>>55274973
>using register unsigned int instead of register size_t
not good
>>
>>55272787
How can you invert a binary tree? If you invert it, it's no longer a tree.
>>
>>55273176
>it has a mechanism in place where if you go over sys.maxint (which is 2^63-1), it will automatically convert into a bignum type number, js actually has a maximum value, python doesn't really
What does python due if a number is too big to be stored in a bignum?
>>
>>55273598
Don't those only exist in POSIX operating systems?
>>
>>55275048
Why is that better than just #including everything recursively in the main file and compiling that?
>>
>>55273513
By that logic, since natural log(e) = 1, logarithm is an average
>>
>>55276660
-c flag stops the compiler from also linking when you compile

>You might ask why there are separate compilation and linking steps. First, it's probably easier to implement things that way. The compiler does its thing, and the linker does its thing -- by keeping the functions separate, the complexity of the program is reduced. Another (more obvious) advantage is that this allows the creation of large programs without having to redo the compilation step every time a file is changed. Instead, using so called "conditional compilation", it is necessary to compile only those source files that have changed; for the rest, the object files are sufficient input for the linker. Finally, this makes it simple to implement libraries of pre-compiled code: just create object files and link them just like any other object file. (The fact that each file is compiled separately from information contained in other files, incidentally, is called the "separate compilation model".)
>>
>>55272438
let avg = List.fold (fun (s,l) x -> (s+x,l+1.0)) (0.0,0.0) >> (fun (s,l) -> s/l)
>>
static double ProperAverage(List<int> list)
{
double prev = list.First();
int index = 1;

foreach(var num in list.Skip(1))
{
prev = ((prev * index) + num) / (index + 1);
index++;
}

return prev;
}

Did I get it right?
>>
>>55272609
>>55275050

Seriously, how the fuck?
>>
>>55275050
>>55277897
var = global values in javascript
let = local
>>
>>55277946
var is function scope while let is block scope.
>>
>>55274585
>debian
fella no self respecting corporation uses this
>>
def average ints
Rational(ints.reduce(:+), ints.size)
end


To get an integer average, use average(list).to_i
To get a floating point average, use average(list).to_f
>>
(defun average (list)
(let ((len (length list))
(sum (apply #'+ list))
(/ sum len)))
>>
File: bait98342223.jpg (12KB, 224x225px) Image search: [Google]
bait98342223.jpg
12KB, 224x225px
>>55277946
>being this stupid
>>
>>55278081
>>55278006
there is no function there
>>
>>55278148
there was no let either.
>>
Function in VBA, done on my phone. How I done did, d00dz?

function averagerator(array as long)
dim sum as long
for x = 0 to ubound(array) - 1
sum = sum + array(x)
next x
averagerator = sum / ubound(array)
end function
>>
None of you niggas even did it right.

What you do is, if the addition of the numbers results in a number greater than the max the variable can hold. Split the number in some way, calculate the averages of the split numbers, then once you print it out combine it in someway.

Get gud m8s
>>
>>55278280
>VBA
kill yourself pls
>>
>>55272501
what if I used BCD ;)
>>
>>55278315
Yeah, and I bet you eschew McDonald's, and only eat haute cuisine. We both know you secretly love it.
>>
int64_t average(int32_t* n, char nlength)
{
int64_t avg;
for(int a=0;a<nlength;a++)
{
avg = avg + n[a];
}
avg = avg / nlength;
}


I mean, it's a shitty way to do it, but you need an INT32_MAX amount of INT32s to reach INT64_MAX, and you're not gonna get that much INT32s with a char max value.
>>
>>55278384
fuck I forgot to return it
>>
>>55274203
kek
>>
>>55273179
Instead of dividing the sum by n, won't this divide by 2^n? I think you do need the length of the list.
>>
>>55274048
>my meme language is superior to C for reasons
Freshly shitted autism
>>
>>55278927
>metaprogramming!
>homoiconic!
>buzzwords!
>>
>>55273484
Median is a kind of average

For all distributions with third moment around the mean equal to zero, the median is exactly equal to the mean
>>
i got a software engineering job today after talking to a dude for 20 minutes over the phone

i literally don't fucking understand the interview process
i've been interviewing for months, i've been to places which made me go through three rounds of interviews
places that have flown me out to interview and then rejected me

i don't fucking get it
i can do your easy meme questions like OP
i can do some of the hard riddle questions, but not all of them

i don't fucking get what they want
i can speak english
i can make coherent analysis of bullshit and explain my reasoning and logic
i can take and follow orders
i thought i was entering NEET land and suddenly decides to drop tens of thousands of dollars on me after talking to me for 20 minutes
>>
>>55273757
>quod erat demonstrandum
>that which was to be proven
what?
>>
>>55273830
>using babby-tier frequentist stats
you would expect CS majors to have better knowledge of statistics than some psychology major
>>
>>55279270
having been on the hiring side before, I can tell you hiring managers sexually get off to rejecting applicants. its the most power they've ever had in their lives and will ever get. I've seen incompetent managers reject 5 perfectly fine candidates in a row for a SHIT job that no one wanted in the first place.
its definitely the dunning kruger effect in overdrive. as soon as they are the person in charge of hiring they think they know everything about who would be good in the position.
and no i'm not just a butthurt guy studies have shown that hiring managers are actually worse than coin flips on predicting performance in a company.
>>
>>55272744
>Can JS even have overflow errors

It's stupid easy to overflow in JS
>>
>requiring more than one clock cycle to perform an average


return (a >> 1) + (b >> 1) + (a & b & 0x1);

>>
>people not accounting for corner cases
I seriously hope you are not employed. I bet you use == for floating point numbers as well.
>>
>>55279402
This is why performance needs to be assessed from multiple perspectives, from below as well as above. But that would mean giving the peasants some small measure of power over their landholders, and we just can't have that!
>>
>>55279704
>using patented code
Enjoy being sued.
>>
>>55279718
Original code do not steal

return (a & b & 0x1) + (b >> 1) + (a >> 1);
>>
>>55272438
I really hope its as bad as you say it is. I will have no trouble getting a job in the future.
>>
>>55279704
I don't program that often, do you mind explaining how this works?
>>
>>55279839
>> is bitshift operator. its the same as dividing by two. you're moving the binary bits over.
it's a lot faster than a multiplication operation on the CPU level. although i bet compilers already try to do that when they can.
>>
>>55272579
>not getting the list size as an argument
>>
>>55276444
Uhh... Bignum can store arbitrarily large numbers...
>>
>>55279883
So bitshifting is just multiplication?
>>
>>55279918
No.
>>
>>55279918
ints are stored in binary like this
0000_1000 = 8
0 2^0 + ... + 1 * 2^3
if you shift it
0000_0100 now its 4
so you can divide or mult by two since computers use binary.

i forget why else bitshifts are useful but they're there.
>>
>>55279936
>>55279964

So bit shifting is moving binary bits, which ultimately changes it numerical value. But why does performing those certain operations give the average?
>>
>>55280000
it's the magic /g/ approved way of averaging ints without getting overflow. something to do with rounding. i don't really care because i've never had to average ints in my career.
>>
File: 1415660521326_3.jpg (209KB, 960x667px) Image search: [Google]
1415660521326_3.jpg
209KB, 960x667px
Since it's a program

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

int main(int argc, char** argv)
{
float sum = 0;

for(int i = 1; i < argc; ++i)
{
sum += atoi(argv[i]);
}

printf("%.2f\n", sum / (argc - 1));

return 0;
}



>inb4 error checking
>>
>>55279964
I hear integer multiplication is implemented in hardware using bitshifts
>>
>>55279713
double x = 1.0;
while (you_are_a_faggot)
x *= 2.0;
if (x == 1.0)
printf("Lies\n");
else
printf("Truth\n");
>>
>>55279918
Left shift = multiplication by two
Right shift = division by two
>>
>>55280093
>x *= 2.0
>>
>>55272438
I refuse to believe anyone wrote that. They wouldn't have screenshot it unless it was written in a way that was self-aware of how ridiculous it was...
>>
Hello, many greetings. I am Pajeet from Bangalore. Your solutions do not successfully used OOP. Here ideal solution.

public abstract class Number {
private int numberValue;

public Number(int x) {
numberValue = x;
}

public int getNumber() {
return numberValue;
}
}

public class Integer extends Number {
private int integerValue;

public Integer(int x) {
super(x);
}
}

public class Average {
public static double getAverage(Number[] numbers) {
double average;
average = getSum(numbers) / numbers.length;

return average;
}

public static double getSum(Number[] numbers) {
double sum = 0;

for (int i = 0; i < numbers.length; i++) {
sum += numbers[i].getNumber();
}
return sum;
}
}

public class Main {
public static void main(String[] args) {
Number[] numbers = { new Integer(1),
new Integer(5),
new Integer(24),
new Integer(3),
new Integer(53)};

double average = Average.getAverage(numbers);

System.out.println("The average is " + average);
}
}
>>
>>55280104
That's pretty cool. Does it work for all numbers?
>>
wow i just realised how stupid and unmotivated most of the programmers on /g/ are
>>
>>55280127
>public abstract class Number
>public Number(int x)

kek, good job Pajeet
>>
>>55280084
>>55279964

a<<b is multiplying a with 2^b
a>>b is dividing by 2^b

Shifting is supposed to be an easy process for a computer. That's why there is a multiplication method called russian (dunno the actual term in English) that handles the multiplication of two integers only with multiplications with and divisions by powers of 2 aka bitshift operations.
>>
>>55280148
If you have a byte with 1000_0000 (128 decimal) and shift left, you get 0000_0000 (0 decimal). Also, I'm not sure how this works for signed integers.
>>
>>55276660
Keeping the compilation units small is not only good for speed but also allows you to implement the information hiding part of abstraction.

Local definition in one file don't pollute the global scope and aren't exposed to the other files.
>>
>>55279704
This breaks on negative integers.

Congratulations, you're fired for trying to write “clever code” that not only fails at the task but also hilarously fails to “outsmart” the compiler and produces wrong results.
>>
File: word.jpg (25KB, 394x500px) Image search: [Google]
word.jpg
25KB, 394x500px
>>55272438
So this is how I should bait /sci/ into doing my math homework? By making a shitty stem-major picture? Or is /g/ just more retarded than any other board?

Well played.
>>
>>55280148
>>55280196

Of course what I said is with a single byte. With a normal 4 byte unsigned integer, your upper limit for left shifts is:

1000_0000 0000_0000 0000_0000 0000_0000 (2147483648 decimal), which when shifted left becomes zero.
>>
Assuming list is a class with iterators implemented,

double avg=0;
while(listIterator!=list.end()){
avg+=(*ListIterator)/(double)list.length();
ListIterator++;
}
>>
>>55280338
It won't overflow on max-ints, works with negative numbers, but it might lose some least significant bits if list uses long numbers. Will work correctly for int.
>>
>>55279918
Bitshifting is multiplication by powers of 2
>>
/* Does not handle overflows */
extern double avg (double arr[], size_t len);
extern float avgf (float arr[], size_t len);
extern long avgl (long arr[], size_t len);
extern long long avgll(long long arr[], size_t len);

#define _avg(NAME, TYPE) \
TYPE NAME ( TYPE arr[], size_t len ) { \
size_t i; \
TYPE sum = ( TYPE ) 0; \
for (i = 0; i < len; i++) \
sum += arr[i]; \
return sum / len; \
}

_avg(avg, double)
_avg(avgf, float)
_avg(avgl, long)
_avg(avgll, long long)
>>
How's this?

#include <stdio.h>

int main(void)
{
int val, sum = 0, cnt = 0;

printf("Enter integers to average: ");
for (;;) {
scanf("%d", &val);
sum += val;
cnt++;

if (getchar() == '\n')
break;
}

if (cnt == 0)
printf("Division by zero.\n");
else
printf("Result: %.3f\n", (float) sum / cnt);

return 0;
}
[\code]
>>
>>55276345
Why?
>>
template <typename T = double, typename ... ArgList>
auto average(ArgList ... args)
{
auto count = sizeof...(args);
T total = T{};

for (auto arg: {args...})
total += arg;

return total / count;
}

int main()
{
std::cout << average(1, 2, 3, 4, 5, 6);
return 0;
}
Thread posts: 317
Thread images: 20


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

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


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