需要分析一组具有0和正整数的向量

时间:2011-10-06 18:15:40

标签: java matlab numbers

我正在使用Matlab,我有一个1x200的数字向量。

我需要按照以下规则为这组数字指定一个“得分”:

  1. 如果有2个或3个或4个连续的正数,那么0.5个点
  2. 如果有五个或更多连续的正数,那么1.0分
  3. 如果没有任何连续的正数,例如:0 0 0 6 0 0,则为0.0点。 (忽略它,将正数视为零)
  4. 如果正整数运行中只有一个零,则忽略该零(将其视为正整数)
  5. 如果有两个或更多连续的零, 会打破连续正数的运行。
  6. 示例:30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0(共计2.0分)

    最后,应该有一个积分。

    此类问题是否有任何有用的功能?

2 个答案:

答案 0 :(得分:0)

这是基于我对这个问题的理解,正如我在上面的问题中所指出的那样。我已经“解压”了所有输出,所以你可以看到发生了什么。

%Rules:
%1. If there are 2 or 3 or 4 consecutive positive numbers, then 0.5 point
%2. If there are five or more consecutive positive numbers, then 1.0 point
%3.  And if there isn't any consecutive positive number, for example: 
%   0 0 0 6 0 0, then 0.0 point. (ignore it, consider that positive 
%   number as zero)
%4. if there is only one zero in the middle of positive integers = ignore 
%   that zero (consider it as a positive integer)
%5. If there are two or more consecutive 0, THEN no point.

%testData = [0 30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 1 2 0 1 2 0 ];
testData = [30 43 54 0 0 0 41 54 14 10 1 0 0 0 0 32 41 98 12 0 0 0 ];
posa = testData>0;
%add 0s at each end so that the diffs at the ends work.
diffa = diff([0 posa 0])
starts = find(diffa ==1)
ends = find(diffa==-1)

% Rule 4 if any end (-1) is immediately followed by a start, that means that there 
%   is a 0 in the middle of a run.  substitute a 1 in the position and recalc.
midZeroLengths = starts(2:end) - ends(1:(end-1));
%pad to account for the fact that we only compared part.
midZeroLengths = [midZeroLengths 0];
if any(midZeroLengths == 1);
    testData(ends(midZeroLengths==1)) = 1;
    posa = testData>0;
    %add 0s at each end so that the diffs at the ends work.
    diffa = diff([0 posa 0])
    starts = find(diffa ==1)
    ends = find(diffa==-1)  
end

runs = ends-starts
halfs = (runs > 1) & (runs < 5)
wholes = (runs > 4)
final = sum(halfs)*0.5 + sum(wholes)

答案 1 :(得分:0)

怎么样:

str = repmat('a', 1, numel(testData));
str(testData > 0) = 'b';
m = regexp(str, 'b+(ab+)*', 'match');
n = cellfun(@numel, m);
score = 0.5 * sum(n >= 2 & n <= 4) + 1.0 * sum(n >= 5);

请注意,我没有运行此功能,因此可能存在错误。