Random Numbers with Objective-C

Hey Guys,
I'm creating a blackjack program and I need to randomize 52 numbers, ensuring not to repeat any number.
I know I can use the following to generate a number between 1-52, but I need the to eliminate the possibility of the same card being drawn twice:
cardNumber = arc4random() % 52 + 1;
Any idea on how I would do this? Code example would be helpful!
Thanks,
Justin

Hi Justin -
Justin Carman wrote:
I'm creating a blackjack program and I need to randomize 52 numbers, ensuring not to repeat any number.
I would initialize an array (the deck) with the card values, then use your random number as the index into the array. Each time a card is chosen just remove its value from the deck and decrement the modulus of the random numbers. NSMutableArray makes a nice deck for this purpose since its count is automatically decremented each time a value is removed. E.g.:
// AppController.m
#import "AppController.h"
#define N_DECK 52
@implementation AppController
@synthesize cardArray; // @property (nonatomic, retain) NSMutableArray *cardArray;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.cardArray = [NSMutableArray arrayWithCapacity:N_DECK];
- (IBAction)newDeck:(id)sender {
[cardArray removeAllObjects];
for (int i = 0; i < N_DECK; i++) {
[cardArray addObject:[NSNumber numberWithInt:i+1]];
// NSLog(@"newDeck: cardArray=%@", cardArray);
- (IBAction)getCard:(id)sender {
// check the array
int count = [cardArray count];
assert(count <= N_DECK);
if (count < 1) {
NSLog(@"getCard: Empty deck");
return;
NSLog(@"getCard: count=%d", count);
// select a card from the array
int index = arc4random() % count;
NSNumber *selected = [cardArray objectAtIndex:index];
NSLog(@"getCard: index=%d selected=%@", index, selected);
// print the value of the selected card
int card = [selected intValue];
NSLog(@"getCard: card=%d", card);
// remove the selected card from the array
[cardArray removeObjectAtIndex:index];
// note selected NSNumber object has been released
// NSLog(@"getCard: cardArray=%@", cardArray);
@end
For extra credit you might want to wrap the above in a custom Deck class.
Hope that helps!
- Ray

Similar Messages

  • Random numbers with leading zeros

    Hi,
    I want to generate random numbers with leading zeros.
    My code so far:
    import java.util.Random;
      Random r = new Random();
      int randInt = r.nextInt(100);My aimed output is something like:
    0012 or 0123 ...
    Thanks
    Jonny

    Hi,
    sorry for not getting it with NumberFormat. I used DecmailFormat instead:
    DecimalFormat df = new DecimalFormat("0000");
    df.setMinimumIntegerDigits(4);
    df.format(r.nextInt(40)));This gave me the right output, like 0013 or 0123 ...
    Thanks
    Jonny

  • Contact list favorites adds random numbers with no name associated

    I have an iphone 4s that will populate random numbers into my favorites list. After deleting them out, they reappear. They are not associated with anyone in my contact list. Any ideas or resolutions?

    Could someone please assist in restoring all contact info.  The last sync session lost all names associated with numbers and the contacts are now showing as an email address only????

  • How to generate random numbers with a known distribution of f(X)=(8X^2 + 1)*Exp( -X^2 )

    Dear All,
    I need to simulate a random number generator which can generate numbers X with the probability distribution of 
     f (X) = ( 8X^2 + 1)*Exp ( -X^2 ).
    This distribution is not a common distribution.
    I have searched a lot, but I still do not know how to realize it.
    Any help on this topic would be highly appreciated.

    Make a lookup table of the integral of your function (normalized to 1)
    Use the rectangle random generator and pipe that value through the lookup table, scale it ... voila.
    Greetings from Germany
    Henrik
    LV since v3.1
    “ground” is a convenient fantasy
    '˙˙˙˙uıɐƃɐ lɐıp puɐ °06 ǝuoɥd ɹnoʎ uɹnʇ ǝsɐǝld 'ʎɹɐuıƃɐɯı sı pǝlɐıp ǝʌɐɥ noʎ ɹǝqɯnu ǝɥʇ'

  • How to generate random numbers with a known distributi​on f(X)=(8X^2 + 1)*Exp( -X^2 ).

    I need to simulate a random number generator which can generate numbers X with the probability distribution of 
     f (X) = ( 8X^2 + 1)*Exp ( -X^2 ).
    This distribution is not a common distribution.
    I have searched a lot, but I still do not know how to realize it.
    Thanks a lot!
    Solved!
    Go to Solution.

    Don't forget to index back into the original X array for correctly scaled data. Here's a simple example (LV 8.0):
    Seems to work just fine.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    DistributionSimulation.png ‏25 KB
    DistributionSim4.vi ‏44 KB

  • Random placement of objects on a specified / unique shaped area

    Hi , Wondering if anyone can help. Basically I saw a humerous
    game where randomly placed pimples grew on a face, and the player
    had to squeeze them against a timer.
    I'm trying to simulate a similar idea, but I can't work out
    how to make the objects appear only in the area of the face. sure,
    I can do it on a rectangle or square. In my mind I am thinking that
    I must use some kind of hit test function to check if it lands on
    the face shaped area.. But yeah my syntax is from another planet.
    Any ideas. Thanks. Probably stupendously easy.

    Hmmm, I'm not too sure. Probably just looping through random
    numbers with a hitTest with shapeFlag set to true would do
    it....but...
    If I was doing this, my requirements might be that the
    "pimple" is also a certain minimum number of pixels from the edge.
    Because the face is a filled in shape with no gaps, then I would
    try to do a 'scan' of the two edges along one axis. Perhaps this
    can be done easier with bitMapData, but I'm not so familiar with
    that yet... here's how I would approach it:
    loop through the pixel rows from 0 to _height of the face
    clip (or the part of the face clip that matters)
    for each row, scan from left and right by pixel until the
    hitTest returns true.
    push an object {xMin: leftXvalue, xMax:rightXvalue} onto a
    scan array that records the left and right pixel _x values for that
    row.
    I now have an array (I would call it scan for example) that I
    can use to check the upper and lower x values that I can use as a
    range (to select a random x value from) after I have selected a
    random y value (which would correspond to the index in the scan
    array). With this x range you could also ensure that the 'pimple'
    was not too close to the edge of the face.
    Doing this pixel level scan could be a little processor
    intensive at the start, especially if its a large image. There may
    be better/easier ways to do it with bitmapData.

  • FPGA 20 random numbers

    Hello,
    I have NI PXIe-7966R FPGA module and i want to generate 20 random numbers with specified distribution. Now i have random number generator with uniform distribuiton and i have quantile function for my distribution in the form of 1000 point array. It takes a lot of logical blocks of FPGA if Im trying to solve this problem with 20 lookup tables or 20 memory blocks with my quantile function. Can you help me to advice?

    Theres an example on NI.com that uses the method outlined in this paper from xilinx. 

  • I need help with this program ( Calculating Pi using random numbers)

    hi
    please understand that I am not trying to ask anymore to do this hw for me. I am new to java and working on the assignment. below is the specification of this program:
    Calculate PI using Random Numbers
    In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
    � / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
    There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
    To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
    Random randomGen = new Random ( System.currentTimeMillis() );
    Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
    A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
    double xPos = (randomGen.nextDouble()) * 2 - 1.0;
    double yPos = (randomGen.nextDouble()) * 2 - 1.0;
    To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
    The class that you will be writing will be called CalculatePI. It will have the following structure:
    import java.util.*;
    public class CalculatePI
    public static boolean isInside ( double xPos, double yPos )
    public static double computePI ( int numThrows )
    public static void main ( String[] args )
    In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
    Computation of PI using Random Numbers
    Number of throws = 100, Computed PI = ..., Difference = ...
    Number of throws = 1000, Computed PI = ..., Difference = ...
    Number of throws = 10000, Computed PI = ..., Difference = ...
    Number of throws = 100000, Computed PI = ..., Difference = ...
    * Difference = Computed PI - Math.PI
    In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
    and below is what i have so far:
    import java.util.*;
    public class CalculatePI
      public static boolean isInside ( double xPos, double yPos )
         double distance = Math.sqrt( xPos * xPos + yPos * yPos );        
      public static double computePI ( int numThrows )
        Random randomGen = new Random ( System.currentTimeMillis() );
        double xPos = (randomGen.nextDouble()) * 2 - 1.0;
        double yPos = (randomGen.nextDouble()) * 2 - 1.0;
        int hits = 0;
        int darts = 0;
        int i = 0;
        int areaSquare = 4 ;
        while (i <= numThrows)
            if (distance< 1)
                hits = hits + 1;
            if (distance <= areaSquare)
                darts = darts + 1;
            double PI = 4 * ( hits / darts );       
            i = i+1;
      public static void main ( String[] args )
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter number of throws:");
        int numThrows = sc.nextInt();
        double Difference = PI - Math.PI;
        System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + PI + ", Difference = " + difference );       
    }when I tried to compile it says "cannot find variable 'distance' " in the while loop. but i thought i already declare that variable in the above method. Please give me some ideas to solve this problem and please check my program to see if there is any other mistakes.
    Thanks a lot.

    You've declared a local variable, distance, in the method isInside(). The scope of this variable is limited to the method in which it is declared. There is no declaration for distance in computePI() and that is why the compiler gives you an error.
    I won't check your entire program but I did notice that isInside() is declared to be a boolean method but doesn't return anything, let alone a boolean value. In fact, it doesn't even compute a boolean value.

  • I am trying to generate an array of 30 random numbers. after every 5 readings a new vi should open and tell the user that 5 readings has been completed. and again carry on with the generation of array.

    since i do not have a transducer now, i am currently generating an array of 30 random numbers. after every 5 readings a warning should be given to the user that 5 readngs are complete. this cycle should repeat. the array size is 30.
    please help me out,  waiting for reply asap.
    once i have the transducer, i will be taking 30 analog samples and then after every 5 smaples that wraning will be displaye din a new VI
    Solved!
    Go to Solution.

    Use a while loop with a time delay representing your sampling period.
    Use the count terminal to check if equals 4, so 4th iteration=5th sample.
    Use a case structure. The true case will only be executed on the 4th iteration.
    In the true case place a subVI  with your desired message in the front panel. Go to the VI properties window and set "open front panel when called".
    The closing condition of the warnign is not giving in your description.
    Consider that rather than usign a subvi for this, you could use the "One/Two/Three button dialog" or "display message" vis at the "dialog and user interface" pallete.
    Please give it a try and send your own VI. Do not expect us to provide a working solution.
    Regards,

  • Problem with Purchase Order creation with Random numbers .

    Hi Experts
    Currently i am facing an issue with Bapi BAPI_PO_CREATE1 to create Purchase order with random numbers for example items 1, 3,5.
    Please let me know the settings .
    Thanks in Advance

    Hi Neha,
    A reset of the release strategy only takes place if
    -  the changeability of the release indicator is set to '4' in
       case of a purchase requisition and '4' or '6' in case of
       another purchasing document (purchase order, request for
       quotation, contract, scheduling agreement),
    -  the document is still subject to the previous release
       strategy,
    -  the new TOTAL NET ORDER VALUE is higher than the old one.
    The total net order value is linked to CEKKO-GNETW for a purchase order,
    CEBAN-GSWRT for a purchase requisition item-wise release and CEBAN-GFWRT
    for a purchase requisition overall release.
    If you have maintained a Tolerance for value changes during release
    (V_161S-TLFAE), the release strategy is reset when the value of the
    document is higher than the percentage you have specified and if the
    document is still subject to the previous release strategy.
    Review the SAP note 365604 and 493900 for more
    information about Release strategy.
    Regards,
    Ashwini.

  • Can I group charts with objects in Numbers 3.0?

    In Numbers 2.1 I could group charts with objects and text.  I can't get this to work in Numbers 3.0.  The objects will group but not the charts.
    I used this to create marked-up charts in Numbers and paste them into a Pages document.
    (I just purchased a new iMac and don't have the old Numbers on it.)

    The only way around this is to print to PDF and open in preview, then use the rectangular selection tool to select the are you want to add to pages, then copy, then paste into Pages.
    You can post feedback to Apple using the menu item "Numbers > Provide Numbers Feedback"
    There are several features that were dropped and may be added back in... see this link:
    http://support.apple.com/kb/HT6049?viewlocale=en_US&locale=en_US

  • How to fill an array with random numbers

    Can anybody tell me how I can fill an array with thousand random numbers between 0 and 10000?

    import java.util.Random;
    class random
         static int[] bull(int size) {
              int[] numbers = new int[size];
              Random select = new Random();
              for(int i=0;i<numbers.length;i++) {
    harris:
    for(;;) {
    int trelos=select.nextInt(10000);
    numbers=trelos;
                        for(int j=0;j<i;j++) {
    if(trelos==numbers[j])
    continue harris;
    numbers[i]=trelos;
    break;
    return numbers;
    /*This method fills an array with numbers and there is no possibility two numbers to be the
         same*/
    /*The following method is a simpler method,but it is possible two numbers to be the same*/
    static int[] bull2(int size) {
         int[] numbers = new int[size];
    Random select = new Random();
    for(int i=0;i<numbers.length;i++)
              numbers[i]=select.nextInt(9);
              return numbers;
         public static void main(String[] args) {
    int[] nikos = random.bull(10);
    int[] nikos2 = random.bull2(10);
    for(int i=0;i<nikos.length;i++)
    System.out.println(nikos[i]);
    for(int i=0;i<nikos2.length;i++)
    System.out.println(nikos2[i]);

  • Working with random numbers and probabilities

    Hi again,
    i am working with random numbers at the moment.
    in the first step i do create a random number between 3 and 8 which is stored to a variable.
    set myVAR1 to random number from 3 to 8 as integer
    Lets assume myVAR1 is 5
    Now i want to select 5 numbers out of number pool from 1 to 8. Each number should be pickable only once.
    How would i realize that ?
    I guess i need some kind of pool, array and then select 5 out of this array, but i am not sure about the syntax.
    In best case i would like to add probabilities to those 8 numbers in the pool.
    i.e.
    1 (5%),2(5%),3(20%),4(10%),5(20%),6(10%),7(15%),8(15%)
    any help is heavily appreciated
    best regards
    fidel

    Hello fidel,
    For selecting unique numbers from given pool, try something like this.
    --SCRIPT 1
    (* select unique numbers from pool *)
    set pool to {1, 2, 3, 4, 5, 6, 7, 8} -- number pool
    set n to random number from 3 to 8 -- selection count
    return {n, random(n, pool)}
    on random(n, pool)
    set kk to {}
    repeat with i from 1 to count pool
    set end of kk to i
    end repeat
    set rr to {}
    repeat n times
    set k to kk's some integer
    set kk's item k to false
    set end of rr to pool's item k
    end repeat
    return rr
    end random
    --END OF SCRIPT 1
    For introducing selection weight of each number in the pool, you may try the below.
    --SCRIPT 2
    (* select unique numbers from pool with stochastic weights *)
    set pool to {1, 2, 3, 4, 5, 6, 7, 8} -- number pool
    set weights to {5, 5, 20, 10, 20, 10, 15, 15} -- selection weight
    set n to random number from 3 to 8 -- selection count
    return {n, random(n, pool, weights)}
    on random(n, pool, weights)
    script o
    property ww : weights
    property pp : {}
    property kk : {}
    property rr : {}
    repeat with i from 1 to count pool
    repeat my ww's item i times
    set end of my pp to pool's item i
    end repeat
    end repeat
    repeat with i from 1 to count my pp
    set end of my kk to i
    end repeat
    repeat n times
    set k to my kk's some integer
    set end of my rr to my pp's item k
    set j to 0
    set i to 1
    repeat with w in my ww
    set j to j + w
    if k > j then
    set i to j + 1
    else
    repeat with h from i to j
    set my kk's item h to false
    end repeat
    set i to 1
    exit repeat
    end if
    end repeat
    end repeat
    return my rr's contents
    end script
    tell o to run
    end random
    --END OF SCRIPT 2
    Hope this may help,
    H
    Message was edited by: Hiroto

  • Need help with random numbers

    hi i need to generate 2 random numbers from array list . and then take out that two numbers from list.
         String[] plcard = { "AC", "KC", "QC", "JC",
              "10C", "9C", "8C", "7C","6C","5C","4C","3C","2C", "AD", "KD", "QD", "JD",
              "10D", "9D", "8D", "7D","6D","5D","4D","3D","2D", "AS", "KS", "QS", "JS",
              "10S", "9S", "8S", "7S","6S","5S","4S","3S","2S", "AH", "KH", "QH", "JH",
              "10H", "9H", "8H", "7H","6H","5H","4H","3H","2H",};
    this is the list if someone can help me i would appreciate
    thanks in advance

    haha, never noticed the .shuffle(List) method!
    maybe java is getting too convenient (just kidding)?
    i never wrote a card game.
    how would the more programmingly gifted of us do this?
    this is my shot at it for what its worth...
    public class Card{
    public Card(int rank, int suit){
    this.rank = rank;
    this.suit = suit;
    int rank (or String i suppose)
    int suit;
    static final club = 1;
    static final spade = 2;
    static final heart = 3;
    static final diamond = 4;
    public class Shuffler{
    public Shuffler(){
    int NumOfDecks = 1;
    Vector ShuffledDeck;
    // num of decks
    for(int i = 0; i < NumOfDecks){
    // 4 suits
    for(int j = 0; j < 4; j++){
    // 13 ranks
    for(int k = 0; k < 13; k++){
    ShuffledDeck.add(new Card(k, j));
    } // suits
    } // num of decks
    Collections.shuffle(ShuffledDeck);
    // Done?
    }

  • Working with random numbers

    is there a way of creating a series of 6 random numbers from 1-9 without repeating a single number? i have currently developed the following method which so far generates a random number excluding zero, but ive no idea of how to ensure that i get different numbers everytime....
    private int randomNumber ()     {
            int num;
            do {
                   num = (int) (Math.random()*10);
            } while (num == 0);
            return num;
    }anyone got any ideas?

    use this insteadRandom rand = new Random();
        // Random integers that range from from 0 to n
        int n = 10;
       int  i = rand.nextInt(n+1);

Maybe you are looking for

  • HP Deskjet 2540 - connect to pc via USB, can I print from android tablet as well?

    Hi, I've just bought a HP Deskjet 2540 all in one printer. I have set it up via USB connection to my windows 7 pc, and it is printing fine. I also have an android tablet.  Can I also print from this whilst using the printer via USB on my pc. Any help

  • APEX Listener 2.0.1 does not restart on power-up of system

    APEX Listener 2.0.1 APEX 4.2.2 Oracle EE 11gR2 Linux RHEL 6.3 GlassFish 3.1.0 After rebooting my Linux server with the above configuration, the APEX Listener is down and needs to be restarted via GlassFish. What may be causing this?  How can I get th

  • PPB - Status field in filter.

    Hi, In Project Planning Board (cj2b) , I want to filter w.r.t status field .How to get the status field in Filter ? Regards, Rani.

  • SD Document Management system(DMS)

    Dearl all; can anyone tell me the standard SPRO settings for SD  Document Management System step by step. Thanking You; Joydeep Mukhopadhyaya

  • IPod Touch Home Button Issue

    Yes, I have an iPod Touch which I just upgraded to the latest 2.2.1 software a few weeks ago. Now my "Home Button" will not take me back to the main screen anymore. I have to completely turn it off and restart it to switch screens and applications. D