How do I randomly select a string from an array in swift?

Javascript selecting a random array?

  • I have this is my code. if(inArray(image)){ //image is an integer e.g 1 or 2 or 3. The code is comparing the value of image to an array. Let's say this is the array. example=new Array(1,2,3); And let's also say the value of image is 2. This is the function that checks whether 2 exists within the array. function inArray(obj){ var j=false; for(var hits=0;hits<example.length;hits++){ if(example[hits]==obj){ j=true; break; } } return j; } All the above code works fine and successfully identifies whether number 2 exists within the example array. But let's say I now have 3 arrays like this. example0=new Array(1,2); example1=new Array(3,4); example2=new Array(5,6); All the above code would still work fine if I were to change example.length and example[hits] to either example0 or example1 or example2. But I want to randomly select one of the 3 arrays. So I have used this code to randomise a number between 0-3. var num=Math.floor(Math.random()*3); I now want to alter this part of my code to adapt to the random number. ... for(var hits=0;hits<example.length;hits++){ if(example[hits]==obj){... So i know i need to concatenate the string 'position' with the random number generated in var num. But whenever I try to do this, it doesn't seem to work. Note: I only want to randomise the number ONCE. This is so I always have the same array when playing the game (unless I refresh the game and then the number is randomised once again). It may seem very easy to do, but it's not obvious to me :/ I'm hoping it's literally a simple solution that I can alter. Is it possible for you to either give an example or modify my code to suit my needs? Please.. (I've been told to use a two dimesional array. How do i use that?

  • Answer:

    Yep, two dimensional array. It's essentially a set of arrays within another array. So... example = new Array(   new Array(1,2),   new Array(3,4),   new Array(5,6) ); // or if your like me and prefer the literal-notation example = [ [1,2], [3,4], [5,6] ]; // then randomly pick your array example = example[ Math.floor( Math.random() * example.length ) ];

James at Yahoo! Answers Visit the source

Was this solution helpful to you?

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.