Jump to content
  • Announcements

    • boen_robot

      Guidelines and Netiquette   03/28/2017

      Posting Problems:   Having problems posting your topic? Read through this: To join, you agree to our terms and conditions and fill out and submit a registration form. An activation email will be sent to your email adress, so you'll need to verify your account. After that the account has to be validated by one of the moderators. This will mean that it can take up to a day to be activated. A couple of things to remember to ensure approval: Don't use an email address in one of those $2 four character .com domains eg. xyds.com. These will be deleted and the domain added to the banned list. Don't use an email address that is within a domain with a bad reputation for spam. A Google search is run on every email address and email domain. Don't sign up with an email address that doesn't exist, doesn't work or requires the sender to answer a quiz before their email can get to you. Put your country and or state and city in the signup form. Blank forms will go to the botton of the "to do" list. And make sure that your email address and your country match, saying you're from Alabama and using a .ru email address is not going to get you activated. After a membership is activated the first few posts will be monitored. Posting spam or unapproved topics described in the agreement results in an immediate ban. The email provider and the IP addresses associated with the account will be banned and all posts will be deleted. These strict measures have been deemed necessary to hinder spam. Sorry for any inconvenience this causes, but it's not liable to change. If, after reading this, you still can't post and don't understand why, contact one of the Moderators listed here.   Topic Guidelines   Including the following information can expedite an accurate response from board members: Must be a Specific Problem or Question related to web design and development Include Code in Question (wrap with   for small blocks of code and for longer blocks   ) Include Code Author Include Extra Notes/Modifications/Attempts Include web link to page/file when possible Content Guidelines   You may not post, upload, link to, or email any Content that contains, promotes, gives instruction about, or provides prohibited Content. Prohibited Content includes any Content that breaks any local, state, county, national or international law. Prohibited Content also includes: No direct or indirect advertising or websites, forums, products, services No hijacking of posts (do not post your question in someone elses) Content that infringes upon any rights [ex. MP3s and ROMs] (including, but not limited to, copyrights and trademarks) Abusive, threatening, defamatory, racist, or obscene Viruses or any other harmful computer software False Information or libel Spam, chain letters, or Pyramid schemes Gambling or Illicit drugs Terrorism Hacking or cheating for internet/online games Warez, Roms, CD-Keys, Cracks, Passwords, or Serial Numbers Pornography, nudity, or sexual material of any kind Excessive profanity Invasive of privacy or impersonation of any person/entity Hacking materials or information Posting Tips   There are more BBcodes than there are buttons for on the reply menu. To get the full list, click "BB Code Help" underneath the clickable smilie face menu. Use   for small snippets of code Use   for lengthy snippets of code Use   if your snippet is HTML (optional) Use   if your snippet is SQL (optional) Rules of Conduct   Be nice. There's no need for calling someone stupid if they ask an 'easy' question. Keep your avatars and signatures absolutely child friendly. We have a younger audience on this forum. Keep your language appropriate for the same reason above. Do not PM moderators for help on the forum. Post on the topic, or create a new one.   Spam:   Recently, as you have all without doubt noticed, we have had lots of spam and advertisement on the forum. Therefore, we'd like to alert you as to what to do when you have found any of the aforementioned annoying messages: it. Immediately. Give a clear reason, please, if the advertising is not evident. DO NOT POST! Report, let the post stay as is, and we will get to it, meanwhile if you continue to post as normal in the other threads, it won't be on the top so long. Refrain from PMing the member. This won't help at all, as they are most likely spambots anyway. Thank you.       Images in signatures:   After thinking of users on dial-up, we have decided to enforce the following rules regarding signatures. Please pay heed to them. Respecting these rules is respecting the members on this forum with dial-up. Signature rules: No animated images AT ALL. No matter the amount of animation. Maximum image widthxheight: 300x150 Maximum image (file) size: 15kb Use calm colors. Do not use highly contrasting images in your signature, as this can get really annoying when seeing several posts from one member in the same thread. The same prohibited content goes for images as for posts. Lastly, use common sense. No lengthy signatures please. Save us some scrolling. Thank you.       Links in signatures:   Please understand that w3schools.com only exists because of voluntary work and is barely supported by the advertising littered throughout the tutorials and the forum. So, please, stop advertising other sites. DO not post links that drive traffic away from the w3schools domain - especially to a site that offers similar if not identical information. Please help support the site by keeping individuals on it. Thank you. Here are some guidelines as to what you can put in your signature: w3schools links --> allowed w3.org links --> allowed browser links --> allowed html editor links --> allowed personal sites --> allowed tutorial sites competing with w3schools --> NOT allowed sites completely irrelevant to webprogramming and this forum --> NOT allowed   Thanks for understanding, and for taking the time to read this. ~W3Schools Modstaff~
