Creating a percentage of marked objects from a bag help

Hey guys, i've had good feedback and help from these forums before so thought i'd pick your brains again...
I'm looking at making a sim/game based around random results.
The experiment im supporting has (for example) 100 rubber ducks in a bag, you pick out 30 and mark them with a cross and place them back in the bag. Then you pick another 30 and note how many of the marked ducks you have found again.
I have some knowledge of Flash and have managed to make a random dice simulator and a few others.
I figure the best way is to forget about manually marking the ducks but instead have a drop down box where you can sellect how many of the 100 will be marked.Then have an action button which produces the results (in numbers?) underneath each corresponding duck (1 normal yellow, one marked).
Anybody able to help?
Thanks very much!!
Ollie

Yes, it makes sense, and the simulation I gave you does that and a bit more.  It actually let's you pick ducks more than just twice.
I do want to make sure I understand the concept clearly, so I'll write things in "my words" just to be clear.
When you say you wish to simulate the picking the ducks, you mean that when the user clicks the bag, the computer will pick the ducks randomly for him, the user will not actually see 100 ducks and start picking each one.  Correct?
If the answer to that is YES, then the button that says "Draw", that's your bag.
Now I separated the part that does the reporting, from the part that does the drawing to let it be more flexible and so that you could slice it better to suit your needs.
My simulation does pick random ducks every time.  Basically what it does, takes 30 ducks out of the bag, marks them and puts them back it.  You click again and it picks 30 ducks out of the bag, marks them, and puts them back in.  So a duck can have more than one x.  Technically speaking, those are very special rubber ducks because they can have 2,147,483,648 'X's on them.
Let's look at the code that actually does this in more detail
function drawFromBucket(event:MouseEvent):void      // could be called drawFromBag
    var ducksPickedList:Array = new Array();       // this is how I keep track of which ducks have been taken OUT of the bag in each draw
    var amountOfDucksToPick:int = 30;               // How many ducks to take out, easily changed to suit your needs
    howManyDraws++;                                      // Keeping count of how many times have we taken ducks out of the bag
                              // Here is where we pick the ducks  This is a loop that will go 30 times or how many you choose above
    for (var index:int = 0; index < amountOfDucksToPick; index++)
         // Pick a duck at random and check to see if we already picked it
         // if we did, pick another.
         var luckyDuckIndex:int;
         do
              luckyDuckIndex  = Math.random() * howManyDucks;     // Pick a duck by it's number
          } while (ducksPickedList.indexOf(luckyDuckIndex) >= 0);  // Check to see if it's out of the bag, if it is out already pick anotherone.
          trace("Lucks duck #" + luckyDuckIndex.toString());   // So you can see in your Console which ducks have been picked.
                                                                // put it in the list that stores the ducks that out of the bag.  This gets reset on every draw from the bag
         ducksPickedList.push(luckyDuckIndex);
        //  Mark that duck
        var luckyDuck:Object = bunchOfDucks[luckyDuckIndex];     // We just had a number this is how we grab the duck that belongs to that number
        luckyDuck.timesSelected++;                                           // We write an X on that duck.
  The reporting function basically tells you how many ducks are there than have more than x amount of 'X's on them, although interesting, not exactly what you needed.  What you need is not that complicated to get, there is multiple ways of doing this, but I'll just edit the function above.
I got rid of the button that showed the results, and just show the results on each draw.
Here is the final code:
stop();
var bunchOfDucks:Array = new Array();
var howManyDucks:int = 100;
var howManyDraws:int = 0;
drawDucksButton.addEventListener(MouseEvent.CLICK,drawFromBucket);
// Create the ducks
for (var duckIndex:int=0; duckIndex < howManyDucks; duckIndex++)
    var oneDuck:Object = new Object();
    oneDuck.timesSelected = 0;
    bunchOfDucks.push(oneDuck);
