A-level Computing/AQA/Paper 1/Skeleton program/2020

From Wikibooks, open books for an open world
< A-level Computing‎ | AQA‎ | Paper 1‎ | Skeleton program
Jump to navigation Jump to search

This is for the AQA A Level Computer Science Specification.

This is where suggestions can be made about what some of the questions might be and how we can solve them.

Please be respectful and do not vandalise the page, as this would affect students' preparation for exams! - Martin
Please do not discuss questions on this page. Instead use the discussion page: Coming soon!

AQA Skeleton Program 2020 - Class Diagram

Section C Predictions[edit]

  • The 2020 paper 1 will contain 1 question in Section C: two parts, worth 1 and 2 marks respectively.
  • What is the function of super() in the definition of the LargeSettlement class? - Not relevant to all languages - Could question be reworded to make it more realistic? (Another option could be: "Explain how Settlement is used as a superclass in the program")
  • State one additional line of code which should be added after the Ben Thor Cuisine default company definition in the Simulation class' constructor in order to make it consistent with the ModifyCompany() function.

Section D Predictions[edit]

Programming Questions on Skeleton Program

  • The 2020 paper 1 will contain 4 questions: a 6 mark, an 8 mark question, a 11 mark question and one 12 mark question - these marks include the screen capture(s), so the likely marks for the coding will be 1-2 marks lower.
  • The 2019 paper 1 contained 4 questions: a 5 mark, an 8 mark question, a 9 mark question and one 13 mark question - these marks include the screen capture(s), so the marks for the coding will be 1-2 marks lower.
  • The 2018 paper 1 contained one 2 mark question, a 5 mark question, two 9 mark questions, and one 12 mark question - these marks include the screen capture(s). In contrast, the 2017 paper 1 contained a 5 mark question, three 6 mark questions, and one 12 mark question.

Current questions are speculation by contributors to this page.

  • Ensure costs are displayed in the following format £X.XX (4 Marks)
  • Add a new Small Settlement class and an option to create a Small Settlement in the simulation launch menu (6 Marks)
  • Add a Close Outlet event which results in an outlet being removed from the simulation (11 Marks)
  • ExpandOutlet() add option for when the capacity is now zero
  • AlterCapacity(Change) correctly calculate the new DailyCosts when new capacity is limited to the max capacity
  • AddCompany(self) add check to see if CompanyName already exists in _Companies
  • RemoveCompany() add option to remove a company instead of removing each of its outlets individually (this is likely to come up, there is no option 5 in the menu so this seems logical)
  • Add a faster option to load in the default scenario
  • Close an outlet for a specified temporary number of days
  • Merge two companies together
  • Advanced a specified number of days
  • Display how many days have passed
  • Display net gain/loss for the companies
  • Display net and average weekly gains/losses for individual outlets
  • Ensure fuel costs can never become negative
  • increase or decrease reputation of a company by three when user gives rating
  • Modify the CalculateDeliveryCost() function so that the shortest path through all Outlets is used to minimise delivery costs (using Breadth-First graph traversal)
  • Add ability to create a new settlement and have outlets set up there
  • Validation on the initial entries for the program to run its menu
  • Validation on coordinates of Outlets, Households etc since two could randomly overlap on the x and y coordinates

change reputation with user's rating[edit]

Java:

  • change reputation method
private void changeReputation(){
        System.out.print("Which company: ");
        String compCR = Console.readLine();
        int indCR = getIndexOfCompany(compCR);
        System.out.print("How do you rate the company? - good or bad : ");
        String rate = Console.readLine();
        if(rate.equals("good")){
            companies.get(indCR).alterReputation(3);
        } else{
            companies.get(indCR).alterReputation(-3);
        }
    }
  • add this to display menu
public void displayMenu() {
        Console.writeLine(System.lineSeparator() + "*********************************");
        Console.writeLine("**********    MENU     **********");
        Console.writeLine("*********************************");
        Console.writeLine("1. Display details of households");
        Console.writeLine("2. Display details of companies");
        Console.writeLine("3. Modify company");
        Console.writeLine("4. Add new company");
        Console.writeLine("6. Advance to next day");
        Console.writeLine("7. Change Reputation");
        Console.writeLine("Q. Quit");
        Console.write(System.lineSeparator() + "Enter your choice: ");
    }
  • add this to run
public void run() {
        String choice = "";
        int index;
        while (!choice.equals("Q")) {
            displayMenu();
            choice = Console.readLine();
            switch (choice) {
                case "1":
                    simulationSettlement.displayHouseholds();
                    break;
                case "2":
                    displayCompanies();
                    break;
                case "3":
                    String companyName;
                    do {
                        Console.write("Enter company name: ");
                        companyName = Console.readLine();
                        index = getIndexOfCompany(companyName);
                    } while (index == -1);
                    modifyCompany(index);
                    break;
                case "4":
                    addCompany();
                    break;
                case "6":
                    processDayEnd();
                    break;
                case "7":
                    changeReputation();
                    break;
                case "Q":
                    Console.writeLine("Simulation finished, press Enter to close.");
                    Console.readLine();
                    break;
            }
        }
    }


VB.NET:


C#:


Delphi/Pascal:


Python:


Power outage event[edit]

Java:

private void processPowerOutageEvent() {
        int numOfDays = rnd.nextInt(3) + 1;
        float amountToLose = rnd.nextFloat();
        Console.writeLine("There has been a powercut, which will last for " + numOfDays + " days, and each company has lost " + amountToLose);
        for (Company c : companies)
            c.balance -= amountToLose;
    }

    private void displayEventsAtDayEnd() {
        boolean hasEvent = false;
        Console.writeLine(System.lineSeparator() + "***********************");
        Console.writeLine("*****   Events:   *****");
        Console.writeLine("***********************" + System.lineSeparator());
        float eventRanNo;
        eventRanNo = rnd.nextFloat();
        if (!companies.isEmpty()) {
            if (eventRanNo < 0.25f) {
                eventRanNo = rnd.nextFloat();
                if (eventRanNo < 0.25f) {
                    processAddHouseholdsEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo < 0.5f) {
                    processCostOfFuelChangeEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo < 0.5f) {
                    processReputationChangeEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo >= 0.5f) {
                    processCostChangeEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo >= 0.25f) {
                    processPowerOutageEvent();
                    hasEvent = true;
                }
            }
            if (processGoBankruptEvent())
                hasEvent = true;
            if (!hasEvent) {
                Console.writeLine("No events.");
            }
        } else {
            Console.writeLine("No more companies. Simulation finished, press Enter to close.");
            Console.readLine();
            System.exit(0);
        }
    }
  • by Lucy W


C#:

Both of these in the simulation class, the display events at end of day is an updated version
private void ProcessPowerCutEvent() //  making an event for the company to loose power for a random amount of time
        {
            int count = 0;
            double numOfDays = Math.Round((rnd.NextDouble() * 10), 0);
            double amountToLose = rnd.NextDouble() *numOfDays * 1000;
            Console.WriteLine("There has been a powercut, which will last for " + numOfDays + " days, and each company has lost " + amountToLose);
            do
            {
                companies[count].ChangeBal(amountToLose);
                count++;
            } while (count < 3);
            dayCounter += (int)(numOfDays);
        }

        
private void DisplayEventsAtDayEnd()
        {
            Console.WriteLine("\n***********************");
            Console.WriteLine("*****   Events:   *****");
            Console.WriteLine("***********************\n");
            double eventRanNo;
            eventRanNo = rnd.NextDouble();
            if (eventRanNo < 0.25)
            {
                eventRanNo = rnd.NextDouble();
                if (eventRanNo < 0.25)
                {
                    ProcessAddHouseholdsEvent();
                }
                eventRanNo = rnd.NextDouble();
                if (eventRanNo < 0.5)
                {
                    ProcessCostOfFuelChangeEvent();
                }
                eventRanNo = rnd.NextDouble();
                if (eventRanNo < 0.5)
                {
                    ProcessReputationChangeEvent();
                }
                eventRanNo = rnd.NextDouble();
                if (eventRanNo >= 0.5)
                {
                    ProcessCostChangeEvent();
                }
                if (eventRanNo >= 0.5)
                {
                    ProcessPowerCutEvent();
                }
            }
            else
            {
                Console.WriteLine("No events.");
            }
        }

This needs to go in the company class


