Team Ai
Apppublic

Purva09/algorithm-battlefield

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
input_generator.py158 linesDownload Raw Back to utils
1"""Input generation and validation utilities"""2 3import random4import string5 6 7def generate_random_input(algorithm_type, size=5):8    """9    Generate random input based on algorithm type in human-readable format10    """11    import random12    import string13 14    if algorithm_type == 'sorting':15        return [random.randint(1, 1000) for _ in range(size)]16 17    elif algorithm_type == 'searching':18        arr = [random.randint(1, 1000) for _ in range(size)]19        return arr20 21    elif algorithm_type == 'string matching':22        # Generate text exactly based on user-provided size23        text = ''.join(random.choices(string.ascii_lowercase, k=size))24        formatted = f"Generated Text ({size} chars): {text}"25        return text, formatted26 27 28    elif algorithm_type in ['graph', 'shortest path']:29        # Generate nodes as letters A, B, C, ...30        nodes = [chr(65 + i) for i in range(min(size, 10))]31        edges = []32 33        # Generate random weighted edges (40% probability)34        for i in range(len(nodes)):35            for j in range(i + 1, len(nodes)):36                if random.random() < 0.4:  # ~40% chance of edge37                    weight = random.randint(1, 20)38                    edges.append((nodes[i], nodes[j], weight))39 40        # Ensure every node appears in at least one edge41        connected = set([n for edge in edges for n in edge[:2]])42        missing = [n for n in nodes if n not in connected]43        for m in missing:44            other = random.choice([n for n in nodes if n != m])45            weight = random.randint(1, 20)46            edges.append((m, other, weight))47 48        # Choose a random start node for shortest path49        start_node = random.choice(nodes)50 51        # Format edges as strings (A,B,10);(B,C,5)52        edges_str = '; '.join([f"({u},{v},{w})" for u, v, w in edges])53 54        # ✅ Include full node list at the top55        formatted = f"{','.join(nodes)}\n{edges_str}\n{start_node}"56        return (len(nodes), edges, start_node), formatted57 58 59    elif algorithm_type == 'mst':60        # Generate nodes as letters A, B, C, ...61        nodes = [chr(65 + i) for i in range(min(size, 10))]62        edges = []63 64        # Generate random weighted edges (40% probability)65        for i in range(len(nodes)):66            for j in range(i + 1, len(nodes)):67                if random.random() < 0.4:68                    weight = random.randint(1, 20)69                    edges.append((nodes[i], nodes[j], weight))70 71        # Ensure all nodes appear in at least one edge72        connected = set([n for edge in edges for n in edge[:2]])73        missing = [n for n in nodes if n not in connected]74        for m in missing:75            other = random.choice([n for n in nodes if n != m])76            weight = random.randint(1, 20)77            edges.append((m, other, weight))78 79        # Format output80        edges_str = '; '.join([f"({u},{v},{w})" for u, v, w in edges])81        formatted = f"{','.join(nodes)}\n{edges_str}"82 83        return (len(nodes), edges), formatted84 85 86    elif algorithm_type in ['0/1 knapsack', '0/1_knapsack']:87 88        n = min(size, 10)89        values = [random.randint(10, 100) for _ in range(n)]90        weights = [random.randint(5, 50) for _ in range(n)]91        capacity = random.randint(sum(weights)//3, sum(weights)//2)92        formatted = (93            f"{n}\n"94            f"Values: {', '.join(map(str, values))}\n"95            f"Weights: {', '.join(map(str, weights))}\n"96            f"Capacity: {capacity}"97        )98        return (n, weights, values, capacity), formatted99 100    elif algorithm_type == 'subset generation':101        num_elements = min(size, 15)102        arr = [random.randint(1, 100) for _ in range(num_elements)]103        return arr104 105    else:106        return [random.randint(1, 1000) for _ in range(size)]107 108 109 110def validate_array_input(input_str):111    """Validate and parse array input from user"""112    try:113        input_str = input_str.strip()114        115        # Try to parse as JSON array116        if input_str.startswith('[') and input_str.endswith(']'):117            import json118            arr = json.loads(input_str)119        else:120            # Try parsing as comma-separated values121            arr = [int(x.strip()) for x in input_str.split(',')]122        123        if not arr or len(arr) > 1000:124            raise ValueError("Array must have between 1 and 1000 elements")125        126        return arr127    128    except Exception as e:129        raise ValueError(f"Invalid array input: {str(e)}")130 131 132def validate_text_input(input_str, max_length=10000):133    """Validate text input for string matching algorithms"""134    input_str = input_str.strip()135    136    if not input_str:137        raise ValueError("Input cannot be empty")138    139    if len(input_str) > max_length:140        raise ValueError(f"Input too long (max {max_length} characters)")141    142    return input_str143 144 145def validate_graph_input(input_str):146    """Validate graph input"""147    try:148        import json149        graph = json.loads(input_str)150        151        if not isinstance(graph, dict):152            raise ValueError("Graph must be a dictionary")153        154        return graph155    156    except Exception as e:157        raise ValueError(f"Invalid graph input: {str(e)}")158