function drawFromBucket(event:MouseEvent):void
    var ducksPickedList:Array = new Array();
    var amountOfDucksToPick:int = 30;
    var amountOfFirstTimePicks:int = 0;
    var amountThatHaveAtLeastOneX:int = 0;
    howManyDraws++;
    for (var index:int = 0; index < amountOfDucksToPick; index++)
         // Pick a duck at random and check to see if we already picked it
         // if we did, pick another.
         var luckyDuckIndex:int;
         do
              luckyDuckIndex  = Math.random() * howManyDucks;
          } while (ducksPickedList.indexOf(luckyDuckIndex) >= 0);
          trace("Lucks duck #" + luckyDuckIndex.toString());
         // put it in the list
         ducksPickedList.push(luckyDuckIndex);
        //  Find the duck that belongs to the number pulled
        var luckyDuck:Object = bunchOfDucks[luckyDuckIndex];
        // We check to see if the duck had a X previously and
        // count accordingly
        if (luckyDuck.timesSelected == 0)
            amountOfFirstTimePicks++;
        else
            amountThatHaveAtLeastOneX++;
            // Write an X on that duck.
        luckyDuck.timesSelected++;            
     showResultsBox.labelNotMarkedBefore.text = amountOfFirstTimePicks.toString();
     showResultsBox.labelHasPreviousX.text = amountThatHaveAtLeastOneX.toString();
     showResultsBox.labelAmountOfDraws.text = howManyDraws.toString();
     getStats();
// Find out how many ducks where picked more than the amount
// specified in the moreThanAmount parameter
function howManyDucksPickedMoreThan(moreThanAmount:int):int
    var count:int = 0;
    for (var duckIndex:int=0; duckIndex < howManyDucks; duckIndex++)
        var oneDuck:Object = bunchOfDucks[duckIndex];
        if ( oneDuck.timesSelected > moreThanAmount)
            count++;
    return count;
function getStats():void
    var pickAmount = 2;
    var resultAmount:int = howManyDucksPickedMoreThan(pickAmount);
    showResultsBox.resultText.text = "There were " +resultAmount.toString() + " ducks picked more than " + pickAmount.toString() + " times in a total of " + howManyDraws.toString() + " draws.";    
Here is the screenshot.  Do not pay to much attention to my ducks. 
What you could use is a reset button that sets everything back to 0 to start over again, also you could easily let the user choose the amount of ducks to pick from the bag, and to select the value that they want to use for the report,  Would probably need that report button again if you choose to add that.  I'll leave those to you.
-Art

