필터 지우기
필터 지우기

Puzzler for a Monday

조회 수: 1 (최근 30일)
the cyclist
the cyclist 2013년 7월 22일
댓글: David Young 2015년 1월 27일
Given a cell array of strings
A = {'MATLAB','HURRAY','SPARKLY','KITTENS','FUN'};
and a particular string value
B = 'KITTENS';
ensure that B is the last element of the cell array. If it isn't, move it to the end of A.
You cannot assume that B appears at all (in which case return A unchanged), but you can assume B does not appear more than once.
[I have a solution, but I post this as a puzzle because I bet someone can find a slicker one.]

답변 (6개)

Azzi Abdelmalek
Azzi Abdelmalek 2013년 7월 22일
idx=strcmp(A,B)
out=[A(~idx) A(idx)]

the cyclist
the cyclist 2013년 7월 22일
Here's mine:
[~,idx] = sort(ismember(A,B));
A = A(idx)

Sean de Wolski
Sean de Wolski 2013년 7월 22일
idx = ismember(A,B);
C = cat(isrow(A)+1,A(~idx),A(idx))
  댓글 수: 1
Evan
Evan 2013년 7월 22일
Awesome. I especially like the "isrow" trick. I'll be remembering that one.

댓글을 달려면 로그인하십시오.


Evan
Evan 2013년 7월 22일
편집: Evan 2013년 7월 22일
Here's my solution. It's ugly, but I think it's fairly general. :P
function A = cell_shuffle(A)
idx = cellfun(@(x)isequal(B,x),A);
A = [A(~idx) A(idx)];
end
This would make for a nice CODY problem, by the way.

Abdullah Caliskan
Abdullah Caliskan 2015년 1월 27일
k=ismember(A,B) A(k)='' if sum(k)==0 A=A; else A=[A B] end

David Young
David Young 2015년 1월 27일
[~, idx] = ismember(B, A);
C = circshift(A, [0 -idx]);
  댓글 수: 1
David Young
David Young 2015년 1월 27일
Note: does not preserve the ordering of the other elements.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Just for fun에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by