Project Euler: Problem 11
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Nguyen Huy
am 14 Jul. 2021
Bearbeitet: John D'Errico
am 16 Jul. 2021
%I have the solution for this problem : https://www.mathworks.com/matlabcentral/cody/groups/50/problems/42936-project-euler-problem-11-largest-product-in-a-grid/solutions/new
% the problem is inspired by Project Euler 11
%It pass 2 test but failed in test 3,i dont know why
%here is my code
function y = PE11(A,k)
[b c]=size(A)
m = 0;
dx = [1, 0, 1,-1];
dy = [0, 1, 1,-1];
%check product on horizontal
for y=1:b
for x=1:c-k
p=1;
for i=0:k-1
p=p*A(y+i*dy(1),x+i*dx(1));
end
m=max(p,m);
end
end
%check product on vertical
for y=1:b-k
for x=1:c
p=1;
for i=0:k-1
p=p*A(y+i*dy(2),x+i*dx(2));
end
m=max(p,m);
end
end
%check product on diagonal form right to left
for y=1:b-k
for x=1:c-k
p=1;
for i=0:k-1
p=p*A(y+i*dy(3),x+i*dx(3));
end
m=max(p,m);
end
end
%check product on diagonal form left to right
for y=b:-1:k
for x=c:-1:k
p=1;
for i=0:k-1
p=p*A(y+i*dy(4),x+i*dx(4));
end
m=max(p,m);
end
end
y=m;
end
1 Kommentar
John D'Errico
am 16 Jul. 2021
Don't add an answer pleading for help. That is not an answer. (I've deleted your non-answer.)
Akzeptierte Antwort
John D'Errico
am 16 Jul. 2021
Bearbeitet: John D'Errico
am 16 Jul. 2021
As far as why it failed test case #3, perhaps you need to write better, more efficient code. The code you wrote will be a bit of a CPU hog, and I recall the Cody problems time out for excessively slow solutions. (I've not looked carefully at your code. But even if it does work, it will get a really poor Cody score. The scoring algorithm for Cody hates massively nested loops when compared to more elegant solutions.)
Since the third test case for that Cody problem is significantly larger than the others, and you claim your code worked for cases 1 and 2, I'll postulate your code is just slow as mollasses on a winter day.
Could your code be used to solve a real PE problem? NO WAY! So you probably need to find a solution that does not use massively nested loops. I can think of at least one, ok, maybe two solutions. (And while I will not tell you how to solve a problem that was put there to make you think, just telling you that massively nested loops are a bad idea might be enough of a clue.)
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical 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!