View Full Version : 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

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

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

Old Pedant

05-19-2012, 02:33 AM

This is the *WRONG* formula for getting a random number!

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:

LOW + ( Math.floor( Math.random( ) * ( HIGH - LOW + 1 ) )

Expressed as a function:

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

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:

Math.floor( Math.random() * arrayName.length )

@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 :)

Philip M

05-19-2012, 07:28 AM

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:

LOW + ( Math.floor( Math.random( ) * ( HIGH - LOW + 1 ) ) )

Expressed as a function:

function randomInt( low, high )

{

return low + ( Math.floor( Math.random( ) * ( high - low + 1 ) ) );

}

Missing brackets!

Old Pedant

05-20-2012, 03:44 AM

Thanks. Sloppy of me. I usually count the left and right parens to be safe. Teach me to not do it one time.

Old Pedant

05-20-2012, 04:28 AM

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.

Old Pedant

05-20-2012, 04:38 AM

Just to pick an example of what VS does.

Say I have typed in

var f = "asfasdf";

var a = f.

at the point where I type that period, VS prompts me with a choice of methods and properties:

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?

Philip M

05-20-2012, 07:27 AM

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.

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):

// '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

Old Pedant

05-21-2012, 06:51 AM

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].

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

Old Pedant

05-22-2012, 03:14 AM

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.

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!

Old Pedant

05-22-2012, 05:28 PM

Okay...maybe if I go through the math you will feel more comfortable.

First of all, be aware that Math.random() always returns a pseudo-random number that is EQUAL TO OR GREATER THAN 0 and LESS THAN 1.

That is, roughly, a number in the range 0.000000 to 0.999999 (actually many more decimal places than that, but let's keep it simple).

So now let's say you have an array of length of 10. So you multiply Math.random() * thearray.length which is Math.random() * 10 which becomes SOME NUMBER in the range

0.000000 * 10 through 0.999999 * 10

which in turn is

0.000000 through 9.999999

Now, Math.floor() is used to simply DISCARD all digits to the RIGHT of the decimal point.

So doing Math.floor( Math.random() * 10 ) converts

0.000000 through 9.999999

to simply

0 through 9

Presto. EXACTLY what you want.

@Old Pedant: thanks a million. Makes perfect sense

Thanks for the time taken to write your replies

Very happy now :)

Powered by vBulletin® Version 4.2.2 Copyright © 2016 vBulletin Solutions, Inc. All rights reserved.