Posted: 1st Sep 2011 17:20
Hi

Is there a function to shuffle an array or is someone writing one to share please? I can't see anything in the documentation.

I've got an array of cards with about 20+ type variables applied to each iteration of the array.

I thought of creating a copy of the array using the same type i.e.

+ Code Snippet
global dim cards[100] as card
global dim shuffledCards[100] as card


And then maybe pick a random one from cards with random(1, 100) to put in the first iteration of shuffledCards etc. and so on for the second, making sure that I'm not duplicating any cards but unfortunately you can't do a simple copy like this as it crashes:

+ Code Snippet
shuffledCards[1] = cards[1]


This works but that would require 20+ lines for all of the type variables in card

+ Code Snippet
shuffledCards[1].name = cards[1].name
shuffledCards[1].group = cards[1].group


Thanks in advance
Posted: 1st Sep 2011 17:30
Searching the forum for "shuffle" brought up...

This

and this
Posted: 1st Sep 2011 17:54
I've seen a few examples (with a Google search) that I was going to work with but the first thing I wanted to try was to copy one array into another but it crashes, and probably because it has multiple type variables applied to each iteration of the array.

I'd have to create multiple lines for each variable in the card type which at the moment is about 20 but could change at a later stage, i.e:

+ Code Snippet
shuffledCards[1].name = cards[1].name
shuffledCards[1].group = cards[1].group
shuffledCards[1].description = cards[1].description


I was just wondering if anyone's written something for AppGameKit that will do this or if there's a prebuilt function in the language to do this.

I'll attempt it with multiple lines for each variable in the array.
Posted: 1st Sep 2011 18:16
Yah, I can't get copying from one array to another to work either. Sure would be nice to be able to do this.
Posted: 1st Sep 2011 18:45
After thinking about it I don't think I really need to shuffle a copy of the array. I've taken the code from the previous forum posts and adapted it slightly for AGK. Now that this totalShuffledDeck stores numbers only which have been shuffled I can use this variable to loop through and take the data from the original cards array. Here's the code that shuffles. You'll have to forgive the variable names.

+ Code Snippet
global dim totalShuffledDeck[100] as integer

function shuffleTotalDeck(numberOfCards)
  for i = 1 to numberOfCards
    totalShuffledDeck[i] = i
  next i

  for i = numberOfCards to 1 step - 1
    randomIndex = random(1, i)
    tmp = totalShuffledDeck[randomIndex]
    totalShuffledDeck[randomIndex] = totalShuffledDeck[i]
    totalShuffledDeck[i] = tmp
    //print(totalShuffledDeck[i])
  next i
endfunction

shuffleTotalDeck(10)