x404.co.uk http://www.x404.co.uk/forum/ |
|
Quick question http://www.x404.co.uk/forum/viewtopic.php?f=4&t=17345 |
Page 1 of 1 |
Author: | Fogmeister [ Wed Oct 03, 2012 5:33 pm ] |
Post subject: | Quick question |
Not a code question, just a concept question... I give you two arrays and they both contain strings. I want you to return to me an array that contains strings common to both arrays. How would you do it? My next post will be the best answer I could come up with in about 3 minutes on the phone to Apple. |
Author: | Fogmeister [ Wed Oct 03, 2012 5:37 pm ] |
Post subject: | Re: Quick question |
Take both array (array1 and array2) and sort their contents alphabetically. Now store two indices i (for array1) and j (for array2). Start at i = 0 and iterate through j from j = 0. When you find a value j where array2[j] is the same string as array1[i] then add that into a third array (resultArray) and increment i by 1 and continue iterating through j. No repeat this until you reach the end of array2. When you reach the end of array2 then resultArray will be an array of all strings that occurred in both array1 and array2. |
Author: | jonbwfc [ Wed Oct 03, 2012 6:27 pm ] |
Post subject: | Quick question |
It would probably be quicker while you're sorting alphabetically to generate an index of both tables by first letter, so you only need to iterate your search through strings where at least the first letters match. Course you could do that all the way through but I'm assuming the strings are of arbitrary length. Or do some kind of fast checksum of each of the strings and compare those - but you'd have to test whether checksum generation & comparison was quicker than just plain string comparisons. |
Author: | EddArmitage [ Wed Oct 03, 2012 6:40 pm ] |
Post subject: | Re: Quick question |
There's all sorts of questions I'd want to know first that'd influence my approach:
|
Author: | forquare1 [ Wed Oct 03, 2012 11:53 pm ] | ||||||||||||||||||
Post subject: | Re: Quick question | ||||||||||||||||||
What language is it in? If I could do it in Perl I think I'd do something like: 1. Convert array 1 to a hash. 2. Iterate through array 2 and see if it exists in the hash. Something like:
The code above runs on my iMac in the following time:
Dict and DictRev are files that contain 173122 words. They both contain the same words but DictRev is reversed. Sorting DictRev by general numeric value (sort -g) gets a similar process time. If I had to do it in Java, I would probably put array1 into a hash table creating hashes of each word, then iterate through array2 creating a hash and seeing if it existed i the hash table. Not sure on the inbuilt data structures of Cocoa, so not sure on my approach using Objective-C. |
Page 1 of 1 | All times are UTC |
Powered by phpBB® Forum Software © phpBB Group https://www.phpbb.com/ |