• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
That's what spread does. It takes iterable things and let's you jam them into arrays (and vise-versa).

Yessssss buuuuut, I'm not learning "ES6" right now. I'm learning "Javascript/C" and trying to understand their quirks/programming faults instead of finding workarounds for those quirks.
 
That's thousands of steps ahead of where I am right now. I keep failing to understand arrays, strings and why you can't just shove strings in arrays.

Like

array = [];
jam_into_array = 5, 6, true;

array = jam_into_array;

Would work, AFAIK. But sentences that state they're strings? Oh hell no, you have to bend over backwards to jam those into the array. :/

Would work like this

array = [];
jam_into_array = [5, 6, true];

array = array.concat(jam_into_array);
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Would work like this

I guess I should've clarified:

Numbers and Booleans go into arrays easy peasy: You can just assign the array those values and they'll go in. But with strings it's impossible to just assign a string to an array because (in C) "strings are an array of characters." It's "what? Why can't I just put that sentence into the array and then have that "array of characters" be an array within an array?
 

Aikidoka

Member
I admit I haven't used OO in Fortran... I've mostly done number-crunching with it (astrophysics computations, for example), and there's not much use of OO when you mostly do massive convolution computations...


The main problem with C/C++ is that there's no n-dimensional table type, so the compiler don't know exactly what you're doing, and is slightly less good at optimizing it.

So you have to do some of the compiler job... and usually, it's either a lot of work, or you'll have a slightly slower code. I would suspect the difference isn't so big now, but I haven't done benchmarks for some time (and some will always argue that 20% increase in speed is significant)

Some people wanted to demonstrate that C++ coud be really quick, though, and developped thinks like Blitz++.

http://blitz.sourceforge.net/

It *is* impressive, often faster than Fortran, and with a syntax I find interesting and expressive.