public void ChangeBal(double amounttoloose) // changing the balance for a power cut event
        {
            balance -= amounttoloose;

        }

*By Michael Tomkinson


VB.NET:


Power cut event for a random company for a random amount of time in hours.

Add into Simulation class:

Public Sub ProcessPowerOutage()

        Randomize()
        Dim noOfDays As Integer = Int((Rnd() * 7) + 1)
        Dim moneyLost As Integer = Int((Rnd() * 1000) + 1)
        Dim totalLoss As Integer
        Dim CompanyNo As Integer = Int(Rnd() * Companies.Count)

        Console.WriteLine(Environment.NewLine & Companies(CompanyNo).GetName() & " is experiencing a powercut:")
        Console.WriteLine(Environment.NewLine & Companies(CompanyNo).GetName() & ". Balance: £" & Companies(CompanyNo).getBalance())

        For i = 1 To noOfDays
            Companies(CompanyNo).alterbalance(moneyLost)
            totalLoss += moneyLost
            Console.WriteLine(Environment.NewLine & "Hour: " & i)
            Console.WriteLine(Companies(CompanyNo).GetName() & " has lost £" & totalLoss & " in " & i & " hours.")
            Console.WriteLine(Companies(CompanyNo).GetName() & ". Balance: £" & Companies(CompanyNo).getBalance())
        Next

        Console.WriteLine(Environment.NewLine & Companies(CompanyNo).GetName() & " has lost £" & totalLoss & " in total." & Environment.NewLine)
    End Sub

Edited DisplayEventsAtDayEnd() subroutine:

Private Sub DisplayEventsAtDayEnd()
        Console.WriteLine(Environment.NewLine & "***********************")
        Console.WriteLine("*****   Events:   *****")
        Console.WriteLine("***********************" & Environment.NewLine)
        Dim EventRanNo As Single
        EventRanNo = Rnd()
        If EventRanNo < 0.25 Then
            EventRanNo = Rnd()
            If EventRanNo < 0.25 Then
                ProcessAddHouseholdsEvent()
            End If
            EventRanNo = Rnd()
            If EventRanNo < 0.5 Then
                ProcessCostOfFuelChangeEvent()
            End If
            EventRanNo = Rnd()
            If EventRanNo < 0.5 Then
                ProcessReputationChangeEvent()
            End If
            EventRanNo = Rnd()
            If EventRanNo >= 0.5 Then
                ProcessCostChangeEvent()
            End If
            EventRanNo = Rnd()
            If EventRanNo < 0.1 Then
                ProcessPowerOutage()
            End If
        Else
            Console.WriteLine("No events.")
        End If
    End Sub

In Company Class add:

Public Function GetBalance() As Single
        Return Balance
    End Function

Public Sub AlterBalance(ByVal Change As Single)
        Balance -= Change
    End Sub


'Hubert (Ousedale School) - 09/11/2019


End of world event[edit]

Java:

Within the Simulation class, make a method processEndOfWorld():

private void processEndOfWorld() 
{
    Console.println("An asteroid has hit the earth. The world has ended.");
    System.exit(0);
}

Within the displayEventsAtDayEnd() method in the Simulation class, add:

if (eventRanNo <= 0.1f)
{
    processEndOfWorld();
}

VB.net:

Make a method Dropworld() in the simulation class:

Sub Dropworld()
        console.writeline("Darkrai used black hole eclipse. A quadrillion quadrillion joules of energy was released in two seconds. The world is gone")
        console.readline()
        Stop
    End Sub

Within the DisplayEventsAtDayEnd() sub in the Simulation class, add:

If EventRanNo < 0.1 Then
                DropWorld()
            End If

Merge companies[edit]

Java:

/* in the Simulation class */
public void mergeCompanies() {
        System.out.println("\n******* Merge Companies *********\n");
        for(int i = 0; i < companies.size();i++ ){
            System.out.println((i+1) + "." + companies.get(i).getName());
        } System.out.println("");
        int com1, com2;
        do {
            System.out.print("Enter 1st Company: ");
            String comTemp1 = Console.readLine();
            try{
                com1 = Integer.parseInt(comTemp1)-1;
            } catch (NumberFormatException e) {
                com1 = -1;
            }
        } while (com1 < 0);
        Company company1 = companies.get(com1);
        companies.remove(com1);
        
        System.out.println("");
        for(int i = 0; i < companies.size();i++ ){
            Console.writeLine((i+1) + "." + companies.get(i).getName());
        } System.out.println("");
        do {
            System.out.print("Enter 2nd Company: ");
            String comTemp2 = Console.readLine();
            try{
                com2 = Integer.parseInt(comTemp2)-1;
            } catch (NumberFormatException e) {
                com2 = -1;
            }
        } while (com2 < 0);
        Company company2 = companies.get(com2);
        companies.remove(com2);
        System.out.print("Enter new Company name: ");
        String comName = Console.readLine();
        float comBal = company2.getBalance() + company1.getBalance();
        float comReputation = (company1.getReputationScore() > company2.getReputationScore())
                ?company1.getReputationScore()
                :company2.getReputationScore();
        float comAvgCost = (company1.getAvgCostPerMeal() + company2.getAvgCostPerMeal())/2;
        float comAvgPrice = (company2.getAvgPricePerMeal() + company2.getAvgPricePerMeal())/2;
        float comDaily = (company1.getDailyCosts() + company2.getDailyCosts())/2;
        float comFuel = (company1.getFuelCostPerUnit() + company2.getFuelCostPerUnit())/2;
        float comBase = (company1.getBaseCostOfDelivery()+company2.getBaseCostOfDelivery())/2;
        List<Outlet> comOutlets = company1.getOutlets();
        comOutlets.addAll(company2.getOutlets());
        Company newCom = new Company(comName, company1.getCategory(), comBal, comReputation, comAvgCost, comAvgPrice, comDaily, comFuel, comBase, comOutlets);
        companies.add(newCom);
    }
/* in the company class */
public Company(String name, String category, float balance, float reputationScore, float avgCostPerMeal, 
            float avgPricePerMeal, float dailyCosts, float fuelCostPerUnit, float baseCostOfDelivery, List<Outlet> outlets) {
        familyOutletCost = 1000;
        fastFoodOutletCost = 2000;
        namedChefOutletCost = 15000;
        familyFoodOutletCapacity = 150;
        fastFoodOutletCapacity = 200;        
        namedChefOutletCapacity = 50;
        this.name = name;
        this.category = category;
        this.balance = balance;
        this.reputationScore = reputationScore;
        this.avgCostPerMeal = avgCostPerMeal;
        this.avgPricePerMeal = avgPricePerMeal;
        this.dailyCosts = dailyCosts;
        this.fuelCostPerUnit = fuelCostPerUnit;
        this.baseCostOfDelivery = baseCostOfDelivery;
        this.outlets = outlets;
    }
    
    public float getBalance() { return balance; }
    public String getCategory() { return category;} 
    public float getAvgCostPerMeal() { return avgCostPerMeal; }
    public float getAvgPricePerMeal() {  return avgPricePerMeal; }
    public float getDailyCosts() { return dailyCosts; }
    public float getFuelCostPerUnit() { return fuelCostPerUnit; }
    public float getBaseCostOfDelivery() {return baseCostOfDelivery;}
    public List<Outlet> getOutlets() {return outlets;}

Go bankrupt event[edit]

Added event for companies to go bankrupt at -10,000

Java:

// create isBankrupt() method in Company class
public boolean isBankrupt() {
	return balance <= -10000;
}
// create method for going bankrupt in Simulation
private boolean processGoBankruptEvent() {
        boolean goneBankrupt = false;
        for (int i = 0; i < companies.size(); i++) {
            if (companies.get(i).isBankrupt()) {
                System.out.println(companies.get(i).getName() + " has gone bankrupt and is closing.");
                companies.remove(i);
                i--;
                goneBankrupt = true;
            }
        }
        return goneBankrupt;
    }
