devinteske

swap_select.sh

Jun 16th, 2021 (edited)
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.82 KB | None | 0 0
  1. #!/bin/bash
  2. declare -a name Rl S R
  3. n=0 s=0
  4. while read LINE; do
  5.         n=$(( n + 1 ))
  6.         name[$n]="$LINE"
  7. done
  8. while [ $s -lt $n ]; do # For each participant as a sender
  9.         s=$(( s + 1 )) x=0 y=0 Rl=( )
  10.         while [ $x -lt $n ]; do
  11.                 x=$(( x + 1 ))
  12.                 [ $x -ne $s ] || continue
  13.                 [ "${S[$x]}" ] && continue # Recipient already has sender
  14.                 y=$(( y + 1 ))
  15.                 Rl[$y]=$x
  16.         done
  17.         if [ $y -gt 0 ]; then
  18.                 R[$s]=${Rl[$((((RANDOM<<15)|RANDOM)%y+1))]}
  19.         else # Randomization left sender sending to self; swap senders
  20.                 R[$s]=${R[1]} R[1]=$s
  21.         fi
  22.         [ $s -eq 1 ] || echo "${name[$s]} -> ${name[${R[$s]}]}"
  23.         S[${R[$s]}]=$s
  24. done
  25. [ $n -lt 1 ] || echo "${name[1]} -> ${name[${R[1]}]}"
Add Comment
Please, Sign In to add comment