But to achieve this, they went the extra mile (when you do a convolution on a table, for example, they don't work line-by-line, but use a Hilbert fractal to lower cache-miss... seems a bit crazy, but really effective!)

Always seemed to me rather a proof-of-concept, and an argument that C++ (and OO) can compete with Fortran, than a real tool, but it works, and well.

The astrophysics group at ORNL has started a massive project of making all their code for core-collapse supernova object-oriented (Fortran specifically). Since supernova modeling involves many different types of physics (fluid dynamics, thermodynamics, gravitation, etc... ) their goal is to have their code easily portable for applications in any combination of those fields. This type of project design certainly seems to be the best way to go about it, imo. Otherwise, any extensions to the project or whatnot will waste so much time copy-and-paste and search-and-replace etc...

The only caveat with C++ that I have heard is that it has some problems or complications with openMPI and openMP, but I'm not sure how true this is or its extent.

What are some good resources to learn object-oriented programming? I am going for a computational science minor and will look into graduate computer science courses about it, but I think it would be best to try and get some prior experience.
 

C0unter

Member
I recently (2 months ago) started my internship at a SaaS startup, really cool people, really fun job and I love it so far. But fuck me, its insane how little I know and I was thinking I was hot shit after doing great in college.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
I know what you mean.... but this sounds silly

Okay?

What is "Javascript/C"?

Javascript and C. I started off with C due to CS50x by Harvard. Ran into the "put strings into arrays" problem, thought "okay, maybe C is just too hard. I'll try JS which is supposed to be 'looser' with it's definitions/types" and ran into the problem again.

I just can't wrap my mind around why it's so hard to assign things into arrays. They're meant to store things, why the hell is it impossible to put strings into arrays without bending over backwards to do it.
 
Javascript and C. I started off with C due to CS50x by Harvard. Ran into the "put strings into arrays" problem, thought "okay, maybe C is just too hard. I'll try JS which is supposed to be 'looser' with it's definitions/types" and ran into the problem again.

I just can't wrap my mind around why it's so hard to assign things into arrays. They're meant to store things, why the hell is it impossible to put strings into arrays without bending over backwards to do it.

I think we're all struggling to see precisely where your problem with the concept is. Especially with Javascript, adding strings to an array and retrieving them is as simple as
Code:
var myArray = [];
myArray[0] = "hello";
myArray[1] = "world!";

console.log(myArray[0] + " " + myArray[1]); // prints 'hello world!'
No bending over backwards required.
 

NotBacon

Member
Ran into the "put strings into arrays" problem, thought "okay, maybe C is just too hard.

C strings are arrays. Literally just arrays of characters. A "put strings into arrays" problem doesn't make much sense. If you mean to copy char arrays into other char arrays, there are plenty of helper functions like strncpy() and memcpy().
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
C strings are arrays. Literally just arrays of characters.

That's what I'm talking about. I had a project to turn in on CS50x that wanted me to put the string in an array. They were talking about what you're saying. Which is "okay, but why can't I just put that string within the array as a type: string? (which CS50's library does as a training wheel) C was complaining about it not being an array or whatever and I just threw my hands up in trying to understand why an array of characters wouldn't want to be put within an array to be like [["this is a string"], 4, true...]
 
That's what I'm talking about. I had a project to turn in on CS50x that wanted me to put the string in an array. They were talking about what you're saying. Which is "okay, but why can't I just put that string within the array as a type: string? (which CS50's library does as a training wheel) C was complaining about it not being an array or whatever and I just threw my hands up in trying to understand why an array of characters wouldn't want to be put within an array to be like [["this is a string"], 4, true...]

Your example at the end of your sentence is an array that has:
a single element array which contains a string("this is a string"),
a number(4),
and a boolean(true).

An array with a string, a number, and a boolean would look like ["this is a string", 4, true]

I'll show you an example of reversing a sentence and then pushing it into an array.

Code:
var my_array = []; // Empty Array
var my_sentence = "A Cow Jumped Over The Moon"; // A sentence duh
my_array.push.apply( my_array, [ 
                                                   my_sentence.split(' ') /* Split on space */
                                                                       .reverse() /* Reverse Array */
                                                                       .join( ' ' ) /* Put everything back together putting spaces between each element */,
                                                   4,
                                                   true ] ); /* By using push.apply I can add multiple elements at once very quickly */
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Your example at the end of your sentence is an array that has:
a single element array which contains a string("this is a string"),
a number(4),
and a boolean(true).

An array with a string, a number, and a boolean would look like ["this is a string", 4, true]

Right.

Okay, I just remembered the problem set. What it wanted was you to take a sentence, shift all the letters and then output it through a series of arrays. Basically putting it into a double-array to shift the letters similar to reversing them.

I took it to mean:

[["Do this and then reverse it"]]. Instead from what I found on C it's like [["D","o"," ", "t", "h", "i", "s", " ", "a",... "t"]] which makes no sense to me outside of it being it's own "array of characters" when I figure you should just be able to shift the entire letters in the string without having to "splice it down" like that.
 
Right.

Okay, I just remembered the problem set. What it wanted was you to take a sentence, shift all the letters and then output it through a series of arrays. Basically putting it into a double-array to shift the letters similar to reversing them.

I took it to mean:

[["Do this and then reverse it"]]. Instead from what I found on C it's like [["D","o"," ", "t", "h", "i", "s", " ", "a",... "t"]] which makes no sense to me outside of it being it's own "array of characters" when I figure you should just be able to shift the entire letters in the string without having to "splice it down" like that.

A solution would be something like this...

Code:
int i = 0;
size_t j = 0;
size_t k = 0;
char sentences[6][256]; /* Assumed null terminated */
char bf[256];
...
for( i = 0; i < 6;++i ) 
{
      k = strlen( sentences[i] ) - 1;
      memset( bf, 0, sizeof( bf ) );
      for( j = k; j >= 0; --j ) 
      {
            if( sentences[i][j] == '  ' ) 
            {
                strcat( bf, &sentences[i][j], k - j + 1);
                k = j - 1;
            } 
      } 
     memset( sentences[i], 0, sizeof( sentences[i] ) );
     memcpy( sentences[i], bf, sizeof( sentences[i] ) );
}

that should reverse six sentences of up to 255 characters as the last byte is reserved for null character. There's probably an off by one error somewhere in the code but it should be fairly close to a solution for that domain.

If you want to visualize it it's better too look at is a grid

sentences as grid
Code:
             ---------------------------------------------
             0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|...|255
sentences[0] T|h|i|s| |i|s| |a| | s| e| n| t| e| n| c| e| 1| .|\0|....
sentences[1] T|h|i|s| |i|s| |a| | s| e| n| t| e| n| c| e| 2| .|\0|....
sentences[2] T|h|i|s| |i|s| |a| | s| e| n| t| e| n| c| e| 3| .|\0|....
sentences[3] T|h|i|s| |i|s| |a| | s| e| n| t| e| n| c| e| 4| .|\0|....
sentences[4] T|h|i|s| |i|s| |a| | s| e| n| t| e| n| c| e| 5| .|\0|....
sentences[5] T|h|i|s| |i|s| |a| | s| e| n| t| e| n| c| e| 6| .|\0|....
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Mmmm, I guess I've just been thinking of the solution wrong. I think "okay, it's a sentence. I want you to go through the letters and switch them while keeping the sentence/'string' together." Instead like your example code, I have to make it a double-array to "splice" the characters out and then shift them or reverse them with a loop.

But anyway, I gave up on that problem and am angry at FreeCodeCamp's intermediate starting example because I followed the example code and they made them functions, but in Javascript .pop and .shift aren't "functions" AFAIK to where you can use them in an array to make them "function-like" on removing something from an array. I figured .reverse was similar where you were basically telling the array if you assigned it just a string "reverse all characters in this you don't need to splice it out."
 
I can't come up with a good solution to this, but here's what I want to do.
I have 3 combo boxes with 3 items to choose from. I want to make it so the 3 combo boxes always have unique values.

I can think of a convoluted way to write this, but it doesn't sound practical. If I had 200 items and no duplicates were allowed, how would I write this? Preferably in C#.
 

Koren

Member
I can think of a convoluted way to write this, but it doesn't sound practical. If I had 200 items and no duplicates were allowed, how would I write this? Preferably in C#.

I'm in a hurry, so I won't try C# (my C# is rusty) and I'll let you the optimization, but, assuming I've understood what you meant, in a kind of pseudo-code:

Code:
Foo(n, k, id) {
    int table[n]

    n--

    while k>0 :
        if C(n, k) > id :
            n--
        else :
            id -= C(n, k)
            k --
            table[k] = n

    return table

This function take the number of objects per bundle (k=3), the number of possible objects (n=200) and a number id between 0 and C(200, 3) and return a list of k different objects.

C(n, k) is n! / (k! (n-k)!)

Two different id will give two different bundles (without order). All possible bundles are tied to an id.

For example:

Foo(3, 200, 0) returns [0, 1, 2]
Foo(3, 200, 98765) returns [78, 83, 84]
Foo(3, 200, 1234567) returns [124, 188, 195]
Foo(3, 200, 1313399) returns [197, 198, 199]

Obviously, there's some optimization possible (you don't need to compute C(n, k) at each step, there's relations between C(n, k), C(n-1, k) and C(n, k-1).

This being done, you can quickly turn an id into a table.

After that, you only need to build a list of unique integers between 0 and C(n,k) (excluded) and call Foo to build the corresponding bundles.
 

Ianan

Member
Hey guys, just recently started learning C++ and have no prior experience programming really. The fundamentals and basics of it are coming along nicely to me but I have a question that I really need to know the answer to.

I'm currently just trying to program something every day for the sake of practice, only simple console based programs. I'm currently just writing a small "banking" program, just a simple thing that keeps track of a value and allows deposit, withdraw, check balance etc.

I was deciding how to go about handling the balance int and came to a cross road. I could pass information as arguments to the withdraw and deposit functions but I was getting lost in code with this. Or I could declare balance as a constant global int, that way I can just simply call it in every function that needs it.

Is there a potential downside to this? I really want to learn with good habits so if this is not the best practice, I don't want to do it and would prefer to force myself doing it the preferred way.

Edit: Also, any of you guys active on Steam interested in letting me add you so I can simply direct these newbie questions at you in future? :p
It would be a great help!

Edit 2: I'm a potato? I just realised balance would need to change in value depending on the users input, so const is not suitable?
 
Weird. Well on PHP >5.5 I guess you could do

Code:
function format_date($timestamp) {
    return date('H:i:s', strtotime($timestamp));
}

$prices = array_column($array_indicators, 'value');
$dates = array_map('format_date', array_column($array_indicators, 'datetime'));

I like it! Thanks!!
 
I hope this still fits within the thread, but I'm trying to learn some Big O notation.

The question is: "How many cost units are spent in the entire process of performing 32 consecutive add operations on an empty array which starts out
at capacity 8, assuming that the array will grow by a constant 2 spaces each time a new item is added to an already full dynamic array?"

I've calculated it out, and it is 260 cost units to add those 32 items. Or ~8.125 average for each addition.

Is this still considered O(1)+ runtime?
 

Koren

Member
I hope this still fits within the thread, but I'm trying to learn some Big O notation.

The question is: "How many cost units are spent in the entire process of performing 32 consecutive add operations on an empty array which starts out
at capacity 8, assuming that the array will grow by a constant 2 spaces each time a new item is added to an already full dynamic array?"

I've calculated it out, and it is 260 cost units to add those 32 items. Or ~8.125 average for each addition.

Is this still considered O(1)+ runtime?
Definitively not.

Let's note n the number of items in the array.

When you add 1 item to the array, there's 2 possible cases:
- there's room, add is O(1)
- there's no more room, add is O(n) because you have to copy all elements in a larger array

By expanding the size to a constant p factor (in your example, p=2), the amortized cost (averaged cost) is

( (p-1) * O(1) + 1 * O(n) ) / p, which is O(n) (p being a constant, for large n, (p-1) * O(1) << O(n), so it's O(n/p) which is O(n).


And therefore, adding n elements to an empty array is O(n^2).


If you want to have O(1) amortized insertion, you need to expand your array using a multiplicative factor for the size, not an additive one. Putting n elements in such a table would be O(n).
 

Koren

Member
And therefore, adding n elements to an empty array is O(n^2).
Just because a graph may make the things more obvious:
KJvE1Fp.png


Definitively quadratic...
 
Definitively not.

Let's note n the number of items in the array.

When you add 1 item to the array, there's 2 possible cases:
- there's room, add is O(1)
- there's no more room, add is O(n) because you have to copy all elements in a larger array

By expanding the size to a constant p factor (in your example, p=2), the amortized cost (averaged cost) is

( (p-1) * O(1) + 1 * O(n) ) / p, which is O(n) (p being a constant, for large n, (p-1) * O(1) << O(n), so it's O(n/p) which is O(n).


And therefore, adding n elements to an empty array is O(n^2).


If you want to have O(1) amortized insertion, you need to expand your array using a multiplicative factor for the size, not an additive one. Putting n elements in such a table would be O(n).

Wait, with a multiplicative factor it is O(n), but with an additive O(n^2)?

I'm not getting those calculations. Or I'm missing something.

But adding 32 elements to the additive case leads to 8.125 average cost per insertion. That's a far cry from n^2. Since n is 32.

edit2: And with a multiplicative factor (doubling), it seems to be O(1)+

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

Koren

Member
Wait, with a multiplicative factor it is O(n), but with an additive O(n^2)?
Yes...

If you double the size of the array each time it's full, adding an element will be amortized O(1).

It's the difference between

8+10+12+14+...+n copies and n insertions

and

8+16+32+64+...+n copies and n insertion


The first one is close to n^2 / 4 for large n

The second one close to 2*n

Is that clear enough?
 

MrOogieBoogie

BioShock Infinite is like playing some homeless guy's vivid imagination
Only a beginner in C, but was wondering if there are any sites with fun little challenges or games to test my skills?
 

JeTmAn81

Member
Wait, with a multiplicative factor it is O(n), but with an additive O(n^2)?

I'm not getting those calculations. Or I'm missing something.

But adding 32 elements to the additive case leads to 8.125 average cost per insertion. That's a far cry from n^2. Since n is 32.

edit2: And with a multiplicative factor (doubling), it seems to be O(1)+

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


Big O is for upper bounds, right? So you're supposed to look at the growth factor as your array size gets very big.

I have to admit I'm not quite understanding how it ends up quadratic. After the first eight inserts, it's constant insertion and then linear insertion every other time. That seems like it would make it closer to O(2n) aka O(n) than O(n^2).

edit: Since I'm comparing copying n elements every time vs. n elements every other time, I guess that's really O(n^2/2) which is the same as O(n^2), isn't it
 

Koren

Member
Sorry, explain it like I'm 5 or something because I just said O(n) and you said "yes it is O(1)"
Sorry, it's not always easy on a forum, I prefer explaining it with a whiteboard ^_^

But adding 32 elements to the additive case leads to 8.125 average cost per insertion. That's a far cry from n^2. Since n is 32.
The prefactor doesn't matter.

You can have 100000000 operations to add 5 elements and have 0(1)

And you can have 5 operations to add 5 elements and have O(n³)

It's only asymptotical behavior.


Suppose that you need K operations to perform a task with n data. How many operations do you need to perform the same task with 2n data ?

About the same number of operations -> O(1)
Two times the number of operations -> O(n)
Four times the number of operations -> O(n²)

For example, you said adding 32 elements to an empty array is 260 operations.

For 64 elements, you would need 1044 operations.

32 x 2 = 64 and "260 x 2² = 1044". So it's O(n²)

edit2: And with a multiplicative factor (doubling), it seems to be O(1)+
Depends on what you're talking about...

When the array sized is multiplied by a constant factor (for example, doubled each time):
- Adding 1 element to an array containing n' elements is amortized O(1)
- Adding n elements to an empty array is O(n)
- Adding n elements to an array containing n' elements is O(n)

When the array size is increased by a constant factor (for example, add 2 spaces)
- Adding 1 element to an array containing n' elements is amortized O(n')
- Adding n elements to an empty array is O(n²)
- Adding n elements to an array containing n' elements is O(n.(n+n'))
 
Sorry, it's not always easy on a forum, I prefer explaining it with a whiteboard ^_^


The prefactor doesn't matter.

You can have 100000000 operations to add 5 elements and have 0(1)

And you can have 5 operations to add 5 elements and have O(n³)

It's only asymptotical behavior.


Suppose that you need K operations to perform a task with n data. How many operations do you need to perform the same task with 2n data ?

About the same number of operations -> O(1)
Two times the number of operations -> O(n)
Four times the number of operations -> O(n²)

For example, you said adding 32 elements to an empty array is 260 operations.

For 64 elements, you would need 1044 operations.

32 x 2 = 64 and "260 x 2² = 1044". So it's O(n²)


Depends on what you're talking about...

When the array sized is multiplied by a constant factor (for example, doubled each time):
- Adding 1 element to an array containing n' elements is amortized O(1)
- Adding n elements to an empty array is O(n)
- Adding n elements to an array containing n' elements is O(n)

When the array size is increased by a constant factor (for example, add 2 spaces)
- Adding 1 element to an array containing n' elements is amortized O(n')
- Adding n elements to an empty array is O(n²)
- Adding n elements to an array containing n' elements is O(n.(n+n'))