hisoka

something I cannot understand in javascript code

Recommended Posts

function sum(input){ if (toString.call(input) !== "[object Array]") return false; var total = 0; for(var i=0;i<input.length;i++) { if(isNaN(input[i])){ continue; } total += Number(input[i]); } return total; } console.log(sum([1,2,3])); console.log(sum([100,-200,3])); console.log(sum([1,2,'a',3]));

In this code I do not understand what is

 total += Number(input[i]);

Number ????

Share this post


Link to post
Share on other sites

you said Number convert the string into numbers so why here in this code I got NAN
 

 function sum()
{
var total = 0;
var letters = ["A" , "B"];
for(x = 0 ; x < letters.length ; x++)
    {
     total += Number(letters[x]);
    }
    document.write(total);
}


var x = sum();

if you run it in the browser you will get NOT A NUMBER OR NAN

Share this post


Link to post
Share on other sites

Because the string "A" cannot be converted to a number.

  • Like 1

Share this post


Link to post
Share on other sites

ok I understand

Quote

It converts the string into a number so that math operations can be done with it

the items inside the array are numbers so why we need to convert them into numbers ???

and therefore why do not we simply write :

 total += input[i];

?

 

 

 

Share this post


Link to post
Share on other sites

IF the values in the array are taken from text type input, the numbers in array will be a string/text, it is precautionary to make sure when used in math operations that 16 + "4" don't equal "164", but 20.

  • Like 1

Share this post


Link to post
Share on other sites
var a = ["123", 123, "1a2b3c", 122.222, "A"];

for(var i=0 ; i<a.length ; i++){
   if(isNaN(a[i])){
     alert('a['+i+'] is not a number (nan)');
   }
}

 

  • Like 1

Share this post


Link to post
Share on other sites

There are things I cannot understand in this code :

function subset(arra, arra_size) { var result_set = [], result; for(var x = 0; x < Math.pow(2, arra.length); x++) { result = []; i = arra.length - 1; do { if( (x & (1 << i)) !== 0) { result.push(arra[i]); } } while(i--); if( result.length >= arra_size) { result_set.push(result); } } return result_set; } console.log(subset([1, 2, 3], 2));

 The Math.pow() function returns the base to the exponent power, that is, baseexponent.

But I do not understand why it is used in the code above ? what is the purpose of it ? and why it is used in combination with

arr.length

what does this mean :

i = arra.length - 1; 

why bitwise and shift operators are used here in this code ? for what purpose ?

(x & (1 << i)) !== 0)

what is the purpose of making an empty array ?

result = [];

 

Share this post


Link to post
Share on other sites

Format that code so it's readable, and add some console.log statements to have it print out what it's doing.

function subset(arra, arra_size) 
{ 
  var result_set = [], result; 
  for(var x = 0; x < Math.pow(2, arra.length); x++) { 
    console.log('x is ' + x);
    result = []; 
    i = arra.length - 1; 
    console.log('i is ' + i);
    do { 
      console.log('(1 << i) is ' + (1 << i));
      console.log('x & (1 << i) is ' + (x & (1 << i)));
      if( (x & (1 << i)) !== 0) { 
        result.push(arra[i]); 
      } 
    } while(i--); 
    console.log('result:');
    console.log(result);
    if( result.length >= arra_size) { 
      result_set.push(result); 
    } 
  } 
  return result_set; 
} 

Do you understand the purpose of that code, do you understand why it returns what it does for the input?

Share this post


Link to post
Share on other sites

Syntactic , this what I could understand so far
f

unction subset(arra, arra_size) {
    var result_set = [],
        result;


    for (var x = 0; x < Math.pow(2, arra.length); x++) {
        result = [];
        i = arra.length - 1;
        do {
            if ((x & (1 << i)) !== 0) {
                result.push(arra[i]);
            }
        } while (i--);

        if (result.length >= arra_size) {
            result_set.push(result);
        }
    }

    return result_set;
}

console.log(subset([1, 2, 3], 2));

the for loop , loops

 Math.pow(2, arra.length)

time . For example here it loops 2 exponent 3 time that is 8 times

 

 i = arra.length - 1; 

is , of course ,  array length -1

if( (x & (1 << i)) !== 0)

each time it loops it looks if

x & (1 << i)) !== 0

put the result in the empty array result []

result.push(arra[i])
while(i--);

is a reverse loop . It reverse the numbers .

 if( result.length >= arra_size)

