cards = 'AAKKQQJJ'; table = nan(4); locations = [... ' ___ \n'... ' | | \n'... ' | X | \n'... ' |___| \n'... ' ___ ___ ___ \n'... ' | | | | | | \n'... ' | X | | X | | X | \n'... ' |___| |___| |___| \n'... ' ___ ___ ___ \n'... ' | | | | | |\n'... ' | X | | X | | X |\n'... ' |___| |___| |___|\n'... ' ___ \n'... ' | | \n'... ' | X | \n'... ' |___| \n']; neighbors = [ 4, 0, 0, 0; 3, 0, 0, 0; 2, 4, 0, 0; 1, 3, 6, 0; 3, 6, 0, 0; 4, 5, 7, 8; 6, 0, 0, 0; 6, 0, 0, 0]; all_perms = perms(cards); card_locations = find(locations == 'X'); for p=1:length(all_perms) table = locations; % fill the table with this permutation this_perm = all_perms(p,:); table(locations == 'X') = all_perms(p,:); % find card locations aces = find(table(card_locations) == 'A'); kings = find(table(card_locations) == 'K'); queens = find(table(card_locations) == 'Q'); jacks = find(table(card_locations) == 'J'); % check rules failed = false; % rule 1: Aces must touch Kings if ~failed for a=1:2 ace_neighbors = neighbors(aces(a),:); pass = false; for n=1:length(ace_neighbors) if ace_neighbors(n) > 0 if table(card_locations(ace_neighbors(n))) == 'K' pass = true; end end end if ~pass failed = true; break; end end end % rule 2: Kings must tuoch Queens if ~failed for k=1:2 king_neighbors = neighbors(kings(k),:); pass = false; for n=1:length(king_neighbors) if king_neighbors(n) > 0 if table(card_locations(king_neighbors(n))) == 'Q' pass = true; end end end if ~pass failed = true; break; end end end % rule 3: Queens must touch Jacks if ~failed for q=1:2 queen_neighbors = neighbors(queens(q),:); pass = false; for n=1:length(queen_neighbors) if queen_neighbors(n) > 0 if table(card_locations(queen_neighbors(n))) == 'J' pass = true; end end end if ~pass failed = true; break; end end end % rule 4: Queens cannot touch Aces if~failed for a=1:2 queen_neighbors = neighbors(queens(q),:); pass = true; for n=1:length(queen_neighbors) if queen_neighbors(n) > 0 if table(card_locations(queen_neighbors(n))) == 'A' pass = false; end end end if ~pass failed = true; break; end end end % rule 5: Two of the same card cannot touch each other if ~failed for c=1:2 ace_neighbors = neighbors(aces(c),:); king_neighbors = neighbors(kings(c),:); queen_neighbors = neighbors(queens(c),:); jack_neighbors = neighbors(jacks(c),:); pass = true; for n=1:length(ace_neighbors) if ace_neighbors(n) > 0 if table(card_locations(ace_neighbors(n))) == 'A' pass = false; break; end end end if pass for n=1:length(king_neighbors) if king_neighbors(n) > 0 if table(card_locations(king_neighbors(n))) == 'K' pass = false; break; end end end end if pass for n=1:length(queen_neighbors) if queen_neighbors(n) > 0 if table(card_locations(queen_neighbors(n))) == 'Q' pass = false; break; end end end end if pass for n=1:length(jack_neighbors) if jack_neighbors(n) > 0 if table(card_locations(jack_neighbors(n))) == 'J' pass = false; break; end end end end if ~pass failed = true; break; end end end if ~failed %found soln fprintf(table); break; end end