-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsource_code.txt
More file actions
371 lines (328 loc) · 11 KB
/
source_code.txt
File metadata and controls
371 lines (328 loc) · 11 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
// main.ts
import { GameEngine } from "./engine";
import { parseFile } from "./parser";
import { basicStrategy } from "./strategy";
import * as fs from "fs";
const fileName = "4-maathai.txt";
(async () => {
const { budget, turns, resources } = await parseFile(`input/${fileName}`);
const engine = new GameEngine(budget, turns, resources);
// Prepare output file
const outputFile = `output/${fileName}`;
const outputLines: string[] = [];
while (!engine.isGameOver()) {
const buyIds = basicStrategy(engine);
if (buyIds.length > 0) {
const success = engine.purchaseResources(buyIds);
if (success) {
const line = `${engine.currentTurn} ${buyIds.length} ${buyIds.join(
" "
)}`;
outputLines.push(line); // Collect lines for file
console.log(line); // Optional: keep console output
}
}
engine.runTurn();
}
// Write to file
fs.writeFileSync(outputFile, outputLines.join("\n"), "utf8");
console.log(`Output written to ${outputFile}`);
console.log(`Total Score: ${engine.getTotalScore()}`);
})();
// engine.ts
import { ResourceDefinition, Turn, ActiveResource } from "./types";
export class GameEngine {
budget: number;
turns: Turn[];
resources: ResourceDefinition[];
activeResources: ActiveResource[] = [];
currentTurn: number = 0;
totalScore: number = 0; // Track total profit
constructor(budget: number, turns: Turn[], resources: ResourceDefinition[]) {
this.budget = budget;
this.turns = turns;
this.resources = resources;
}
purchaseResources(resourceIds: number[]): boolean {
const cost = resourceIds.reduce((sum, id) => {
const def = this.resources.find((r) => r.id === id)!;
return sum + def.activationCost;
}, 0);
if (cost > this.budget) return false;
this.budget -= cost;
for (const id of resourceIds) {
const def = this.resources.find((r) => r.id === id)!;
const newResource: ActiveResource = {
definition: def,
remainingLife: def.lifecycle,
cooldownRemaining: 0,
turnsRemainingActive: def.activeTurns,
storedBuildings: def.effectType === "E" ? 0 : undefined,
};
this.applyCTypeEffects(newResource); // Apply C-type effects at purchase
this.activeResources.push(newResource);
}
return true;
}
private applyCTypeEffects(newResource: ActiveResource) {
const cResources = this.activeResources.filter(
(r) => r.definition.effectType === "C" && r.turnsRemainingActive > 0
);
for (const c of cResources) {
const percentage = c.definition.effectValue!;
const factor =
percentage >= 0 ? 1 + percentage / 100 : 1 / (1 - percentage / 100);
newResource.remainingLife = Math.max(
1,
Math.floor(newResource.definition.lifecycle * factor)
);
}
}
runTurn(): number {
const turn = this.turns[this.currentTurn];
let buildingsPowered = 0;
let maintenanceCost = 0;
let profitPerBuilding = turn.profitPerBuilding;
let minBuildings = turn.minBuildings;
let maxBuildings = turn.maxBuildings;
// Apply special effects
const activeEffects = this.activeResources
.filter((r) => r.turnsRemainingActive > 0 && r.remainingLife > 0)
.reduce((acc, r) => {
acc[r.definition.effectType] = acc[r.definition.effectType] || [];
acc[r.definition.effectType].push(r);
return acc;
}, {} as Record<string, ActiveResource[]>);
// A: Smart Meter
let aFactor = 1;
if (activeEffects["A"]) {
activeEffects["A"].forEach((r) => {
const percentage = r.definition.effectValue!;
aFactor *=
percentage >= 0 ? 1 + percentage / 100 : 1 - percentage / 100;
});
}
// B: Distribution Facility
if (activeEffects["B"]) {
let bFactor = 1;
activeEffects["B"].forEach((r) => {
const percentage = r.definition.effectValue!;
bFactor *=
percentage >= 0 ? 1 + percentage / 100 : 1 - percentage / 100;
});
minBuildings = Math.max(0, Math.floor(minBuildings * bFactor));
maxBuildings = Math.max(0, Math.floor(maxBuildings * bFactor));
}
// D: Renewable Plant
if (activeEffects["D"]) {
let dFactor = 1;
activeEffects["D"].forEach((r) => {
const percentage = r.definition.effectValue!;
dFactor *=
percentage >= 0 ? 1 + percentage / 100 : 1 - percentage / 100;
});
profitPerBuilding = Math.max(0, Math.floor(profitPerBuilding * dFactor));
}
// Update resources and calculate buildings powered
this.activeResources.forEach((res) => {
if (res.remainingLife <= 0) return;
if (res.cooldownRemaining > 0) {
res.cooldownRemaining--;
if (res.cooldownRemaining === 0 && res.remainingLife > 0) {
res.turnsRemainingActive = res.definition.activeTurns; // Restart active period
}
} else if (res.turnsRemainingActive > 0) {
const adjustedRU = Math.max(
0,
Math.floor(res.definition.buildingsPowered * aFactor)
);
buildingsPowered += adjustedRU;
maintenanceCost += res.definition.periodicCost;
res.turnsRemainingActive--;
if (
res.turnsRemainingActive === 0 &&
res.definition.maintenanceTurns > 0
) {
res.cooldownRemaining = res.definition.maintenanceTurns;
}
}
res.remainingLife--;
});
// E: Accumulator
let storedBuildings = 0;
const eResources = this.activeResources.filter(
(r) => r.definition.effectType === "E" && r.turnsRemainingActive > 0
);
if (eResources.length > 0) {
const surplus = buildingsPowered - maxBuildings;
if (surplus > 0) {
eResources.forEach((e) => {
const capacity = e.definition.effectValue!;
e.storedBuildings = Math.min(
capacity,
(e.storedBuildings || 0) + surplus / eResources.length
);
});
buildingsPowered = maxBuildings;
}
if (buildingsPowered < minBuildings) {
const needed = minBuildings - buildingsPowered;
let available = eResources.reduce(
(sum, e) => sum + (e.storedBuildings || 0),
0
);
if (available >= needed) {
let remaining = needed;
eResources.forEach((e) => {
const take = Math.min(remaining, e.storedBuildings || 0);
e.storedBuildings! -= take;
remaining -= take;
});
buildingsPowered = minBuildings;
}
}
}
// Calculate profit
let profit = 0;
if (buildingsPowered >= minBuildings) {
profit = Math.min(buildingsPowered, maxBuildings) * profitPerBuilding;
}
this.budget += profit - maintenanceCost;
this.totalScore += profit;
this.currentTurn++;
// Remove expired resources
this.activeResources = this.activeResources.filter(
(r) => r.remainingLife > 0
);
return profit;
}
isGameOver(): boolean {
return this.currentTurn >= this.turns.length;
}
getTotalScore(): number {
return this.totalScore;
}
}
// parser.ts
import fs from "fs";
import readline from "readline";
import { ResourceDefinition, ResourceEffectType, Turn } from "./types";
export async function parseFile(filePath: string): Promise<{
budget: number;
turns: Turn[];
resources: ResourceDefinition[];
}> {
return new Promise((resolve) => {
const readStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: readStream,
crlfDelay: Infinity,
});
let budget = 0;
let resourceCount = 0;
let turnCount = 0;
let lineIndex = 0;
const turns: Turn[] = [];
const resources: ResourceDefinition[] = [];
rl.on("line", (line) => {
const parts = line.trim().split(" ");
if (lineIndex === 0) {
// First line: D R T
budget = parseInt(parts[0], 10);
resourceCount = parseInt(parts[1], 10);
turnCount = parseInt(parts[2], 10);
} else if (lineIndex <= resourceCount) {
// Resource lines
const [
id,
activationCost,
periodicCost,
activeTurns,
maintenanceTurns,
lifecycle,
buildingsPowered,
effectType,
effectValue,
] = parts;
resources.push({
id: parseInt(id, 10),
activationCost: parseInt(activationCost, 10),
periodicCost: parseInt(periodicCost, 10),
activeTurns: parseInt(activeTurns, 10),
maintenanceTurns: parseInt(maintenanceTurns, 10),
lifecycle: parseInt(lifecycle, 10),
buildingsPowered: parseInt(buildingsPowered, 10),
effectType: effectType as ResourceEffectType,
effectValue: effectValue ? parseInt(effectValue, 10) : undefined,
});
} else {
// Turn lines
const [minBuildings, maxBuildings, profitPerBuilding] = parts;
turns.push({
minBuildings: parseInt(minBuildings, 10),
maxBuildings: parseInt(maxBuildings, 10),
profitPerBuilding: parseInt(profitPerBuilding, 10),
});
}
lineIndex++;
});
rl.on("close", () => {
resolve({ budget, turns, resources });
});
});
}
// strategy.ts
import { GameEngine } from "./engine";
export function basicStrategy(engine: GameEngine): number[] {
const turn = engine.turns[engine.currentTurn];
const affordable = engine.resources
.filter((r) => r.activationCost <= engine.budget)
.sort((a, b) => a.activationCost - b.activationCost);
if (affordable.length === 0) return [];
// Prioritize E for stability, D for profit boost, then X for simplicity
const eResource = affordable.find((r) => r.effectType === "E");
const dResource = affordable.find(
(r) => r.effectType === "D" && r.effectValue! > 0
);
const xResource = affordable.find((r) => r.effectType === "X");
if (
eResource &&
turn.minBuildings >
engine.activeResources.reduce(
(sum, r) =>
sum +
(r.turnsRemainingActive > 0 ? r.definition.buildingsPowered : 0),
0
)
) {
return [eResource.id]; // Buy E if we risk missing minBuildings
}
if (dResource) return [dResource.id]; // Boost profit with D
if (xResource) return [xResource.id]; // Fallback to cheapest X
return [affordable[0].id]; // Default to cheapest
}
// types.ts
export type ResourceEffectType = "A" | "B" | "C" | "D" | "E" | "X";
export interface ResourceDefinition {
id: number;
activationCost: number;
periodicCost: number;
activeTurns: number;
maintenanceTurns: number;
lifecycle: number;
buildingsPowered: number;
effectType: ResourceEffectType;
effectValue?: number; // Percentage for A, B, C, D; capacity for E
}
export interface Turn {
minBuildings: number;
maxBuildings: number;
profitPerBuilding: number;
}
export interface ActiveResource {
definition: ResourceDefinition;
remainingLife: number;
cooldownRemaining: number;
turnsRemainingActive: number;
storedBuildings?: number; // For E-type
}