This question already has answers here:
Getting Top 10 Highest Numbers From Array?
(5 answers)
Closed 8 years ago.
I have a bunch of NSArrays filled with numbers. Is there anyway that I can somehow grab a specific number, specifically like:
Third highest number in array, or 24th highest number in array?
But I don't want to just grab the number, I also need a reference to the index it was in the array as well, if that can be retained in the process.
Thanks.
Third highest number in array, or 24th highest number in array?
Create a temporary copy of the array and sort it ascending.
Get the number at index 3-1 or 24-1.
I also need a reference to the index it was in the array as well
Now use indexOfObject: or indexOfObjectIdenticalTo: to get the actual index.
Starting with the sorted numbers array from my answer here Getting Top 10 Highest Numbers From Array? :
NSUInteger wanted = 24 or anything;
NSUInteger count = 0;
NSNumber* previous = nil;
for (NSDictionary* entry in numbers)
{
if ( wanted == 1 ) return entry;
if (previous == nil)
{
// first entry
previous = entry[#"number"];
++ count;
continue;
}
// same number? skip it.
if ( entry[#"number"] isEqualTo: previous ) continue;
// if we get here, we found a different number we may be interested in
++ count;
if ( count == wanted ) return entry;
}
// nothing found
return nil;
The result is a line in the numbers array from the previous question. An array of the form #[ #"number" : #<number>, #"parent" : <source array> ].
Related
This question already has answers here:
Find the majority element in array
(26 answers)
Closed last month.
This post was edited and submitted for review 18 days ago.
Find number which is occur more than N/3 times in array. not N/2 times? just look at question first.
Without Using Moore's Algorithms.
You will need to take into account the maximum (What is your worst scenario).
Unless you have not checked all elements in your array, 2 can compete till the end.
Lets assume you have the following array:
[1,2,3,1,2,2,1,2]
when you are at element 4, 1 is the winner with a count of 2.
at element 5, 1 & 2 are equal represented.
at element 6, 2 is the winner with a count of 3.
etc.
Based on this example you can see you will need to run over all of teh elements one time: O(n)
int majorityElement(int a[], int size){
// your code here
//Moore Voting Algorithm
//Finding the candidate element
int count = 1, res = 0;
for(int i=1;i<size;i++){
if(a[i]==a[res]) count++;
else count--;
if(count==0){
res = i;
count = 1;
}
}
//Checking
count = 0;
for(int i=0;i<size;i++){
if(a[i]==a[res]) count++;
}
return count>size/2? a[res]: -1;
}
Given that a number can contain only digits from 1 to 8 (with no repetition), and is of length 8, how can we hash such numbers without using a hashSet?
We can't just directly use the value of the number of the hashing value, as the stack size of the program is limited. (By this, I mean that we can't directly make the index of an array, represent our number).
Therefore, this 8 digit number needs to be mapped to, at maximum, a 5 digit number.
I saw this answer. The hash function returns a 8-digit number, for a input that is an 8-digit number.
So, what can I do here?
There's a few things you can do. You could subtract 1 from each digit and parse it as an octal number, which will map one-to-one every number from your domain to the range [0,16777216) with no gaps. The resulting number can be used as an index into a very large array. An example of this could work as below:
function hash(num) {
return parseInt(num
.toString()
.split('')
.map(x => x - 1), 8);
}
const set = new Array(8**8);
set[hash(12345678)] = true;
// 12345678 is in the set
Or if you wanna conserve some space and grow the data structure as you add elements. You can use a tree structure with 8 branches at every node and a maximum depth of 8. I'll leave that up to you to figure out if you think it's worth the trouble.
Edit:
After seeing the updated question, I began thinking about how you could probably map the number to its position in a lexicographically sorted list of the permutations of the digits 1-8. That would be optimal because it gives you the theoretical 5-digit hash you want (under 40320). I had some trouble formulating the algorithm to do this on my own, so I did some digging. I found this example implementation that does just what you're looking for. I've taken inspiration from this to implement the algorithm in JavaScript for you.
function hash(num) {
const digits = num
.toString()
.split('')
.map(x => x - 1);
const len = digits.length;
const seen = new Array(len);
let rank = 0;
for(let i = 0; i < len; i++) {
seen[digits[i]] = true;
rank += numsBelowUnseen(digits[i], seen) * fact(len - i - 1);
}
return rank;
}
// count unseen digits less than n
function numsBelowUnseen(n, seen) {
let count = 0;
for(let i = 0; i < n; i++) {
if(!seen[i]) count++;
}
return count;
}
// factorial fuction
function fact(x) {
return x <= 0 ? 1 : x * fact(x - 1);
}
kamoroso94 gave me the idea of representing the number in octal. The number remains unique if we remove the first digit from it. So, we can make an array of length 8^7=2097152, and thus use the 7-digit octal version as index.
If this array size is bigger than the stack, then we can use only 6 digits of the input, convert them to their octal values. So, 8^6=262144, that is pretty small. We can make a 2D array of length 8^6. So, total space used will be in the order of 2*(8^6). The first index of the second dimension represents that the number starts from the smaller number, and the second index represents that the number starts from the bigger number.
I have a .mat file that contains data from the years 2006-2100. Each year, there is a different number of lines. I need to count how many lines are 2006, how many are 2007, etc.
The set up, by column, is: Year, Month, Day, Lat, Long
I just want to count the number of rows containing the same Year entry and get an array back with an array containing that info.
I'm thinking a for or while loop should work, but I don't know how to right it.
If we assume your data are in a numeric matrix, you can just do:
num_lines2006 = sum(data(:,1)==2006);
data2006 = data(data(:,1)==2006),:);
If you want to add a column with number of rows for corresponding year, here is a solution with a loop:
for k=size(data,1):-1:1
num_year(k,1) = sum(data(:,1)==data(k,1));
end
data = [data num_year];
Here is a solution without loop:
[unq_year,~,idx] = unique(data(:,1),'stable');
num_year = grpstats(data(:,1),unq_year,#numel);
data = [data num_year(idx)];
To count numeric entries, you may want to use histc
years = unique(data(:,1);
counts = histc(data(:,1),years);
Since you just want to count the number of rows you could just write something simple like:
years = unique(data(:, 1));
counts = arrayfun(#(year) nnz(data(:, 1) == year), years);
years contains the unique years, and numRows the number of times they are found.
You could also use a one-liner inspired by Jonas' answer:
[counts, years] = hist(data(:,1), unique(data(:,1))');
I have an array of objects. Each object has property "date" and "title".
I want to populate sectioned UITableView with those items like:
Section 1 - 2012.06.12 (taken from object.date)
Cell 1.1: Title 1 (taken from object.name)
Cell 1.2: Title 2
Cell 1.3: Title 3
...
Section 2 - 2012.06.13
Cell 2.1: Title 1
Cell 2.2: Title 2
..
Section 3 ..
I can do that by manually creating 1..n NSMutableArrays for all date combinations and filling them with object.name values. But the problem is I do not know how many date combinations there are, so it should be done dynamically. Also, the date property can repeat in different objects
My object structure is:
Object
-NSDate - date
-NSString - title
UPD:
I was thinking if it is possible to create NSDictionary, where the key would be my date and the object would be NSArray, which contains all my items for the key-date. But I do not know how to do that dynamically.
I hope I explained my question clearly enough.
Thank you in advance!
You can create arrays based on date.You have array of objects, so iterate through this array of objects to get distinct dates, as follows:
for(int i =0;i<[objectsArr count];i++)
{
if(![newDateArr containsObject:[objectsArr objectAtIndex:i].date])
{
[newDateArr addObject:[objectsArr objectAtIndex:i].date];
}
NSMutableArray *newTitleArray = [newTitleDictionary objectForKey:#"[objectsArr objectAtIndex:i].date"];
if(newTitleArray != nil)
{
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
else
{
newTitleArray = [[[NSMutableArray alloc] init] autorelease];
[newTitleArray addObject:[objectsArr objectAtIndex:i].title];
}
[newTitleDictionary setValue:newTitleArray forKey:#"[objectsArr objectAtIndex:i].date"];
}
where newTitleDictionary and newDateArr are declare outside this method.Now you can use both is newTitleDictionary and newDateArr to populate tableview.
If I understand you correctly, you want to put an object into an array and then use that array to populate a table view?
Just add the date object each time to the NSMutableArray.
[myArray addObject:dateObject];
Then when it comes to populating the table view..
DateObject *newDateObj = [myArray objectAtIndex:index];
I hope this helps and I understood your question
EDIT To answer now I understand a bit more.
Step 1
Check through the existing array of dates and see if there are any that match maybe by iterating through it using a for loop. Search online for how to compare NSDate.
Step 2 If it doesn't match any then insert it into the array as an array with just that date on it's own so the array count will be one. If it does match then insert it into the array along with that one making the array count 2 or more.
Step 3 When it comes to declaring the section amount for the table just return the dateHolderArray count.
Step 4 When declaring the amount of rows in each section, return the array count for the array thats inside the dateHolderArray.
Step 5 Display the content when it comes to populating the cells with information. It becomes just a task of getting the dates from the arrays using the section ids and row ids.
This is how I would do it, there are probably many other methods. Any questions just ask
i am trying to add individual integers to a certain array
my array is in this form
array= number +1
how can i make lets say number be a array = 2 +3 +1
where 2 and 3 are two different distinct obhects that should be commutatively added.
i hope i am clear. I dont want the numbers to be added so that the aboce equations would equal 0. i want it to be equal to 2 then 3 then 1....
NSMutableArray????
Do something like this:
int d = 0;
for (d = 0; i <100; i++)
{
[array addObject:[[NSString alloc] initWithFormat:#"%d", d]];
}
or whatever you want it to be
edit:
To add the numbers, just use intvalue