---
title: "Untitled"
author: "warehouse com1"
date: "2026-10-23"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
# ============================================================
# Name:             Mohammed Nawaf
# Student Number:   2541121
# Programme:        MSc Data and Artificial Intelligence
# Module:           Advanced Statistical Programming
# Module Code:      ACCA7022
# Lecturer:         Dr Aliyu Sambo
# Assessment Title: Smart Warehouse Inventory Simulation
# Date:             October 2026
# Purpose:          Generate and manipulate simulated warehouse
#                   data in R using loops only.
# ============================================================

```
```{r}
# ------------------------------------------------------------
# Setup: fixed seed and constants
# ------------------------------------------------------------
set.seed(123)

base_units     <- 100
time_per_unit  <- 0.85
num_days       <- 28
num_zones      <- 5
num_categories <- 6
total_rows     <- num_days * num_zones * num_categories

```
```{r}
# ============================================================
# Part A: Generate Warehouse Data
# ============================================================

# Pre-allocate vectors for each column
day_col      <- integer(total_rows)
zone_col     <- integer(total_rows)
category_col <- integer(total_rows)
units_col    <- integer(total_rows)
time_col     <- numeric(total_rows)

# Nested loops: one row per day / zone / category combination
row_index <- 1
for (day in 1:num_days) {
  for (zone in 1:num_zones) {
    for (category in 1:num_categories) {

      random_variation <- sample(-12:12, 1)
      units_processed  <- base_units + (zone * 8) + (category * 5) + random_variation
      processing_time  <- units_processed * time_per_unit

      day_col[row_index]      <- day
      zone_col[row_index]     <- zone
      category_col[row_index] <- category
      units_col[row_index]    <- units_processed
      time_col[row_index]     <- round(processing_time, 2)

      row_index <- row_index + 1
    }
  }
}

# Build the dataframe
warehouse_data <- data.frame(
  Day            = day_col,
  Zone           = zone_col,
  Category       = category_col,
  UnitsProcessed = units_col,
  ProcessingTime = time_col
)

# Display first 10 rows and dimensions
cat("\n--- Part A: First 10 rows of warehouse_data ---\n")
print(head(warehouse_data, 10))
cat("\nNumber of rows:   ", nrow(warehouse_data), "\n")
cat("Number of columns:", ncol(warehouse_data), "\n")

```
```{r}
# ============================================================
# Part B: Total Units Processed per Zone
# ============================================================

zone_totals <- data.frame(
  Zone       = 1:num_zones,
  TotalUnits = numeric(num_zones)
)

# For each zone, add up units from every matching row
for (zone in 1:num_zones) {
  zone_total <- 0
  for (i in 1:nrow(warehouse_data)) {
    if (warehouse_data$Zone[i] == zone) {
      zone_total <- zone_total + warehouse_data$UnitsProcessed[i]
    }
  }
  zone_totals$TotalUnits[zone] <- zone_total
}

cat("\n--- Part B: zone_totals ---\n")
print(zone_totals)

```
```{r}
# ============================================================
# Part C: Average Processing Time per Product Category
# ============================================================

category_average_time <- data.frame(
  Category              = 1:num_categories,
  AverageProcessingTime = numeric(num_categories)
)

# For each category, total the time and count the matching records
for (category in 1:num_categories) {
  time_total   <- 0
  record_count <- 0
  for (i in 1:nrow(warehouse_data)) {
    if (warehouse_data$Category[i] == category) {
      time_total   <- time_total + warehouse_data$ProcessingTime[i]
      record_count <- record_count + 1
    }
  }
  category_average_time$AverageProcessingTime[category] <- round(time_total / record_count, 2)
}

cat("\n--- Part C: category_average_time ---\n")
print(category_average_time)
```


```{r}
# ============================================================
# Part D: Identify Stock Processing Anomalies
# ============================================================

# Matrices to hold totals and counts for each day (rows) and zone (columns)
daily_zone_total <- matrix(0, nrow = num_days, ncol = num_zones)
daily_zone_count <- matrix(0, nrow = num_days, ncol = num_zones)

# Step 1: accumulate units and counts per day / zone
for (i in 1:nrow(warehouse_data)) {
  d <- warehouse_data$Day[i]
  z <- warehouse_data$Zone[i]
  daily_zone_total[d, z] <- daily_zone_total[d, z] + warehouse_data$UnitsProcessed[i]
  daily_zone_count[d, z] <- daily_zone_count[d, z] + 1
}

# Step 2: calculate the average for each day / zone
daily_zone_avg <- matrix(0, nrow = num_days, ncol = num_zones)
for (d in 1:num_days) {
  for (z in 1:num_zones) {
    daily_zone_avg[d, z] <- daily_zone_total[d, z] / daily_zone_count[d, z]
  }
}

# Step 3: attach the average to each record and flag anomalies
avg_col     <- numeric(total_rows)
anomaly_col <- logical(total_rows)

for (i in 1:nrow(warehouse_data)) {
  d     <- warehouse_data$Day[i]
  z     <- warehouse_data$Zone[i]
  units <- warehouse_data$UnitsProcessed[i]
  avg   <- daily_zone_avg[d, z]

  avg_col[i]     <- round(avg, 2)
  anomaly_col[i] <- (units > avg * 1.15) | (units < avg * 0.85)
}

processing_anomalies <- data.frame(
  Day              = warehouse_data$Day,
  Zone             = warehouse_data$Zone,
  Category         = warehouse_data$Category,
  UnitsProcessed   = warehouse_data$UnitsProcessed,
  DailyZoneAverage = avg_col,
  Anomaly          = anomaly_col
)

# Display first 10 anomaly rows
anomaly_rows <- processing_anomalies[processing_anomalies$Anomaly == TRUE, ]
cat("\n--- Part D: First 10 anomalies ---\n")
print(head(anomaly_rows, 10))
```


```{r}
# ============================================================
# Part E: Most Productive Day for Each Zone
# ============================================================

peak_zone_days <- data.frame(
  Zone       = 1:num_zones,
  Day        = integer(num_zones),
  TotalUnits = numeric(num_zones)
)

# For each zone, find the day with the highest total
# (daily totals reused from Part D; ties keep the earliest day)
for (z in 1:num_zones) {
  best_day   <- 1
  best_total <- daily_zone_total[1, z]
  for (d in 2:num_days) {
    if (daily_zone_total[d, z] > best_total) {
      best_total <- daily_zone_total[d, z]
      best_day   <- d
    }
  }
  peak_zone_days$Day[z]        <- best_day
  peak_zone_days$TotalUnits[z] <- best_total
}

cat("\n--- Part E: peak_zone_days ---\n")
print(peak_zone_days)


```

## R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

```{r cars}
summary(cars)
```

## Including Plots

You can also embed plots, for example:

```{r pressure, echo=FALSE}
plot(pressure)
```

Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