// edit method in Simulation
private void displayEventsAtDayEnd() {
        boolean hasEvent = false;
        Console.writeLine(System.lineSeparator() + "***********************");
        Console.writeLine("*****   Events:   *****");
        Console.writeLine("***********************" + System.lineSeparator());
        float eventRanNo;
        eventRanNo = rnd.nextFloat();
        if (!companies.isEmpty()) {
            if (eventRanNo < 0.25f) {
                eventRanNo = rnd.nextFloat();
                if (eventRanNo < 0.25f) {
                    processAddHouseholdsEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo < 0.5f) {
                    processCostOfFuelChangeEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo < 0.5f) {
                    processReputationChangeEvent();
                    hasEvent = true;
                }
                eventRanNo = rnd.nextFloat();
                if (eventRanNo >= 0.5f) {
                    processCostChangeEvent();
                    hasEvent = true;
                }
            }
            if (processGoBankruptEvent())
                hasEvent = true;
            if (!hasEvent) {
                Console.writeLine("No events.");
            }
        } else {
            Console.writeLine("No more companies. Simulation finished, press Enter to close.");
            Console.readLine();
            System.exit(0);
        }
    }
  • by Lucy W


C#:

i have done this slightly differently, i have made it so that after 7 days of being in debt then the company will be forced closed

class Company

   {
       private static Random rnd = new Random();
       protected string name, category;
       protected double balance, reputationScore, avgCostPerMeal, avgPricePerMeal, dailyCosts, familyOutletCost, fastFoodOutletCost, namedChefOutletCost, fuelCostPerUnit, baseCostOfDelivery;
       protected List<Outlet> outlets = new List<Outlet>();
       protected int familyFoodOutletCapacity, fastFoodOutletCapacity, namedChefOutletCapacity;
       protected bool isindebt;                                                                         // mmaking a bool to store if the company is in debt
       protected int daysindebt;
 


“LINE 390 to 420”

public bool GetIfInDebt() // function of if the company is in debt

       {
           if (balance < 0)
           {
               daysindebt++; // increments how many days the company has been in debt for
               if (daysindebt == 7)
               {
                   CompanyForcedClose();
                   return true;
               }
               return true;
           }
           else
           {
               daysindebt = 0;
               return false;
           }
       }
       public void CompanyForcedClose()                           // procedure for a company to close when in debt for more than a week. could be changed to close outlets down at first.
       {
           if (isindebt == true && daysindebt ==7)   
           {
               while (outlets.Count > 0) // calls the other subroutines while there are more than one outlet
               {
                   CloseOutlet(0);
               }             
           }
       }

Process day end subroutine updated

public string ProcessDayEnd()

       {
           string details = "";
           double profitLossFromOutlets = 0;
           double profitLossFromThisOutlet = 0;
           double deliveryCosts;
           if (outlets.Count > 1)
           {
               deliveryCosts = baseCostOfDelivery + CalculateDeliveryCost();
           }
           else
           {
               deliveryCosts = baseCostOfDelivery;
           }
           details += "Daily costs for company: " + dailyCosts.ToString() + "\nCost for delivering produce to outlets: " + deliveryCosts.ToString() + "\n";
           for (int current = 0; current < outlets.Count; current++)
           {
               profitLossFromThisOutlet = outlets[current].CalculateDailyProfitLoss(avgCostPerMeal, avgPricePerMeal);
               details += "Outlet " + (current + 1) + " profit/loss: " + profitLossFromThisOutlet.ToString() + "\n";
               profitLossFromOutlets += profitLossFromThisOutlet;
           }
           details += "Previous balance for company: " + balance.ToString() + "\n";
           balance += profitLossFromOutlets - dailyCosts - deliveryCosts;
           details += "New balance for company: " + balance.ToString();
           isindebt = GetIfInDebt();
           // calling the subroutines that i have made  
           
           
           return details;
       }


Get details subroutine

public string GetDetails()

       {
           string details = "";
           details += "Name: " + name + "\nType of business: " + category + "\n";
           details += "Current balance: " + balance.ToString() + "\nAverage cost per meal: " + avgCostPerMeal.ToString() + "\n";
           details += "Average price per meal: " + avgPricePerMeal.ToString() + "\nDaily costs: " + dailyCosts.ToString() + "\n";
           details += "Delivery costs: " + CalculateDeliveryCost().ToString() + "\nReputation: " + reputationScore.ToString() + "\n";
           details += "Number of outlets: " + outlets.Count.ToString() + "\nOutlets\n";
           details += "\nIs the company in debt? " + isindebt.ToString() + "\n";                                                                                     // puts whether the company is in debt in the details
         
           if (isindebt == true)                                                                                                                          // displays how many days in debt if the company is in debt 
           {
               details += "\n Days the company has been in debt for " + daysindebt.ToString() + " days \n\n";
           }
            
           for (int current = 1; current < outlets.Count + 1; current++)
           {
               details += current + ". " + outlets[current - 1].GetDetails() + "\n";
           }
           return details;
       }

This needs to be in the simulation class.

public void DeleteCompany(int index) // new subroutine to delete a company which has had all its outlets closed

       {
           int outlets = companies[index].GetNumberOfOutlets();
           if (outlets == 0)
           {
             
                   Console.WriteLine("That company has now closed down as it has no outlets.");
                   companies.RemoveAt(index);
                                               
           }
       }

and it is called in process day end which is shown here

public void ProcessDayEnd()
       {
           int index = 0;
           
           do                                              // calls the other subroutine while the company count is changing
           {
               DeleteCompany(index);
               index++;
           } while (index < companies.Count);
           double totalReputation = 0;
           List<double> reputations = new List<double>();
           int companyRNo, current, loopMax, x = 0, y = 0;
           foreach (var c in companies)
           {
               c.NewDay();
               totalReputation += c.GetReputationScore();
               reputations.Add(totalReputation);
           }
           loopMax = simulationSettlement.GetNumberOfHouseholds() - 1;
           for (int counter = 0; counter < loopMax + 1; counter++)
           {
               if (simulationSettlement.FindOutIfHouseholdEatsOut(counter, ref x, ref y))
               {
                   companyRNo = rnd.Next(1, Convert.ToInt32(totalReputation) + 1);
                   current = 0;
                   while (current < reputations.Count)
                   {
                       if (companyRNo < reputations[current])
                       {
                           companies[current].AddVisitToNearestOutlet(x, y);
                           break;
                       }
                       current++;
                   }
               }
           }
           DisplayCompaniesAtDayEnd();
           DisplayEventsAtDayEnd();
           dayCounter++;                                                                //incrementing the days
         
       }
  • By Michael Tomkinson*



Remove Company[edit]

C#:

make a new method called RemoveCompany.
public void removeCompany()
        {
            Console.Write("Enter company name: ");
            string name = Console.ReadLine();
            bool found = false;
            for(int i = 0; i < companies.Count; i++)
            {
                Console.WriteLine(companies[i]);
                if(companies[i].GetName() == name)
                {
                    companies.RemoveAt(i);
                    Console.WriteLine("Company removed");
                    found = true;
                }
            }
            if (!found)
            {
                Console.WriteLine("Company not found.");
            }
        }

modify the Run method to add a new case for option 5

public void Run()
        {
            string choice = "";
            int index;
            while (choice != "Q")
            {
                DisplayMenu();
                choice = Console.ReadLine();
                switch (choice)
                {
                    case "1":
                        simulationSettlement.DisplayHouseholds();
                        break;
                    case "2":
                        DisplayCompanies();
                        break;
                    case "3":
                        string companyName;
                        index = -1;
                        while (index == -1)
                        {
                            Console.Write("Enter company name: ");
                            companyName = Console.ReadLine();
                            index = GetIndexOfCompany(companyName);
                        }
                        ModifyCompany(index);
                        break;
                    case "4":
                        AddCompany();
                        break;
                    case "5":
                        removeCompany();
                        break;
                    case "6":
                        ProcessDayEnd();
                        break;
                    case "Q":
                        Console.WriteLine("Simulation finished, press Enter to close.");
                        Console.ReadLine();
                        break;
                }
            }
        }

lastly, modify the DisplayMenu method to write the option to the console.

public void DisplayMenu()
        {
            Console.WriteLine("\n*********************************");
            Console.WriteLine("**********    MENU     **********");
            Console.WriteLine("*********************************");
            Console.WriteLine("1. Display details of households");
            Console.WriteLine("2. Display details of companies");
            Console.WriteLine("3. Modify company");
            Console.WriteLine("4. Add new company");
            Console.WriteLine("5. Remove a company");
            Console.WriteLine("6. Advance to next day");
            Console.WriteLine("Q. Quit");
            Console.Write("\n Enter your choice: ");
        }


Delphi/Pascal:

Java BUT ACTUALLY GOOD:

Shows list of companies to be removed

public void removeCompany(){
        for(int i = 0; i < companies.size();i++ ){
            Console.writeLine((i+1) + "." + companies.get(i).getName());
        }
        Console.writeLine("Choose company to be removed: ");
        int removeCompany = (Integer.parseInt(Console.readLine())-1);
        companies.remove(removeCompany);
        run();
    }

public void run() {
        String choice = "";
        int index;
        while (!choice.equals("Q")) {
            displayMenu();
            choice = Console.readLine();
            switch (choice) {
                case "1":
                    simulationSettlement.displayHouseholds();
                    break;
                case "2":
                    displayCompanies();
                    break;
                case "3":
                    String companyName;
                    do {
                        Console.write("Enter company name: ");
                        companyName = Console.readLine();
                        index = getIndexOfCompany(companyName);
                    } while (index == -1);
                    modifyCompany(index);
                    break;
                case "4":
                    addCompany();
                    break;
                case "6":
                    processDayEnd();
                    break;
                case "7":
                    removeCompany();
                case "Q":
                    Console.writeLine("Simulation finished, press Enter to close.");
                    Console.readLine();
                    break;
            }
        }
    }

Obviously add the option for 7 in the menu so they know to press it. Solution by Owain Bestley

Java:

'method in java to remove a company from given user input

public void removeCompany(){
        System.out.print("Which company: ");
        String rem = Console.readLine();
        int ind = getIndexOfCompany(rem);
        companies.remove(ind);
        
        }

'displaying menu option to remove a company in java

public void displayMenu() {
        Console.writeLine(System.lineSeparator() + "*********************************");
        Console.writeLine("**********    MENU     **********");
        Console.writeLine("*********************************");
        Console.writeLine("1. Display details of households");
        Console.writeLine("2. Display details of companies");
        Console.writeLine("3. Modify company");
        Console.writeLine("4. Add new company");
        Console.writeLine("6. Advance to next day");
        Console.writeLine("7. Remove company");
        Console.writeLine("Q. Quit");
        Console.write(System.lineSeparator() + "Enter your choice: ");
    }

'adding remove company under run()

public void run() {
        String choice = "";
        int index;
        while (!choice.equals("Q")) {
            displayMenu();
            choice = Console.readLine();
            switch (choice) {
                case "1":
                    simulationSettlement.displayHouseholds();
                    break;
                case "2":
                    displayCompanies();
                    break;
                case "3":
                    String companyName;
                    do {
                        Console.write("Enter company name: ");
                        companyName = Console.readLine();
                        index = getIndexOfCompany(companyName);
                    } while (index == -1);
                    modifyCompany(index);
                    break;
                case "4":
                    addCompany();
                    break;
                case "6":
                    processDayEnd();
                    break;
                case "7":
                    removeCompany();
                    break;
                case "Q":
                    Console.writeLine("Simulation finished, press Enter to close.");
                    Console.readLine();
                    break;
            }
        }
    }

Python:

'Changes to add a new option for remove company in Run Subroutine

  def Run(self):
    Choice = ""
    while Choice != "Q":
      self.DisplayMenu()
      Choice = input()
      if Choice == "1":
        self._SimulationSettlement.DisplayHouseholds()
      elif Choice == "2":
        self.DisplayCompanies()
      elif Choice == "3":
        Index = -1
        while Index == -1:
          CompanyName = input("Enter company name: ")
          Index = self.GetIndexOfCompany(CompanyName)
        self.ModifyCompany(Index)
      elif Choice == "4":
        self.AddCompany()
      elif Choice == "5":
        CompanyName = input("what company would you like to delete: ")
        del(self._Companies[self.GetIndexOfCompany(CompanyName)])
      elif Choice == "6":
        self.ProcessDayEnd()
      elif Choice == "Q":
        print("Simulation finished, press Enter to close.")
        input()

* Sir Graham Balfour

VB.NET:

'Changes to add a new option for remove company in Run Subroutine

    Public Sub Run(ByVal Days As Integer)
        Dim Choice As String = ""
        Dim Index As Integer
        While Choice <> "Q"
            DisplayMenu(Days)
            Choice = Console.ReadLine()
            Select Case Choice
                Case "1"
                    SimulationSettlement.DisplayHouseholds()
                Case "2"
                    DisplayCompanies()
                Case "3"
                    Dim CompanyName As String
                    Do
                        Console.Write("Enter company name: ")
                        CompanyName = Console.ReadLine()
                        Index = GetIndexOfCompany(CompanyName)
                    Loop Until Index <> -1
                    ModifyCompany(Index)
                Case "4"
                    AddCompany()

                'Add Fith option in Subroutine run
                Case "5"
                    RemoveCompany()
                Case "6"
                    Dim HowMany As Integer

                    Console.WriteLine("How many days would you like to advance? ")
                    HowMany = Console.ReadLine()

                    Days = Days + HowMany

                    ProcessDayEnd(HowMany)
                Case "Q"
                    Console.WriteLine("Simulation finished, press Enter to close.")
                    Console.ReadLine()
            End Select
        End While
    End Sub

    'New Remove Company Subroutine in simulation class

    Public Sub RemoveCompany()

        Dim CompanyToRemove As String
        Dim Index As String

        Console.WriteLine("Enter the name of the company you would like to remove: ")
        CompanyToRemove = Console.ReadLine()

        Try

            Index = GetIndexOfCompany(CompanyToRemove)
            Companies.RemoveAt(Index)

            Console.WriteLine()
            Console.WriteLine(CompanyToRemove & " removed!")
            Console.WriteLine()

        Catch

            Console.WriteLine()
            Console.WriteLine("Company: " & CompanyToRemove & " doesn't exist")
            Console.WriteLine()

        End Try

    End Sub

'Code created by Folkestone Grammar School for Girls Student - 20/09/2019

Run for many days[edit]

Add an option to run simulation for many days (>1)

C#:

This is the subroutine for the menu. in this i have also validated the menu choice.

public void Run()

       {
           string choice = "";
           int index;
           while (choice != "Q")
           {
               DisplayMenu();
               do {                                                                                                 // validation for the menu choice
                   choice = Console.ReadLine();
                   switch (choice)
                   {
                       case "1":
                           simulationSettlement.DisplayHouseholds();
                           break;
                       case "2":
                           DisplayCompanies();
                           break;
                       case "3":
                           string companyName;
                           index = -1;
                           while (index == -1)
                           {
                               Console.Write("Enter company name: ");
                               companyName = Console.ReadLine();
                               index = GetIndexOfCompany(companyName);
                           }
                           ModifyCompany(index);
                           break;
                       case "4":
                           AddCompany();
                           break;
                       
                           RemoveCompany();
                           break;
                       case "6":
                           ProcessDayEnd();
                           break;
                       case "7":
                           AdvanceMultipleDays(); // added a new case that will advance many days
                           break;
                       case "Q":
                           Console.WriteLine("Simulation finished, press Enter to close.");
                           Console.ReadLine();
                           break;
                   }
                   if((int.Parse(choice) > 0 && int.Parse(choice) < 8) || choice != "Q")                             // repeats untill this = true
                   {
                       Console.WriteLine("Pleas Re Enter a valid choice");
                   }
               } while ((int.Parse(choice) > 0 && int.Parse(choice) < 8) || choice != "Q");
       } }
   }

