Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import annotations
- from typing import List
- import itertools
- import random
- # The chromosome is as follows:
- # "101001"
- # [Node(1), Node(0), Node(1), Node(0), Node(0), Node(1)]
- class Node:
- _id = itertools.count().__next__
- def __repr__(self):
- return f'{self.index} -> {self.next}'
- def __init__(self, value):
- self.value = value
- self.index = Node._id()
- self.next: Node = None
- def set_next(self, next: Node):
- self.next = next
- class Graph:
- def __init__(self, node_count):
- self.node_count = node_count
- self.nodes = self.generate_nodes()
- def generate_nodes(self):
- # create nodes
- nodes: List[Node] = [
- Node(random.randint(0, 1)) for _ in range(self.node_count)]
- # create edges
- for node in nodes:
- if random.randint(0, 2) >= 1:
- edge: Node = random.choice(nodes)
- while True:
- if (edge.index == node.index):
- edge = random.choice(nodes)
- continue
- if(node.next and edge.next):
- if(node.index == edge.next.index):
- if(edge.index == node.next.index):
- edge = random.choice(nodes)
- continue
- if node.next and edge.next:
- print(f"{node.index} -> {edge.next.index}")
- print(f"{edge.index} -> {node.next.index}")
- break
- node.next = edge
- return nodes
- def fitness(self):
- """ The graph only uses black and white, as a result, a solution is
- either optimal, or invalid. """
- fitness_score = 1
- for node in self.nodes:
- if node.next and node.next.value == node.value:
- fitness_score = 0
- return fitness_score
- graph = Graph(5)
- # for node in graph.nodes:
- # print(node)
- # print("Chromosome:", ''.join(str(node.value) for node in graph.nodes))
- # print("Fitness:", graph.fitness())
Advertisement
Add Comment
Please, Sign In to add comment