Also sorry for the confusion but I am talking average runtime.

Thanks for the explanation. So while the average unit cost for 32 elements is 8.135 or whatever, the average cost of 64 units is 16.3.

I guess my question is why is the amortized still considered O(n) for that? I do get why adding n elements is O(n^2) though.
 

Koren

Member
So while the average unit cost for 32 elements is 8.135 or whatever, the average cost of 64 units is 16.3.

I guess my question is why is the amortized still considered O(n) for that?
Because the average cost here is roughly 0.26*n

The factor before n doesn't matter, it can be 0.001 or 1000000.0...

The fact is the cost increase linearly with the number of elements.
 
Because the average cost here is roughly 0.26*n

The factor before n doesn't matter, it can be 0.001 or 1000000.0...

The fact is the cost increase linearly with the number of elements.

In this case, why do we say that average cost is O(1)+ in the doubling scenario?

Couldn't I find some factor *n that would get me the average cost of each insertion?

Actually it would be 0.055 * n approximately unless I'm mistaken.
 

Koren

Member
In this case, why do we say that average cost is O(1)+ in the doubling scenario?

Couldn't I find some factor *n that would get me the average cost of each insertion?

Actually it would be 0.055 * n approximately unless I'm mistaken.
For 32 insertions, if you start empty with 8 cases, you need 56 operations, 1.7 average

