Cody Problem 11-20 Solutions

Problem 11. Back and Forth Rows

function b = back_and_forth(n)
  for i = 1:2:n
      b(i,:) = (i-1)*n+1:i*n;
  end
  for j = 2:2:n
      b(j,:) = j*n : -1 : (j-1)*n+1;
  end
end


Problem 12. Fibonacci sequence

function f = fib(n)
    a(1) = 1
    a(2) = 1
    for i = 3:n
        a(i) = a(i-1)+a(i-2);
    end       
  f = a(n);
end

Problem 13. Remove all the consonants

function s2 = refcn(s1)
  s2=regexprep(s1,'(?=[a-z])[^aeiou]','','ignorecase');
end

%正则表达式


Problem 14. Find the numeric mean of the prime numbers in a matrix.

function out = meanOfPrimes(in)
    num = 0;
    sum = 0;
    for i = 1:length(in)
        if isprime(in(i))
            num = num + 1;
            sum = sum + in(i);
        end
    end
    out = sum / num;
end


Problem 15. Find the longest sequence of 1's in a binary sequence

function y = lengthOnes(x)
  y = max([0, regexp(x, '1+', 'end')-regexp(x, '1+', 'start')+1]);
end


Problem 16. Return the largest number that is adjacent to a zero

function y = nearZero(x)
    y = -inf;
    x = [-inf, x, -inf];
    y = max(y, max([x(find(x==0)-1),x(find(x==0)+1)]));
    
end


Problem 17. Find all elements less than 0 or greater than 10 and replace them with NaN

function y = cleanUp(x)
  x(find(x<0 | x>10)) = NaN;
  y = x;
end

Problem 18. Bullseye Matrix

function a = bullseye(n)
   a = discretize(spiral(n), [0 1:2:n].^2+.5);  
end


Problem 19. Swap the first and last columns

function B = swap_ends(A)
    if length(A) > 1
      B = [A(:, end),A(:, 2:end-1),A(:, 1)];
    else
        B = A;
end


Problem 20. Summing digits

function b = sumDigits(n)
    c = 2^n;
    a = num2str(c);
    b = sum(str2num(a(:)));
end










  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值