您的位置:首页 > 编程语言 > MATLAB

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

2013-08-25 18:36 671 查看
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
if cnt == 3
B(r, c) = 1;
end
end
end
end
end

matlab里本身有一个函数life,也是关于这个问题的。不过没仔细看,不知道能不能直接用。

UPD: 看到了非常漂亮的解法,这应该也是图像处理里面常用的手段。利用卷积求出周围格子的和。

function B = life(A)
B = convn(A([end,1:end,1],[end,1:end,1]), ones(3), 'valid');
B = B == 3 | A & B == 4;


Problem 53. Duplicates

% Write a function that accepts a cell array of strings and returns another cell array of strings with only the duplicates retained.
%
% Examples:
%
%  Input  strs = {'a','b','a'}
%  Output dups is 'a'
%
%  Input  strs = {'a','b','c'}
%  Output dups is Empty cell array: 0-by-1

function dups = duplicates(strs)
dups = {};
for k = 1:length(strs)
for l = (k+1):length(strs)
if strs{k} == strs{l}
vis = 0;
for m = 1:length(dups)
if dups{m} == strs{k}
vis = 1;
end
end
if ~vis
dups = [dups strs(k)];
end
end
end
end

strs{k}是一个字符串,strs(k)还是一个cell。

UPD: 可以用cellfun改写成这样.

function dugs = duplicates(strs)
u = unique(strs);
dugs = u(cellfun(@(x) sum(strcmp(x, strs)) > 1, u));


Problem 54. Maximum running product for a string of numbers

% Given a string s representing a list of numbers, find the five consecutive numbers that multiply to form the largest number. Specifically, given s return the index i to the first of those five numbers. You can assume the maximum product is unique.
%
% Example:
%
%  Input  s = '123454321'
%  Output i = 3
%
% since the product of [3 4 5 4 3] is larger than any of the alternatives.
%
% Inspired by Problem 8 from Project Euler

function i = running_product(s)
i = 1; mxmul = 0;
for k = 1:(length(s)-4)
mul = 1;
for l = k:(k+4)
mul = mul*(s(l) - '0');
end
if mul > mxmul
mxmul = mul;
i = k;
end
end

UPD: 利用arrayfun改写。

function ans = running_product(s)
[~, ans] = max(arrayfun(@(x) prod(s(x:x+4)-'0'), 1:length(s)-4));


Problem 55. Counting Sequence

% Given a vector x, find the "counting sequence" y.
%
% A counting sequence is formed by "counting" the entries in a given sequence.
%
% For example, the sequence
%
%  x = 5, 5, 2, 1, 1, 1, 1, 3
%
% can be read as
%
%  Two 5's, one 2, four 1's, one 3
%
% which translates to
%
%  y = 2, 5, 1, 2, 4, 1, 1, 3
%
% So y is the counting sequence for x.
%
% For this problem, all elements in the sequences x and y will be in the range from 1 to 9.

function y = CountSeq(x)
x = [x 0]; y = [];
k = 1;
while x(k) ~= 0
now = x(k); cnt = 0;
while now == x(k)
cnt = cnt + 1;
k = k + 1;
end
y = [y cnt now];
end

UPD: 可以用diff函数改写。

function y = CountSeq(x)
idx = find(diff([x nan]));
y = reshape([diff([0 idx]); x(idx)], 1, []);


Problem 56. Scrabble Scores

% Given a word, determine its score in Scrabble.
%
% The input string will always be provided in lower case. Use the English language Scrabble letter values as found in this Wikipedia reference: letter distributions for English.
%
% Example:
%
%  Input  str = 'matlab'
%  Output score is 10.

function score = scrabble_score(str)
cnt = ones(1, 128); score = 0;
cnt('k') = 5;
cnt('j') = 8;
cnt('x') = 8;
cnt('q') = 10;
cnt('z') = 10;
cnt('b') = 3;
cnt('c') = 3;
cnt('m') = 3;
cnt('p') = 3;
cnt('f') = 4;
cnt('h') = 4;
cnt('v') = 4;
cnt('w') = 4;
cnt('y') = 4;
cnt('g') = 2;
cnt('d') = 2;
sum(cnt(str));


Problem 57. Summing Digits within Text

% Given a string with text and digits, add all the numbers together.
%
% Examples:
%
%  Input str = '4 and 20 blackbirds baked in a pie'
%  Output total is 24
%
%  Input str = '2 4 6 8 who do we appreciate?'
%  Output total is 20

function total = number_sum(str)
total = 0;
R = regexp(str, '\d+', 'match');
for k = 1:length(R)
now = str2num(R{k});
total = total + now;
end

'\d'表示数字,'+'表示出现一次或多次。

UPD: matlab的写法。

function ans = number_sum(str)
sum(cellfun(@(x) str2double(x), regexp(str, '\d+', 'match')));


Problem 58. Tic Tac Toe FTW

% Given a tic tac toe board:
%
%     1 represents X
%     0 represents empty.
%     -1 represents O
%
% It is X's move. If there is an immediate win possibility, choose a square for an immediate win. Otherwise return 0.
%
% Return absolute index of the square of choice. If multiple square are valid, return them in order.
%
% Example:
%
%  Input  a = [ 1  0  1
%              -1  1  0
%               0 -1 -1]
%  Output wins is [4 8]

function wins = ticTacToe(a)
idx = find(a == 0);
wins = [];
for l = 1:length(idx)
    a(idx(l)) = 1;
    flag = 0;
    for k = 1:3
        row = a(k, 1) + a(k, 2) + a(k, 3);
        col = a(1, k) + a(2, k) + a(3, k);
        if row == 3 || col == 3
            flag = 1;
        end
    end
    if a(1, 1) + a(2, 2) + a(3, 3) == 3 || a(1, 3) + a(2, 2) + a(3, 1) == 3
        flag = 1;
    end
    if flag == 1
        wins = [wins idx(l)];
    end
    a(idx(l)) = 0;
end
if isempty(wins)
    wins = 0;
end

Problem 59. Pattern matching

% Given a matrix, m-by-n, find all the rows that
4000
have the same "increase, decrease, or stay same" pattern going across the columns as the first row does. Do not list the row as a match to itself.
%
% Example:
%
%  Input  a = [1 2 3 0
%              5 6 7 9
%              2 7 8 7]
%  Output b is 3
%
% since the third column follows the increase-increase-decrease pattern used in vector a.

function b = matchPattern(a)
sa = size(a); b = [];
for k = 2:sa(1)
flag = 1;
for l = 2:sa(2)
if ~((a(1,l)>a(1,l-1) && a(k,l)>a(k,l-1)) || (a(1,l)<a(1,l-1) && a(k,l)<a(k,l-1)) || (a(1,l) == a(1,l-1) && a(k,l) == a(k,l-1)))
flag = 0;
end
end
if flag
b = [b, k];
end
end

UPD: 用sign和diff函数改写。

function ans = matchPattern(a)
first = sign(diff(a(1,:)));
find(arrayfun(@(x) all(sign(diff(a(x,:))) == first), 2:size(a,1)))+1;
end


从这开始用vim写了...

Problem 60. The Goldbach Conjecture

function [p1,p2] = goldbach(n)
p1 = n;
p2 = n;
for k = 2:n
if isprime(k) && isprime(n - k)
p1 = k; p2 = n - k;
break;
end
end
end

无聊的模拟题开始多起来了...没写注释的都是在网页上敲的...

如果有更为简单的方法,请给我留言,谢谢!

允许转载,转载请注明出处: http://blog.csdn.net/lkjslkjdlk/article/details/10306527
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息