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

1 Ansicht (letzte 30 Tage)
Hidd_1
Hidd_1 am 5 Apr. 2021
Bearbeitet: Rik am 26 Apr. 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.

Akzeptierte Antwort

David Hill
David Hill am 5 Apr. 2021
Bearbeitet: David Hill am 5 Apr. 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.

Weitere Antworten (1)

Abhinav
Abhinav am 26 Apr. 2023
Bearbeitet: Rik am 26 Apr. 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

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by