check for a pair in power hand

3 ビュー (過去 30 日間)
Jason Earls
Jason Earls 2021 年 3 月 23 日
編集済み: Jan 2021 年 3 月 23 日
i am trying to check for a pair, I need to compare each value in an array to each other in the array.
the difference will be a multuple of 13. exampe 1 and 14 would be a pair.
if mod (card[ct1]-card[ct2],13) ==0; but not sure how to write it. any help appreciated.

採用された回答

Rik
Rik 2021 年 3 月 23 日
The feasibility of this depends on the size of the arrays involved. If your vectors are too large, the implicit expansion will cause problems.
v1=randi(26,8,1);
v2=randi(26,8,1);
[ind1,ind2]=find(mod(v1-v2.',13)==0);
pairs=[v1(ind1),v2(ind2)]
pairs = 3×2
8 8 21 8 13 26

その他の回答 (1 件)

Jan
Jan 2021 年 3 月 23 日
編集済み: Jan 2021 年 3 月 23 日
The trivial approach would be two nested loops:
card = randi(20, 1, 1000);
result = zeros(2, numel(card)); % Pre-allocate to maximum size
c = 0;
for i1 = 1:numel(card)
for i2 = 1:numel(card)
if mod(card(i1) - card(i2), 13) == 0
c = c + 1;
result(1, c) = i1;
result(2, c) = i2;
end
end
end
result = result(:, 1:c); % Crop unused elements
Rik's vectorized apporach is smarter.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by