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

1 vue (au cours des 30 derniers jours)
Hidd_1
Hidd_1 le 5 Avr 2021
Modifié(e) : Rik le 26 Avr 2023
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.

Réponse acceptée

David Hill
David Hill le 5 Avr 2021
Modifié(e) : David Hill le 5 Avr 2021
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 commentaire
Hidd_1
Hidd_1 le 5 Avr 2021
Modifié(e) : Hidd_1 le 5 Avr 2021
It worked Thank you!

Connectez-vous pour commenter.

Plus de réponses (1)

Abhinav
Abhinav le 26 Avr 2023
Modifié(e) : Rik le 26 Avr 2023
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

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by