How do I select multiple values from my JSON file without repeating?

0 favourites
  • 5 posts
From the Asset Store
In this template the music plays without looping in your game
  • I'm making a trivia game. I have a JSON file with 300 questions and answers but I only want individual 'games' to consist of 7 questions.

    Currently I can iterate throught the first 7 items with something like

    JSON.Get("Questions." & vNum-1 & "." & 0)

    where the array key is "Questions", vNum is a parameter passed in and index 0 holds the question. So, for example, on the start of the layout vNum = 1 so this retrieves

    Questions.0.0

    which is the question of the first item in JSON. vNum then is incremented by 1 so the next run gets

    Questions.1.0.

    How can I get 7 random items from this list of 300 without repeating any? I know I could try

    JSON.Get("Questions." & random(JSON.ArraySize("Questions")) & "." & 0)

    but I can't be sure that this won't return duplicates.

    Tagged:

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Take a look at the 'Advanced Random' object, you can create a Permutation table which can generate a shuffled output of numbers from 1-300.

    So if the Permutation output is 97,3,155,9,88.... for example, you can access the values with AR.Permutation(0) which would be 97 and AR.Permutation(1) which would be 3.

  • Thanks lionz! That's pretty much what I did

    So I created a couple of variables: curPermTablePos to save what index of the permutation table to look at, gameLength to save how many random items I wanted to get.

    Then I created a permuation table with 7 (gameLength) values betweeon 0 and 50. I found if I left the offset at 0 I would only get values 0-7 in my permutation table, so I changed it to be

    int(random(qCount-gameLength))

    where qCount is the total number of questions there are, so this evaluates to

    int(random(50-7))

    so I get a random offset of a whole number between 0 and 43.

    When I get a question I call

    which uses the curPermTablePos variable to load a random entry from my list of questions.

    Once I have loaded the question I just increment curPermTablePos by 1 to get the next question.

  • When calling the function with the variable it looks fine but when you set up the table I think that's wrong as you will only have a shuffled 1-7 when you need 1-300. The length should be 300 (or qcount) and offset 1.

    To pick only 7 questions you do it at the function call level with the incrementing variable. You can view the permutation table in debug view, it should be a shuffled output of 300 values, the first 7 of which become the questions using the function call and variable.

  • Ah ok. That makes things a bit clearer., thank you

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)