Skip to content
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

adding a matrix equalization algorithm #11360

Merged
merged 3 commits into from
May 1, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
45 changes: 45 additions & 0 deletions matrix/matrix_equalization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import sys
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
import sys
from sys import maxsize



def array_equalization(vector: list[int], k: int) -> int:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Self-documenting variable names, please.

Suggested change
def array_equalization(vector: list[int], k: int) -> int:
def array_equalization(vector: list[int], step_size: int) -> int:

"""

This algorithm equalizes all elements of the input vector
to a common value, by making the minimal number of
"updates" under the constraint of a step size (k)

>>> array_equalization([1, 1, 6, 2, 4, 6, 5, 1, 7, 2, 2, 1, 7, 2, 2], 4)
4
>>> array_equalization([22, 81, 88, 71, 22, 81, 632, 81, 81, 22, 92], 2)
5
>>> array_equalization([-22, 81, -88, 71, 22, 81, 632, 81, -81, -22, 92], 2)
5
>>> array_equalization([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 5)
0
>>> array_equalization([sys.maxsize for c in range(10)], 3)
0
>>> array_equalization([22, 22, 22, 33, 33, 33], 2)
2

Copy link
Member

@cclauss cclauss Apr 24, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need tests that have the same vector but different values for step-size including -1, 0, 1.3, and maxsize.

"""
unique_elements = set(vector)
min_updates = sys.maxsize

for element in unique_elements:
elem_index = 0
updates = 0
while elem_index < len(vector):
if vector[elem_index] != element:
updates += 1
elem_index += k
else:
elem_index += 1
min_updates = min(min_updates, updates)

return min_updates


if __name__ == "__main__":
from doctest import testmod

testmod()