This is the subroutine for advancing many days

public void AdvanceMultipleDays()     // new subroutine to advance many days
       {
           Console.WriteLine("How many days would you like to advance?");
           int AdvancingDays = int.Parse(Console.ReadLine());
           for (int i = 0; i < AdvancingDays ; i++)
           {
               ProcessDayEnd();
           }
       }

Delphi/Pascal:

Java:

System.out.print("Enter the number of days you want to advance: ");
int days = Integer.parseInt(Console.readLine());
for (int i = 0; i < days; i++) {
processDayEnd();
}
  • by Benny

Python:

  def Run(self):
    Choice = ""
    while Choice != "Q":
      self.DisplayMenu()
      Choice = input()
      if Choice == "1":
        self._SimulationSettlement.DisplayHouseholds()
      elif Choice == "2":
        self.DisplayCompanies()
      elif Choice == "3":
        Index = -1
        while Index == -1:
          CompanyName = input("Enter company name: ")
          Index = self.GetIndexOfCompany(CompanyName)
        self.ModifyCompany(Index)
      elif Choice == "4":
        self.AddCompany()
      elif Choice == "6":
        self.ProcessDayEnd()
      elif Choice == "7":
        self.MultipleDayEnd()
      elif Choice == "Q":
        print("Simulation finished, press Enter to close.")
        input()