For 64, you need 120, 2. average

For 128, you need 248, 2. average

It's constant, it doesn't depends on n...
 

Koren

Member
Got it. Thank you for explaining this all to me.
No problem... It's often difficult to grasp the concept at first (especially since it's not the easiest example), but it's easier once you've used it a coupled times.

It doens't always tell the complete story, though, sometimes...

Inverting a matrix with Gauss-Jordan or LU algorithms is O(n³). There's O(n^2.373) algorithms, but in practice, the prefactor is so large that O(n³) will be quicker unless n is really, really, really big (read: computers are usually not powerful enough to invert a matrix large enough so the "better" algorithm is quicker)
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
array = string.split('').reverse();

Alright, I did my solution with two arrays and had these be separate. But your method would be something like

Code:
function(arg) {
array = [];
array = arg.split("").reverse().join("");
}

function("This is a string");

to be valid, yeah? Or does join not go in with that because of something messing with it?
 

Chris R

Member
Alright, I did my solution with two arrays and had these be separate. But your method would be something like

Code:
function(arg) {
array = [];
array = arg.split("").reverse().join("");
}

function("This is a string");

to be valid, yeah? Or does join not go in with that because of something messing with it?

Join will work. Give your function a name though, something like this

Code:
function reverseString(strIn) {
	return strIn.split('').reverse().join('');
}
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Ah, okay. Well like I said, I went with a two array assign process which showed each step individually.

