Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts

    Need array creation and popping from the middle advice

    I want to create an array of 1 - X
    (X could be 10, 20, 30 or any number)

    Then I want to randomly choose a number from 1 - X

    I now want to remove the random choice - and then do the same again twice

    Question 1: How do I create the array in the first place?

    Answer: var x=[0,1,2,3,4,5,6,7,8,9,10];

    I'd much prefer it if I could do something like this:

    var x=[0...10];

    This would create the same, except, I don't have to type out all the numbers! And if I needed to increase the number in the array, I could simply just change the last number

    I've just made the syntax up
    I was hoping something similar shorthand existed
    Or do I have to do this by creating a loop?

    Question 2: how do I pop an item from the middle or somewhere other than the beginning or end?

    I've googled and all I can find is how to remove the first and last items!

    The way I see it:

    - Get a solution for popping from the middle of an array
    I'm sure I'll find a solution to this if I looked - but is it optimal to be doing it this way?

    - Instead, maybe I could fill my array in a random order in the first place - and then just pop at the beginning or end??

    Which is the best solution?

    Any code to start me off would be great

    Thanks


    OM

  • #2
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts
    thanks for that - that's really helpful

    i have coded the following (before getting your reply about how best to fill up the array):

    var numberoffiles = [1,2,3,4,5,6,7,8,9,10];

    var random_page_index = Math.ceil(Math.random()*numberoffiles.length) - 1;

    var random_page_selector = "random_html_code/random_" + numberoffiles[random_page_index] + ".html";

    numberoffiles.splice(random_page_index, 1); // only removing one index, thus the 1

    $("#random_load1").load
    (
    random_page_selector, function()
    {
    $("#random_load1").trigger("create");
    }
    );

    random_page_index = Math.ceil(Math.random()*numberoffiles.length) - 1;

    random_page_selector = "random_html_code/random_" + numberoffiles[random_page_index] + ".html";

    numberoffiles.splice(random_page_index, 1); // only removing one index, thus the 1

    $("#random_load2").load
    (
    random_page_selector, function()
    {
    $("#random_load2").trigger("create");
    }
    );

    random_page_index = Math.ceil(Math.random()*numberoffiles.length) - 1;

    random_page_selector = "random_html_code/random_" + numberoffiles[random_page_index] + ".html";

    numberoffiles.splice(random_page_index, 1); // only removing one index, thus the 1

    $("#random_load3").load
    (
    random_page_selector, function()
    {
    $("#random_load3").trigger("create");
    }
    );

    The above code is for use with jquerymobile

    I'm unsure how I can optimise the above
    I'm unsure how to use any number for the following code:

    $("#random_loadX").load
    (
    random_page_selector, function()
    {
    $("#random_loadX").trigger("create");
    }
    );

    (X being the select number)

    Thanks in advance!


    OM

  • #3
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts
    figured it out (i just thought it would be more complex!):


    for(i = 1; i < 4; i++)
    {
    random_page_index = Math.ceil(Math.random()*numberoffiles.length) - 1;

    random_page_selector = "random_html_code/random_" + numberoffiles[random_page_index] + ".html";

    numberoffiles.splice(random_page_index, 1); // only removing one index, thus the 1

    var divname = "#random_load" + i;

    $(divname).load
    (
    random_page_selector, function()
    {
    $(divname).trigger("create");
    }
    );
    }

    thanks for the help

  • #4
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,441
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    This is the *WRONG* formula for getting a random number!
    Code:
    random_page_index = Math.ceil(Math.random()*numberoffiles.length) - 1;
    Math.random() *CAN* return a ZERO value. (It's unlikely, but it CAN happen.)

    So when and if that happens your formula would end up assigning -1 to random_page_index.

    THERE IS ONE AND ONLY ONE correct way to get a random integer.

    The general forumula for a random integer between (and inclusive of) LOW and HIGH is:
    Code:
         LOW + ( Math.floor( Math.random( ) * ( HIGH - LOW + 1 ) )
    Expressed as a function:
    Code:
    function randomInt( low, high )
    {
         return low + ( Math.floor( Math.random( ) * ( high - low + 1 ) );
    }
    In the simple case where LOW is zero, and you want number from 0 to HIGH, the form becomes
    Code:
        Math.floor( Math.random( ) * ( HIGH + 1 ) )
    NOTE CAREFULLY that when you are trying to get an element of an array, then the value of arrayName.length is *ALREADY* HIGH+1 (because the length is indeed one more than the highest array element number).

    And so:
    Code:
        Math.floor( Math.random() * arrayName.length )
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    OM2 (05-19-2012)

  • #5
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts
    @Old Pedant: thank u

    the problem u refer to actually did happen!
    i ended up doing what u suggested already - but i didn't actually know necessarily that it was the correct answer

    good to learn from the masters

  • #6
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,985
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    Quote Originally Posted by Old Pedant View Post
    THERE IS ONE AND ONLY ONE correct way to get a random integer.

    The general forumula for a random integer between (and inclusive of) LOW and HIGH is:
    Code:
         LOW + ( Math.floor( Math.random( ) * ( HIGH - LOW + 1 ) ) )
    Expressed as a function:
    Code:
    function randomInt( low, high )
    {
         return low + ( Math.floor( Math.random( ) * ( high - low + 1 ) ) );
    }
    Missing brackets!
    Last edited by Philip M; 05-19-2012 at 07:30 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,441
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Thanks. Sloppy of me. I usually count the left and right parens to be safe. Teach me to not do it one time.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,441
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    I do use an IDE. Visual Studio, most of the time (because so much of my work is in ASP or ASP.NET). And, yes, it highlights such errors. It also highlights HTML and CSS errors. And even tells me when I reference an image URL that it can't find. And much more. (Example: when writing JavaScript, it knows about all my global variables and functions and gives me "Intellisense": If I start typing the name of a function, it shows me the matching choices, so I can just click on one and use it. Or if I use a JS standard method, say String.split(), it reminds me that the method takes only one argument of type regexp. I have no idea if other IDE's do as much, because I really need VisualStudio for the ASP.NET support and the JS and HTML and CSS support is just gravy.)

    But I don't bother using it for typing in snippets that I post here. 85% of the code I type here is code I have just rattled off into the stupid little <textarea> of the forum. 10% of the code I have typed into Notepad (yes, Notepad, not Notepad+) and have then actually tested on my machine. 5% or less of the code I have bothered to use Visual Studio for. And usually that's when I'm just modifying code I already have sitting around.

    SHOULD I be more careful, and always use the IDE and always test my code? Maybe. But quite frankly I don't have time. Now and then I actually have to work for a living.
    Last edited by Old Pedant; 05-20-2012 at 04:32 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,441
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Just to pick an example of what VS does.

    Say I have typed in
    Code:
    var f = "asfasdf";
    var a = f.
    at the point where I type that period, VS prompts me with a choice of methods and properties:
    Code:
    anchor
    big
    blink
    bold
    charAt
    charCodeAt
    constructor
    fixed
    fontcolor
    fontsize
    ... and more to a total of 38 choices ...
    Some of those may be IE only and/or obsolescent, but all the relevant methods of String are shown.

    If I type "subs" then it narrows the list to substr and substring. If I choose substr( then it prompts me with start,len whereas if choose substring( it prompts with start,end. And so on.

    Does Netbeans do that? For JavaScript?
    Last edited by Old Pedant; 05-20-2012 at 04:42 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #10
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,985
    Thanks
    203
    Thanked 2,536 Times in 2,514 Posts
    I have to confess that I use just Notetab. But I always test any code before I post it here not only to be sure that it does what it is supposed to but to iron out any typos, missing brackets etc. For some reason I often manage to spell document docuemnt.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #11
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts
    guys, thanks for all the replies

    i had a mistake in my code
    thanks to another thread, i managed to correct

    in my code, the first element was null - which i definitely did not want!
    + i was using numberoffiles.length - which mean that i had one more than i needed

    the code i have now is (comments and old code commented out still left in):

    Code:
    // 'direction' below should be the id of one of the elements
    $("#frontpage").live
    (
    	"pagebeforeshow", 
    	function()
    	{
    		// Our files are called random_1.html, random_2.html, random_3.html etc
    		var totalNumberOfFiles = 10;
    		// var numberoffiles = [];
    		var numberoffiles = new Array();
    		for (i = 1; i <= totalNumberOfFiles; i++) 
    		{
    			// numberoffiles[i] = i;
    			numberoffiles.push(i);
    		}
    		
    		// console.log(numberoffiles);
    
    		var random_page_index;
    		var random_page_selector;
    		
    		for(i = 1; i < 4; i++)
    		{
    			random_page_index = Math.ceil(Math.random()* (numberoffiles.length-1)) ;
    			
    			random_page_selector = "random_html_code/random_" + numberoffiles[random_page_index] + ".html";
    			
    			numberoffiles.splice(random_page_index, 1); // only removing one index, thus the 1
    		
    			var divname = "#random_load" + i;
    		
    			$(divname).load
    			(
    				random_page_selector, function()
    				{
    					$(divname).trigger("create");
    				}
    			);
    		}
    		
    	}
    );
    have i missed anything? looks ok to me i think

    thanks

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,441
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    I told you your random number generator is wrong. You even agreed with me. But there it is back in all its invalid gory [sic].
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    I told you your random number generator is wrong. You even agreed with me. But there it is back in all its invalid gory [sic].
    hmmm... it's 8am and i've been up all night coding - so i'm not thinking straight

    i tested and all seems to be ok

    if numberoffiles has 10 items in it, then the following will give me a random number between 0 and 9:

    random_page_index = Math.ceil(Math.random()* (numberoffiles.length-1)) ;

    that's exactly what i want

    i am NOT an expert in javascript: but, i would instinctively would have thought that Math.random() is the more optimal way since it's an in built function as opposed to a simple function that is 2 or 3 lines that u have to put together?

    let me know what u think

    ALSO: what IS Math.random() useful for?

    thanks

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,441
    Thanks
    76
    Thanked 4,372 Times in 4,337 Posts
    Go look for my prior post. Post #6 in this same thread. About the right way to use Math.random(). Where you agreed with me.

    Using Math.ceil() is the mistake. Math.random() is fine, but then you need to change the rest of the code.

    You don't have to be a JavaScript expert. You just have to use the answers you are given.
    Last edited by Old Pedant; 05-22-2012 at 03:20 AM.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    OM2
    OM2 is offline
    New Coder
    Join Date
    Apr 2012
    Posts
    59
    Thanks
    7
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by Old Pedant View Post
    Go look for my prior post. Post #6 in this same thread. About the right way to use Math.random(). Where you agreed with me.

    Using Math.ceil() is the mistake. Math.random() is fine, but then you need to change the rest of the code.

    You don't have to be a JavaScript expert. You just have to use the answers you are given.
    @old pedant: i've been through the past posts and feel like a giant idiot now
    the answers where there in front of me

    i am still unclear though
    i now have changed code to:

    random_page_index = Math.floor( Math.random() * numberoffiles.length );

    let's say my array is [1,2,3,4,5,6,7,8,9,10]

    i want random_page_index to be any one of 0,1,,3,4,5,6,7,8,9

    i just want to be 100% sure that it won't return 10 - since there will be nothing at myArray[10]

    i've read up about Math.floor and Math.random() - just wan to be sure i'm ok - which i think i am!


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •