Advertisement
Guest User

Horse-Racing Duals BASH

a guest
Nov 6th, 2015
358
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.17 KB | None | 0 0
  1. read N
  2. touch list      # create file named list
  3. for (( i=0; i<N; i++ )); do
  4.     read Pi     # store in Pi
  5.     echo $Pi >> list    # append to file list
  6. done
  7.  
  8. #cat List : list >& 2
  9.  
  10. sort -n list > sorted   # sort file list and create file sorted
  11.  
  12. #echo Sorted : >& 2
  13. #cat sorted >& 2
  14.  
  15. minimum=99999999
  16. distance=0
  17. previous=0
  18. first=$(head -n 1 sorted)   # first horse from sorted
  19.  
  20. #echo head : $first >& 2
  21.  
  22. for i in $(cat sorted); do  # iterate through lines from sorted
  23.     #echo i : $i >& 2
  24.     if [ $i != $first ]; then
  25.         #echo -e '\t' first : $previous >& 2
  26.         #echo -e '\t' second : $i >&2
  27.         let "distance=i-previous"   # calculate distance
  28.         #echo -e '\t' "$distance = $i-$previous" >& 2
  29.        
  30.         # Since list is sorted i know that distance is always >= 0
  31.         #echo -e '\t' distance : $distance >& 2
  32.        
  33.         if [ $distance -lt $minimum ]; then    
  34.             let "minimum=distance"      # store minimal distance
  35.         fi
  36.  
  37.         let "previous=i"    # current i horse becomes previous
  38.     else
  39.         let "previous=i"    # first horse becomes previous
  40.     fi
  41.  done
  42.  
  43. echo "$minimum"     # print minimum
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement