Cody Problem 38. Return a list sorted by number of occurrences
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Hidd_1
el 5 de Abr. de 2021
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.
0 comentarios
Respuesta aceptada
David Hill
el 5 de Abr. de 2021
Editada: David Hill
el 5 de Abr. de 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 comentario
Más respuestas (1)
Abhinav
el 26 de Abr. de 2023
Editada: Rik
el 26 de Abr. de 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
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!