32 lines
981 B
Bash
Executable File
32 lines
981 B
Bash
Executable File
#!/bin/bash
|
|
|
|
# Make temp files to store the sorted lists.
|
|
sorted_left_file=$(mktemp)
|
|
sorted_right_file=$(mktemp)
|
|
|
|
# Use awk to cut out a column, then sort by general numeric value, and store in a temp file.
|
|
left=$(awk '{print $1}' input.txt | sort -g --field-separator=\n -o $sorted_left_file)
|
|
right=$(awk '{print $2}' input.txt | sort -g --field-separator=\n -o $sorted_right_file)
|
|
|
|
# Print the filenames for debugging.
|
|
echo $sorted_left_file
|
|
echo $sorted_right_file
|
|
|
|
# Initialize the cumulative sum of absolute differences.
|
|
running_total=0
|
|
|
|
# Read from the two sorted files, and save the cumulative sum of absolute differences
|
|
# between corresponding lines.
|
|
while read left_val right_val; do
|
|
difference=$((left_val - right_val))
|
|
if [ $difference -lt 0 ]; then
|
|
abs_value=$((difference * -1))
|
|
else
|
|
abs_value=$difference
|
|
fi
|
|
running_total=$((running_total + abs_value))
|
|
|
|
done <<< $(paste $sorted_left_file $sorted_right_file)
|
|
|
|
echo $running_total
|