def DisplayMenu(self):
    print("\n*********************************")
    print("**********    MENU     **********")
    print("*********************************")
    print("1. Display details of households")
    print("2. Display details of companies")
    print("3. Modify company")
    print("4. Add new company")
    print("6. Advance to next day")
    print("7. Advance a set number of days")
    print("Q. Quit")
    print("\nEnter your choice: ", end = "")
def MultipleDayEnd(self):
    try:
      numberOfDays = int(input("How many days would you like to advance?"))
      for i in range(numberOfDays +1):
        self.ProcessDayEnd()
    except:
      print("Integer not accepted")

VB.NET:

'Add option 7 in Run() Subroutine in Simulation class

Public Sub Run()
        Dim Choice As String = ""
        Dim Index As Integer
        While Choice <> "Q"
            DisplayMenu()
            Choice = Console.ReadLine()
            Select Case Choice
                Case "1"
                    SimulationSettlement.DisplayHouseholds()
                Case "2"
                    DisplayCompanies()
                Case "3"
                    Dim CompanyName As String
                    Do
                        Console.Write("Enter company name: ")
                        CompanyName = Console.ReadLine()
                        Index = GetIndexOfCompany(CompanyName)
                    Loop Until Index <> -1
                    ModifyCompany(Index)
                Case "4"
                    AddCompany()
                Case "6"
                    ProcessDayEnd()

'Option 7 added
                Case "7"
                    ProcessMultipleDays()
                Case "Q"
                    Console.WriteLine("Simulation finished, press Enter to close.")
                    Console.ReadLine()
            End Select
        End While
    End Sub


'Add ProcessMultipleDays() Subroutine to Simulation Class

Public Sub ProcessMultipleDays()

        Dim noOfDays As Integer

        Try
            Console.Write("How many days do you want to advance? ")
            noOfDays = Console.ReadLine

            For i = 1 To noOfDays
                ProcessDayEnd()
            Next

        Catch ex As Exception
            Console.WriteLine("")
            Console.WriteLine("Invalid Input")
            Console.WriteLine("")
        End Try

    End Sub

'Hubert (Ousedale School) - 13/11/2019

Day Counter[edit]

Display a counter of how many days have passed

C#:

make a new int varible in the simulation class and initlise it in constructor.

class Simulation
{
  private static Random rnd = new Random();
  '''private int dayCounter;'''
  protected Settlement simulationSettlement;
  protected int noOfCompanies;
  protected double fuelCostPerUnit, baseCostForDelivery;
  protected List<Company> companies = new List<Company>();

  public Simulation()
  {
    fuelCostPerUnit = 0.0098;
    baseCostForDelivery = 100;
    '''dayCounter = 1;'''
  }
}

modify the ProcessDayEnd method to increment the counter

public void ProcessDayEnd()
        {
            double totalReputation = 0;
            List<double> reputations = new List<double>();
            int companyRNo, current, loopMax, x = 0, y = 0;
            foreach (var c in companies)
            {
                c.NewDay();
                totalReputation += c.GetReputationScore();
                reputations.Add(totalReputation);
            }
            loopMax = simulationSettlement.GetNumberOfHouseholds() - 1;
            for (int counter = 0; counter < loopMax + 1; counter++)
            {
                if (simulationSettlement.FindOutIfHouseholdEatsOut(counter, ref x, ref y))
                {
                    companyRNo = rnd.Next(1, Convert.ToInt32(totalReputation) + 1);
                    current = 0;
                    while (current < reputations.Count)
                    {
                        if (companyRNo < reputations[current])
                        {
                            companies[current].AddVisitToNearestOutlet(x, y);
                            break;
                        }
                        current++;
                    }
                }
            }
            DisplayCompaniesAtDayEnd();
            DisplayEventsAtDayEnd();
            '''dayCounter++;''' 
        }


modify the menu to display the day number

