Luleå University of Technology
LTU courses · Computer Science & Engineering Fundamentals
D0015E
A broad survey course: Hammurabi strategy simulation, Arduino embedded programming, LaTeX typesetting, algorithm complexity analysis, and engineering ethics. Five modules, one course.
Module A: Hammurabi simulation game
Govern ancient Sumeria for 10 years
Hammurabi is one of the earliest computer games, a resource-allocation strategy game named after the 2nd-millennium BC Babylonian king. Each year you decide how many acres to buy or sell, how much grain to feed your people, and how much to plant. Survive 10 years and your rule is evaluated against history's great leaders.
Full browser port of the classic Hammurabi game. Govern for 10 years: allocate grain, feed your people, plant crops, buy and sell land. Starve too many or let land per person drop and the people overthrow you.
- The game lasts 10 years, one decision per year.
- Each year: buy or sell acres, feed your people, and plant crops.
- Each person needs 20 bushels of grain per year to survive.
- Each person can till at most 10 acres.
- Each acre needs 1 bushel of seed to plant.
- Land price fluctuates from 17 to 26 bushels per acre.
- If too many people starve the people will overthrow you.
- Survive all 10 years and your rule is ranked against great figures in history.
- First: feed everyone. Allocate 20 bushels × population to food. Starvation loses the game.
- Second: plant all land. You need 1 bushel per acre and 1 person per 10 acres. Plant as much as you can afford.
- Third: buy land cheap. If price is 17-19, consider buying. Above 23, consider selling.
- A plague can halve your population. Keep grain reserves for bad harvests.
- Rats eat 0-7% of grain randomly each year, factor this into your planning.
Hammurabi (originally "HMRABI") was written in BASIC around 1968-1973. It appeared in 101 BASIC Computer Games (1973) by David Ahl and became one of the most widely distributed early computer games.
It is widely considered the grandfather of resource management and strategy games, a direct ancestor of games like Civilization, SimCity, and Dwarf Fortress.
Hammurabi himself was the sixth king of Babylon (c. 1810-1750 BC), famous for the Code of Hammurabi, one of the oldest and most complete written legal codes.
// This is the game state.
var gameState;
gameState = {
year : 0,
starved : 0,
newcomers : 0,
population : 0,
acres : 0,
bushels : 0,
harvest : 0,
rats : 0,
price : 0,
internalAcres : 0,
internalBushels : 0,
totalStarved: 0
};
/* Returns the minimum of the three input values. */
function minimum(firstValue, secondValue, thirdValue) {
if (firstValue <= secondValue) {
if (firstValue <= thirdValue) {
return firstValue;
} else {
return thirdValue;
}
} else if (secondValue <= thirdValue) {
return secondValue;
} else {
return thirdValue;
}
}
/* Returns the slider which has the id sliderId. */
function getSlider(sliderId) {
return document.getElementById(sliderId);
}
/* Outputs the value of the slider with the id sliderId
to the element with the id outputElementId. */
function updateSliderValueOutput(sliderId, outputElementId) {
document.getElementById(outputElementId).innerHTML = document.getElementById(sliderId).value;
}
/* Helper function.
function helperFunction(sliderId, outputElementId) {
var slider = document.getElementById(sliderId);
outputElement = document.getElementById(outputElementId);
outputElement.innerHTML = " " + slider.min + " " + slider.max + " " + slider.step;
}*/
/* Outputs the momentary game state. */
function writeGameState() {
document.getElementById("year").innerHTML = "Rapport för år: " + gameState.year;
document.getElementById("starved").innerHTML = "Ihjälsvultna: " + gameState.starved;
document.getElementById("newcomers").innerHTML = "Inflyttade: " + gameState.newcomers;
document.getElementById("population").innerHTML = "Befolkning: " + gameState.population;
document.getElementById("acres").innerHTML = "Tunnland: " + gameState.acres;
document.getElementById("bushels").innerHTML = "Skäppor: " + gameState.bushels;
document.getElementById("harvest").innerHTML = "Skörd: " + gameState.harvest;
document.getElementById("rats").innerHTML = "Råttor: " + gameState.rats;
document.getElementById("price").innerHTML = "Pris: " + gameState.price;
updateSliderValueOutput("sliderAcrestosellbuy", "outputAcrestosellbuy");
updateSliderValueOutput("sliderFeedpeople", "outputFeedpeople");
updateSliderValueOutput("sliderPlantwithseed", "outputPlantwithseed");
}
/* Sets and outputs the initial game state. */
function gameStart() {
gameState.year = 1;
gameState.starved = 0;
gameState.newcomers = 5;
gameState.population = 100;
gameState.acres = 1000;
gameState.bushels = 2800;
gameState.harvest = 3;
gameState.rats = 200;
gameState.price = randomNumber(10) + 16;
gameState.internalAcres = gameState.acres;
gameState.internalBushels = gameState.bushels;
gameState.totalStarved = 0;
/* We have to set value after we set min and max,
because if min and max are set after value has
been set the Google Chrome browser changes value
again which leads to a bug in the game.
We could not figure out the concrete operation
of the Google Chrome browser which leads to this
behaviour, despite extensive search on the internet.
Issue found out: 12/15/2011 */
var acresSlider = getSlider("sliderAcrestosellbuy");
acresSlider.min = -gameState.acres;
acresSlider.max = Math.floor(gameState.internalBushels / gameState.price);
acresSlider.value = 0;
acresSlider.step = 1;
var feedSlider = getSlider("sliderFeedpeople");
feedSlider.min = 0;
feedSlider.max = gameState.internalBushels;
feedSlider.value = 0;
feedSlider.step = 1;
var plantSlider = getSlider("sliderPlantwithseed");
plantSlider.min = 0;
plantSlider.max = minimum(gameState.internalAcres, 10 * gameState.population, gameState.internalBushels);
plantSlider.value = 0;
plantSlider.step = 1;
writeGameState();
}
/* Takes the value of the slider for acres to sell or buy
and adds it to the acres value. The result is stored
in internal acres. */
function updateInternalAcres() {
gameState.internalAcres = gameState.acres + parseInt(getSlider("sliderAcrestosellbuy").value);
}
/* Takes the values of the sliders for acres to sell or buy,
feed people and plant with seed, subtracts them from
bushels and stores the result in internal bushels. */
function updateInternalBushels() {
var acresToSellOrBuy = parseInt(getSlider("sliderAcrestosellbuy").value);
var bushelsForFeeding = parseInt(getSlider("sliderFeedpeople").value);
var bushelsForPlanting = parseInt(getSlider("sliderPlantwithseed").value);
gameState.internalBushels = gameState.bushels - acresToSellOrBuy * gameState.price - bushelsForFeeding - bushelsForPlanting;
}
/* Updates the max property of the acres to buy or sell slider. */
function updateMaximumAcresToSellBuy() {
var acresSlider = getSlider("sliderAcrestosellbuy");
acresSlider.max = Math.floor(gameState.internalBushels / gameState.price) + parseInt(acresSlider.value);
}
/* Updates the max property of the feed people slider. */
function updateMaximumFeedPeople() {
var feedSlider = getSlider("sliderFeedpeople");
feedSlider.max = gameState.internalBushels + parseInt(feedSlider.value);
}
/* Updates the max property of the plant with seed slider. */
function updateMaximumPlantWithSeed() {
var plantSlider = getSlider("sliderPlantwithseed");
plantSlider.max = minimum(gameState.internalAcres, 10 * gameState.population, gameState.internalBushels + parseInt(plantSlider.value));
}
/* This function gets called when the value of the slider
which determines how much acres will be bought or sold
is changed.
It changes the value of the internal acres as following:
- minus button: decrement the internal acres by 1
- plus button: increment the internal acres by 1
- slider: add the new value to internal acres
The values of the internal bushels, the maximum of
feed people and plant with seed are also changed. */
function onChangeAcres(elementId) {
if (elementId === "minusbuttonAcrestosellbuy") {
getSlider("sliderAcrestosellbuy").value = parseInt(getSlider("sliderAcrestosellbuy").value) - 1;
} else if (elementId === "plusbuttonAcrestosellbuy") {
getSlider("sliderAcrestosellbuy").value = parseInt(getSlider("sliderAcrestosellbuy").value) + 1;
}
updateSliderValueOutput("sliderAcrestosellbuy", "outputAcrestosellbuy");
updateInternalAcres();
updateInternalBushels();
updateMaximumFeedPeople();
updateMaximumPlantWithSeed();
}
/* This function gets called when the value of the slider
which determines how much bushels will be used for feeding
is changed.
The values of the internal bushels, the maximum of
acres to sell or buy and plant with seed are changed. */
function onChangeFeeding(elementId) {
if (elementId === "minusbuttonFeedpeople") {
getSlider("sliderFeedpeople").value = parseInt(getSlider("sliderFeedpeople").value) - 1;
} else if (elementId === "plusbuttonFeedpeople") {
getSlider("sliderFeedpeople").value = parseInt(getSlider("sliderFeedpeople").value) + 1;
}
updateSliderValueOutput("sliderFeedpeople", "outputFeedpeople");
updateInternalBushels();
updateMaximumAcresToSellBuy();
updateMaximumPlantWithSeed();
}
/* This function gets called when the value of the slider
which determines how much bushels will be used for planting
is changed.
The values of the internal bushels, the maximum of
acres to sell or buy and feed people are changed. */
function onChangePlanting(elementId) {
if (elementId === "minusbuttonPlantwithseed") {
getSlider("sliderPlantwithseed").value = parseInt(getSlider("sliderPlantwithseed").value) - 1;
} else if (elementId === "plusbuttonPlantwithseed") {
getSlider("sliderPlantwithseed").value = parseInt(getSlider("sliderPlantwithseed").value) + 1;
}
updateSliderValueOutput("sliderPlantwithseed", "outputPlantwithseed");
updateInternalBushels();
updateMaximumAcresToSellBuy();
updateMaximumFeedPeople();
}
/* Returns a random number between 1 and maxValue. */
function randomNumber(maxValue) {
var number = Math.floor(Math.random() * maxValue + 1);
return number;
}
/* Returns 15% of the time the boolean value true
and 85% of the time the boolean value false. */
function plague() {
var plagueOccurs;
if (randomNumber(100) <= 15) {
plagueOccurs = true;
} else {
plagueOccurs = false;
}
return plagueOccurs;
}
/* Returns 40% of the time the boolean value true
and 60% of the time the boolean value false. */
function ratsProblem() {
var ratsProblemOccurs;
if (randomNumber(10) <= 4) {
ratsProblemOccurs = true;
} else {
ratsProblemOccurs = false;
}
return ratsProblemOccurs;
}
/* If there is a problem with rats, they eat 1/10, 2/10 or
3/10 of the bushels. Otherwise they eat none. */
function bushelsEatenByRats() {
var bushelsEaten;
if (ratsProblem()) {
bushelsEaten = Math.floor((randomNumber(3) / 10) * gameState.bushels);
} else {
bushelsEaten = 0;
}
return bushelsEaten;
}
/* Returns a random number between 1 and 8. */
function harvestPerAcre() {
var harvest = randomNumber(8);
return harvest;
}
/* Calculates how many people starved, depending on
the number of bushels which were used to feed
people. */
function calculateStarvedPeople() {
var numberPeopleStarved = gameState.population - Math.floor(parseInt(getSlider("sliderFeedpeople").value) / 20);
if (numberPeopleStarved <= 0) {
return 0;
} else {
return numberPeopleStarved;
}
}
/* Calculates the number of newcomers, depending on
the internal number of acres, internal number of
bushels and the size of the population.
Formula:
(20 * number of acres you have + amount of grain you have in storage) / (100 * population) + 1*/
function calculateNewcomers() {
return Math.floor((20 * gameState.internalAcres + gameState.internalBushels) / (100 * gameState.population)) + 1;
}
/* The function returns true if more than 45% of the
original population starved. Otherwise it returns
false. */
function tooManyPeopleStarved() {
var originalPopulation = gameState.population + gameState.starved - gameState.newcomers;
if (Math.floor((gameState.starved / originalPopulation) * 100) > 45) {
return true;
} else {
return false;
}
}
/* If the maximum number of turns is not fulfilled yet and
not too many people starved, the new game state is being
calculated and outputted.
If too many people starved the user is being informed
that he is kicked out of office.
Otherwise the end-page is shown which informs the user
about his performance. */
function finishTurn() {
if (plague()) {
alert("En hemsk pest slår till!\n" + "Halva befolkningen dör.");
gameState.population = Math.floor(gameState.population / 2);
}
gameState.starved = calculateStarvedPeople();
gameState.totalStarved = gameState.totalStarved + gameState.starved;
gameState.newcomers = calculateNewcomers();
gameState.population = gameState.population - gameState.starved + gameState.newcomers;
gameState.harvest = harvestPerAcre();
gameState.bushels = gameState.internalBushels + gameState.harvest * parseInt(getSlider("sliderPlantwithseed").value);
gameState.rats = bushelsEatenByRats();
gameState.bushels = gameState.bushels - gameState.rats;
gameState.internalBushels = gameState.bushels;
gameState.price = randomNumber(10) + 16;
gameState.acres = gameState.internalAcres;
if (gameState.year < 10 && !tooManyPeopleStarved()) {
gameState.year++;
var acresSlider = getSlider("sliderAcrestosellbuy");
acresSlider.min = -gameState.acres;
acresSlider.max = Math.floor(gameState.internalBushels / gameState.price);
acresSlider.value = 0;
acresSlider.step = 1;
var feedSlider = getSlider("sliderFeedpeople");
feedSlider.min = 0;
feedSlider.max = gameState.internalBushels;
feedSlider.value = 0;
feedSlider.step = 1;
var plantSlider = getSlider("sliderPlantwithseed");
plantSlider.min = 0;
plantSlider.max = minimum(gameState.internalAcres, 10 * gameState.population, gameState.internalBushels);
plantSlider.value = 0;
plantSlider.step = 1;
writeGameState();
} else if (tooManyPeopleStarved()) {
alert("Du har orsakat att 45% av befolkningen svultit ihjäl!\n" + "Du har avsatts.\n" + "Försök igen.");
gameStart();
} else {
var averagePeopleStarved = Math.floor(gameState.totalStarved / 10);
var acrePerPerson = Math.floor(gameState.acres / gameState.population);
alert("Total prestation\n" + "Genomsnittligt antal ihjälsvultna per år: " + averagePeopleStarved + "\n" + "Befolkning: " + gameState.population + "\n" + "Tunnland per person: " + acrePerPerson);
gameStart();
}
}<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Hammurabi</title>
<link rel="stylesheet" href="hammurabi.css">
<script src="hammurabi.js" defer></script>
<link rel="icon" type="image/png" href="logo.png">
<!--
This script waits until the page is loaded,
then starts the game by calling gameStart().
It checks if gameStart exists before calling it.
-->
<script defer>
document.addEventListener('DOMContentLoaded', function () {
if (typeof gameStart === 'function') gameStart();
});
</script>
</head>
<body>
<!--
Bilden på sidan
-->
<div class="hero-row">
<img src="Babylonian.png" alt="Babylonian" class="side-img side-img--abs">
</div>
<header class="site-header">
<div class="container">
<!-- Logo image for the game -->
<img src="logo.png" alt="Hammurabi logotyp" class="site-logo">
<!-- Main title of the game -->
<h1>Hammurabi</h1>
<!-- Navigation menu -->
<nav class="top-nav">
<a href="#om-spelet">Om spelet</a>
<a href="#om-kungen">Om Hammurabi</a>
<a href="#regler">Regler</a>
<a href="#kallor">Källor</a>
</nav>
</div>
</header>
<!--
Main content area.
Uses a two-column layout:
- Left: the game controls and status
- Right: information and instructions
-->
<main class="container layout">
<!--
Spelkontroller
-->
<section aria-label="Spelkontroller" class="card card--accent-blue">
<h2 id="year" aria-live="polite">TEXT-SOM-BYTS-UT-AV-JS-FILEN</h2>
<ul id="people" class="panel card card--accent-green">
<li id="starved">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
<li id="newcomers">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
<li id="population">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
</ul>
<ul id="economy" class="panel card card--accent-purple">
<li id="acres">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
<li id="bushels">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
<li id="harvest">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
<li id="rats">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
<li id="price">TEXT-SOM-BYTS-UT-AV-JS-FILEN</li>
</ul>
<form onsubmit="return false">
<fieldset>
<legend>
Tunnland sälja/köpa:
<span class="value" id="outputAcrestosellbuy"></span>
</legend>
<div class="row">
<button class="button red" id="minusbuttonAcrestosellbuy"
onclick="onChangeAcres('minusbuttonAcrestosellbuy')" type="button"
aria-label="Minska">
<svg width="20" height="20" viewBox="0 0 20 20"
aria-hidden="true">
<rect x="4" y="9" width="12" height="2" rx="1" />
</svg>
</button>
<input type="range" id="sliderAcrestosellbuy"
min="-1000" max="1000" step="1" value="0"
onchange="onChangeAcres('sliderAcrestosellbuy')">
<button class="button blue" id="plusbuttonAcrestosellbuy"
onclick="onChangeAcres('plusbuttonAcrestosellbuy')"
type="button" aria-label="Öka">
<svg width="20" height="20" viewBox="0 0 20 20"
aria-hidden="true">
<rect x="9" y="4" width="2" height="12" rx="1" />
<rect x="4" y="9" width="12" height="2" rx="1" />
</svg>
</button>
</div>
</fieldset>
<!--
Slider for how much food to give the people.
-->
<fieldset>
<legend>
Mat till folket:
<span class="value" id="outputFeedpeople"></span>
</legend>
<div class="row">
<button class="button red" id="minusbuttonFeedpeople"
onclick="onChangeFeeding('minusbuttonFeedpeople')"
type="button">-</button>
<input type="range" id="sliderFeedpeople"
min="0" max="2800" step="1" value="0"
onchange="onChangeFeeding('sliderFeedpeople')">
<!-- Button to increase food amount -->
<button class="button blue" id="plusbuttonFeedpeople"
onclick="onChangeFeeding('plusbuttonFeedpeople')" type="button">+
</button>
</div>
</fieldset>
<fieldset>
<legend>
Sådd:
<span class="value" id="outputPlantwithseed"></span>
</legend>
<div class="row">
<button class="button red" id="minusbuttonPlantwithseed"
onclick="onChangePlanting('minusbuttonPlantwithseed')"
type="button">-
</button>
<input type="range" id="sliderPlantwithseed"
min="0" max="1000" step="1" value="0"
onchange="onChangePlanting('sliderPlantwithseed')">
<button class="button blue" id="plusbuttonPlantwithseed"
onclick="onChangePlanting('plusbuttonPlantwithseed')"
type="button">+
</button>
</div>
</fieldset>
<div class="actions-row">
<!-- Button to restart the game -->
<button class="button yellow" type="button" onclick="gameStart()">
Starta om</button>
<!-- Button to finish and send orders -->
<button class="button green" type="button" onclick="finishTurn()">
Detta är min order!
</button>
<!--
Hjälp knappen.
-->
<details class="help-pop">
<!-- Looks like a button, opens the help -->
<summary class="button neutral" aria-label="Hur funkar spelet?">
Hjälp
</summary>
<div class="help-pop__card card">
<h3 class="help-pop__title">Snabbguide</h3>
<ul class="bullets">
<li>Spelet pågår i <strong>10 år</strong> (10 rundor).</li>
<li><strong>Mat:</strong> 20 skäppor behövs per person/år.</li>
<li><strong>Sådd:</strong> 1 skäppa per tunnland. Max sådd =
<em>min</em>(tunnland, 10×befolkning, skäppor).</li>
<li><strong>Landpris</strong> varierar varje år.</li>
<li><strong>Råttor/pest</strong> kan slå till vissa år.</li>
<li>Försök hålla folket mätta och så all mark om möjligt.</li>
</ul>
<p class="small">
Vill du läsa mer? Se
<a href="Hammurabi Game - Play Hammurabi Online-1.pdf"
target="_blank" rel="noopener">Regler</a>.
</p>
</div>
</details>
</div>
</form>
</section>
<!--
RIGHT COLUMN: Info and instructions
These sections do not change during the game.
They explain the rules, background, and sources.
-->
<aside aria-label="Rapport och info" class="stack">
<!-- Section about the game itself -->
<section id="om-spelet" class="info card card--tint-blue">
<h2>Om spelet</h2>
<p>
Hammurabi är ett av de första spelen som gjordes år 1968, du har i
uppgift att ta över en stad och vägleda den genom 10 år av skörd,
svält, och pest. Ditt mål är att hålla så många av dina invånare vid
liv som möjligt och att maximera mängden land du äger vid slutet av
de 10 åren.
Lycka till!
</p>
</section>
<!-- Section about King Hammurabi -->
<section id="om-kungen" class="info card card--tint-amber">
<h2>Om Hammurabi (kungen)</h2>
<p>
Hammurabi var den sjätte kungen av Babylon, som regerade från cirka
1792 f.Kr. till 1750 f.Kr. Han är mest känd för sin lagkodex, en av de
äldsta och mest kompletta lagkoderna som har bevarats från den antika
världen.
</p>
</section>
<!-- Section with the rules of the game -->
<section id="regler" class="info card card--tint-green">
<h2>Regler</h2>
<ul class="bullets">
<li>Varje år: gör dina val och klicka <em>Detta är min order!</em>
</li>
<li>Mat: <strong>20 skäppor</strong> föder <strong>1 person</strong>
per år.</li>
<li>Sådd: Du kan högst så
<strong>min(tunnland, 10 × befolkning, skäppor i lager)</strong>.
</li>
<li>Pris per tunnland varierar (slump inom spelet).</li>
<li>Råttor kan äta upp spannmål vissa år; pest kan halvera
befolkningen.</li>
<li>Om för många svälter ett år blir du avsatt.</li>
<li>Efter år 10 får du en sammanfattning av din prestation.</li>
</ul>
</section>
<!-- Section with sources and links -->
<section id="kallor" class="info card card--tint-purple">
<h2>Källor</h2>
<ul class="bullets">
<li><a href="https://en.wikipedia.org/wiki/Hammurabi" target=
rel >Wikipedia: Om Hammurabi</a></li>
<li><a href="Hammurabi Game - Play Hammurabi Online-1.pdf" target=
rel >Regler</a></li>
<li><a href=
"https://www.nationalgeographic.com/culture/article/hammurabi"
target= rel >Logo Image</a></li>
<li><a href=
"https://warhistory.org/es/@msw/article/babylonia-enemy-of-assyria"
target= rel >Standing Image</a></li>
</ul>
</section>
</aside>
</main>
<footer class="site-footer">
<div class="container small">© 2025 - Studentprojekt för LTU</div>
</footer>
</body>
</html>
<!--
1-change colors on the right boxes --- Done
2- fix the information --- dome
3- change buttons --- Done
4- fix footer --- Done
5- max 80 char/line --- Done
6- add pictures (optional) --- Done
7- add comments to the code --- Done
8- fix any other issues --- Done
9- Understand the code
10. Ref img --- done
-->Circuits, sensors, and sound
Physical computing with Arduino. Four circuits exploring digital output, analog input, light-dependent resistors, and tone generation, building from a simple blinking LED up to a melody-playing buzzer that syncs with LEDs.
Progressive Arduino exercises: LED blink timing, potentiometer-controlled blink rate, LDR ambient light sensor driving LED brightness, and a buzzer playing a melody with LEDs alternating on each note.
int ledRed = 7; // Red LED pin
int ledBlue = 6; // Blue LED pin
void setup() {
pinMode(ledRed, OUTPUT);
pinMode(ledBlue, OUTPUT);
}
void loop() {
digitalWrite(ledRed, HIGH);
digitalWrite(ledBlue, HIGH);
delay(2000); // on for 2 seconds
digitalWrite(ledRed, LOW);
digitalWrite(ledBlue, LOW);
delay(2000); // off for 2 seconds
}
// Variations tested:
// delay(500) / delay(3500) → short flash, long pause
// delay(1) / delay(1) → PWM-like flicker at ~500 Hzint potPin = A0; // Potentiometer on analog pin A0
int ledRed = 7;
void setup() {
pinMode(ledRed, OUTPUT);
}
void loop() {
int potPosition = analogRead(potPin); // 0-1023
// Map pot range to blink delay 50ms-1000ms
int delayTime = map(potPosition, 0, 1023, 50, 1000);
digitalWrite(ledRed, HIGH);
delay(delayTime);
digitalWrite(ledRed, LOW);
delay(delayTime);
}int ldrPin = A0; // Light-dependent resistor
int ledRed = 7;
int ledBlue = 6;
void setup() {
pinMode(ledRed, OUTPUT);
pinMode(ledBlue, OUTPUT);
}
void loop() {
int ldrValue = analogRead(ldrPin); // 0-1023
int brightness = map(ldrValue, 0, 1023, 0, 255); // map to PWM range
analogWrite(ledBlue, brightness); // brighter in more light
analogWrite(ledRed, brightness);
delay(50);
}
// analogWrite uses PWM, only works on pins 3,5,6,9,10,11 on Unoconst int buzzerPin = 10;
int ledRed = 7;
int ledBlue = 6;
#define NOTE_C4 262
#define NOTE_D4 294
#define NOTE_E4 330
#define NOTE_G4 392
#define NOTE_C5 523
#define NOTE_REST 0
void setup() {
pinMode(buzzerPin, OUTPUT);
pinMode(ledRed, OUTPUT);
pinMode(ledBlue, OUTPUT);
playMelody();
}
void loop() {} // melody plays once on startup
void playMelody() {
int melody[] = { C4, D4, E4, G4, C5, C4, D4, E4, G4, C5,
C4, D4, E4, G4, C5, NOTE_REST };
int duration[] = { 200,200,200,200,400, 200,200,200,200,400,
200,200,200,200,400, 250 };
for (int i = 0; i < 16; i++) {
digitalWrite(ledRed, LOW);
digitalWrite(ledBlue, LOW);
if (melody[i] != NOTE_REST) {
// Alternate LEDs on even/odd notes
if (i % 2 == 0) digitalWrite(ledRed, HIGH);
else digitalWrite(ledBlue, HIGH);
tone(buzzerPin, melody[i]);
} else {
noTone(buzzerPin);
}
delay(duration[i]);
noTone(buzzerPin);
delay(50); // gap between notes
}
digitalWrite(ledRed, LOW);
digitalWrite(ledBlue, LOW);
}Academic writing with LaTeX
Two mathematical documents typeset in LaTeX. The Koch Snowflake paper proves two theorems about the fractal's infinite perimeter and finite area using formal proof environments. The Ski Slope paper solves a Swedish national exam problem using calculus, finding where a hill is steepest by analysing the second derivative.
Two academic papers using LaTeX theorem/proof environments, aligned equations, figure insertion, and BibTeX citations.
\section{A Famous Fractal: The Koch Snowflake}
The \emph{Koch snowflake} is based on work by the Swedish mathematician
Helge von Koch \cite{koch}. It is constructed from an equilateral triangle
by repeating this process infinitely:
\begin{quote}
\textit{Divide all segments into three equal parts. For each middle
segment, draw an outward equilateral triangle, then remove the middle.}
\end{quote}
% --- Theorem 1: Infinite perimeter ---
\begin{theorem}
The Koch snowflake has infinite length.
\end{theorem}
\begin{proof}
Let $N_n = 3 \cdot 4^n$ be the number of segments after $n$ iterations,
and $L_n = s / 3^n$ the length of each segment. Then
\[
N_n L_n = 3s \left(\frac{4}{3}\right)^n \to \infty \quad (n \to \infty).
\]
Since $4/3 > 1$, the total length diverges.
\end{proof}
% --- Theorem 2: Finite area ---
\begin{theorem}
The Koch snowflake has finite area.
\end{theorem}
\begin{proof}
In iteration $n$, the number of new triangles is $T_n = \tfrac{3}{4} \cdot 4^n$
and each has area $a_n = a_0 / 9^n$. The total area after $n$ iterations:
\[
A_n = \frac{a_0}{5}\!\left(8 - 3\!\left(\tfrac{4}{9}\right)^{\!n}\right)
\;\xrightarrow{n\to\infty}\; \frac{8a_0}{5} \quad \text{(finite)}.
\]
\end{proof}\section{Höjdprofilen och dess derivata}
The height profile of the slope is given by
\begin{equation}
y(x) = x^2 e^{-0.5x}. \label{eq:y}
\end{equation}
Using the product rule $\frac{d}{dx}(uv) = u'v + uv'$ with
$u = x^2,\; v = e^{-0.5x}$:
\begin{align}
y'(x) &= 2x\,e^{-0.5x} + x^2(-0.5)e^{-0.5x} \nonumber \\
&= e^{-0.5x}(2x - 0.5x^2). \label{eq:yprime}
\end{align}
\section{Maximal branthet} % "maximum steepness"
Setting $y''(x) = 0$ and factoring out the always-positive $e^{-0.5x}$:
\begin{align}
y''(x) &= e^{-0.5x}(0.25x^2 - 2x + 2) = 0 \nonumber \\
\Rightarrow\quad & x^2 - 8x + 8 = 0.
\end{align}
By the quadratic formula:
\begin{align}
x &= \frac{8 \pm \sqrt{64-32}}{2} = 4 \pm 2\sqrt{2}.
\end{align}
Analysis shows $x_1 = 4 - 2\sqrt{2} \approx 1.17$ km is a maximum of $y'$,
so the slope is steepest at $\boxed{x \approx 1.17 \text{ km}}$.Maximum subarray: three algorithms, three complexities
Finding the largest sum of a contiguous subsequence. Three approaches (O(n³) brute force, O(n²) with reuse, and O(n²) with prefix sums), analysed in a LaTeX report co-authored with a classmate.
Compare all three algorithms visually. Enter a list of numbers and watch each approach find the maximum subarray, with step counts shown live.
// Three nested loops, all possible subsequences
// Time complexity: O(n³)
static int maxSubCubic(int[] a) {
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
int sum = 0;
for (int k = i; k <= j; k++) // recompute sum each time
sum += a[k];
maxSum = Math.max(maxSum, sum);
}
}
return maxSum;
}
// Steps: n³/6 → if n doubles, steps × 8// Two loops, extend running sum instead of restarting
// Time complexity: O(n²)
static int maxSubQuad1(int[] a) {
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
int sum = 0;
for (int j = i; j < a.length; j++) {
sum += a[j]; // reuse: don't restart inner loop from i
maxSum = Math.max(maxSum, sum);
}
}
return maxSum;
}
// Steps: n²/2 → if n doubles, steps × 4// Precompute prefix sums, then check all pairs in O(1) each
// Build: O(n), Query: O(1) each, Total: O(n²)
static int maxSubPrefix(int[] a) {
int n = a.length;
int[] prefix = new int[n + 1];
for (int i = 0; i < n; i++)
prefix[i + 1] = prefix[i] + a[i]; // prefix[j] = a[0]+...+a[j-1]
int maxSum = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j <= n; j++)
// sum from i to j-1 = prefix[j] - prefix[i]
maxSum = Math.max(maxSum, prefix[j] - prefix[i]);
return maxSum;
}
// Key insight: sum(i..j) = prefix[j+1] - prefix[i] → O(1) lookup\section{Diskussion och sammanfattning}
\textbf{Jämförelse.}
De kvadratiska metoderna är mycket snabbare än den kubiska
metoden, men alla metoder ger samma resultat.
\textbf{Big-O i vardagsord.}
Om listans längd $n$ ökar med 10, ökar antalet beräkningssteg
med $1000\times$ för den kubiska metoden men bara $100\times$
för de kvadratiska metoderna.
\begin{align}
\text{Cubic: } &O(n^3) \label{eq:cubic} \\
\text{Quad 1: } &O(n^2) \label{eq:quad1} \\
\text{Quad 2: } &O(n) + O(n^2)\cdot O(1) = O(n^2) \label{eq:quad2}
\end{align}
\begin{thebibliography}{99}
\bibitem{bentley}
Jon Bentley.
\textit{Programming Pearls: Algorithm Design Techniques}.
CACM, 27(9):865--873, 1984.
\end{thebibliography}Yrkesrollen: the engineer's professional identity
A written assignment co-authored in LaTeX covering gender equality in tech, engineering virtues, professional licensing, and the ethics of refusing clients. Based on course readings from Sven Ove Hansson's Teknik och etik.
Five questions on gender equality, engineering virtues, licensing, and professional ethics. Written in Swedish, co-authored with a classmate, typeset in LaTeX.
- Better decisions & innovation. Diverse groups have more perspectives and fewer blind spots. This improves user-centred design, risk assessment, and requirements analysis.
- Identifying and developing talent. An inclusive workplace attracts more candidates and reduces turnover, saving money and retaining key people long-term.
- Customer value, compliance & reputation. Actively promoting equality reduces legal risk, strengthens the brand, and opens new markets as products are designed for a broader audience.
- Structured meetings for equal voice. Collect ideas via anonymous forms before meetings so proposals are judged on content, not who sent them. Use speaker lists, timing, and rotating chairs.
- Transparent recruitment & promotion. Blind CV reviews, standardised competency profiles, diverse hiring panels, and data-driven bias correction.
- Mentorship & sponsorship programmes. Formal mentor/sponsor schemes with scheduled time during work hours, with effect and engagement tracked to ensure long-term success.
Yes. In addition to general virtues like justice and temperance, engineering requires specific qualities:
- A sense of responsibility for impact on society
- Truthfulness and honesty in data and communication
- Care for environment and safety
- Judgement in ambiguous situations
- Moral courage to speak up when something is wrong
These align with the principles of responsibility, impartiality, openness about risks, and loyalty described in the honour code.
For: Engineers significantly influence infrastructure, the environment, and human lives. Professional regulation could allow licences to be revoked for serious violations and strengthen public trust.
Against: Standardised certification risks being discriminatory and ineffective given the broad scope of the engineering sector. Innovation may be hampered, and organisations and processes are often held responsible instead of individuals.
Position: Implement limited licencing for safety-critical areas (e.g. electrical authority) combined with strict organisational criteria. Focus regulation where risks are highest to preserve flexibility elsewhere.
Selected question: Should engineers ethically be able to "judge" their clients, unlike lawyers or doctors who must help everyone?
For: Technical expertise is a public good. Using it neutrally reduces bias. Even in controversial projects, innovations that benefit society can emerge.
Against: The honour code requires engineers to abstain from projects that are questionable or conflict with their own convictions. Engineers also have obligations to the environment and public, not just their clients.
Position: When the primary purpose of a project conflicts with fundamental ethical principles (such as human rights violations), engineers must be able to refuse. In other situations, engineers should demand transparency, conduct risk assessments, and establish guidelines to minimise harm.
What I learned
Hammurabi is a handful of numbers that change once a year. Most of the work is checking that the player cannot spend more grain, land or people than there are.
With Arduino, a sensor is just a number to read and a lamp is just a pin to set, but the wiring has to be right as well as the code.