I'm having some trouble getting an array to be filled properly. I'm attempting to get a deck of cards to be loaded into an array and then shuffled which does work fine initially, however, after I do a check to see if there are enough cards left, the array does not load properly and everything more or less breaks.
Here's the relevant code. Any help would be greatly appreciated. Thanks!
var deck = {
//base deck before shuffle
baseDeck: ['d02', 'd03', 'd04', 'd05', 'd06', 'd07', 'd08', 'd09', 'd10', 'd11', 'd12', 'd13', 'd14', 'h02', 'h03', 'h04', 'h05', 'h06', 'h07', 'h08', 'h09', 'h10', 'h11', 'h12', 'h13', 'h14', 'c02', 'c03', 'c04', 'c05', 'c06', 'c07', 'c08', 'c09', 'c10', 'c11', 'c12', 'c13', 'c14', 's02', 's03', 's04', 's05', 's06', 's07', 's08', 's09', 's10', 's11', 's12', 's13', 's14'],
//Deck Shoe
shoe: [],
//pull deck #, return to shoe
shuffleDeck: function () {
this.shoe.length = 0;
this.shoe = this.baseDeck;
for (i = 0; i < this.shoe.length; i++) {
var randomPlace = Math.floor(Math.random() * 50) + 1;
var currentPlace = this.shoe[i];
this.shoe[i] = this.shoe[randomPlace];
this.shoe[randomPlace] = currentPlace;
}
}
}
var cardRetrieval = {
//return card vals
getCard: function (curHand) {
var q = curHand.push(deck.shoe.shift());
this.checkValue(curHand);
showCards(curHand, q);
if (deck.shoe.length <= 40) {
deck.shuffleDeck();
}
}
Everything works fine until the if statement at the bottom that checks if there are 40+ cards in the shoe array. But when it attempts to shuffle the deck again, it breaks.
The trouble is with this:
this.shoe.length = 0;
this.shoe = this.baseDeck;
You're not making a copy of the baseDeck into the shoe. Instead you're overwriting the reference to the empty Array you created for shoe, and you're replacing it with a reference to the same Array that baseDeck references.
So it works the first time you shuffle, because this.shoe.length = 0 is not yet affecting the baseDeck. But when you shuffle the second time, you're destroying the baseDeck. (Basically, with that first shuffle, you were using the baseDeck instead of a copy of it.)
Change it to this:
this.shoe.length = 0;
this.shoe = this.baseDeck.slice(0);
This will make a clean copy of baseDeck that is referenced by shoe each time.
There are 2 problems with your random number, 1) it will never be 0 - the first card in the deck, and 2) it may exceed the array size.
Use this instead:
var randomPlace = Math.floor(Math.random() * this.shoe.length);
Related
1 of spades,1 of diamonds,1 of clubs,1 of hearts,2 of spades,2 of diamonds,2 of clubs,2 of hearts,3 of spades,3 of diamonds,3 of clubs,3 of hearts,4 of spades,4 of diamonds,4 of clubs,4 of hearts,5 of spades,5 of diamonds,5 of clubs,5 of hearts,6 of spades,6 of diamonds,6 of clubs,6 of hearts,7 of spades,7 of diamonds,7 of clubs,7 of hearts,8 of spades,8 of diamonds,8 of clubs,8 of hearts,9 of spades,9 of diamonds,9 of clubs,9 of hearts,10 of spades,10 of diamonds,10 of clubs,10 of hearts
,,,
[This is what the program returns]
I'm trying to make a program in JavaScript that allows someone to play poker. I am using the ProcessingJS terminal in Khan Academy. Below is my full program so far. What it's supposed to do is make an array called deck which includes the names of all the cards (not including the face cards) in a deck of cards. That part of the program works. The next part attempts to make a new array called current that is an exact copy of deck. It then tries to print out current, and it does so successfully.
The last for loop is what is causing the problem. It tries to take a random card from current and copy it to another array called player which is supposed to be the player's hand. It then tries to remove that card from the array current.
However, when it tries to print out the array player, all it prints is three commas. I have no idea what the issue is and I have looked at many websites that talk about push and splice. I really have no idea what is wrong.
Again, I want the program to display the player's hand. Thank you for your help.
var deck = [];
var current = [];
var enemy = [];
var player = [];
var suits = ['spades', 'diamonds', 'clubs', 'hearts'];
for (var i = 1; i < 11; i++) {
for (var x = 0; x < 4; x++) {
if (i <= 10) {
deck.push(i + ' of ' + suits[x]);
}
}
}
for (var c = 0; c < 40; c++) {
current[c] = deck[c];
}
println(current);
var y;
for (var a = 0; a < 4; a++) {
y = random(0, (current.length - 1));
player.push(current[y]);
current.splice(y);
}
println(player);
Why not just simplify this without using splice?
From what I understand, you're drawing the card using random. So, just push that card to the players hand with player.push(current[y]).
Also, when you call current.splice(y), I don't think you're deleting just the card that was drawn. That deletes every card in the deck after the index y. Change this to current.splice(y, 1).
The following is a subroutine that I excised from my main program. It executes as a stand-alone script, but does not behave in the intended manner any better than it did in the main program:
//Generate permanent array of all possible directional marker pairs,
//excluding 0,0. Also generate array length the "hard" way
var potential_direction_pairs = [];
var length_of_potential_direction_pairs_array = 0;
for (var x_count = -1; x_count < 2; x_count++) {
for (var y_count= -1; y_count < 2; y_count++) {
if (x_count == 0 && y_count == 0) {}
else {
potential_direction_pairs.splice(0, 0, [x_count, y_count]);
length_of_potential_direction_pairs_array += 1
}
}
}
//Create temporary and mutable copy of permanent directional marker array.
var direction_pairs_being_tried = potential_direction_pairs;
//Iterate over all elements in temporary marker array. Use permanent array
//length, as temporary array length will change with each loop.
for (var count = 0, current_direction_pair_being_tried; count < length_of_potential_direction_pairs_array; count++) {
//Count out current length of (shrinking) temporary array.
for (var pair_index = 0; direction_pairs_being_tried[pair_index] != undefined; pair_index++) {}
//Choose a random marker pair from temporary array...
var random_index = Math.floor(Math.random() * pair_index);
//...and store it temporarily in a single-pair array.
current_direction_pair_being_tried = direction_pairs_being_tried[random_index];
//Remove the randomly chosen marker pair from larger temporary array.
direction_pairs_being_tried.splice(random_index, 1);
//Insert temporary "tracer" to display current state of intended
//"permanent" array.
console.log("Potential direction pairs: " + potential_direction_pairs);
//Insert another "tracer" to display current state of intended
//temporary array.
console.log("Direction pairs being tried: " + direction_pairs_being_tried);
//"Tracer" showing current state of temporary single-pair array.
console.log("Current direction pair being tried: " + current_direction_pair_being_tried);
}
Only one of the two "2D" arrays is meant to change, but as you can see from the following screenshot of terminal window output, both do: output of simple subroutine. My knowledge of scope/closure/etc is still pretty shaky, but my suspicions lie that direction. Any help would be appreciated (including a brief explanation), but I'm especially keen on the simplest possible correction to make this work.
Thanks in advance,
Rob
var direction_pairs_being_tried = potential_direction_pairs; is not a copy of an array, it's pointing to the same array. You can copy an array with
var direction_pairs_being_tried = potential_direction_pairs.slice()
I'm trying to change the following (that currently returns a random number from an array), so that each random number is different from the last one chosen.
function randomize(arr) {
return arr[Math.floor(Math.random()*arr.length)];
}
oracleImg = [];
for (var i=1;i<=6;i++) {
oracleImg.push(i);
}
randOracleImg = randomize(oracleImg);
I tried the following, but it's not always giving me a number different from the last number.
function randomize(arr) {
var arr = Math.floor(Math.random()*arr.length);
if(arr == this.lastSelected) {
randomize();
}
else {
this.lastSelected = arr;
return arr;
}
}
How can I fix this?
Your existing function's recursive randomize() call doesn't make sense because you don't pass it the arr argument and you don't do anything with its return value. That line should be:
return randomize(arr);
...except that by the time it gets to that line you have reassigned arr so that it no longer refers to the original array. Using an additional variable as in the following version should work.
Note that I've also added a test to make sure that if the array has only one element we return that item immediately because in that case it's not possible to select a different item each time. (The function returns undefined if the array is empty.)
function randomize(arr) {
if (arr.length < 2) return arr[0];
var num = Math.floor(Math.random()*arr.length);
if(num == this.lastSelected) {
return randomize(arr);
} else {
this.lastSelected = num;
return arr[num];
}
}
document.querySelector("button").addEventListener("click", function() {
console.log(randomize(["a","b","c","d"]));
});
<button>Test</button>
Note that your original function seemed to be returning a random array index, but the code shown in my answer returns a random array element.
Note also that the way you are calling your function means that within the function this is window - not sure if that's what you intended; it works, but basically lastSelected is a global variable.
Given that I'm not keen on creating global variables needlessly, here's an alternative implementation with no global variables, and without recursion because in my opinion a simple while loop is a more semantic way to implement the concept of "keep trying until x happens":
var randomize = function () {
var lastSelected, num;
return function randomize(arr) {
if (arr.length < 2) return arr[0];
while (lastSelected === (num = Math.floor(Math.random()*arr.length)));
lastSelected = num;
return arr[num];
};
}();
document.querySelector("button").addEventListener("click", function() {
console.log(randomize(["a","b","c","d"]));
});
<button>Test</button>
Below code is just an example, it will generate 99 numbers and all will be unique and random (Range is 0-1000), logic is simple just add random number in a temporary array and compare new random if it is already generated or not.
var tempArray = [];
var i=0;
while (i != 99) {
var random = Math.floor((Math.random() * 999) + 0);
if (tempArray.indexOf(random)==-1) {
tempArray.push(random);
i++;
} else {
continue;
}
}
console.log(tempArray);
here is a version which will ensure a random number that is always different from the last one. additionally you can control the max and min value of the generated random value. defaults are max: 100 and min: 1
var randomize = (function () {
var last;
return function randomize(min, max) {
max = typeof max != 'number' ? 100 : max;
min = typeof min != 'number' ? 1 : min;
var random = Math.floor(Math.random() * (max - min)) + min;
if (random == last) {
return randomize(min, max);
}
last = random;
return random;
};
})();
If you want to ALWAYS return a different number from an array then don't randomize, shuffle instead!*
The simplest fair (truly random) shuffling algorithm is the Fisher-Yates algorithm. Don't make the same mistake Microsoft did and try to abuse .sort() to implement a shuffle. Just implement Fisher-Yates (otherwise known as the Knuth shuffle):
// Fisher-Yates shuffle:
// Note: This function shuffles in-place, if you don't
// want the original array to change then pass a copy
// using [].slice()
function shuffle (theArray) {
var tmp;
for (var i=0; i<theArray.length;i++) {
// Generate random index into the array:
var j = Math.floor(Math.random()*theArray.length);
// Swap current item with random item:
tmp = theArray[i];
theArray[j] = theArray[i];
theArray[i] = tmp;
}
return theArray;
}
So just do:
shuffledOracleImg = shuffle(oracleImg.slice());
var i=0;
randOracleImg = shuffledOracleImg[i++]; // just get the next image
// to get a random image
How you want to handle running out of images is up to you. Media players like iTunes or the music player on iPhones, iPads and iPods give users the option of stop playing or repeat from beginning. Some card game software will reshuffle and start again.
*note: One of my pet-peeves is music player software that randomize instead of shuffle. Randomize is exactly the wrong thing to do because 1. some implementations don't check if the next song is the same as the current song so you get a song played twice (what you seem to want to avoid) and 2. some songs end up NEVER getting played. Shuffling and playing the shuffled playlist from beginning to end avoids both problems. CD player manufacturers got it right. MP3 player developers tend to get it wrong.
I have two arrays (representing a deck of cards), one filled with the values 1-52, and another filled with nothing. I want to take the position randomly from the first array and take that object and put it into the next spot available in the randomized array. I have this so far:
var shufdeck = new Array();
while(sufdeck.length < 52)
{
i = Math.floor(Math.random()*52);
//shufdeck[0] = deck[i] etc.
}
I'm not sure if I should be using splice or something else to take it out of the first array and put it into the second. If possible shufdeck[] should be filled and deck[] would be empty.
How can I shuffle an array?
Yes, you should splice out the chosen card, so:
var shuffledDeck = [];
while (deck.length) {
shuffledDeck.push(deck.splice(Math.random()*deck.length | 0, 1)[0]);
}
or to be a little more efficient:
var i = deck.length;
while (i) {
shuffledDeck.push(deck.splice(Math.random()*i-- | 0, 1)[0]);
}
Note that this will destroy deck. If you don't want that, copy it first:
var deckToShuffle = deck.slice();
WARNING: CPU Usage goes to 100%, be careful.
Link to the jsFiddle
This script has been written to design a dynamic snake and ladder board. Everytime the page is refreshed a new board is created. Most of the time all of the background images do not appear, and the CPU usage goes up to 100%. But on occasion all of them appear and the CPU usage is normal.
Opera shows some of the background images, Firefox lags and asks me if I wish to stop the script.
I believe that the problem is with these lines of code:
for(var key in origin) // Need to implement check to ensure that two keys do not have the same VALUES!
{
if(origin[key] == random_1 || origin[key] == random_2 || key == random_2) // End points cannot be the same AND starting and end points cannot be the same.
{
valFlag = 1;
}
console.log(key);
}
Your algorithm is very ineffective. When array is almost filled up, you literally do millions of useless iterations until you're in luck and RNG accidentally picks missing number. Rewrite it to:
Generate an array of all possible numbers - from 1 to 99.
When you need a random numbers, generate a random index in current bounds of this array, splice element and this random position, removing it from array and use its value as your desired random number.
If generated numbers don't fit some of your conditions (minDiff?) return them back to array. Do note, that you can still stall in loop forever if everything that is left in array is unable to fit your conditions.
Every value you pull from array in this way is guaranteed to be unique, since you originally filled it with unique numbers and remove them on use.
I've stripped drawing and placed generated numbers into array that you can check in console. Put your drawing back and it should work - numbers are generated instantly now:
var snakes = ['./Images/Snakes/snake1.png','./Images/Snakes/snake2.jpg','./Images/Snakes/snake3.gif','./Images/Snakes/snake4.gif','./Images/Snakes/snake5.gif','./Images/Snakes/snake6.jpg'];
var ladders = ['./Images/Ladders/ladder1.jpg','./Images/Ladders/ladder2.jpg','./Images/Ladders/ladder3.png','./Images/Ladders/ladder4.jpg','./Images/Ladders/ladder5.png'];
function drawTable()
{
// Now generating snakes.
generateRand(snakes,0);
generateRand(ladders,1);
}
var uniqNumbers = []
for(var idx = 1; idx < 100; idx++){ uniqNumbers.push(idx) }
var results = []
function generateRand(arr,flag)
{
var valFlag = 0;
var minDiff = 8; // Minimum difference between start of snake/ladder to its end.
var temp;
for(var i = 0; i< arr.length; ++i) {
var valid = false
// This is the single place it still can hang, through with current size of arrays it is highly unlikely
do {
var random_1 = uniqNumbers.splice(Math.random() * uniqNumbers.length, 1)[0]
var random_2 = uniqNumbers.splice(Math.random() * uniqNumbers.length, 1)[0]
if (Math.abs(random_1 - random_2) < minDiff) {
// return numbers
uniqNumbers.push(random_1)
uniqNumbers.push(random_2)
} else {
valid = true
}
} while (!valid);
if(flag == 0) // Snake
{
if(random_1 < random_2) // Swapping them if the first number is smaller than the second number.
{
var temp = random_1; random_1 = random_2; random_2 = temp
}
}
else // Ladders
{
if(random_1>random_2) // Swapping them if the first number is greater than the second number.
{
var temp = random_1; random_1 = random_2; random_2 = temp
}
}
// Just for debug - look results up on console
results.push([random_1, random_2])
}
}
drawTable()
I had a problem like this using "HighCharts", in a for loop - "browsers" have an in-built functionality to detect dead scripts or infinite loops. So the browsers halts or pop-ups up a message saying not responding. Not sure if you have that symptom!
This was resulted from a "loop" with a large pool of data. I wrote a tutorial on it on CodeProject, you might try it, and it might be your answer.
http://www.codeproject.com/Tips/406739/Preventing-Stop-running-this-script-in-Browsers