Anyway, I'm onto Factorializing numbers. Don't give me the solution, but I'm thinking it's gonna involve:

-an if-else (if n > 0) { //factor code here } else { //answer is 1 due to 0 = 1 in factors }
-A do-while or for loop (to interate and put the numbers into an array by counting up to n and then multiplying each number 1 * 2 * 3 * 4... up to n
-Return the calculation of n at the end by assigning it a new variable(?). Otherwise return n if the product of the equation/factors is assigned to n.

Am I on the right track in that thought process?
 
Ok why is this throwing an error. It's going to be something dumb.

Code:
System.out.printf("%2s %12s %17s %13s %13s %7s %10s\n", " #" + " Description" + "        Area(sqf)" + "        $/sqf" + "    Frac.Agro" + " #Trees " + "Taxes     ");

I'm getting a Missing Format Argument Exception: Format specifier %12s

It's printing the line, but then throwing the error after the fact.
 

luoapp

Member
Code:
" #" + " Description" + "        Area(sqf)" + "        $/sqf" + "    Frac.Agro" + " #Trees " + "Taxes     "

that is one single string, should use , instead of +
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Explain the .reduce method in Javascript to me?

Code:
var array = [];
for (var i = 1; i <= arg; i++) {
    array.push(i);
}

Will return [1, 2, 3, 4, 5, 6,...] until it hits the argument of function this is in.

If I want to do mathmatical calculations with ALL the pushed elements of the array (1 + 2 + 3 + 4 + 5), reduce apparently will do that? But for the like me I can't seem to figure out the function for it.

"array.reduce(arg * i);" isn't a function?
 

Somnid

Member
Explain the .reduce method in Javascript to me?

Code:
var array = [];
for (var i = 1; i <= arg; i++) {
    array.push(i);
}

Will return [1, 2, 3, 4, 5, 6,...] until it hits the argument of function this is in.

If I want to do mathmatical calculations with ALL the pushed elements of the array (1 + 2 + 3 + 4 + 5), reduce apparently will do that? But for the like me I can't seem to figure out the function for it.

"array.reduce(arg * i);" isn't a function?

Code:
    [1,2,3].reduce((sum, x) => s + x, 0) //6

The function takes the previous (running) value (sum) and the element of the array (x). The second parameter of reduce is the starting value.
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
Code:
    [1,2,3].reduce((sum, x) => s + x, 0) //6

The function takes the previous (running) value (sum) and the element of the array (x). The second parameter of reduce is the starting value.

So wait, you can't use reduce on something that is going to be an argument to put itself and the previous values into the array?

It'd have to be something like "[1, 2, 3]" instead of "array" or am I misreading and you're just putting the values there instead of the variable/array?

Also reduce is just for addition? I thought you were able to multiply with it?
 

Somnid

Member
So wait, you can't use reduce on something that is going to be an argument to put itself and the previous values into the array?

It'd have to be something like "[1, 2, 3]" instead of "array" or am I misreading and you're just putting the values there instead of the variable/array?

Also reduce is just for addition? I thought you were able to multiply with it?

I'm writing short hand code. Maybe this make more sense?

Code:
var array = [1,2,3];
var result = array.reduce(function(sum, x){
    return sum + x;
}, 0)
//result = 6

You can do lots of other things.

Code:
var array = [1,2,3];
var result = array.reduce(function(product, x){
    return product * x;
}, 1)
//result = 6

This would be 1*2*3
 

TheSeks

Blinded by the luminous glory that is David Bowie's physical manifestation.
That second bit is what I'm looking for. But I'm apparently not getting it. Using "array, arg" for the function arguments and then "return array * arg" returns blank/nothing.

I mean looking at your example code, I can get what it's trying to do. But I'm not sure what/where "product" is coming in and how to translate that into my own array. Edit: Oh, duh. Product is an argument. But I'm not sure where it's taking from. If it's taking 1 * 2 then why is 1 for the secondary/outside the function argument needed? To be 1 * 1 before 1 * 2?
 

Somnid

Member
That second bit is what I'm looking for. But I'm apparently not getting it. Using "array, arg" for the function arguments and then "return array * arg" returns blank/nothing.

I mean looking at your example code, I can get what it's trying to do. But I'm not sure what/where "product" is coming in and how to translate that into my own array.

"reduce" is a method off an array, so you'd have all your values in an array and call reduce on it. The array is not an argument. The first argument of the reduce function is the previous value.

So you call array.reduce([function], [initialValue]);
1) the reduce function will get (initialValue, array[0]) passed into it.
2) the reduce function will get (result from 1, array[1]) passed into it.
3) the reduce function will get (result from 2, array[2]) passed into it.
...
N) the reduce function will get (result from n-1, array[n-1] passed into it
 
Top Bottom