{}
run-icon
main.py
# Online Python compiler (interpreter) to run Python online. # Write Python 3 code in this online editor and run it. # Demo: Mapping Array Items to Hexagonal Spiral Coordinates # Purpose: Demonstrate how to map a 1D array to 2D hexagonal coordinates # in a spiral pattern, with looping using modular arithmetic def get_hex_spiral_coords(index, array_size): """ Convert a 1D array index to 2D hexagonal spiral coordinates. Args: index (int): Position in the original array array_size (int): Total size of the input array Returns: tuple: (x, y) coordinates in 2D hexagonal space How it works: - Uses modular arithmetic (index % array_size) to loop back - Creates a spiral pattern by tracking layers and positions - Center is at (0,0), spiraling outward """ # Use modulo to wrap around if index exceeds array size wrapped_index = index % array_size # If index is 0, return center point if wrapped_index == 0: return (0, 0) # Determine which "layer" of the spiral we're on # Each layer is a hexagon with 6 sides layer = 1 while wrapped_index > 6 * layer: wrapped_index -= 6 * layer layer += 1 # Calculate position within current layer side_length = layer side = (wrapped_index - 1) // side_length # Which of 6 sides pos = (wrapped_index - 1) % side_length # Position along side # Convert to x,y coordinates based on side number x, y = 0, 0 if side == 0: # Right x = layer y = -side_length + pos elif side == 1: # Top-right x = side_length - pos y = layer - pos elif side == 2: # Top-left x = -pos y = layer elif side == 3: # Left x = -layer y = side_length - pos elif side == 4: # Bottom-left x = -side_length + pos y = -layer + pos elif side == 5: # Bottom-right x = pos y = -layer return (x, y) def print_hex_mapping(data): """ Print the array items with their hexagonal coordinates. Args: data (list): Input array to map """ print("\nArray Mapping to Hexagonal Spiral:") print("Index | Value | (X,Y) Coordinates") print("-" * 40) for i, value in enumerate(data): x, y = get_hex_spiral_coords(i, len(data)) print(f"{i:5d} | {value:5d} | ({x:2d}, {y:2d})") # Test data and main program def main(): """ Main entry point of the program. Creates test data and demonstrates the hexagonal spiral mapping. """ # Test data: simple array of numbers test_array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print("=== Hexagonal Spiral Mapping Demo ===") print(f"Original array: {test_array}") print(f"Array size: {len(test_array)}") # Show basic mapping print_hex_mapping(test_array) # Demonstrate wrapping with larger indices print("\nDemonstrating wrapping with larger indices:") for i in range(15, 20): # Some indices beyond array size x, y = get_hex_spiral_coords(i, len(test_array)) wrapped_value = test_array[i % len(test_array)] print(f"Index {i:2d} -> Value {wrapped_value:2d} -> ({x:2d}, {y:2d})") # This is the Python entry point # The if statement ensures main() only runs if this is the main script if __name__ == "__main__": main()
Output