Function that pulls a name from a list at random but doesn't repeat

15 次查看(过去 30 天)
I'm working on a two-part assignment that requires a function to pick a random index from a list of names. The function itself needs to check if the index has been pulled before so that it doesn't repeat any names. This is what I have so far,
function name = pick_name(list)
persistent ind_picked
n_picked = length(ind_picked);
n_list = length(list);
if isempty(n_picked)
ind = randi(n_list);
ind_picked = ind;
name = list(ind);
else
while found == find(ind_picked==ind)
ind = randi(n_list);
ind_picked = [ind_picked,ind];
end
name = list(ind);
end
What am I doing wrong??
  4 个评论
David Fletcher
David Fletcher 2018-4-14
编辑:David Fletcher 2018-4-14
All those variables that you are carefully declaring in the if condition on the first call of the function will go out of scope when the function exits (the condition on the if statement is slightly iffy as well - shouldn't it be if n_picked==0). On the second call because n_picked is persistent and no longer has a length of 0all those variables declared in the if condition won't execute and so ind won't exist when you are trying to use it in the while condition of your else statement (where is found defined btw). It might be worth detailing what your 'prescribed steps' are exactly. It will always be harder to pick a number that doesn't exist in a list of numbers that have already been picked rather than remove a number from a list of numbers that haven't already been picked.

请先登录,再进行评论。

采纳的回答

David Fletcher
David Fletcher 2018-4-14
编辑:David Fletcher 2018-4-14
listNames={'a','b','c','d','e','f','g','n','h'}
for iter=1:9
name=pick_name(listNames)
end
function name = pick_name(list)
persistent ind_picked
candidate=randi(length(list));
if isempty(ind_picked)
%Initialize persistent variable with random index
ind_picked=candidate;
else
%look for int that is not already in the list
while any(candidate==ind_picked)
candidate=randi(length(list));
end
ind_picked=[ind_picked candidate];
end
name=list{candidate};
end
Some things you may want to consider and make improvements: something bad happens if you call the function and all items in the list have already been picked. Maybe there should also be a way to 'reset' the function so it forgets it's internal list of picked indexes. Personally, I would also clearly state why this is a bad approach to the problem, and that the while loop could be eliminated, and the code much simplified by instead maintaining a list of indexes that had not been picked.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by