MATLAB Answers

Project Euler: Problem 11

조회 수: 5(최근 30일)
Nguyen Huy
Nguyen Huy 2021년 7월 14일
편집: John D'Errico 2021년 7월 16일
% 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
John D'Errico
John D'Errico 2021년 7월 16일
Don't add an answer pleading for help. That is not an answer. (I've deleted your non-answer.)

댓글을 달려면 로그인하십시오.

채택된 답변

John D'Errico
John D'Errico 2021년 7월 16일
편집: John D'Errico 2021년 7월 16일
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개)

제품


릴리스

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by