Skip to content

Instantly share code, notes, and snippets.

@greymd
Last active August 12, 2018 01:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greymd/15edae8aa86960c13d0b9026fe43ac44 to your computer and use it in GitHub Desktop.
Save greymd/15edae8aa86960c13d0b9026fe43ac44 to your computer and use it in GitHub Desktop.
Divide integer num much equally with bash
#!/bin/bash
ceiling () {
local divide="$1";shift
local by="$1"
printf "%s\\n" $(( ( divide + by - 1 ) / by ))
}
equalized_partition_nums () {
local number="$1";shift
local count="$1"
local upper lower upper_count lower_count
upper="$(ceiling "$number" "$count")"
lower=$(( upper - 1 ))
lower_count=$(( upper * count - number ))
upper_count=$(( count - lower_count ))
# echo "upper_count=$upper_count upper=$upper lower_count=$lower_count lower=$lower "
eval "printf '${upper} %.0s' {1..$upper_count}"
(( lower_count > 0 )) && eval "printf '${lower} %.0s' {1..$lower_count}"
}
equalized_partition_nums 100 10 | awk 4
equalized_partition_nums 100 6 | awk 4
equalized_partition_nums 9 4 | awk 4
IFS=" " read -r -a arr <<< "$(equalized_partition_nums 9 4)"
seq 0 "${#arr[@]}" | while read -r i ;do
printf '%s=%s\n' "$i" "${arr[i]}"
don
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment