Dag: 7
SprÄk: Matlab
Körtid: 26 s
Orkade inte implementera nÄgot bÀttre Àn bubble-sort, sÄ hastigheten blev dÀrefter.
fid=fopen('day7.txt');
handM = [];
while ~feof(fid)
line = fgetl(fid);
handM = [handM; handNo(line)', str2double(extractAfter(line, " "))];
end
handM1 = bubbleSort(handM, @isBetter1);
Score1 = sum(handM1(:, end).*[length(handM1(:, end)):-1:1]');
handM2 = bubbleSort(handM, @isBetter2);
Score2 = sum(handM2(:, end).*[length(handM2(:, end)):-1:1]');
fclose(fid);
disp(['Task 1: ', num2str(Score1)])
disp(['Task 2: ', num2str(Score2)])
function y = isBetter1(hand1, hand2)
y = true;
a = groupcounts(reshape(hand1, [], 1));
b = groupcounts(reshape(hand2, [], 1));
if max(b)<max(a)
return
end
if numel(a)<numel(b)
return
elseif (numel(a) == numel(b)) && (max(b)==max(a))
if find(hand1>hand2, 1) < find(hand2>hand1, 1)
return
elseif isempty(find(hand2>hand1, 1))
return
end
end
y = false;
end
function y = isBetter2(hand1, hand2)
y = true;
joker1 = sum(hand1==11);
hand1(hand1==11)=1;
joker2 = sum(hand2==11);
hand2(hand2==11)=1;
a = groupcounts(reshape(hand1(hand1~=1), [], 1));
b = groupcounts(reshape(hand2(hand2~=1), [], 1));
if isempty(a)
a = 0;
end
if isempty(b)
b = 0;
end
if (max(b)+joker2)<(max(a)+joker1)
return
end
if max(numel(a), 1)<max(numel(b), 1)
return
elseif (numel(a)) == (numel(b)) && ((max(b)+joker2)==(max(a)+joker1))
if find(hand1>hand2, 1) < find(hand2>hand1, 1)
return
elseif isempty(find(hand2>hand1, 1))
return
end
end
y = false;
end
function hand = handNo(line)
hand = char(extractBefore(line, " "));
hand = strrep(hand, "A","E");
hand = strrep(hand, "T","A");
hand = strrep(hand, "J","B");
hand = strrep(hand, "Q","C");
hand = char(strrep(hand, "K","D")');
hand = hex2dec(hand');
end
function handM=bubbleSort(handM, isBetter)
swap = true;
sw=0;
while swap
swap = false;
for k = 1:length(handM(:, 1))-max(1,sw)
if isBetter(handM(k+1, 1:end-1), handM(k, 1:end-1))
temp = handM(k, :);
handM(k,:) = handM(k+1,:);
handM(k + 1,:) = temp;
swap = true;
end
end
sw=sw+1;
end
end