[matlab]mathworks上的cody challenge题解及一些常用函数的总结(6)

UPD: 更新前是C++...更新后希望有点matlab的样子了...

Part 6. Problem 51 - Problem 60.

Problem 51. Find the two most distant points

% Given a collection of points, return the indices of the rows that contain the two points most distant from one another. The input vector p has two columns corresponding to the x and y coordinates of each point. Return ix, the (sorted) pair of indices pointing to the remotest rows. There will always be one unique such pair of points.
% 
% So if
% 
%  p = [0 0]
%      [1 0]
%      [2 2]
%      [0 1]
% 
% Then
% 
%  ix = [1 3]
% 
% That is, the two points p(1,:) and p(3,:) are farthest apart.

function ix = mostDistant(p)
mxdis = 0; ix = [1 2];
sp = size(p);
for k = 1:sp(1)
    for l = (k+1):sp(1)
        dist = sqrt((p(k,1)-p(l,1))^2+(p(k,2)-p(l,2))^2);
        if dist > mxdis
            mxdis = dist;
            ix(1) = k;
            ix(2) = l;
        end
    end
end

UPD: 可以用dist, triu函数改写成这样.

function idx = mostDistant(p)
p = triu(dist(p'));
[r c] = find(p == max(p(:)));
idx = [r c];
triu(A), 取矩阵A的上三角矩阵,其余置为0.

Problem 52. What is the next step in Conway's Life?

function B = life(A)
  B = A;
  rmove = [-1 -1 -1 0 1 1 1 0];
  cmove = [-1 0 1 1 1 0 -1 -1];
  sa = size(A);
  for r = 1:sa(1)
    for c = 1:sa(2)
      cnt = 0;
      for k = 1:8
        g = r + rmove(k); h = c + cmove(k);
        if g < 1 g = g + sa(1); elseif g > sa(1) g = g - sa(1); end
        if h < 1 h = h + sa(2); elseif h > sa(2) h = h - sa(2); end
         cnt = cnt + A(g, h);
      end
      if A(r, c) == 1
        if cnt < 2 || cnt > 3
          B(r, c) = 0;
        end
      else
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值