How to pick random element in 2D array

This is the contents of my constructor. How is the best way to pick a random element in a 8x8 array and assign it "Q"?
     public DancingQueen()
          board = new char [BOARD_SIZE][BOARD_SIZE];
          for (int i = 0; i < board.length; i++)
               for (int j = 0; j < board.length; j++)
                    board[i][j] = SPACE;
               Random generator = new Random();
               int r = generator.nextInt(8);
               int c = generator.nextInt(8);     
               board[r][c] = "Q";

Better make that 'Q' instead of "Q". The rest is fine though.
kind regards,
Jos

Similar Messages

  • How to delete an  element in an array...(simple way)

    hi,
    Newbie here... please help how to delete an element in an array list?
    there are alot of codes but they're complicated for a newbie like me..
    (simple codes would be better ..:) thank you...

    makk_88 wrote:
    since u want the simple method.....
    just overrite the position of the element that need to be deleted with the next element in the array..
    by doing this, element need to be deleted will not be accessibe..
    i think u got..what i'm saying.
    thnx..Mak,
    Say we wish to delete the second element of an array a[1]. Do you really believe that a[1] = a[2] somehow magically deletes a[1]? I really don't think so Tim.
    Two eggs, minus 1, equals two eggs? Interesting theory, but I think you're probably wrong.
    *@OP:* My advise is just use an ArrayList.
    Cheers. Keith.

  • How to show the elements of an array?

    How to show the elements of an array, when the array size changes every loop?
    It's possible to use node property?
    thanks
    Vicens
    Win XP/ LV7.1
    Attachments:
    show elements.PNG ‏184 KB

    Basically it is (at least in LV8.0). There is a property "Number of Rows" which sets the number of visible rows. If your 1D array is placed horizontally, use "Number of Columns".
    Using LV8.0
    Don't be afraid to rate a good answer...

  • How to insert 1 element in 2D array?

    There is an example of how to replace element in 2D array, but I would like to insert (not replace), I use the insert element. it does not work for 2 D array.
    Attachments:
    find_and_map_defect_to_image736X554.vi ‏46 KB

    You need to tell more about what you want done. What exactly does it mean
    to insert into a 2D array? Are you inserting into the row or column or
    both? By that I mean to ask what parts of the array get their indices
    incremented. Then what should happen at the endpoints? If you insert a
    point into one row then that row will have one more element than the others.
    Should the last element in that row be lost or should the other rows get a
    zero appended?
    "trout00" wrote in message
    news:[email protected]..
    > There is an example of how to replace element in 2D array, but I would
    > like to insert (not replace), I use the insert element. it does not
    > work for 2 D array.

  • How to average each element in an array

    I have data from a Gage Card that I would like to average.  I am tuning a laser over a 50 mA range and for each 1mA increment in current, I am taking 100 scans.  Each scan consisting of about 200 points.  I cannot average more than 10 shots using the Gagecard so I would like to capture 100 scans, and average them to reduce noise.  Currently, I have my capture vi inside of a for loop which repeats 100 times and each scan writes to a file, but I would like ony 1 scan (the lower noise averaged one) per current increment.  
    How can I average each element of 100 arrays and output this to an array?
    Thanks for the help 

    It sounds like you want to average element 0 across 100 arrays and make that element 0 of the new averaged array.  Then average element 1 across 100 arrays and make that element 1 of the new array ...   ?????
    How are you working with your 100 1-D arrays now? 
    What you should do is make a 2-D array where one dimension is 100 (for the number of individual arrays) and the other dimension is how many elements are in those 100 1-D arrays.  Then you can use for loops with auto indexing to break the 2-D array down into each row or column, do the average of that array, and autoindex on the other side to build back up into the new 1-D array of averages.  You may need to to a transpose array going into your for loop in case the arrays are indexed in the wrong direction.
    Message Edited by Ravens Fan on 01-21-2008 04:26 PM
    Attachments:
    Example_BD.png ‏6 KB

  • How to find the elements of an array

    I want to find the number of elements in an array, and I can't find the tutorial that shows how to find it. If anyone could point me in the right direction, it would be greatly appreciated.

    warnerja wrote:
    flounder wrote:
    DrLaszloJamf wrote:
    You mean x.length?<pbs>
    Depends upon your interpretation of "number of elements in the array"
    int[] numbers = new int[10];
    numbers[0] = 42;
    numbers[1] = 666;Number of elements in the array is 2 not 10.
    </pbs>If you used something other than a primitive type for the array element type you could have a case. A value of integer zero for the other elements is still a value, so there are indeed 10 elements there.Even if it were not primitive, every element would have a value. That value would either be null or a reference.

  • How to pick random MC frame?

    How can I pick random frame from movie clip, so that mc doesn't loop. Movie clip is a symbol. I made symbol defined it as mc, mc contains 4 frames, each frame contains some object. Any advice?

    OK I'll try to explain.
    I have mc which contains 4 objects each in separate frame.
    I have 5 spots, where those objects appear.
    Right now those four objects loop, but I need, that on object shows up on one spot other one on other spot and so on, randomly.
    I made function which makes those objects appear on random coordinates.

  • How to add new elements in an array of Objects of Type Figure??

    I have a Figure class which has many attributes(variables). Then I create an array of Figures for example
    Figs[] figures = new Figure[18];
    Later I need to add new Figures to this array at different positions. In my case I have to use the same array.
    Is there any way so I can add new Figure elements to this array??
    If u have an answer to this question, please share with me.
    Thanks
    Amit

    There are many ways to solve this problem, including creating new arrays as needed, and using System.arraycopy() to move things around. However, the best way is to use ArrayList, as discussed above.
    What you cannot do is use toArray() and cast back to String[]. Object[] is not a subclass of String[], even if all of the objects in the Object[] are Strings!
    There are two ways to get around this. Create a String[] and copy the Object[] into it with System.arraycopy, or the easy way, which is to use the toArray(Object[]) method. It allows you to specify by example the array class you wish returned. If the array is large enough, it will populate the array directly, otherwise it will create a new one of the same base class. That means any of the following approaches will work, the final decision is mostly a matter of style:
        // create a zero length array to pass as an exemplar
        public final static String STRING_ARRAY_TYPE[]  new String[0];
        String s[] = (String[]) a.toArray(STRING_ARRAY_TYPE);Or:
        String t[] = new String[a.size()];
        a.toArray(t);Or:
        String t[] = a.toArray(new String[a.size()]);;I prefer the first approach generally, and it avoids any race conditions between the evaluation of the ArrayList size and the toArray; however, since ArrayList methods are not synchronized, you probably should do some synchronizing of your own.
    Hope this helps.

  • How to replace cluster element in an array?

    hi,
    I have understood preferable choice is to initialise array first and replace elements in an array instead of inserting new element in an array e.g. in a while loop.
    So I started to this evaluate since I have an application where I want to read lots of measurements from a txt file and display them in a XY graph. XY graph must show Y value and corresponding X value either red if it is out of range and in green if it is in range. I found a solution to do it with an array of clusters.
    In attached example I have two different methdologies represented. My problem is that upper solution doesn't display content of all measurements. Can somebody tell me what I'm doing wrong ?
    regards,
    petri
    Solved!
    Go to Solution.
    Attachments:
    plot test 3.vi ‏19 KB

    Petri wrote:
    ... using cluster with three elements was a method I found to put red and green dots in one XY graph, eg. Y=coordinateY, X(green)=NaN,X(red)=coordinateX. Perhaps there is a better way to display the data, but I couldn't find it.
    That is an odd thing and makes little sense. Why three? four, five, etc are NOT supported, so what if you want more than one color? (in range, fail high, fail low?). For more detail see the discussion here.
    In any case, reading all these values from a datafile and creating xy plots is trivial. I would recommend to use complex data. a single complex array will graph IM vs RE. For multiple plots, combine them using "build cluster array". No loops needed.
    Here's a quick draft. Of course you need to decide if the data is in columns or rows, etc. so modify as needed.
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    plot2XY.PNG ‏7 KB

  • How to increment an element in an array and put it back in the same array?

    I have an array of values generated by another part of my program. My goal is to count the number of occurences for each integer value in the array and put these values in a new array. This new array will be a histogram of the input array. My approach is to do auto-indexing with a for loop. In the loop I use a "index array" to get the current value of the histogram array and a "replace array subset" to update the array element with "current+1". The problem is that when I wire the output of the "replace array subset" VI back to its input, I get a wire error. I guess I cannot wire it like that, but what should I do? Is there a completely different approach to do this that
    is more elegant?
    Thanks for your help!
    Benoit

    Hi Benoit,
    I believe the thing that's missing is a shift register.
    Right-click on the edge of your "For loop" and select add shift register.
    Wire an initialized array to the shift register left terminal before entering the "for loop". Wire from this same terminal (inside the loop) as the source of the info used in your "index array" and replace array. The results of these two operations (just the way you are doing it now) gets wired to the "right terminal" of the shift register (inside the loop).
    What ever you stuff into the right terminal, gets returned via the left terminal on the next iteration of the loop. When the loop is done, your final array of counts can be accessed by wiring from the "right terminal" (outside the loop).
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

  • How to randomize the elements in an array!!

    Hi,
    If i have an array, with say 50 integers which may be in some kind of order, is there a special method which could randomize these numbers for me? If not does anyone know of an algorithm which could do this?
    Many thanks
    Cath

    Hi,
    You could do that this way:
    int data[] = new int[50];
    for (int i=0; i<50;i++) {
       data[i] = (int)(Math.random() * 100);
    This code generates a random number between 0 and 1 and multiplies it by 100. This way, the resulting number will be between 0 and 100. If you want another order of data, you could multiply the ramdomly generated number by the greatest value you are expecting to be generated.
    Regards,
    Filipe Fedalto

  • How to pick random HU in EWM?

    Hello,
    I have the current situation in which a warehouse task is generated to pick a certain HU in order for it to be transferred to the GI-ZONE. This is due to a consumption in ERP. The issue is that I have a pallet in which I have 200 of these HUs (all with the same batch number). The WT suggests me a HU but it is rather difficult to send the picker to search among the 200 HUs to find and confirm it in the RF environment. I would like the system to let the picker choose his WO on which he is working and allow him to scan a random HU and replace the one from the pick WT (if of course is from the same batch). I know I can use Exception handling but this might prove to be used a lot and so it is not an exception anymore.
    At the storage type level, from which I pick, I have put the Level of Avail. Qty to value 1 - Storage Bin as the theory states but it doesn't help. Have you got an idea of what should be done?
    Thanks.

    Better make that 'Q' instead of "Q". The rest is fine though.
    kind regards,
    Jos

  • How can I supply elements of an array to the New-ADUser Class. Or can I do this another way?

    Hi, I want to write a function to create a new user, and I want to keep it as simple as possible.
    For example, I want to be able to call the function like.
    CreateNewUser John Doe
    The function itself will need to pass the value of the name, in this example John Doe into an array. And then I want to be able to reference that array for everything else.
    e.g
    Function CreateNewUser($fname,$lname)
    [string[]]]$objName = $fname,$lname
    New-ADUser -name $objname -givenname $objname[0] -surname $objname[1]
    I hope you get the idea. Is this possible, am I doing it right, and is there a better way of doing this?
    Thanks

    If you are just trying to make it look a bit cleaner you can use splatting so new-aduser isn't incredibly long...here is an example.
    $Params = @{
    Name = $DisplayName
    SamAccountName = $SamAccountName
    UserPrincipalName = $UserPrincipalName
    GivenName = $GivenName
    Surname = $Surname
    DisplayName = $DisplayName
    Path = $Path
    AccountPassword = $Password
    Enabled = $True
    ChangePasswordAtLogon = $True
    HomeDirectory = $HomeDirectory
    ScriptPath = $ScriptPath
    EmployeeID = $EmployeeID
    Department = $Department
    Division = $Division
    New-ADUser @Params
    The splatting will definitely help, but I think what the OP is really looking for is a wrapper to make the command line really simple. I have a function I use called Copy-AdUser that does several things internally to support our business needs. The command
    line is simple:
    Copy-AdUser -Instance gwashing -GivenName Abraham -SurName Lincoln -Title President -Location 'White House'
    Now you may not need to copy an existing user, but the ideas are the same. You can accept basic information about the user as parameter values and then in the guts of the function you can calculate all the other attributes, group membership, etc. The function
    looks something like this:
    Function Copy-ADUser {
    #.SYNOPSIS
    # Creates new Active Directory user based on attributes #and group membership of an existing user
    #.DESCRIPTION
    # Creates an Active Directory user based on an existing #user's group membership and Organizational Unit.
    # Requires that the MS Active Directory module is loaded.
    #.EXAMPLE
    # Copy-AdUser -Instance gwashing -GivenName Abraham #-SurName Lincoln -Title "President" -Location "White House"
    [CmdletBinding()]
    Param
    # Template user. Copies parent OU and group membership
    [Parameter(Mandatory=$true,Position=0)]
    $Instance,
    [Parameter(Mandatory=$True,Position=1)]
    [String]$GivenName,
    [Parameter(Mandatory=$True,Position=2)]
    [String]$SurName,
    [Parameter(Mandatory=$True,Position=3)]
    [String]$Title,
    # building code for primary location
    [Parameter(Mandatory=$True,Position=4)]
    [String]$Location,
    # Optional. Department or division (IT, HR, etc.)
    [Parameter(Mandatory=$False)]
    [String]$Department,
    # Optionally specify the SAMAccountName if it needs to be different than the standard formula
    [Parameter(Mandatory=$False)]
    [string]$SamAccountName = ($GivenName.tolower().substring(0,1) +
    $SurName.ToLower().Substring(0, [System.Math]::Min(7, $SurName.Length))),
    # Optionally specify the UPN prefix if it needs to be different.
    # This will be used for email addresses and the UPN
    [Parameter(Mandatory=$False)]
    [string]$UPNPrefix = ($GivenName.tolower() + '.' + $SurName.tolower())
    # company specific variables
    $EmailDomain = '@domain.com'
    $HomeFolderPath = '\\Server\Share'
    # calculate stuff
    $Instance = Get-ADUser $Instance -Properties *
    $OU = $Instance |
    Select-Object @{n='ParentContainer';e={$_.DistinguishedName -replace "CN=$($_.cn),",''}}
    $ADGroups = $Instance.MemberOf
    $UserPrincipalName = ($UPNPrefix + $EmailDomain)
    $FirstLast = "$GivenName $SurName"
    $Proxies = "SMTP:$UserPrincipalName"
    $HomeFolder = "$HomeFolderPath\$($SAMAccountName.ToUpper())"
    # Create the Active Directory User
    If(Get-ADUser -Filter {SAMAccountName -eq $SAMAccountName})
    Write-Warning "User with name $SamAccountName already exists!
    Please try again and specify unique values for the -samaccountname and -UPNPrefix parameters."
    Return
    Else
    $Attributes = @{
    Name = $FirstLast
    GivenName = $GivenName
    SurName = $SurName
    UserPrincipalName = $UserPrincipalName
    SAMAccountname = $SAMAccountName
    AccountPassword = (Read-host -assecurestring 'Enter Password')
    DisplayName = $FirstLast
    Description = "$Location $Title"
    EmailAddress = $UserPrincipalName
    homedrive = 'H:'
    HomeDirectory = $HomeFolder
    ScriptPath = 'login.bat'
    Title = $Title
    Company = $Location
    Department = $Department
    path = $OU.ParentContainer
    Enabled = $True
    OtherAttributes = @{proxyaddresses=$Proxies}
    New-Aduser @Attributes
    # Add User to the same groups as the UserToCopy
    $ADGroups |
    ForEach-Object {
    Add-ADGroupMember -Identity $_ -Members $SAMAccountName
    # Create home folder and set permissions
    Do
    Set-FolderPermission -Path $HomeFolder -User $SamAccountName -Permission 'Fullcontrol' -ErrorAction SilentlyContinue
    Until
    (Get-ACL $Homefolder).Access.IdentityReference -like "*$SamAccountName*"
    Please note this is probably not ready for you to use. You can change any of the internal logic to support naming schemes and paths that your organization uses. Also, there is a call to a function at the bottom that creates a home folder and sets permissions
    on that folder. I haven't included that function so this part will error out.

  • How to add an element to an array, then be able to remove it specifically

    So i have a list of numbers. The user is able to then add numbers to that list. I have a button which allows the user to remove any number of their choice by typing that number in a textbox. For some reason the numbers that the user add to the list will not dissapear when chosen whereas the original numbers go away no problem.
    The name of the array itself is mesEntiers and the name of the texbox is : IntegersIn_txt
    Here is the code :
    function supprimer(event:MouseEvent):void
      var indiceChiffre:int;
      indiceChiffre =(mesEntiers.indexOf(IntegersIn_txt.text));
      // La méthode indexOf renvoie l'indice d'un élément ou -1 si non trouvé.
      trace("testBtn")
      if (indiceChiffre != -1)
      for (var i=indiceChiffre; i <mesEntiers.length; i++)
      mesEntiers[i] = mesEntiers[i+1];
      trace("test")
      mesEntiers.pop();
      } // Fin fonction supprimer.

    Two things I can think of (I ran a small test)...
    1) Make sure your textfield is a single line, not multiline...  multilines end up with extra stuff in them that you can't see.
    2) Convert the text into a number unless the array is holding strings...  indiceChiffre =(mesEntiers.indexOf(Number(IntegersIn_txt.text)));

  • Hihow to insert 2 elements into 2D array?

    Hi I had a hard time figuring out how to insert 2 elements into 2D arrays. 
    I tried using replace and insert array functions but it does not work right way.
    I am using LV7.1. See the pic below.
    How do I insert elements in that way?
    Pls advise
    Clement

    Well, "replace array subset" is not the right tool, because it keeps the size of the array constant. Insert into array only works for entire rows or columns.
    You need a hybrid approach, because you want to insert elements at the beginning of column 1 while padding the remaining columns to the new lenght of column 1. This won't be efficient but there are plenty of ways to do that (here is one example with DBL arrays, should work equally well for string arrays as in your case).
    How much flexibility do you need? Is it always at the beginning of the first column? Are the arrays huge (=is performance an issue)? Is this a rare operations or do you constantly need to do this (e.g. inside a loop).
    In any case this seems like a rather arbitrary and somewhat silly operation. What is the practical purpose?
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    WeirdMerge.vi ‏21 KB

Maybe you are looking for

  • How to configure link between 2921 and SM-D-ES3G-48-P EtherSwitch Service Module

    hi, I can't do that like the procedure given by Cisco. http://www.cisco.com/en/US/partner/docs/routers/access/interfaces/software/feature/guide/eesm_sw.html#wp1942894 Cisco Procedure : interface gi10/0 ip address x.x.x.x x.x.x.x service-module gigabi

  • How to find the duplicate in the table

    i have a table with the 3 columns table name - employee empcode firstname lastname 123 xyz pk 456 yzz pk 101 kkk jk ALTER TABLE employee ADD (CONSTRAINT employee_PK PRIMARY KEY (empcode , firstname , lastname)) all the three columns make as porimary

  • Android Adobe reader don't open pdf Hyperlink

    Hi all, i'm trying to develop an android application, and i would like to know why the adobe reader don't recognize the hyperlink in a pdf file... I would like to know if my settings are wrong or the adobe reader application does not support that fea

  • Oracle 9i iDS (9.0.2.0.1) Core / Non-Core Patches

    Hello, I realise that there are at least 3 patches available out there for Oralce 9i iDS (9.0.2.0.1) running on Windows XP Pro. I am working with WebForms/WebReports migration project from 6i to 9i and running into all sort of errors. I get the feeli

  • Lakhs Currency in Thousands format in Oracle Report

    Hi Gurus, I have an requirement to change the currency amount display format should be in thousands for the lakhs currency since our client into UAE region and they wont use the lakhs currency format. Regards Ram