Skip to content

Add Maximum Array Rotation in Awk #4675

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 24, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions archive/a/awk/maximum-array-rotation.awk
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
function usage() {
print "Usage: please provide a list of integers (e.g. \"8, 3, 1, 2\")"
exit(1)
}

function str_to_number(s) {
return (s ~ /^\s*[+-]*[0-9]+\s*$/) ? s + 0 : "ERROR"
}

function str_to_array(s, arr, str_arr, idx, result) {
split(s, str_arr, ",")
for (idx in str_arr) {
result = str_to_number(str_arr[idx])
if (result == "ERROR") {
delete arr
arr[1] = "ERROR"
break
} else {
arr[idx] = result
}
}
}

function maximum_array_rotation(arr, n, i, s, w, wmax) {
# Calculate sum and initial array rotation
for (i = 1; i <= n; i++) {
s += arr[i]
w += (i - 1) * arr[i]
}

# Initialize maximum array rotation
wmax = w

# Adjust array rotation and update maximum
for (i = 1; i < n; i++) {
w += n * arr[i] - s
if (w > wmax) {
wmax = w
}
}
return wmax
}

BEGIN {
if (ARGC < 2) {
usage()
}

str_to_array(ARGV[1], arr)
arr_len = length(arr)
if (!arr_len || arr[1] == "ERROR") {
usage()
}

result = maximum_array_rotation(arr, arr_len)
printf("%d\n", result)
}