put a condition so that while does not loop infinitely

 

 result_set.push(result);

push the sub arrays in the array

 result_set

I cannot understand  the code semantically :

1) math.pow is an exponent mathematical function . What has it to do with array length and for loop in the code above . What is the logical beyond using it ?

2) what is the logic beyond  using bitwise operators in the if condition ?

if( (x & (1 << i)) !== 0)
3)
 i = arra.length - 1; 

  what is the logic beyond substracting the  array length from 1 ?

4) in the function parameters I understand why the arra is used but why  arra-size is used ?

 

Quote

 

Do you understand the purpose of that code, do you understand why it returns what it does for the input?


 

here is the purpose of it :

http://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php

no I do not understand why it returns what it does for the input because i as I mentioned above i do not get what the code line by line , semantically , does ?

 

 

Share this post


Link to post
Share on other sites

Like that page says, it returns all subsets longer or equal to a certain length.  Do you understand what a subset is?

Share this post


Link to post
Share on other sites

Well, if you know what a subset is, and you know that this function finds subsets, then you should be able to figure out the answers to some of those questions.

math.pow is an exponent mathematical function . What has it to do with array length and for loop in the code above . What is the logical beyond using it ?

It's the number of possible subsets.

what is the logic beyond  using bitwise operators in the if condition ?

That's how it determines which elements to pull from the source array for each subset.  If you run the version I posted with all of the output it makes it more obvious.

what is the logic beyond substracting the  array length from 1 ?

That's backwards, it subtracts 1 from the array length, and that is the index of the last element in the array.

in the function parameters I understand why the arra is used but why  arra-size is used ?

It's the minimum size for the returned subsets.  Passing 2 means they aren't interested in the subsets with a length of 0 or 1.

Share this post


Link to post
Share on other sites
Quote

 If you run the version I posted with all of the output it makes it more obvious.

with all due respect , after running the version you posted to me , things become more obscure :

Here is the whole code :
 

function subset(arra, arra_size) {
    var result_set = [],
        result;
    for (var x = 0; x < Math.pow(2, arra.length); x++) {
        console.log('x is ' + x);
        result = [];
        i = arra.length - 1;
        console.log('i is ' + i);
        do {
            console.log('(1 << i) is ' + (1 << i));
            console.log('x & (1 << i) is ' + (x & (1 << i)));
            if ((x & (1 << i)) !== 0) {
                result.push(arra[i]);
            }
        } while (i--);
        console.log('result:');
        console.log(result);
        if (result.length >= arra_size) {
            result_set.push(result);
        }
    }
    return result_set;
}

var matrix = subset([2, 5, 6], 2);

I run it line by line :

console.log('x is ' + x);

gives

x is 0x is 1x is 2x is 3x is 4x is 5x is 6x is 7

console.log('i is ' + i);

gives

i is 2i is 2i is 2i is 2i is 2i is 2i is 2i is 2

console.log('(1 << i) is ' + (1 << i));
            console.log('x & (1 << i) is ' + (x & (1 << i)));

give

