function [XBest, this] = sampleGridWithoutReplacement(this)
% Return XBest and update this.SampledGridIndices. Return [] if
% the grid has already been fully sampled.
%

%   Copyright 2016-2023 The MathWorks, Inc.

if gridFullySampled(this)
    XBest = [];
else
    Divs = this.PrivOptions.NumGridDivisions;
    Indices = iFindUnusedGridIndices(Divs, this.SampledGridIndices);
    XBest = XFromGridIndices(this, Indices);
    this.SampledGridIndices(end+1, :) = Indices;
end
end

function Indices = iFindUnusedGridIndices(NumGridDivisions, SampledGridIndices)
if isempty(SampledGridIndices)
    for p=numel(NumGridDivisions):-1:1
        Indices(p) = randi(NumGridDivisions(p));
    end
else
    Indices = SampledGridIndices(1,:);
    while ismember(Indices, SampledGridIndices, 'rows')
        for p=1:numel(NumGridDivisions)
            Indices(p) = randi(NumGridDivisions(p));
        end
    end
end
end