public void DisplayMenu()
        {
            Console.WriteLine("\n*********************************");
            Console.WriteLine("**********    MENU     **********");
            Console.WriteLine("*********************************");
            '''Console.WriteLine($"Day: {dayCounter}");'''
            Console.WriteLine("*********************************");
            Console.WriteLine("1. Display details of households");
            Console.WriteLine("2. Display details of companies");
            Console.WriteLine("3. Modify company");
            Console.WriteLine("4. Add new company");
            Console.WriteLine("5. Advance multiple days");
            Console.WriteLine("6. Advance to next day");
            Console.WriteLine("Q. Quit");

Delphi/Pascal:

Java:

add integer days to Simulation class and set it to zero

class Simulation {
    protected Settlement simulationSettlement;
    protected int noOfCompanies;
    protected float fuelCostPerUnit, baseCostForDelivery;
    protected List<Company> companies = new ArrayList();
    private static Random rnd = new Random();
    public int days = 0;

............................}

'under Simulation class, add following methods: '1. to increment days

public void DayCounter(){
        days += 1;
    }

2. to output no of days passed

public void NoOfDays(){
        if(days != 1){
        System.out.println(days +" days have passed");
        } else{
            System.out.println(days +" day has passed");
        }
    }

'add this to run() method as well in right order and correct use of methods

public void run() {
        String choice = "";
        int index;
        
        while (!choice.equals("Q")) {
            displayMenu();
            choice = Console.readLine();
            DayCounter();
            switch (choice) {
                case "1":
                    simulationSettlement.displayHouseholds();
                    break;
                case "2":
                    displayCompanies();
                    break;
                case "3":
                    String companyName;
                    do {
                        Console.write("Enter company name: ");
                        companyName = Console.readLine();
                        index = getIndexOfCompany(companyName);
                    } while (index == -1);
                    modifyCompany(index);
                    break;
                case "4":
                    addCompany();
                    break;
                case "6":
                    processDayEnd();
                    break;
                case "7":
                    removeCompany();
                    break;
                case "Q":
                    Console.writeLine("Simulation finished, press Enter to close.");
                    Console.readLine();
                    break;
             
            }
            NoOfDays();
            
            
        }
    }

Python:

class Simulation:
  def __init__(self):
    self._DayCount = 0
    self._Companies = []
    self._FuelCostPerUnit = 0.0098
    self._BaseCostforDelivery = 100

 def ProcessDayEnd(self):
    TotalReputation = 0.0
    Reputations = []
    for C in self._Companies:
      C.NewDay()
      TotalReputation += C.GetReputationScore()
      Reputations.append(TotalReputation)
    LoopMax = self._SimulationSettlement.GetNumberOfHouseholds() - 1
    for Counter in range (0, LoopMax + 1):
      EatsOut, X, Y = self._SimulationSettlement.FindOutifHouseholdEatsOut(Counter)
      if EatsOut:
        CompanyRNo = random.randint(1, int(TotalReputation))
        Current = 0
        while Current < len(Reputations):
          if CompanyRNo < Reputations[Current]:
            self._Companies[Current].AddVisitToNearestOutlet(X, Y)
            break
          Current += 1
    self.__DisplayCompaniesAtDayEnd()
    self.__DisplayEventsAtDayEnd()
    self._DayCount += 1
    print("day:", self._DayCount)

- Sir Graham Balfour

VB.NET:

Public Sub Run()

'Add new variable that will be the counter of days
        Dim daysCount As Integer = 0
        Dim Choice As String = ""
        Dim Index As Integer
        While Choice <> "Q"
            DisplayMenu()
            Choice = Console.ReadLine()
            Select Case Choice
                Case "1"
                    SimulationSettlement.DisplayHouseholds()
                Case "2"
                    DisplayCompanies()
                Case "3"
                    Dim CompanyName As String
                    Do
                        Console.Write("Enter company name: ")
                        CompanyName = Console.ReadLine()
                        Index = GetIndexOfCompany(CompanyName)
                    Loop Until Index <> -1
                    ModifyCompany(Index)
                Case "4"
                    AddCompany()
                Case "5"
                    RemoveCompany()
                Case "6"
                    ProcessDayEnd()
'Every time we advance 1 day, the counter increments by 1.
                    daysCount += 1
                    Console.WriteLine("Day: " & daysCount)
                Case "Q"
                    Console.WriteLine("Simulation finished, press Enter to close.")
                    Console.ReadLine()
            End Select
        End While
    End Sub

'Hubert (Ousedale School) - 13/11/2019

Display Costs (£x.xx)[edit]

Question description

C#:

public static string getPoundsFormat(double toChange)
        {
            string changed = "";
            changed = toChange.ToString("C", CultureInfo.CurrentCulture);
            return changed;
        } //doubt this will be a question since you'd have to change a lot of lines

Delphi/Pascal:

Java:

'for given currency format, add in each class:

public DecimalFormat df = new DecimalFormat("£.00");

'to display any of the costs in £x.xx, eg:

df.format(dailyCosts)

Python:

def Round(money):
  money = "£" + str('{:.2f}'.format(money))
  return money

  def GetDetails(self):
    Details = "Coordinates: (" + str(self._XCoord) + ", " + str(self._YCoord) + ")     Capacity: " + str(self._Capacity) + "      Maximum Capacity: "
    Details += str(self._MaxCapacity) + "      Daily Costs: " + Round(self._DailyCosts) + "      Visits today: " + str(self._VisitsToday)
    return Details

  def GetDetails(self):
    Details = ""
    Details += "Name: " + self._Name + "\nType of business: " + self._Category + "\n"
    Details += "Current balance: " + Round(self._Balance) + "\nAverage cost per meal: " + Round(self._AvgCostPerMeal) + "\n"
    Details += "Average price per meal: " + Round(self._AvgPricePerMeal) + "\nDaily costs: " + Round(self._DailyCosts) + "\n"
    Details += "Delivery costs: " + Round(self.CalculateDeliveryCost()) + "\nReputation: " + str(self._ReputationScore) + "\n\n"
    Details += "Number of outlets: " + str(len(self._Outlets)) + "\nOutlets\n"
    for Current in range (1, len(self._Outlets) + 1):
      Details += str(Current) + ". " + self._Outlets[Current - 1].GetDetails() + "\n"
    return Details

VB.NET:

Check if company name is taken[edit]

AddCompany(self) add a check to see if CompanyName already exists in _Companies

C#:

Delphi/Pascal:

Java:

This is just an edit to the addCompany() function in the Simulation Class.

 public void addCompany() {
        int balance, x, y;
        String companyName, typeOfCompany;
        Console.write("Enter a name for the company: ");
        companyName = Console.readLine();
        String existingNames;
        for(int i = 0; i < companies.size();i++ ){
            existingNames = companies.get(i).getName();
            while(companyName.equals(existingNames)){
                Console.print("Company name taken, please enter another name: ");
                companyName = Console.readLine();
            }
        }

Created by the one and only Jorge Bishop

Python:

  def AddCompany(self):
    NameCheck = True
    while NameCheck == True:
      CompanyName = input("Enter a name for the company: ")
      NameCheck = False
      for name in self._Companies:
        checking=name.GetName()
        if checking==CompanyName:
          print('company name taken')
          NameCheck = True
    Balance = int(input("Enter the starting balance for the company: "))
    TypeOfCompany = ""
    while not(TypeOfCompany == "1" or TypeOfCompany == "2" or TypeOfCompany == "3"):
      TypeOfCompany = input("Enter 1 for a fast food company, 2 for a family company or 3 for a named chef company: ")
    if TypeOfCompany == "1":
      TypeOfCompany = "fast food"
    elif TypeOfCompany == "2":
      TypeOfCompany = "family"
    else:
      TypeOfCompany = "named chef"
    X, Y = self._SimulationSettlement.GetRandomLocation()
    NewCompany = Company(CompanyName, TypeOfCompany, Balance, X, Y, self._FuelCostPerUnit, self._BaseCostforDelivery)
    self._Companies.append(NewCompany)

VB.NET:

Public Sub AddCompany()
        'Use this variable as a condition for your while loop to stop you from continuing with a name already in use
        Dim checkName As Boolean = True
        Dim Balance, X, Y As Integer
        Dim CompanyName, TypeOfCompany As String
        'Use the name variable as a holder for the name you're checking your chosen name against in the ArrayList
        Dim name As String
        'Add in a while loop to check through the ArrayList of company names to check if the chosen name has already been used.
        While checkName = True
            Console.Write("Enter a name for the company: ")
            CompanyName = Console.ReadLine()
            checkName = False
            For i = 0 To Me.Companies.Count - 1
                name = Me.Companies(i).GetName()
                If CompanyName = name Then
                    Console.WriteLine("Company name is already in use")
                    checkName = True
                End If
            Next
        End While

        Console.Write("Enter the starting balance for the company: ")
        Balance = Console.ReadLine()
        Do
            Console.Write("Enter 1 for a fast food company, 2 for a family company or 3 for a named chef company: ")
            TypeOfCompany = Console.ReadLine()
        Loop Until TypeOfCompany = "1" Or TypeOfCompany = "2" Or TypeOfCompany = "3"
        If TypeOfCompany = "1" Then
            TypeOfCompany = "fast food"
        ElseIf TypeOfCompany = "2" Then
            TypeOfCompany = "family"
        Else
            TypeOfCompany = "named chef"
        End If
        SimulationSettlement.GetRandomLocation(X, Y)
        Dim NewCompany As New Company(CompanyName, TypeOfCompany, Balance, X, Y, FuelCostPerUnit, BaseCostForDelivery)
        Companies.Add(NewCompany)
    End Sub

TM ~ Ouse

Fuel cost always positive[edit]

Ensure fuel costs can never become negative

C#:

 
in the company class makes sure it is always positive
 public void AlterFuelCostPerUnit(double change)
        {
            fuelCostPerUnit += change;
            if (fuelCostPerUnit < 0) // checks if below zero 
            {
                fuelCostPerUnit -= fuelCostPerUnit; // if below zero then makes the negative positive
            }
        }

*By Michael Tomkinson

Delphi/Pascal:

Java:

Python:

def __ProcessCostOfFuelChangeEvent(self):
    FuelCostChange = random.randint(1, 9) / 10.0
    UpOrDown = random.randint(0, 1)
    CompanyNo = random.randint(0, len(self._Companies) - 1)
    if UpOrDown == 1:
      if self._Companies[CompanyNo]._FuelCostPerUnit<FuelCostChange:
        UpOrDown=0
    if UpOrDown == 0:
      print("The cost of fuel has gone up by " + str(FuelCostChange) + " for " + self._Companies[CompanyNo].GetName())
    else:
      print("The cost of fuel has gone down by " + str(FuelCostChange) + " for " + self._Companies[CompanyNo].GetName())
      FuelCostChange *= -1
    self._Companies[CompanyNo].AlterFuelCostPerUnit(FuelCostChange)

VB.NET:

'Add a new public function to the company class to get access to the current value of FuelCostPerUnit
    Public Function GetFuelCostPerUnit() As Integer
        Return FuelCostPerUnit
    End Function

'Edit the ProcessCostOfFuelChangeEvent() Sub in the Simulation Class
    Private Sub ProcessCostOfFuelChangeEvent()
        Dim FuelCostChange As Single = (Int(Rnd() * 9) + 1) / 10
        Dim UpOrDown As Integer = Int(Rnd() * 2)
        Dim CompanyNo As Integer = Int(Rnd() * Companies.Count)
        'Add in a separate if statement to change the value of the upordown to 0 if the current fuelcost change is going to result in a negative fuelcostchange
        If UpOrDown = 1 Then
            If Me.Companies(CompanyNo).GetFuelCostPerUnit() < FuelCostChange Then
                UpOrDown = 0
            End If
        End If

        If UpOrDown = 0 Then
            Console.WriteLine("The cost of fuel has gone up by " & FuelCostChange.ToString() & " for " & Companies(CompanyNo).GetName())
        Else
            Console.WriteLine("The cost of fuel has gone down by " & FuelCostChange.ToString() & " for " & Companies(CompanyNo).GetName())
            FuelCostChange *= -1
        End If
        Companies(CompanyNo).AlterFuelCostPerUnit(FuelCostChange)
    End Sub

TM ~ Ouse

Small settlement[edit]

Add small settlement class and provide an option in the launch menu

C#:

Delphi/Pascal:

Java:

By changing the Settlement class to 0 instead of just taking away an integer we can avoid having any issues where we may get a negative integer. We can also now create a custom sized Settlement.

public Settlement() {
        xSize = 0;
        ySize = 0;
        startNoOfHouseholds = 0;
        createHouseholds();
    }

class DefaultSettlement extends Settlement{
    public DefaultSettlement() {
        xSize = 1000;
        ySize = 1000;
        startNoOfHouseholds = 250;
        createHouseholds();
    }
}

class LargeSettlement extends DefaultSettlement {
    public LargeSettlement(int extraxSize, int extraySize, int extraHouseholds) {
        super();
        super.xSize += extraxSize;
        super.ySize += extraySize;
        super.startNoOfHouseholds += extraHouseholds;
        for (int count = 1; count <= extraHouseholds; count++) {
            addHousehold();
        }
    }
}

class SmallSettlement extends Settlement {
    public SmallSettlement(int XSize, int YSize, int Households) {
        super();
        super.xSize = XSize;
        super.ySize = YSize;
        super.startNoOfHouseholds = Households;
        for (int count = 1; count <= Households; count++) {
            addHousehold();
        
    }
}

You also have to alter the simulation class to accomodate for the change, calling the default simulation class instead of just simulation.

 public Simulation() {
        fuelCostPerUnit = 0.0098f;
        baseCostForDelivery = 100;
        String choice;
        Console.write("Enter L for a large settlement, S for a small settlement and anything else for a normal size settlement: ");
        choice = Console.readLine();
        if (choice.toUpperCase().equals("L")) {
            int extrax, extray, extraHouseholds;
            Console.write("Enter additional amount to add to x size of settlement: ");
            extrax = Integer.parseInt(Console.readLine());
            Console.write("Enter additional amount to add to y size of settlement: ");
            extray = Integer.parseInt(Console.readLine());
            Console.write("Enter additional number of households to add to settlement: ");
            extraHouseholds = Integer.parseInt(Console.readLine());
            simulationSettlement = new LargeSettlement(extrax, extray, extraHouseholds);
        }
        else if(choice.toUpperCase().equals("S")){
            int sizeX, sizeY, noHouseholds;
            Console.write("Enter  x size of settlement: ");
            sizeX = Integer.parseInt(Console.readLine());
            Console.write("Enter y size of settlement: ");
            sizeY = Integer.parseInt(Console.readLine());
            Console.write("Enter number of households in settlement: ");
            noHouseholds = Integer.parseInt(Console.readLine());
            simulationSettlement = new SmallSettlement(sizeX,sizeY,noHouseholds);
        }
        else {
            simulationSettlement = new DefaultSettlement();            
        }

Solution made by Owain Bestley (Listen to Hachiko)

Python:

class SmallSettlement(Settlement):
  def __init__(self, LowerXSize, LowerYSize, LowerHouseholds):
    self._XSize = 1000 - LowerXSize
    self._YSize = 1000 - LowerYSize
    self._StartNoOfHouseholds = 250 -  LowerHouseholds
    self._Households = []
    for Count in range (1, self._StartNoOfHouseholds + 1):
      self.AddHousehold()


class Simulation:
  def __init__(self):
    self._DayCount = 0
    self._Companies = []
    self._FuelCostPerUnit = 0.0098
    self._BaseCostforDelivery = 100
    Choice = input("Enter L for a large settlement, S for a small settlement,  anything else for a normal size settlement: ")
    if Choice == "L":
      ExtraX = int(input("Enter additional amount to add to X size of settlement: "))
      ExtraY = int(input("Enter additional amount to add to Y size of settlement: "))
      ExtraHouseholds = int(input("Enter additional number of households to add to settlement: "))
      self._SimulationSettlement = LargeSettlement(ExtraX, ExtraY, ExtraHouseholds)
      ###
    elif Choice == "S":
      LowerX = 1001
      LowerY = 1001
      LowerHouseholds = 251
      while LowerX >= 1000 or LowerY >= 1000 or LowerHouseholds >= 250:
        print("X and Y reductions cannot equal to or more than 1000 and Household reduction cannot be equal to or more than 250")
        LowerX = int(input("Enter the amount of X size you want to reduce the settlement by: "))
        LowerY = int(input("Enter the amount of y size you want to reduce the settlement by: "))
        LowerHouseholds = int(input("Enter the amount of households you want to reduce in the settlement: "))
      self._SimulationSettlement = SmallSettlement(LowerX, LowerY, LowerHouseholds)
      ###
    else:
      self._SimulationSettlement = Settlement()            
    Choice = input("Enter D for default companies, anything else to add your own start companies: ")
    if Choice == "D":
      self._NoOfCompanies = 3
      Company1 = Company("AQA Burgers", "fast food", 100000, 200, 203, self._FuelCostPerUnit, self._BaseCostforDelivery)
      self._Companies.append(Company1)
      self._Companies[0].OpenOutlet(300, 987)
      self._Companies[0].OpenOutlet(500, 500)
      self._Companies[0].OpenOutlet(305, 303)
      self._Companies[0].OpenOutlet(874, 456)
      self._Companies[0].OpenOutlet(23, 408)
      self._Companies[0].OpenOutlet(412, 318)
      Company2 = Company("Ben Thor Cuisine", "named chef", 100400, 390, 800, self._FuelCostPerUnit, self._BaseCostforDelivery)
      self._Companies.append(Company2)
      Company3 = Company("Paltry Poultry", "fast food", 25000, 800, 390, self._FuelCostPerUnit, self._BaseCostforDelivery)
      self._Companies.append(Company3)
      self._Companies[2].OpenOutlet(400, 390)
      self._Companies[2].OpenOutlet(820, 370)
      self._Companies[2].OpenOutlet(800, 600)
    else:
      self._NoOfCompanies = int(input("Enter number of companies that exist at start of simulation: "))
      for Count in range (1, self._NoOfCompanies + 1):
        self.AddCompany()

VB.NET:

'Add in a new class called SmallSettllement that inherits its values from settlement
Class SmallSettlement
    Inherits Settlement

    Public Sub New(ByVal ReduceXBy As Integer, ByVal ReduceYBy As Integer, ByVal ReduceHousingBy As Integer)
        Me.XSize = 1000 - ReduceXBy
        Me.YSize = 1000 - ReduceYBy
        Me.StartNoOfHouseholds = 250 - ReduceHousingBy
        For count = 1 To (StartNoOfHouseholds + 1)
            Me.AddHousehold()
        Next

    End Sub
End Class

Public Sub New()
        FuelCostPerUnit = 0.0098
        BaseCostForDelivery = 100
        Dim Choice As String
        'Add in a choice for a small settlement on the choice display in the public sub new of simulation
        Console.Write("Enter L for a large settlement, S for a small settlement & anything else for a normal size settlement: ")
        Choice = Console.ReadLine()
        If Choice = "L" Then
            Dim ExtraX, ExtraY, ExtraHouseholds As Integer
            Console.Write("Enter additional amount to add to X size of settlement: ")
            ExtraX = Console.ReadLine()
            Console.Write("Enter additional amount to add to Y size of settlement: ")
            ExtraY = Console.ReadLine()
            Console.Write("Enter additional number of households to add to settlement: ")
            ExtraHouseholds = Console.ReadLine()
            SimulationSettlement = New LargeSettlement(ExtraX, ExtraY, ExtraHouseholds)
            'Add in an elseif for the choice of a small settlement in the public sub new of simulation.
        ElseIf Choice = "S" Then
            Dim reducexby As Integer = 1001
            Dim reduceyby As Integer = 1001
            Dim reducehousingby As Integer = 251
            While reducexby >= 1000 Or reduceyby >= 1000 Or reducehousingby >= 250
                Console.WriteLine("X & Y cannot be reduced by more than 999 and Housing cannot be reduced by more than 249.")
                Console.WriteLine("Please enter how much you would like to reduce the X size by: ")
                reducexby = Console.ReadLine()
                Console.WriteLine("Please enter how much you would like to reduce the Y size by: ")
                reduceyby = Console.ReadLine()
                Console.WriteLine("Please enter how much you would like to reduce the number of houses by: ")
                reducehousingby = Console.ReadLine()
            End While
            SimulationSettlement = New SmallSettlement(reducexby, reduceyby, reducehousingby)
            '
        Else
            SimulationSettlement = New Settlement()
        End If

TM ~ Ouse

Doesn't accept integers with ExtraX/Y[edit]

Question description

C#:

Delphi/Pascal:

Java:

Python:

VB.NET:

Add a Close Outlet event[edit]

Adds a random event function which removes an outlet from a company

C#:

Delphi/Pascal:

Java:

  • Under Simulation class add following method
public void closeOutletEvent(){
        int indexCOE = rnd.nextInt((companies.size()-1)+1) +1;
        int outletIndexCOE = rnd.nextInt((companies.get(indexCOE).getNumberOfOutlets()-1)+1) +1;
        for(int i = 0; i<=companies.size();i++){
            if(i == indexCOE){
                boolean closeCompany = companies.get(indexCOE).closeOutlet(outletIndexCOE-1);
                    if (closeCompany) {
                        Console.writeLine("That company has now closed down as it has no outlets.");
                        companies.remove(indexCOE);
                    }
            }
        }
        System.out.println("An outlet has been closed");
    }
  • also under displayEventsAtDayEnd() method, add some of the extra lines of code below:
private void displayEventsAtDayEnd() {
        Console.writeLine(System.lineSeparator() + "***********************");
        Console.writeLine("*****   Events:   *****");
        Console.writeLine("***********************" + System.lineSeparator());
        float eventRanNo;
        eventRanNo = rnd.nextFloat();
        if (eventRanNo<100f){
            eventRanNo = rnd.nextFloat();
            if (eventRanNo < 0.5f) {
                closeOutletEvent();
            }
        }
        if (eventRanNo < 0.25f) {
            eventRanNo = rnd.nextFloat();
            if (eventRanNo < 0.25f) {
                processAddHouseholdsEvent();
            }
            eventRanNo = rnd.nextFloat();
            if (eventRanNo < 0.5f) {
                processCostOfFuelChangeEvent();
            }
            eventRanNo = rnd.nextFloat();
            if (eventRanNo < 0.5f) {
                processReputationChangeEvent();
            }
            eventRanNo = rnd.nextFloat();
            if (eventRanNo >= 0.5f) {
                processCostChangeEvent();
            }
            
        } else {
            Console.writeLine("No events.");
        }
    }

Python:

def __ProcessCloseOutletEvent(self):
  indx = random.randrange(0,len(self._Companies))
  randomCompany = self._Companies[indx]

  print(str(randomCompany._Name+" has closed an outlet"))
  randomCompany.CloseOutlet(random.randrange(0,randomCompany.GetNumberOfOutlets()))
  remove = randomCompany.GetNumberOfOutlets()
  print(remove)
  if remove <= 0:
    print(randomCompany._Name+" has closed down due to not having any more outlets open")
    del(self._Companies[indx])
  else:
    pass

VB.NET:

Add a faster option to load in the default scenario[edit]

Add a faster option to load in the default scenario

C#:

Delphi/Pascal:

Java:

public Simulation() {
        fuelCostPerUnit = 0.0098f;
        baseCostForDelivery = 100;
        String choice;
        Console.write("Enter L for a large settlement, anything else for a normal size settlement: ");
        choice = Console.readLine();
        if (choice.equals("L")) {
            int extrax, extray, extraHouseholds;
            Console.write("Enter additional amount to add to x size of settlement: ");
            extrax = Integer.parseInt(Console.readLine());
            Console.write("Enter additional amount to add to y size of settlement: ");
            extray = Integer.parseInt(Console.readLine());
            Console.write("Enter additional number of households to add to settlement: ");
            extraHouseholds = Integer.parseInt(Console.readLine());
            simulationSettlement = new LargeSettlement(extrax, extray, extraHouseholds);
        } else {
            simulationSettlement = new Settlement();            
        }
        Console.write("Enter D for default companies, anything else to add your own start companies: ");
        choice = Console.readLine();
        if (choice.equals("D")) {
            System.out.print("Do you want to load faster or slower? - faster or slower");
            String speedOption = Console.readLine();
            if(speedOption.equals("faster")){
                LoadFasterInDefaultScenario();
            } else{
                noOfCompanies = 3;
            Company company1 = new Company("AQA Burgers", "fast food", 100000, 200, 203, fuelCostPerUnit, baseCostForDelivery);
            companies.add(company1);
            companies.get(0).openOutlet(300, 987);
            companies.get(0).openOutlet(500, 500);
            companies.get(0).openOutlet(305, 303);
            companies.get(0).openOutlet(874, 456);
            companies.get(0).openOutlet(23, 408);
            companies.get(0).openOutlet(412, 318);
            Company company2 = new Company("Ben Thor Cuisine", "named chef", 100400, 390, 800, fuelCostPerUnit, baseCostForDelivery);
            companies.add(company2);
            Company company3 = new Company("Paltry Poultry", "fast food", 25000, 800, 390, fuelCostPerUnit, baseCostForDelivery);
            companies.add(company3);
            companies.get(2).openOutlet(400, 390);
            companies.get(2).openOutlet(820, 370);
            companies.get(2).openOutlet(800, 600);
            }
            
        } else {
            Console.write("Enter number of companies that exist at start of simulation: ");
            noOfCompanies = Integer.parseInt(Console.readLine());
            for (int count = 1; count <= noOfCompanies; count++) {
                addCompany();
            }
        }
    }

public void LoadFasterInDefaultScenario(){
        noOfCompanies = 3;
            Company company1 = new Company("AQA Burgers", "fast food", 100000, 200, 203, fuelCostPerUnit, baseCostForDelivery);
            companies.add(company1);
            companies.get(0).openOutlet(300, 987);
            companies.get(0).openOutlet(500, 500);
            companies.get(0).openOutlet(305, 303);
            companies.get(0).openOutlet(874, 456);
            companies.get(0).openOutlet(23, 408);
            companies.get(0).openOutlet(412, 318);
            Company company2 = new Company("Ben Thor Cuisine", "named chef", 100400, 390, 800, fuelCostPerUnit, baseCostForDelivery);
            companies.add(company2);
            Company company3 = new Company("Paltry Poultry", "fast food", 25000, 800, 390, fuelCostPerUnit, baseCostForDelivery);
            companies.add(company3);
            companies.get(2).openOutlet(400, 390);
            companies.get(2).openOutlet(820, 370);
            companies.get(2).openOutlet(800, 600);
}

Python:

 Choice = input("Enter D for default scenarios, anything else for your own scenario.")
        Choice = Choice.upper()
        if Choice == "D":
            self._SimulationSettlement = Settlement()
            self._NoOfCompanies = 3
            Company1 = Company("AQA Burgers", "fast food", 100000, 200, 203, self._FuelCostPerUnit,
                               self._BaseCostforDelivery)
            self._Companies.append(Company1)
            self._Companies[0].OpenOutlet(300, 987)
            self._Companies[0].OpenOutlet(500, 500)
            self._Companies[0].OpenOutlet(305, 303)
            self._Companies[0].OpenOutlet(874, 456)
            self._Companies[0].OpenOutlet(23, 408)
            self._Companies[0].OpenOutlet(412, 318)
            Company2 = Company("Ben Thor Cuisine", "named chef", 100400, 390, 800, self._FuelCostPerUnit,
                               self._BaseCostforDelivery)
            self._Companies.append(Company2)
            Company3 = Company("Paltry Poultry", "fast food", 25000, 800, 390, self._FuelCostPerUnit,
                               self._BaseCostforDelivery)
            self._Companies.append(Company3)
            self._Companies[2].OpenOutlet(400, 390)
            self._Companies[2].OpenOutlet(820, 370)
            self._Companies[2].OpenOutlet(800, 600)
        else:
            Choice = input("Enter L for a large settlement, anything else for a normal size settlement: ")
            Choice = Choice.upper()
            if Choice == "L":
                while True:

                    ExtraX = input("Enter additional amount to add to X size of settlement: ")
                    ExtraY = input("Enter additional amount to add to Y size of settlement: ")
                    ExtraHouseholds = input("Enter additional number of households to add to settlement: ")
                    try:
                        ExtraX = int(ExtraX)
                        ExtraY = int(ExtraY)
                        ExtraHouseholds = int(ExtraHouseholds)
                        break
                    except ValueError:
                        print("Those are not a number try again")
                        continue

VB.NET: