File size: 2,117 Bytes
0d3476b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import json
import logging
from flask import request, jsonify
from routes import app

logger = logging.getLogger(__name__)

@app.route('/digital-colony', methods=['POST'])
def evaluate():
    data = request.get_json()
    logging.info("Data received for evaluation: {}".format(data))

    results = []
    try: 
        for item in data:
            generations = item['generations']
            colony = list(map(int, item['colony']))
            logging.info(f"Evaluating colony: {colony} for {generations} generations")
            weight = calculate_weight_after_generations(colony, generations)
            logging.info(f"Weight of colony: {weight}")
            results.append(str(weight))
        logging.info("Results: {}".format(results))
        return jsonify(results)
    except Exception as e:
        logging.error("Error occurred while processing data: {}".format(e))
        return jsonify([])


    logging.info("Results: {}".format(results))
    return jsonify(results)
def calculate_signature(d1, d2, signature_cache):
    pair = (d1, d2)
    if pair in signature_cache:
        return signature_cache[pair]
    
    if d1 > d2:
        signature = d1 - d2
    elif d2 > d1:
        signature = 10 - (d2 - d1)
    else:
        signature = 0

    signature_cache[pair] = signature
    return signature

def generate_next_colony(colony, signature_cache):
    new_colony = []
    weight = sum(colony)
    for i in range(len(colony) - 1):
        d1, d2 = colony[i], colony[i + 1]
        signature = calculate_signature(d1, d2, signature_cache)
        new_digit = (weight + signature) % 10
        new_colony.append(d1)
        new_colony.append(new_digit)
    new_colony.append(colony[-1])
    return new_colony

def calculate_weight_after_generations(initial_colony, generations):
    colony = [int(d) for d in initial_colony]
    signature_cache = {}
    for _ in range(generations):
        colony = generate_next_colony(colony, signature_cache)
        # print(colony, sum(colony))
        # print("")
    return sum(colony)