ファイル1には、ランダムにペアにする必要がある単語のリストが含まれています。
Tiger
Cat
Fish
Frog
Dog
Mouse
Elephant
Monkey
ファイル2には、ランダムペアリング中に(すべてのソリューションで)使用してはならないペアが含まれています。
Elephant-Dog
Cat-Fish
Monkey-Frog
Dog Elephant、Fish Cat、Frog MonkeyもペアがFile2に表示されるため(方向に関係なく)削除する必要があります。合計6つのソリューションが必要で、各ソリューションには最大5対必要です。 Tiger-CatとCat-Tigerは同じと見なされ、ソリューションに一緒に表示される場合は削除する必要があります。同じペア(たとえば、カエル - 犬)が複数のソリューションに表示されることがあります。
出力は次のとおりです(ここには1つの解決策しかありません)。
Tiger-Cat
Cat-Dog
Monkey-Cat
Frog-Dog
Elephant-Cat
ベストアンサー1
bash
解決策:
for i in {1..6}; do
printf '==== solution %d ====\n' "$i"
# initialize solution
solution=()
while [ ${#solution[@]} -lt 5 ]; do
# select two random lines from file1
w1=$(shuf -n 1 file1)
w2=$(shuf -n 1 file1)
# skip if word1 is the same as word2
[ "$w1" == "$w2" ] && continue
# skip if pair exists in same solution or is not allowed from file2
cat <(printf '%s\n' "${solution[@]}") file2 | grep -qx "$w1-$w2" && continue
cat <(printf '%s\n' "${solution[@]}") file2 | grep -qx "$w2-$w1" && continue
# output
solution+=("${w1}-${w2}")
done
printf '%s\n' "${solution[@]}"
done
出力:
==== solution 1 ====
Fish-Monkey
Elephant-Mouse
Dog-Tiger
Mouse-Fish
Dog-Cat
==== solution 2 ====
Cat-Frog
Elephant-Monkey
Cat-Mouse
Tiger-Elephant
Fish-Tiger
==== solution 3 ====
Cat-Frog
Tiger-Monkey
Frog-Elephant
Dog-Fish
Elephant-Cat
==== solution 4 ====
Cat-Dog
Mouse-Elephant
Monkey-Elephant
Cat-Monkey
Tiger-Cat
==== solution 5 ====
Tiger-Monkey
Tiger-Cat
Mouse-Monkey
Mouse-Fish
Monkey-Cat
==== solution 6 ====
Monkey-Mouse
Dog-Monkey
Monkey-Fish
Tiger-Elephant
Cat-Tiger