Similar Messages

  • How to create and instance of Java Object from an XML Document.

    Hi,
    How can we use a XML Document to create an instance of Java Object and do vice versa ie from the Java Object creating the XML Document.
    XML Document is available in the form of a String Object.
    Are there helper class available to achieve this.
    I need to do this in a Servlet.
    Regards
    Pramod.

    JAXB is part of JavaSE while Xmlbeans claims full schema support and full infoset fidelity.
    If the standard APIs do all that you need well then use them.

  • How to create a universe in Business Object from BW

    Dear Memebers
    I need your help, I'm trying to create a report in business object using a cube as datasource, but when execute it does not appears the text, for example costumer 1000, his name is coca-cola.
    Does anyone help me?, maybe i does not set something
    Thanks a lot
    Ariel

    Hi Ariel,
    Not sure what BW is? If this is not related to using a SDK you may want to post your question in the Business Objects enterprise or Crystal Report Designer Forum.
    Thank you
    Don

  • I can't read a Object from file, Please help me

    i want to write a Object into File. this is code of Object
    class objStoreCus implements Comparable, Serializable
    String customerID = new String();
    String customerName = new String();
    String customerEmail = new String();
    objStoreCus(String cusID, String cusName, String cusEmail)
    customerID = cusID;
    customerName = cusName;
    customerEmail = cusEmail;
    objStoreCus(){}
    public int compareTo(Object o)
    objStoreCus oS = new objStoreCus();
    oS = (objStoreCus)o;
    return(customerEmail.compareTo(oS.customerEmail));
    private void writeObject(ObjectOutputStream s) throws IOException {
    s.defaultWriteObject();
    private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
    try
    s.defaultReadObject();
    }catch(IOException ie){throw new IOException();}
    catch(ClassNotFoundException cnt){throw new ClassNotFoundException();}
    And I was wrote above Object into File by this code :+
    FileOutputStream fos;
    ObjectOutputStream oos;
    FileInputStream fis;
    ObjectInputStream ois;
    public void writeObjToFile(objStoreCus obj)
    try
    fos = new FileOutputStream("Exrcise3.ex3", true);
    }catch(FileNotFoundException fnfe){}
    try
    oos = new ObjectOutputStream(fos);
    //ghi doi tuong vao file
    oos.writeObject(obj);
    //dong stream
    oos.close();
    fos.close();
    }catch(IOException ie){}
    But i can't read above Object from file. allway have a Exception occur "StreamCorruptedException".
    this is code read Object form file :
    *parameter is ArrayList will be store Object from file.
    public void readObjFromFile(ArrayList al)
    try
    fis = new FileInputStream("Exrcise3.ex3");
    }catch(FileNotFoundException fnfe){}
    try
    ois = new ObjectInputStream(fis);
    while(true)
    try
    objStoreCus osc = new objStoreCus();
    osc = (objStoreCus)ois.readObject();
    System.out.println(osc.customerEmail);
    }catch(Exception e)
    e.printStackTrace();
    //System.out.println();
    break;
    ois.close();
    fis.close();
    }catch(IOException ie){}
    }

    Problem lies in
    os = new FileOutputStream("Exrcise3.ex3", true);
    You are trying to append to that file, You should always use new file to serialize objects.
    os = new FileOutputStream("Exrcise3.ex3");
    Try with above line.

  • How to create a java.util.Date object from a date String?

    How do I convert a String representation of a date in for the format dow mon dd hh:mm:ss zzz yyyy (e.g. "Mon Aug 27 17:12:59 EDT 2001") into a Date object? This you might note is the output of the Date classes toString() method. I don't want to have to parse this string. Thanks!

    Try this out
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMdd");
    String d = "19990831";
    Calendar cal = Calendar.getInstance();
    cal.setTime(sdf.parse(d));To create the SimpleDateFormat with a diffrent format check out all the possibilities here
    http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html
    Hope this helps
    Regards
    Omer

  • Can we create a 2 dimensionnal array (Object[][]) from List.toArray() ?

    I have a List that contains arrays and want to obtain a 2D array from the data stored into the list.
      //Creation of the list
      List list = new ArrayList() ;
      Object anArray = new Object[]{"One", "Two", "Three"} ;
      list.add(anArray) ;
      anArray = new Object[]{"Four", "Five", "Six"} ;
      list.add(anArray) ;
      anArray = new Object[]{"Seven", "Eight", "Nine"} ;
      list.add(anArray) ;
      //Creation of the array
      Object[][] data = (Object[][]) list.toArray() ;
      //We should obtain the same as :
      data = new Object[][]{
        {"One", "Two", "Three"},
        {"Four", "Five", "Six"},
        {"Seven", "Eight", "Nine"}
      } ;How can I, with a single instruction convert my List to an array of arrays (Object[][]) ?

    Object[][] data = (Object[][]) list.toArray(new Object[0][0]);

  • Creating File objects from all files in a folder.

    Hi, I'm not too brilliant of a programmer, so this may be an obvious one that I could find in the API.
    My goal is to compare files for similarities and then give some output, that's not too important.
    My question is: How do I create an array of File objects from a folder of *.txt files, without creating each individually? Is there a way to simply get all the files from the folder?
    File I/O is still pretty new to me. If I didn't give a good enough explanation, please say so.
    Thank you very much!

    Note by the way that a File represents an abstract pathname, the idea of a file as a location. It doesn't specify the file's contents, nor does it require that the file it represents actually exists. A better name might be "theoretical file" or "directory listing entry".
    So getting a whole bunch of File objects is itself perhaps not necessary (although it could be useful).
    To expand on reply #1, look for File methods whose names start with "list".

  • Extracting Array of objects from web service

    After a couple days of head banging I now have a webservice
    call executing and I am trying to extract / create a class from the
    ResultEvent:
    If the xml returned from the web service is:
    <people>
    <person name="Mike" />
    <person name="Dave" />
    </people>
    and the class is:
    class Person
    public var Name:String;
    The result event is:
    private function doResults(result:ResultEvent):void
    // how do I create an array of Person objects from result, I
    would also like to know how to create a typed array something like
    class PersonList if possible. I just need the raw how to loop the
    result and set the values on the class
    Thanks,
    Mike

    Well I wound up with just trial and error until I got it
    working, Im sure this will be improved as I go, but it's enough to
    press on with the app for now, this code is in the result function
    and result is the ResultEvent wich appears to be an array of
    generic objects representing the objects returned by the service.
    This in no way uses FDS and is talking to a simple dotnet / asp.net
    web service.
    // here app is a singleton class for app level data it is
    bindable and is used to update the view which in this example is
    bound to a public var MyObjects which in this case is an
    ArrayCollection, I unbox to MyObject in a custom view control
    for (var s:String in result.result)
    m = new MyObject();
    m.ID = result.result[s].ID;
    m.Name = result.result[s].Name;
    m.Type = result.result[s].Type;
    app.MyObjects.addItem(m);
    It also appears that you should create the WebService one
    time, and store refrences to the methods during app startup, the
    methods are called Operations and it appears you set the result and
    fault events then call send on the operation to get the data.
    // store this in a singleton app class
    var ws:WebService = new WebService();
    ws.wsdl = "
    http://dev.domain.com/WebService.asmx?WSDL";
    ws.addEventListener("result",doResults);
    ws.addEventListener("fault",doFault);
    ws.loadWSDL();
    // this is the operation which is also stored in the
    singleton app class
    var op:AbstractOperation = ws.getOperation("GetModules");
    // elsewere in the app we get the operation refrence setup
    result and fault and call send, then copy the generic object into
    our cutom classes using the first chunk of code above
    op.addEventListener("result",doResults);
    op.addEventListener("fault",doFault);
    op.send();
    I thought I would post this as I could find no such example
    in the offline or online docs, If anyone has a better way or see's
    a problem please post.
    I hope helps others with non FDS service calls and I look
    forward to hearing comments.
    Thanks,
    Mike

  • Problem Create object from superclass

    Hi,
    I have a problem with classes:
    I have one abstract superclass which has a method to create objecto for its children class.
    CREATE OBJECT R_FLIGHT TYPE (l_class_name)
         EXPORTING
           i_sflight = l_sflight.
    l_class_name: has the name of my children class
    My children class has this properties:
    A dump its triggered when I try to create object from the superclass.
    Best Regards

    Hello,
    I think that you defined the instantiation level of the superclass as PROTECTED & from the screenshot i can see that the instantiation level is protected & the class is marked as "Final".
    Are you having a factory method which returns the instance of the abstract class & you use it to achieve polymorphism?
    May be a little bit insight into your coding can help us
    BR,
    Suhas

  • Can you create an object from a string

    I have been working on creating a dynamic form, creating the
    form items from an xml file. I am getting very close to conquering
    this task. I will share it when it's complete.
    However, I am stuck at the moment trying to create an object
    from a string. For example, if the xml item is an HBox I want to
    create an HBox. Like this: parentObject = new arrayOfFormItems[
    index ]..type ()
    This isn't working. First, is this possible using some syntax
    I am unaware of in Flex? I don't want to use a large if or case
    statement if possible.
    Thanks in advance for your help!

    Thank you very much. Indeed that did solve the one problem. I
    missed the casting as a Display Object. That is awesome!
    I do still however, have to instantiate one of every item I
    want to dynamically create or I get the following error when I try
    to create a dynamic object that I have not instantiated before.
    ReferenceError: Error #1065: Variable HBox is not defined.
    at global/flash.utils::getDefinitionByName()
    at MyForm/buildForm()
    at DynamicForm/::onComplete()
    at
    flash.events::EventDispatcher/flash.events:EventDispatcher::dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at flash.net::URLLoader/flash.net:URLLoader::onComplete()
    I read that you have no choice but to instantiate one of each
    type to force the linker to link the code for that class into the
    .swf. Unless you know another way to force it.
    This is what I have in my Application mxml to get it to work:
    <mx:HBox>
    <mx:Text visible="false"/>
    <mx:TextArea visible="false"/>
    <mx:TextInput visible="false"/>
    <mx:DateField visible="false"/>
    </mx:HBox>
    And those are the types I'm using to test with. . . I will
    have to add all the others I want to use as well . . .

  • Can I create a network object from CIDR format or do I need to use IP - netmask?

    Have a cisco ASA running ASA V 8.3
    Wondering what the correct syntax is or even if it is possible to create a network object from a list of IP's in CIDR format? 
    Typically just do this:
    Create network-object
    object-group network name
    network-object 1.2.3.0 255.255.255.0
    Would like to do this: 
    network-object 1.2.3.0/24
    thanks!

    Hi,
    As far as I know the ASA does not support entering a network/subnet mask in such format in any of its configurations.
    - Jouni

  • Creating new graphics object from a existing one and sending it for print

    Hello,
    i have a graphics object which is big in size, I am creating a new graphics object from the existing one as given below
    //map is a graphic object
    Graphic g1 = (Graphic)map.create(x,y,width,height);
    Graphic g2 = (Graphic)map.create(x,y,width1,height1);
    Graphic g3 = (Graphic)map.create(x,y,width2,height2);
    arrayList.add(g1);
    arrayList.add(g2);
    arrayList.add(g3);
    Now I want to send the graphic object g1,g2,g3 for print in the method
    public int print (Graphics g, PageFormat pf, int idx) throws PrinterException {
    // Printable's method implementation
    if (curPageFormat != pf) {
    curPageFormat = pf;
    pages = repaginate (pf);
    if (idx >= 3)) {
    return Printable.NO_SUCH_PAGE;
    g = (Graphics) arrayList.get(idx);
    return Printable.PAGE_EXISTS;
    This is not working... what is wrong. can anybody suggest..
    I tried standardprint.java to print a object inside a scrollpane, it is not printing the entire diagram. so I am thinking of something like this.... Please let me know what to do....
    Thanks
    Serj

    The easy way to do this is create a copy using Windows Explorer.
    Open the project and go to File > Rename.
    Then you have your 2013 ready made project.
    See www.grainge.org for RoboHelp and Authoring tips
    @petergrainge

  • Dynamically create Value Objects from XML file

    Hi
    I want to create a value object from Xml file dynamically,like in the xml file i have the name of the variable and the datatype of the variable.is it possible do that,if so how.

    Read about apache's Digester tool. This is part of the Jakartha project. This tool helps in creating java objects from the XML files. I am not sure, if that is what u r looking for.

  • Why can't I create new object from a class that is in my big class?

    I mean:
    class A
    B x = new B;
    class B
    and how can I solve it if I still want to create an object from B class.
    Thank you very much :)

    public class ItWorksNow  {
      public ItWorksNow() {
      public static void main ( String[] argv )  throws Exception {
        ItWorksNow.DaInnaClass id = new ItWorksNow().new DaInnaClass();
      public class DaInnaClass {
    }

  • Unable to create a Driver object from driver with Media type string CTC PHO

    Hi All,
    I am trying to develop a siebel cti adapter for avaya.
    I have loaded a custom dll into siebel server but it is throwing error "SBL-CSR-00500: Unable to create a Driver object from driver C:\Mydriver\cti.dll with Media-Type-String CTC Phone ".
    It has been long time without any progress.
    Please help
    Thanks
    Nishant

    Hi tomhowell,
    According to your description, my understanding is that you got an error when you created a site from a custom site template after migrading SharePoint 2010 to your server.
    Did you have the original solution file of the site template? Please re-deploy the solution to your SharePoint site, then create a site from the new site template, compare the result.
    Also use  SPDisposeCheck to indentify the memory leak:
    http://archive.msdn.microsoft.com/SPDisposeCheck
    http://www.fewlines4biju.com/2012/11/detected-use-of-sprequest-for.html
    Here are some similar posts for your reference:
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/3a25eb86-8415-4053-b319-9dd84a1fd71f/detected-use-of-sprequest-for-previously-closed-spweb-object-please-close-spweb-objects-when-you?forum=sharepointdevelopmentprevious
    http://social.msdn.microsoft.com/Forums/en-US/50ce964f-94a6-4fda-abc0-caa34e7111f1/error-detected-use-of-sprequest-for-previously-closed-spweb-object-occurs-when-new-site-gallery
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

Maybe you are looking for

  • On "save image as...", Firefox requests a download location

    OS: Windows 7 64-bit Browser: Firefox 4.0.1 I recently did a clean install of Windows and all related programs, Firefox included. I now find that, no matter what, Firefox always asks me where to save my file when I right click an image and select "Sa

  • Syntax for taking export with 'Query' parameter

    Hi all Please help me regarding syntax for taking export with query parameter

  • Sequence in parent and row level security

    Hi, I have a column with "seq in parent" for the "autogen type" property in Designer. I also have row level security (RLS) (or fine grained access control) on this column's table. Since there are data that could not be seen because of the RLS and the

  • Outlook not responding opening a PDF

    We've had this issue with Adobe Reader XI, and Outlook 2010. What happens is when a PDF attachment is opened inm Outlook, Outlook will freeze and crash. If the user right click the PDF attachment in Outlook and chooses either option of "Preview" or "

  • 2 buttons in stage with 2 differents code = all button execute all code

    hello it realy strange i have 2div with 2 actions, one per div : -1 to load an url (touchstart and click) window.open("myurl", "_blank"); -1 to reload animation (touchstart and click) sym.play(0); sym.getSymbol(oscar).play(0); sym.getSymbol(cliquer).