(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1(1 << i) is 4(1 << i) is 2(1 << i) is 1

x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 1x & (1 << i) is 0x & (1 << i) is 2x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 2x & (1 << i) is 1x & (1 << i) is 4x & (1 << i) is 0x & (1 << i) is 0x & (1 << i) is 4x & (1 << i) is 0x & (1 << i) is 1x & (1 << i) is 4x & (1 << i) is 2x & (1 << i) is 0x & (1 << i) is 4x & (1 << i) is 2x & (1 << i) is 1
 

 console.log('result:');
        console.log(result);

give

result:result:result:result:result:result:result:result:

255,266,26,56,5,2

except the last result all the results of console log  the version you gave me  are obscure and made me more confused 

Moreover I still do not understand how math.pow gives the number of all possible subset ?!!!

I read the tutorials about javascript in w3school site which were very useful and helped me a lot but even so I could not get a clear understanding about the code above . Justsomeguy could you please tell me what should I do in order to be able to understand very well the code above ?

 

Share this post


Link to post
Share on other sites

Hold on, are you running different versions of that code with only 1 of the console.log statements?  If so, I think you're missing the point of having all of those console.log statements.  Also, the console.log statement where it prints i should probably go inside that do loop, the point is so that you can use that to see what the calculations are doing.

Moreover I still do not understand how math.pow gives the number of all possible subset ?!!!

If you have a set with 3 items in it, how many possible subsets can you create?  The answer is 8 - 23.  If the set has 4 items in it, then there are 16 possible subets - 24. You use Math.pow to get that value from the length of the set.  If you don't understand that then work it out on paper.

  • Thanks 1

Share this post


Link to post
Share on other sites
Quote

Hold on, are you running different versions of that code with only 1 of the console.log statements?

 

that what I , unfortunately , did . However , I run it again with all the console.log statements inside it and , now the logic of the code becomes far more clear to me than before . Moreover , now I understand very well the logic beyond using the Math.pow function . However even with this :

 

 

I still cannot grasp very well  the use of bitwise operators in the code

Quote

That's how it determines which elements to pull from the source array for each subset

and this :

 

(1 << i) is 1
x & (1 << i) is 0
result:
Array [ 2 ]
x is 3
i is 2
(1 << i) is 4
x & (1 << i) is 0
(1 << i) is 2
x & (1 << i) is 2
(1 << i) is 1
x & (1 << i) is 1
result:
Array [ 2, 1 ]
x is 4
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 0
(1 << i) is 1
x & (1 << i) is 0
result:
Array [ 3 ]
x is 5
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 0
(1 << i) is 1
x & (1 << i) is 1
result:
Array [ 3, 1 ]
x is 6
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 2
(1 << i) is 1
x & (1 << i) is 0
result:
Array [ 3, 2 ]
x is 7
i is 2
(1 << i) is 4
x & (1 << i) is 4
(1 << i) is 2
x & (1 << i) is 2
(1 << i) is 1
x & (1 << i) is 1
result:
Array [ 3, 2, 1 ]

I am still unable to understand how and why  the bitwise operators are used to determine which element is pulled from the set and pushed in the subset ??

Could you please make it more clear to me

 

Share this post


Link to post
Share on other sites

That's how it figures out which elements to pull for each subset, so that it creates every subset.  For an array with 3 elements, you can think of each subset as containing the numbers in the positions that are set to 1 if you map out 0 to 8 in binary:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0 
1 0 1
1 1 0
1 1 1

Those are the 8 possible subsets.  Bit-shifting the 1 to the left will have it start with 0 0 1, 0 1 0, or 1 0 0, and then ANDing that value with the other counter will provide that list of sets.  When you're looking at the debug output for those operations it helps to convert the numbers to binary values, because that's what it's doing.

Share this post


Link to post
Share on other sites

now the things become more clear : the shift operator is used to change the position of the numbers in the set and the and operator is used to concatenate them together so that they form all possible subset . What I understood ,  too , is that the number of subsets in a set of x elements is 2 exponent x . The code above is taken from this page :

http://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php

In the end of the code , there is this instruction :

console.log(subset([1, 2, 3], 2));

and the expected output from it is  , as mentioned ,

 

Expected output : [[2, 1], [3, 1], [3, 2], [3, 2, 1]] 

which are 4 subsets

however if we take a look at the array in the instruction above , we will see that it contains 3 elements . So 2 exponent 3 is 8 . So normally we need to have 8 subsets and not 4 subsets . So why we got 4 subsets ?

Edited by hisoka

Share this post


Link to post
Share on other sites

Normally , the second parameter passed to the function is 3 not 2 because the size of [1,2,3] is 3 not 2  . I know it is 3 through this :

var array = [1, 2, 3] ; var x = array.length ; console.log(x) ;

the output is 3 not 2 and 2 exponent 3 is 8 not 4

 

 

Share this post


Link to post
Share on other sites

You do realise that the indexing of array starts from 0 not 1, so if you use array length (3) for last item in array (which will be index 2), it will come up as undefined, unless you use array.length -1 for the last record.

Share this post


Link to post
Share on other sites

The second parameter indicates the size of the subsets to search for, not the size of the initial set.

The expected output is wrong. The people who provided the exercise mentioned it here: http://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php#comment-3039932910

The output should only have subsets with two elements.

  • Thanks 1

Share this post


Link to post
Share on other sites
Quote

The second parameter indicates the size of the subsets to search for, not the size of the initial set.

That is it thank you . Sorry , I did not read the comments . Next time I will read the comments too and look al all possible corners of the page :)

Quote

You do realise that the indexing of array starts from 0 not 1, so if you use array length (3) for last item in array (which will be index 2), it will come up as undefined, unless you use array.length -1 for the last record.

Yes I realise . However if the computer begins to calculate from 0 not from 1 like humans so why the output  here :

var array = [1, 2, 3] ; var x = array.length ; console.log(x) ;

is 3 and not 2 ?

 

Share this post


Link to post
Share on other sites

The length is 3.  The indexes go from 0 to 2.  That is 3 elements, which is why the length is 3.  0, 1, 2 -> that's 3 elements.

  • Thanks 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×