MATLAB Answers

the cyclist
1

Puzzler for a Monday

Asked by the cyclist
on 22 Jul 2013
Latest activity Commented on by David Young
on 27 Jan 2015
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.]

  0 Comments

Sign in to comment.

6 Answers

Azzi Abdelmalek
Answer by Azzi Abdelmalek
on 22 Jul 2013

idx=strcmp(A,B)
out=[A(~idx) A(idx)]

  0 Comments

Sign in to comment.


Sean de Wolski
Answer by Sean de Wolski
on 22 Jul 2013

idx = ismember(A,B);
C = cat(isrow(A)+1,A(~idx),A(idx))

  1 Comment

Evan
on 22 Jul 2013
Awesome. I especially like the "isrow" trick. I'll be remembering that one.

Sign in to comment.


the cyclist
Answer by the cyclist
on 22 Jul 2013

Here's mine:
[~,idx] = sort(ismember(A,B));
A = A(idx)

  0 Comments

Sign in to comment.


Evan
Answer by Evan
on 22 Jul 2013
Edited by Evan
on 22 Jul 2013

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.

  0 Comments

Sign in to comment.


Answer by Abdullah Caliskan on 27 Jan 2015

k=ismember(A,B) A(k)='' if sum(k)==0 A=A; else A=[A B] end

  0 Comments

Sign in to comment.


David Young
Answer by David Young
on 27 Jan 2015

[~, idx] = ismember(B, A);
C = circshift(A, [0 -idx]);

  1 Comment

David Young
on 27 Jan 2015
Note: does not preserve the ordering of the other elements.

Sign in to comment.