Cody Problem 38. Return a list sorted by number of occurrences

1 次查看(过去 30 天)
I found difficulties with the Problem 38 on Cody here is my solution:
function y = popularity(x)
[a,b]=size(x);
s=ones(a,b);
for i=1:b
for j=1:b
if i~=j
if x(i)==x(j)
s(i) = s(i) +1;
end
end
end
end
[A,o]= sort(s,'descend');
for k =1:b
L(k)=x((o(k)));
end
y= unique(L,'stable');
end
Unfortunately it doesn't work for the second case, can anyone help me with that!
Thanks in advance.

采纳的回答

David Hill
David Hill 2021-4-5
编辑:David Hill 2021-4-5
Take a look at the functions, histcounts(), sort(), and unique(). By combining these functions you can answer the problem in a few lines without any loops.

更多回答(1 个)

Abhinav
Abhinav 2023-4-26
编辑:Rik 2023-4-26
function output_array = popularity(input_array)
%% First make unique array
unique_input_array = unique(input_array);
%% Create occurences - keys pair array
table_occurence = zeros(length(unique_input_array),2);
table_occurence(:,2) = unique_input_array';
for i = 1:length(unique_input_array)
occurrence = numel(find(input_array == unique_input_array(i)));
table_occurence(i,1) = occurrence;
end
%% Sort by occurences in descending order
sorted_table = sortrows(table_occurence,'descend');
occurences = sorted_table(:,1);
keys = sorted_table(:,2);
%% Find keys that have same occurences and store sorted keys in new array
occurences_total = unique(occurences,'stable');
output_array = [];
for j = 1:length(occurences_total)
[row,~] = find(occurences == occurences_total(j));
aa = sort(keys(row));
output_array = [output_array, [aa']];
end
end

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by