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

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

2013-09-29 00:33 981 查看
Part 8. Problem 71 - Problem 80.

前几天把暑假剩的两道题过了,把cody challenge做完了。最近快放国庆了,又有大段空闲时间了,白天学学算法,晚上把这个坑填了...

后面这些代码都重写了。

Problem 71. Read a column of numbers and interpolate missing data

% Given an input cell array of strings s, pick out the second column and turn it into a row vector of data. Missing data will be indicated by the number 9999. If you encounter missing data, you should perform linear interpolation to the nearest accurate data points (missing data will not occur in the first or last element).
%
% The first row is always descriptive text. So if the input cell array s is
%
%  s = { ...
%     'Day  Temp'
%     '  1   -5'
%     '  2   19'
%     '  3   1'
%     '  4   9999'
%     '  5   3'};
%
% then the output variable t is the following row vector.
%
%  t = [-5 19 1 2 3];
%
% Here's an example of real-world data.

function ans = read_and_interp(s)
s = str2num(char(s(2:end)));
id = (s(:,2) ~= 9999);
interp1(s(id,1), s(id,2), s(:,1))';
end

先找出所有有效的数据点,然后用interp1来计算出缺失点的值。

Problem 72. Interpolator

% You have a two vectors, a and b. They are monotonic and the same length. Given a value, va, where va is between a(1) and a(end) find the a(n), a(n+1) that flank it. Now interpolate the value, vb, such that it is proportionally between b(n) and b(n+1).
%
% va can land exactly on a value of a.

function ans = interpolator(va, a, b)
interp1(a, b, va, 'linear');
end

题目要求的是实现线性拟合的功能。给出两个序列{ai}和{bi},使得b = f(a)。要求的是在某一点f(x)的值。

interp1就是实现这样功能的函数。当然它不仅可以线性拟合,还可以用别的方式拟合。

Problem 73. Replace NaNs with the number that appears to its left in the row

% Replace NaNs with the number that appears to its left in the row.
%
% If there are more than one consecutive NaNs, they should all be replaced by the first non-NaN value to the immediate left of the left-most NaN. If the NaN is in the first column, default to zero.
%
% For example, if
%
% x = [NaN  1   2  NaN NaN 17  3  -4 NaN]
%
% then
%
% y = [ 0   1   2   2   2  17  3  -4  -4]

function x = replace_nans(x)
for i = find(isnan(x))
if i == 1
x(i) = 0;
else
x(i) = x(i-1);
end
end
end

对每个NaN替换为它左边第一个不为NaN的数。这里还是递推比较简洁。

Problem 74. Balanced number

% Given a positive integer find whether it is a balanced number. For a balanced number the sum of first half of digits is equal to the second half.
%
% Examples:
%
%  Input  n = 13722
%  Output tf is true
%
% because 1 + 3 = 2 + 2.
%
%  Input  n = 23567414
%  Output tf = true
%
% All palindrome numbers are balanced.
%
% This is partly from Project Euler, Problem 217.

function ans = isBalanced(n)
n = num2str(n); hf = floor(length(n)/2);
sum(n(1:hf)) == sum(n(end-hf+1:end));
end

给出一个数字,判断其前半部和后半部的数字和是否相等。

Problem 75. Find the palindrome

% Given the string a, find the longest palindromic sub-string b.
%
% So when
%
%  a = 'xkayakyy';
%
% you should return
%
%  b = 'kayak';

function b = pal(a)
mxlen = 0;
for i = 1:length(a)
for j = i:length(a)
if all(a(i:j) == a(j:-1:i))
nowlen = j - i + 1;
if nowlen > mxlen
mxlen = nowlen;
b = a(i:j);
end
end
end
end
end

求最长回文子串。数据小,没想太多,直接暴力吧...标准的做法是O(n)的Manacher算法。

Problem 76. De-dupe

% Remove all the redundant elements in a vector, but keep the first occurrence of each value in its original location. So if
%
%  a = [5 3 6 4 7 7 3 5 9]
%
% then
%
%  dedupe(a) = [5 3 6 4 7 9]

function ans = dedupe(a)
unique(a, 'stable');
end


去掉所有重复元素。对于重复元素,保留第一个出现的。用unique即可完成任务。

Problem 77. Clean the List of Names

% Given a list of names in a cell array, remove any duplications that result from different capitalizations of the same string. So if
%
%  names_in = {'bert','arthur','Bert','Fred'};
%
% the
%
%  names_out = clean_list(names_in)
%
% results in
%
%  names_out = {'bert','arthur','Fred'};
%
% Always take the first occurrence of the duplicated string

function ans = clean_list(in)
[~, ans] = unique(upper(in), 'stable');
in(ans);
end

依法炮制。先把大小写转换为相同的,再找第一个出现的。

Problem 78. Implement a ROT13 cipher

% Replace each character in string s1 with the character that is shifted 13 positions from it (wrap back to the beginning if necessary). So A ? N, B ? O, and so on until Y ? L and Z ? M. Case of the output should match the case of the input, so a ? n. Non-alphabetic characters are left in place and untouched.
%
% If
%
%  s1 = 'I love MATLAB'
%
% then
%
%  s2 = 'V ybir ZNGYNO'
%
% See the Wikipedia article for more info.

function s = rot13(s)
id = (s >= 'a' & s <= 'z');
s(id) = char(mod(s(id) - 'a' + 13, 26) + 'a');
id = (s >= 'A' & s <= 'Z');
s(id) = char(mod(s(id) - 'A' + 13, 26) + 'A');
end


Problem 79. DNA N-Gram Distribution

% Given a string s and a number n, find the most frequently occurring n-gram in the string, where the n-grams can begin at any point in the string. This comes up in DNA analysis, where the 3-base reading frame for a codon can begin at any point in the sequence.
%
% So for
%
%  s = 'AACTGAACG'
%
% and
%
%  n = 3
%
% we get the following n-grams (trigrams):
%
%  AAC, ACT, CTG, TGA, GAA, AAC, ACG
%
% Since AAC appears twice, then the answer, hifreq, is AAC. There will always be exactly one highest frequency n-gram.
%
% This problem was originally inspired by a MATLAB Newsgroup discussion.

function s = nGramFrequency(s, n)
s = arrayfun(@(x) s(x:x+n-1), 1:length(s)-n+1, 'UniformOutput', false);
u = unique(s);
cellfun(@(x) sum(strcmp(x, s)), u, 'UniformOutput', false);
[~, id] = max([ans{:}]);
s = u{id};
end

找出长度为n的滑动字符串中出现次数最多的。

Problem 80. Test for balanced parentheses

% Given the input inStr, give the boolean output out indicating whether all the parentheses are balanced.
%
% Examples:
%
%     If inStr is '(()', the output is false.
%     If inStr is '(xyz)(ab)' the output is true.
%     If inStr is ')(', the output is false.
%
% The string may include characters other than ( and ), but you should ignore them.
%
% Incidentally, this problem was inspired from the Rosetta Code site. Why not create a few problems of your own by poking around the tasks at Rosetta Code?

function ans = isBalanced(str)
cumsum((str == '(') - (str == ')'));
ans(end) == 0 & all(ans >= 0);
end

判断括号是否匹配。对于每一个下标i满足当前'('的数目大于等于')'的数目,且对于整个字符串'('的数目和')'的数目相同即可。

当然也可以用栈。

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

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