Another question about problem using arrays

Hey guys, if you helped me answer my other problems thanks a bunch and again thank you to all the people who try to help us learn the unique language of Java. Anyway the other problem goes like this:
Return the number of even ints in the given array. Note: the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.
countEvens({2, 1, 2, 3, 4}) ?? 3
countEvens({2, 2, 2}) ?? 3
countEvens({1, 3, 5}) ?? 0
Ok so basically I would want to count all the evens in an array and basically if I use the module operator I can figure out whether something is even or not if it returns me a 0. So I know there will be an if statement there. I'm wondering if I would have to also use a "for each" statement to check every element. I would also need a variable to keep count of the number of elements that are even. Any suggestions on how the implementation of this method should be like?

Hey thanks a bunch actually, I just pretty much reasoned it out and ended up with this:
public int countEvens(int[] nums) {
int count = 0;
for (int e:nums)
     if ((e%2)==0)
        count++;
   return count;      
}Really appreciate the help.

Similar Messages

  • Question about problem using arrays...

    Hey guys, thanks a bunch for the help - I always really appreciate how you guys can take the time to help us people still learning about this amazing language. Anyway the problem goes like this:
    Given an int array, return a new array with double the length where its last element is the same as the original array, and all the other elements are 0. The original array will be length 1 or more. Note: by default, a new int array contains all 0's.
    makeLast({4, 5, 6}) ?? {0, 0, 0, 0, 0, 6}
    makeLast({1, 2}) ?? {0, 0, 0, 2}
    makeLast({3}) ?? {0, 3}//this is basically what it's supposed to do
    public int[] makeLast (int[] nums)
    So I'm just wonder on how the implementation would be like. I know that I would first want to double the array length. After that, I would want to replace every element of the original array with 0's but keep the last element the same. Any suggestions guys?

    So I'm just wonder on how the implementation would be like. I know that I would first want to double the array length.Well, you can't double the length per se. You can't dynamically change the size of an array. Rather, you'll need to create a new array with the size as specified by the homework assignment.
    After that, I would want to replace every element of the original array with 0's but keep the last element the same.Since it's a new array, you wouldn't actually replace anything.
    Any suggestions guys?Hint: the default value, in an array of numbers, is zero.

  • Yet another question about super raid - GS70

    Yes, another question about Super Raid...I recently picked up the cheapest model of the GS70 on newegg which comes with 1 mSata SSD...just a mediocre one if I remember reading correctly.  I'm interested in using MSI's Super Raid once my warranty is over with and have been reading a couple posts here:
    1. Walk through of how to reinstall OS
    --> https://forum-en.msi.com/index.php?topic=167198.msg1224063#msg1224063
    2. I'll need a Super Raid card with links to get some, for about $100 each
    --> https://forum-en.msi.com/index.php?topic=171722.msg1252847#msg1252847
    3. I can't get Super Raid unless it originally came with it?
    --> https://forum-en.msi.com/index.php?topic=171185.msg1249640#msg1249640
    So what's the bottom line? Would I still be able to enable super raid in the future or am I SOL since it didn't come with it originally?
    thanks!

    The GT70 CAN come with an adapter that has 2 (on the older, GT70 0NX models) or 3 (on newer GT70 20X models) sockets for mSATA drives. It's an optional part, that takes place of the primary SATA drive in the notebook, and physically has a different part that connects to the motherboard. If it doesn't come with the SuperRaid adapter, then it just has support for a single 2.5" SATA drive.
    The GS70 on the otherhand, has this built into the motherboard and there is no swapping it out for a normal 2.5" SATA drive. You can only use mSATA drives (on those ports). The GS70 is meant to be an ultrabook, and therefore does not have the same ability as the GT70 to house up to 2 full size 2.5" SATA drives.
    That's really the main difference here. Without physically seeing a GT70 to see how the SuperRaid adapter works, it's slightly difficult to explain.
    But in the end, I wouldn't worry about the SuperRaid....The GS70 should have support for Intel Raid Management Engine, in which case that's all you really need.

  • ANOTHER Question about my iMac G3. Mac OS X and RAM

    Hey, I have ANOTHER question about my iMac G3.
    I know that I'm supposed to have the latest firmware updates for my iMac G3 running OS 8.1, which I do, but I read some where these firmware updates could only be updated if you're running OS 9.2. Yet when I run the firmware updater, it says my firmware is up to date. I just wanted to make sure this was correct because I just ordered an OS X 10.2 CD today, and I don't want my mac to be "dead" when I install it.
    My next question is how much RAM can my mac hold. It's an iMac G3 with a 233 mhz processor, if that makes a differemce.
    Again, thanks to the people who have helped me with my first Mac.

    hi there--
    unfortunately you require system 9.1 or 9.2 for the required firmware update 1.2 for your computer http://docs.info.apple.com/article.html?artnum=86117. so you'll have to install that if you want to install 10.2. it may work for you for a little while, but then you could possibly lose all your information. so i wouldn't advise attempting installing 10.2 without the correct firmware. [ : ) ]

  • Another question about gmail

    I just posted a question about adding gmail and it was answered.  Now, I have another question,  I added the new gmail account.  It shows in the mail preferences under accounts.  Incoming mail addressed to gmail comes to the Archive Box. But I still can't send mail by gmail because in the drop down menu on the email it only lists my other two accounts.  Gmail is not an option.  I highlighted gmail in the account list and it showed that as the account in use.  But, still there was no gmail option on the email form in the sender box.  How do I fix that?

    You need to look at and read over these very carefully.
    http://support.apple.com/kb/TS3276
    The link above is about sending issues.  The one below is about setting up or confiquring new e-mail.
    http://support.apple.com/kb/HT1277
    Good Luck to you and welcome to the Discussions.
    Don

  • Another question about adding music to iPhone

    Apologies for yet another question regarding adding music to an iPhone but I am completely stuck.
    I bought a new laptop in January (it runs windows 8). I've authorised it and synced my phone to it before. I've used it to add music before.
    Lately I've just been buying music directly from itunes on my phone but I wanted to add some music from my older collection that is on an external harddrive.
    I've gone through the process of syncing the phone again, which has wiped whatever was on there. I made sure I'd ticked on the "manually manage music" box. 
    It's put all my purchased music back but it still will not let me drag and drop music from my external harddrive. When I hover over with the file it has "link" but it won't actually send the music to the phone.
    Is there a way for me to do this without putting music on to my itunes library? I don't like itunes and I definitely don't want to add the music to my laptop as it defeats the purpose of having an external harddrive! Sorry for such a long-winded explanation.

    Just to add... I've now tried adding music to the library (getting desperate here) and it's not letting me do that either. Just says 'link'.
    This is the most frustrating thing ever. Why are the simplest of tasks made so difficult? It seems like it only works if you buy the music from the iTunes store.

  • Yet another question about burners for iDVD 6

    It's not my intention to be redundant and the question about which DVD burners are compatible with the most recent release of iDVD has been asked a few times since iLife '06 was released at MacWorld last week. Yet, though Apple has announced it, why have they not posted a list of compatible devices?
    Or, is the onus on the manufacturers to certify that their burners are compatible with iDVD 6?
    In either case, has anyone determined if this information is available and, if so, where?
    Thanks.

    Or, is the onus on the manufacturers to certify that their burners are compatible with iDVD 6?
    Check with the support sections of the manufacturer's websites - after all, THEY are the ones trying to sell burners.

  • Another question about using objects in SQL queries

    Hi gurus, I need your thoughts on this:
    I have created generic object type "tree" - the constructor takes as a parameter sql query returning "node_id" and "parent_node_id". As a tree - the object has all related to a tree structure member functions and one of them is "oldest_relative" (the tree may not be fully connected - it may be more like a set of many trees, so it's not necessary all nodes to have the same root).
    I also have departments table with the following fields: department_id, parent_department_id, department_name,...
    all records in the table w/out parent_departments (parent_department_id is null) are considered divisions.
    Now if I run the following query:
    SELECT "DEPARTMENT_ID", "PARENT_DEPARTMENT_ID", "DEPARTMENT", tree('select department_id "node_id", parent_department_id "parent_node_id" from departments').oldest_relative("DEPARTMENT_ID") "DIVISION_ID" FROM departments
    my question is: Is the tree object created for every row or does Oracle somehow caches the object since the object itself is not changing but only the parameter for the oldest_relative member function.
    The table only has a few hunderd records and I can't see much of a difference in the execution time btw the query above and query like this:
    SELECT "DEPARTMENT_ID", "PARENT_DEPARTMENT_ID", "DEPARTMENT", b.t.oldest_relative("DEPARTMENT_ID") "DIVISION_ID"
    FROM departments left join (select tree('select department_id "node_id", parent_department_id "parent_node_id" from departments') t from dual) b on 1 = 1
    where the object is clearly created just ones. (there is probably a better way to do it instead of this join)
    Pls elaborate
    George

    Hi, TREE is not a function but PL/SQL object type I have written representing tree structure. The Oracle version is 10g.

  • Another question about the pitch slider problem

    Hi everybody!
    Anybody can answer me with the solution for my pitch slider? When i import a MP3 from itunes, press ctrl + alt + G and go to the track editor, check the 'follow tempo & pitch' and the pitch slider won't move.
    I see answers to use the AUPitch Effect, but i think it's not 'sufficient' for me... if there's an functionality, I want to use, else it's a critical bug for me...
    I'm a developer too and a bug without a solution is very very bad for the developer...
    Searching in Google, apple support threads and nothing.... anybody else?
    Best Regards!
    Vinicius P. de Souza/Brazil
    Please, sorry for my poor english!

    I don't think Mr Jobs reads this forum.
    What do you mean by "not sufficient"? The AUPitch plugin can be tuned a lot finer than the pitch slider - the only downsides I can see are (1) that it takes up one of the effects slots and (b) that two regions on the same track can't have different pitch corrections.

  • Question about problem with  file using clipping mask

    I am using Photoshop CS6.  I purchased a digital frame with a clipping mask on Etsy.   When I go to insert the picture into the frame using the clipping mask the picture continues to show through the edges of the frame (as shown in the picture).  I have tried locking the layer but it doesn't work.  Any suggestions?

    Try this, move layer 2 below 3 don't clip them.
    With the ellipse selection tool drag out a circle that encompasses the area that the image should show
    Create a mask for the shape (make sure the shape layer is selected {now layer 2 was 3} click on the icon at the bottom of the layers panel that looks like a circle inside a square)
    You should now see your image.
    If you are stuck, capture your screen to show your progress.
    Tips for the selection tool:
    You can hold down the shift key to constrain to a circle,
    You can hold down the alt key to draw a circle selection from its center,
    You can hold down both modifier key for a perfect circle drawn from center.
    Finally you can hold down the space bar to move the selection before letting go of the mouse button.

  • Question about comparing an array of names to a hash table

    I'm still learning Powershell but feel like I have the basics now. I have a new project I'm working on and want some input as the best way to do this:
    The Problem:
    Let's say you have a list of several hundred video game titles and the dollar value of each in a text or two column CSV file.
    The example CSV file looks likes this:
    Game, Price
    Metroid, $15.00
    The Legend of Zelda!, $12.00
    Mike Tyson's Punch-Out!, $18.00
    Super Mario Bros., $16.00
    Kung Fu, $7.00
    You have another list of just the video game titles, this most likely is just a text file with each title listed on its own line.
    The example text file looks like this:
    Kung Fu
    Metroid
    Mike Tysons Punch-Out
    Legend of Zelda
    What I think would happen in the Script:
    Use import-csv and create a hash table that will contain a key = Title and the value = the price.
    Use import-csv and create an array for the title names.
    Foreach loop through each Game Title and match the value against the Hash Table, if there's a match found, put that into another array that will later add all prices of each item and give you a total sum.
    The challenge:
    So far when I try and do one line examples of comparing names against the hash table it seems to only work with exact name matches. In the above example I've purposely made the game titles slightly different because in the real world people just write things
    differently.
    With that said, I've tried using the following single line to match things up and it only seems to work if the values match exactly.
    $hash_table.ContainsKey("Game Title")
    Is there a regex I should use to change the input of the game titles before creating the hash table or doing the compare? Is there another matching operator that is better and matching with String values that have slightly different grammar. An example would
    be the game "The Legend of Zelda". Sometimes people just put "Legend of Zelda", that's close but not exact. I think using a regex to remove extra spaces and symbols would work, but what about for matching of words or letters??
    Any ideas would be very helpful and thanks!

    There's no pat answer for this.
    You can create an array from the hash table keys:
    $hashtable = @{"The Legend of Zelda" = 15.00}
    $titles = $hashtable.getenumerator() | select -ExpandProperty Name
    And then test that using a wildcard match:
    $titles -like "*Game Title*"
    and see if it returns just one match.  If it does then use that match to do your lookup in the hash table.  If it returns 0, or more than one match then you need to check the spelling or qualify the title search some more.
    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

  • Question about Automator using Spaces.

    I don't think this is the right place for this question, but I figured I am probably going to need to write an applescript to do what I want, so I decided to put it here.
    I have an automation to open some Word documents on my idisk, then open Dictionary, then open Safari with some tabs. But the problem comes in with spaces. I have Word and Dictionary open on Space 1 and Safari open in Space 3. When the automation ends, I end on Space 3 and would like to know how I add a function to set the focus back to Space 1. It's not all that detrimental to the success of my Automation, but I only use Safari for research and would like to focus to end back on word. I have tried switching which apps open first, but I still end up on the 3rd Space.
    My other question is, where can I go for reference to commands in Xcode and AppleScript that deal with Spaces? I love using that function and I have had some ideas about scripts that could help me with them, but I don't even know were I would start with commands.

    There are several solutions to this.
    The first option would be to send the appropriate key command to switch to space 1. If you've left your preferences as the defaults then you can:
    <pre class=command>tell application "System Events" to keystroke "1" using {control down}</pre>
    Which will send a Ctrl-1 and switch to space 1.
    An alternative, which may be even better, is to activate the application you want to be frontmost:
    <pre class=command>tell application "Microsoft Word" to activate</pre>
    This should activate the application and switch to that application's space.

  • Another question about a VI I obtained from a NI forum.

    The append_column VI attached below has two FOR LOOPs. When this VI is executed The first FOR LOOP executes 10 times as indicated by the CONSTANT 10 wired to the [COUNT] or [N]. My question falls after the first FOR LOOP is complete. How is the second FOR LOOP activated. I thought the [N] had to be wired for the FOR LOOP to execute? In this VI the second FOR LOOP doesn't have the [N] wired to anything so how does it know to execute 10 times which it does?
    Attachments:
    append_column.vi ‏47 KB

    Hi
    Actually there is a another way to set the number of times a FOR loop should run, which is illustrated by the VI in question.
    Any array input to the FOR loop may used to set the number of times to run. Look at the string array input of the VI, inside the FOR loop the array is not an array anymore, but rather simple strings, this input is set to "Enable indexing". Inside the loop the individual elements of the array is automatically extracted from the array one at a time. I.e the first run of the loop extracts the first element of the array, the second run of the loop gets the second element of the array. The FOR loop will run until all the elemnts of the array has been "read".
    You win twice with this design, first, You don't have to know how many times to
    run the loop, it will always run as many times as there are elements in the array. Second, You don't have to index the array inside the loop with array indexing tools, it is automatically done by the FOR loop.
    You enable / disable this feature by right-clicking the array connection on the loop and selsecting enable/disable array.
    tomcat

  • Another question about generics

    Consider the following hierarchy of classes:
    class Fruit {...}
    class Orange extends Fruit {...}
    class Apple extends Fruit{...}
    Now I need to declare a collection wherein I could store any type of Fruit (including its derivated classes), but also gather some fruits.
    I hare read that for reading I need to declare the collection as follows:
    Set<? extends Fruit> fruitSet = new HashSet<Fruit>();
    and for writing I need the following declaration:
    Set<? super Fruit> fruitSet = new HashSet<Fruit>();
    My question is, is there an efficient way to declare the collection so that both operations be feasible in the class? In the current version, I use generic method and need to re-cast for some calls.
    Can anyone help?

    What they're talking about is the fact that parameterized types are not covariant. You can't treat a List<Rectangle> as a List<Shape> because they are not the same thing. Arrays on the other are covariant, you can treat a Rectangle[] as a Shape[].
    No, with your example it will not generate a compile time error, but I do see what you're getting at.
    public void readFruit(Set<Fruit> fSet) {
        // snip
    Set<Apple> fruits = new HashSet<Apple>();
    readFruit(fruits); // error because Set<Apple> is NOT a Set<Fruit>It has nothing to do with whether or not fruits contains Apples and Oranges, it's how fruits is declared. While a Set<Fruit> may contain Apples and Oranges a Set<Orange> is not a Set<Fruit>. So if you attempt to pass a Set<Orange> to a method that takes a Set<Fruit> you might as well be trying to pass an int to a method that accepts a String, they're not the same, there is no is-a relationship. So this is what you do:
    public void readFruits(Set<? extends Fruit> fSet) {
        // snip
    // All work because it will take any Set<E> where E extends Fruit.
    readFruits(new HashSet<Fruit>());
    readFruits(new HashSet<Apple>());
    readFruits(new HashSet<Orange>());What this says is that fSet can be any Set<E> where E is a subtype of Fruit. It doesn't matter what implementations the Set actually contains. If it's a Set<Fruit> and it contains Apples, it doesn't matter, it's simply allowing you to pass a Set<Apple> or Set<Orange> as opposed to only being able to pass a Set<Fruit>.

  • Yet another question about 24-bits

    I have just combined an Echo Audio Indigo IO with Adobe Audition 1.5 in hopes to have a reasonably good laptop recorder. That need is met quite well.
    There are a number of discussions about bit depth in these forums. The answers become obfuscated by internal conversions done in audio cards, software, and Windows drivers. My current interest is simply how to get 24 bits of unadultered data from a D/A convertor to a data file using Audition. This data will be used to analyze pitch, frequency and intonation and any changes to the data will affect the results.
    Both the Indigo IO and Audition claim 24-bit support and I am convinced that both meet these claims fully. In spite of this there is no evidence that the card, Windows, and the software together will actually meet this claim without a 16-bit conversion along the line. What really matters is whether or not 24-bits of audio can travel from the card to the data file without any changes.
    Question 1: In Audition 1.5 for Windows under "Options/Device Properties/Wave In/Supported Formats" for the Indigo IO the highest density recording listed is 16-bit stereo at a 96K sample rate. What properties do other users find for their 24-bit cards?
    Question 2: The wave programming calls (waveInGetDevCaps) don't include capability definitions for anything beyond 16-bit depth at a 96K sample rate. Where in Windows is there evidence of true support for anything greater than 16-bit Audio?
    Question 3: What software is there that will go directly to the sound card or driver and write 24 unadultered bits to a file?

    I had trouble setting up my 24bit/96k ADAC to record 24-bit in audition. The best way to be sure audition is getting the 24bit samples as 24 bits is to check the status bar when recording. If it says 'Recording as 24 bit' then it's all setup right. If it says 'Recording as 16 bit' then the 32-bit float driver or the 24-bit driver reported an error and audition tried to fall back on the 16 bit version and succeeded. The problem I had was that the driver didn't handle 32-bit floats so it errored out and audition recorded as 16 bits. The only solution was to select the 24-bit option under "Options/Device Properties/Wave In(or out)".
    Just a note. A true 24-bit ADC will send 24 bits to the driver and the driver itself will convert the bits to whatever format it supports. If the driver is instructed to convert to normalized floats the software will simply do something like this:
    SampleOut = SampleIn / 8388608.0;
    This doesn't add any coloration to the audio because a float is really just a 24 bit integer with 8 bits added to tell the FPU where to put the decimal point. Converting down from 24-bits of course degrades quality and converting from 24 bits up to a true 32 bit integer would NOT add any quality to the audio. When stored in a file, 24 bits is 24 bits whether its a float or an integer.
    >Question 2:The wave programming calls (waveInGetDevCaps) don't include capability definitions for anything beyond 16-bit depth at a 96K sample rate. Where in Windows is there evidence of true support for anything greater than 16-bit Audio?
    The website showing waveInGetDevCaps function information doesn't show all the possible format tags or even the sample rates. It is only showing the most compatible forms for drivers. The WAVEFORMAT and WAVEFORMATEX structures used for the drivers are also used in the 'fmt ' chunk of RIFF WAVE files. I've written a lot of software for parallel use with audition using wave files and windows and I can say from experience that when recording 24 bits with audition you're getting the full 24 bits. If your driver truly supports 24 bit samples then audition will allow you to select the 24 bit samples option under "Options/Device Properties/Wave In(or out)" and audition will display 'Recording as 24-bits' when recording. Once recorded Audition no doubt converts ALL bit depths to its internal format which I believe is 32 (or 64) bit float, and if you don't process the file and wish to save as 24 bit integers then the samples saved will be exactly what the ADC sent to the driver.

Maybe you are looking for

  • About using categories and perspectives for new user

    We are just beginning a conversion and upgrade project to convert our Web site to Oracle Portal. I'm trying to get a good handle on some different things we need to resolve as part of the project. One of the first decisions is using Categories and Pe

  • "Sorry, a serious error has occurred" in CS6

    Hello, I have recently been receiving this error message alot while working on a project. "Sorry, a serious error has occurred that requires Adobe Premiere Pro to shut down. We will attempt to save your current project." It makes rename the project I

  • Get highest value from 1 of the tables in a join between 2 tables

    Hi, i want to join 2 table: - SALES - MATERIAL These table are joined by: - Material ID - Sales date -> start date The problem is that it could be that 1 sales can have 2 records in material, but what i need to have is the latest record from material

  • HP all-in-one c301 will not save scanned doc in Mavericks upgrade

    I have recently installed the free OS X Mavericks upgrade to my Macbook Pro.  My HP all-in-one c301 will scan, but the scans do not save.  The saved pdf looks like a bunch of gray lines when I reopen the saved file.  Has anyone already found a work a

  • Sound iPad not working

    Why sound on my iPad is not working? I do setting ON, but still not working