0

I have a game that I am trying to get going that displays a random card, but it draws duplicates. I don't want to duplicates to be used. I am using about 100 images-I just put the few in so you guys would understand.

How can I make it so it doesn't show any duplicates?

Thank you in advance, I have checked elsewhere, and with numbers it seems easier. I am a little lost using images...

<script>
var cards = new Array();

cards.push("images/apple.jpg");
cards.push("images/pear.jpg");
cards.push("images/banana.jpg");
cards.push("images/grape.jpg");
cards.push("images/tree.jpg");
cards.push("images/dog.jpg");
cards.push("images/cat.jpg");
cards.push("images/house.jpg");

var lastPics = new Array();
var currentPic = cards[0];

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function pickimg2() {
  var image = cards[getRandomInt(0, cards.length - 1)];
  var innerHtml = ""
  document.randimg.src = image;
  document.getElementById("copy").src = image;

  lastPics.splice(0,0,image);
  if (lastPics.length > 5) {
    lastPics.pop();
  }
  lastPics.forEach(function(item){
    innerHtml = innerHtml 
        + "<img name='copy' style='width:200px;height:200px;display:inline-block;
        padding:10px 10px 0px 10px;box-shadow: 0 12px 8px -8px black;' src="+item+" />"
  });
  document.getElementById("lastPicsDiv").innerHTML = innerHtml;
}
</script>
Arnaud Peralta
  • 1,287
  • 1
  • 16
  • 20
samlf3rd
  • 15
  • 7

1 Answers1

0

So what you're doing is just picking random cards. Since they're at random you're likely to end up with duplicates.

Instead you want to make an array with every card in, then shuffle the array so it's in a random order.

You can shuffle an array by sorting by Random - 0.5.

PhonicUK
  • 13,486
  • 4
  • 43
  • 62
  • Phonic, thanks. But, the code sorts nicely. But, I know there is a way to check to see if the string is present and remove it. Right? – samlf3rd Aug 21 '18 at 20:36
  • Shuffling an array by sorting like that [doesn't give uniform distribution](https://stackoverflow.com/a/18650169/5743988). – 4castle Aug 21 '18 at 20:46
  • Is there a way I can check for the "src" in my printout of already picked cards? Then tell it to ignore that and start over? – samlf3rd Aug 21 '18 at 20:58
  • 4castle-are you saying shuffling how I am using it in my code-or the response? I am a semi-noob with Javascript and don't use it often besides to make a form validate and post to db... – samlf3rd Aug 22 '18 at 16:54
  • There has to be a way to do this easily without rewriting this entirely. No? – samlf3rd Aug 27 '18 at 15:30