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

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

A-level Computing. This is Comp1 for the new Computer Science Specification. Keep in mind that there is another Comp1 exam for Computing (for retakes and this is the place for this older exam. There should be a new wiki for Computer Science with links from both wikis to each other.

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

Please be respectful and do not vandalise or tamper with the page, as this would affect students' preparation for their exams!

Contents

Add Wind[edit]

C#[edit]

static void SeedLands(char[,] Field, int Row, int Column)
        {
            if (Row >= 0 && Row < FIELDLENGTH && Column >= 0 && Column < FIELDWIDTH)
            {
                if (Field[Row, Column] == SOIL)
                {
                    Field[Row, Column] = SEED;
                }
            }
        }

        static void SimulateAutumn(char[,] Field)
        {
            Random RAND = new Random();
            int winddir = RAND.Next(1, 9);
            if (winddir == 1)
            {
                Console.WriteLine("No wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row - 1, Column - 1);
                            SeedLands(Field, Row - 1, Column);
                            SeedLands(Field, Row - 1, Column + 1);
                            SeedLands(Field, Row, Column - 1);
                            SeedLands(Field, Row, Column + 1);
                            SeedLands(Field, Row + 1, Column - 1);
                            SeedLands(Field, Row + 1, Column);
                            SeedLands(Field, Row + 1, Column + 1);
                        }
                    }
                }

            }
            if (winddir == 2)
            {
                Console.WriteLine("North wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row, Column - 1);
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row, Column + 1);
                            SeedLands(Field, Row + 1, Column - 1);
                            SeedLands(Field, Row + 1, Column + 1);
                            SeedLands(Field, Row + 2, Column - 1);
                            SeedLands(Field, Row + 2, Column);
                            SeedLands(Field, Row + 2, Column + 1);
                        }
                    }
                }
            }
            if (winddir == 3)
            {
                Console.WriteLine("North East wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row, Column + 1);
                            SeedLands(Field, Row, Column + 2);
                            SeedLands(Field, Row + 1, Column);
                            SeedLands(Field, Row + 1, Column + 2);
                            SeedLands(Field, Row + 2, Column);
                            SeedLands(Field, Row + 2, Column + 1);
                            SeedLands(Field, Row + 2, Column + 2);
                        }
                    }
                }
            }
            if (winddir == 4)
            {
                Console.WriteLine("East Wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row - 1, Column);
                            SeedLands(Field, Row - 1, Column + 1);
                            SeedLands(Field, Row - 1, Column + 2);
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row, Column + 2);
                            SeedLands(Field, Row + 1, Column);
                            SeedLands(Field, Row + 1, Column + 1);
                            SeedLands(Field, Row + 1, Column + 2);
                        }
                    }
                }
            }
            if (winddir == 5)
            {
                Console.WriteLine("South east wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row - 2, Column);
                            SeedLands(Field, Row - 2, Column + 1);
                            SeedLands(Field, Row - 2, Column + 2);
                            SeedLands(Field, Row - 1, Column);
                            SeedLands(Field, Row - 1, Column + 2);
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row, Column + 1);
                            SeedLands(Field, Row, Column + 2);
                        }
                    }
                }
            }
            if (winddir == 6)
            {
                Console.WriteLine("South Wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row - 2, Column - 1);
                            SeedLands(Field, Row - 2, Column);
                            SeedLands(Field, Row - 2, Column + 1);
                            SeedLands(Field, Row - 1, Column - 1);
                            SeedLands(Field, Row - 1, Column + 1);
                            SeedLands(Field, Row, Column - 1);
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row, Column + 1);
                        }
                    }
                }
            }
            if (winddir == 7)
            {
                Console.WriteLine("South West wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row - 2, Column - 2);
                            SeedLands(Field, Row - 2, Column - 1);
                            SeedLands(Field, Row - 2, Column);
                            SeedLands(Field, Row - 1, Column - 2);
                            SeedLands(Field, Row - 1, Column);
                            SeedLands(Field, Row, Column - 2);
                            SeedLands(Field, Row, Column - 1);
                            SeedLands(Field, Row, Column);
                        }
                    }
                }
            }
            if (winddir == 8)
            {
                Console.WriteLine("West Wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row - 1, Column - 2);
                            SeedLands(Field, Row - 1, Column - 1);
                            SeedLands(Field, Row - 1, Column);
                            SeedLands(Field, Row, Column - 2);
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row + 1, Column - 2);
                            SeedLands(Field, Row + 1, Column - 1);
                            SeedLands(Field, Row + 1, Column);
                        }
                    }
                }
            }
            if (winddir == 9)
            {
                Console.WriteLine("North West wind");
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            SeedLands(Field, Row, Column - 2);
                            SeedLands(Field, Row, Column - 1);
                            SeedLands(Field, Row, Column);
                            SeedLands(Field, Row + 1, Column - 2);
                            SeedLands(Field, Row + 1, Column);
                            SeedLands(Field, Row + 2, Column - 2);
                            SeedLands(Field, Row + 2, Column - 1);
                            SeedLands(Field, Row + 2, Column);
                        }
                    }
                }
            }
            
        }

Make Sure The Number of Years Entered Is Valid[edit]

VB.Net[edit]

   Function GetHowLongToRun() As Integer
       Dim Years As Integer
       Dim Valid As Boolean = False                                                ' This line is new
       Console.WriteLine("Welcome to the Plant Growing Simulation")
       Console.WriteLine()
       Console.WriteLine("You can step through the simulation a year at a time")
       Console.WriteLine("or run the simulation for 0 to 5 years")
       Console.WriteLine("How many years do you want the simulation to run?")
       Do                                                                         ' I added this do loop
           Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
           Years = Console.ReadLine()
           Try
               If Years > -2 And Years < 6 Then
                   Valid = True
               End If
           Catch ex As Exception
               Console.WriteLine("Invalid value entered. Please try again.")
           End Try
       Loop Until Valid                                                            ' This is the end of what I added
       Return Years
   End Function

Fire[edit]

Answer:

Function GetHowLongToRun() As Integer
	Dim Years As Integer
	Dim num1 As Boolean
	Console.WriteLine("Welcome to the Plant Growing Simulation")
	Console.WriteLine()
	Console.WriteLine("You can step through the simulation a year at a time")
	Console.WriteLine("or run the simulation for 0 to 5 years")
	Console.WriteLine("How many years do you want the simulation to run?")
	
	Do
		Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
		Years = Console.ReadLine()
		If Years > 5 Or Years < -1 Then
			num1 = False
			Console.WriteLine("Invalid number")
		Else
			num1 = True
		End If
		
	Loop Until num1 = True
	Return Years
End Function

' Alternative Solution which doesn't crash when non numerical values are entered:
Function GetHowLongToRun() As Integer
	Dim Years As Integer
	Console.WriteLine("Welcome to the Plant Growing Simulation")
	Console.WriteLine()
	Console.WriteLine("You can step through the simulation a year at a time")
	Console.WriteLine("or run the simulation for 0 to 5 years")
	Console.WriteLine("How many years do you want the simulation to run?")
	Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
	Do
		Try
		Years = Console.ReadLine()
		Catch
		End Try
		If Years > 5 Or Years < -1 Then
			Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
		End If
	Loop Until Years <= 5 And Years >= 1 Or Years = -1
	Return Years
End Function

' Alternative solution that accounts for numbers outside of the specified range, non-numerical values, and non-integers within the range:
Function GetHowLongToRun() As Integer
'Additional variable required to check if input it decimal or not.
	Dim Year As String
	Dim Years As Integer
	Dim Valid As Boolean
	Console.WriteLine("Welcome to the Plant Growing Simulation")
	Console.WriteLine()
	Console.WriteLine("You can step through the simulation a year at a time")
	Console.WriteLine("or run the simulation for 0 to 5 years")
	Console.WriteLine("How many years do you want the simulation to run?")
	
	While Valid = False
'Try-Catch validation in case string entered.
		Try
		Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
		Year = Console.ReadLine()
'Validation for decimals.
		If Year = CInt(Year) Then
			Years = Year
		End If
		
		Catch ex As Exception
		Valid = False
		Years = -10
		End Try
		
'Validation if number not in range.
		If Years < -1 Or Years > 5 Or Years = 0 Then
			Console.WriteLine("The entry was not valid. Please try again.")
			Console.WriteLine()
			Valid = False
		Else
			Valid = True
		End If
		End While
		
		Return Years
	End Function

Java Solution[edit]

Answer:

JAVA:

static int GetHowLongToRun()
  {
    int Years = 69;
    Console.println("Welcome to the Plant Growing Simulation");
    Console.println();
    Console.println("You can step through the simulation a year at a time");
    Console.println("or run the simulation for 0 to 5 years");
    Console.println("How many years do you want the simulation to run?");
    do {
	try {
	     Years = Console.readInteger("Enter a number between 0 and 5, or -1 for stepping mode: ");
	     } catch (NumberFormatException e) {
	      Years = -999;
	     }
	if ((Years < -1) || (Years > 5)) {
	     Console.println("Invalid input, please enter a valid number");
	   }
	} while ((Years < -1) || (Years > 5));
    return Years;
  }

Python Solution[edit]

Answer:

PYTHON

#METHOD 1

def GetHowLongToRun():
  print('Welcome to the Plant Growing Simulation')
  print()
  print('You can step through the simulation a year at a time')
  print('or run the simulation for 1 to 5 years')
  print('How many years do you want the simulation to run?')
  while True:
    Years = int(input('Enter a number between 1 and 5, or -1 for stepping mode: '))
    print('You must enter a number between 1 - 5, or -1')
    if Years > 0 and Years <= 5 or Years == -1:
      return Years
#Come on y'all, you gotta b e l i e v e

#METHOD 2

def GetHowLongToRun():
  print ("Welcome to the Plant Growing Simulation")
  print ()
  print ("You can step through the simulation a year at a time")
  print ("or run the simulation for 0 to 5 years")
  print ("How many years do you want the simulation to run?")
  Years = input("Enter a number between 0 and 5, or -1 for stepping mode: ")

  while type(Years) != int:
    try:
      Years = int(Years)
      if Years not in range(-1,6):
        Years = input("Must be in range -1 to 5")
    except:
      Years = input("Must be an integer")
  return Years

#Shout out to the lads and big man Ross

C# Solution[edit]

Answer:

static int GetHowLongToRun()
        {
            bool valid = false;
            int Years = -2;
            Console.WriteLine("Welcome to the Plant Growing Simulation");
            Console.WriteLine();
            Console.WriteLine("You can step through the simulation a year at a time");
            Console.WriteLine("or run the simulation for 0 to 5 years");
            while (valid == false)
            {
                Console.WriteLine("How many years do you want the simulation to run?");
                Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ");
                try
                {
                    Years = Convert.ToInt32(Console.ReadLine());
                    valid = true;
                    if (Years < -1 || Years > 5 || Years == 0)
                    {
                        Console.WriteLine("Please enter a valid number");
                        valid = false;
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine("Invalid input.");
                }
            }
            return Years;

        }

Delphi/Pascal Solution[edit]

Answer:

//The '{}' indicates the lines of code I have added ontop of the vanilla skeleton code
Function GetHowLongToRun() : Integer;                                         
Var                                                                           
  Years : Integer;
Begin
  repeat{}                                                                      //Added Repeat Loop to repeat input stage
      Writeln('Welcome to the Plant Growing Simulation');                       //if invalid integer is put in
      Writeln;
      Writeln('You can step through the simulation a year at a time');
      Writeln('or run the simulation for 0 to 5 years');
      Writeln('How many years do you want the simulation to run?');
      Write('Enter a number between 0 and 5, or -1 for stepping mode: ');
      Readln(Years);
      if (Years < -2) or (Years = -2) or (Years > 6) or (Years = 6){}           //If input is anything but a number between
      then begin{}                                                              //-1 and 5, then it will be rejected, and
              Writeln ('Please enter a valid integer');{}                       //error message will be displayed, prompting
              Writeln;{}                                                        //user to try again.
           end;{}
  until (Years > -2) and (Years < 6);{}                                        //Repeat loop will repeat everything run until
  GetHowLongToRun := Years;                                                    //a valid integer is inputted
End;

Crop Virus[edit]

C# Solution[edit]

Answer:

//minor edit to the simulate summer subroutine
// James Barlow BTC
        static void SimulateSummer(char[,] Field)
        {
            Random RandomInt = new Random();
            int RainFall = RandomInt.Next(0, 3);
            int Virus = RandomInt.Next(0, 5);
            int PlantCount = 0;
            if (RainFall == 0)
            {
                PlantCount = 0;
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            PlantCount++;
                            if (PlantCount % 2 == 0)
                            {
                                Field[Row, Column] = SOIL;
                            }
                        }
                    }
                }
                Console.WriteLine("There has been a severe drought");
                CountPlants(Field);
            }
            if (Virus == 0)
            {
                PlantCount = 0;
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            PlantCount++;
                            if (PlantCount % 3 == 0)
                            {
                                Field[Row, Column] = SOIL;
                            }
                        }
                    }
                }
                Console.WriteLine("There has beeen a Virus that has destroyed some of your plants");
                CountPlants(Field);
            }
        }
Extremely similar to the rainfall subroutine but i noticed this method would also work.

Java Solution[edit]

Answer:

static void SimulateAutumn(char[][] Field)
  {
    for (int Row = 0; Row < FIELDLENGTH; Row++)
    {
      for (int Column = 0; Column < FIELDWIDTH; Column++)
      {
        if (Field[Row][Column] == PLANT)
        {
          SeedLands(Field, Row - 1, Column - 1);
          SeedLands(Field, Row - 1, Column);
          SeedLands(Field, Row - 1, Column + 1);
          SeedLands(Field, Row, Column - 1);
          SeedLands(Field, Row, Column + 1);
          SeedLands(Field, Row + 1, Column - 1);
          SeedLands(Field, Row + 1, Column);
          SeedLands(Field, Row + 1, Column + 1);

        }

        if (Field[Row][Column] == PLANT || Field[Row][Column] == SEED) {
        	Random RandomInt = new Random();
            int RadomInt = RandomInt.nextInt(100);
        	if(RadomInt < 4) {
          	  SimulateDisease(Field, Row, Column);
            }
        }
      }
    }
  }
  static void SimulateDisease(char[][] Field, int Row, int Column) {
	  //Console.println(Row + " " + Column);
	  Console.println("Disease has struck!");
	  for(int i = Row-2; i < Row+3; i++) {
		  for(int y = Row-2; y < Column+3; y++) {
			  try {
			  if (Field[i][y] == SEED || Field[i][y] == PLANT ) {
			     Field[i][y] = SOIL;
			  }
			  }catch (Exception e) {
				  Console.println("ERROR");
			  }
			 
		  }
	  }
  }
//Inder Panesar

Python Solution[edit]

Answer:

def CropVirus(Field, Row, Column):
  if Row >= 0 and Row < FIELDLENGTH and Column >= 0 and Column < FIELDWIDTH:
      Field[Row][Column] = VIRUS
  return Field
                        
def SimulateAutumn(Field): 
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      if Field[Row][Column] == PLANT:
        Field = SeedLands(Field, Row - 1, Column - 1)
        Field = SeedLands(Field, Row - 1, Column)
        Field = SeedLands(Field, Row - 1, Column + 1)
        Field = SeedLands(Field, Row, Column - 1)
        Field = SeedLands(Field, Row, Column + 1)
        Field = SeedLands(Field, Row + 1, Column - 1)
        Field = SeedLands(Field, Row + 1, Column)
        Field = SeedLands(Field, Row + 1, Column + 1)
  if randint(0,3) == 1:
    Row = randint(0,FIELDLENGTH)
    Column = randint(0,FIELDWIDTH)
  
    Field = CropVirus(Field, Row - 1, Column - 1)
    Field = CropVirus(Field, Row - 1, Column)
    Field = CropVirus(Field, Row - 1, Column + 1)
    Field = CropVirus(Field, Row, Column - 1)
    Field = CropVirus(Field, Row, Column )  
    Field = CropVirus(Field, Row, Column + 1)
    Field = CropVirus(Field, Row + 1, Column - 1)
    Field = CropVirus(Field, Row + 1, Column)
    Field = CropVirus(Field, Row + 1, Column + 1)

Python Solution 2[edit]

Answer:

def SimulateSpring(Field):
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      if Field[Row][Column] == SEED:  
        Field[Row][Column] = PLANT
  CountPlants(Field)
  Field = CropVirus(Field)
#This is where the virus function is called
  if randint(0, 1) == 1:
    Frost = True
  else:
    Frost = False
  if Frost:    
    PlantCount = 0
    for Row in range(FIELDLENGTH):
      for Column in range(FIELDWIDTH):
        if Field[Row][Column] == PLANT:
          PlantCount += 1
          if PlantCount % 3 == 0:
            Field[Row][Column] = SOIL
    print('There has been a frost')
    CountPlants(Field)
  return Field

def CropVirus(Field):
    if randint(0,5) == 1:
#This chooses a random number between 0 and 5 and if it is equal to 1 the virus begins.
        NumberOfPlants = 0
        for Row in range(FIELDLENGTH):
            for Column in range(FIELDWIDTH):
              if Field[Row][Column] == PLANT:
                if randint(0,1) == 1:
                    Field[Row][Column] = SOIL
        print('There has been a virus!')
        return Field
    else:
        return Field

VB.NET Solution[edit]

Answer:

Sub SimulateOneYear(ByVal Field(,) As Char, ByVal Year As Integer)
        '' Simulate Crop Virus is called here every season, however individual seasons can be removed.
        Field = SimulateSpring(Field)
        SimulateCropVirus(Field)
        Display(Field, "spring", Year)

        Field = SimulateSummer(Field)
        SimulateCropVirus(Field)
        Display(Field, "summer", Year)

        Field = SimulateAutumn(Field)
        SimulateCropVirus(Field)
        Display(Field, "autumn", Year)

        Field = SimulateWinter(Field)
        SimulateCropVirus(Field)
        Display(Field, "winter", Year)

    End Sub
    Function SimulateCropVirus(ByVal Field As Char(,)) As Char(,)
        Dim NumberOfPlantsKilled As Integer
        ''This chooses a random number between 0 and 5 and if it is equal to 1 the virus begins.
        If Math.Round(Rnd() * 5) = 1 Then
            NumberOfPlantsKilled = 0
            For Row = 0 To FIELDLENGTH - 1
                For Column = 0 To FIELDWIDTH - 1
                    If Field(Row, Column) = PLANT Then
                        If Math.Round(Rnd() * 1) = 1 Then
                            Field(Row, Column) = SOIL
                            NumberOfPlantsKilled += 1
                        End If
                    End If
                Next
            Next
            Console.WriteLine("There has been a virus!")
            If NumberOfPlantsKilled = 0 Then
                Console.WriteLine("No Plants have been harmed.")
            ElseIf NumberOfPlantsKilled = 1 Then
                Console.WriteLine("1 Plant has been Killed.")
            Else
                Console.WriteLine(NumberOfPlantsKilled & " Plants have been Killed.")
            End If
            Return Field
        Else
            Return Field
        End If
    End Function

Also VB[edit]

Answer:

Function GetHowLongToRun() As Integer
	Dim Years As Integer
	Dim num1 As Boolean
	Console.WriteLine("Welcome to the Plant Growing Simulation")
	Console.WriteLine()
	Console.WriteLine("You can step through the simulation a year at a time")
	Console.WriteLine("or run the simulation for 0 to 5 years")
	Console.WriteLine("How many years do you want the simulation to run?")
	
	Do
		Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
		Years = Console.ReadLine()
		If Years > 5 Or Years < -1 Then
			num1 = False
			Console.WriteLine("Invalid number")
		Else
			num1 = True
		End If
		
	Loop Until num1 = True
	Return Years
End Function

' Alternative Solution which doesn't crash when non numerical values are entered:
Function GetHowLongToRun() As Integer
	Dim Years As Integer
	Console.WriteLine("Welcome to the Plant Growing Simulation")
	Console.WriteLine()
	Console.WriteLine("You can step through the simulation a year at a time")
	Console.WriteLine("or run the simulation for 0 to 5 years")
	Console.WriteLine("How many years do you want the simulation to run?")
	Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
	Do
		Try
		Years = Console.ReadLine()
		Catch
		End Try
		If Years > 5 Or Years < -1 Then
			Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
		End If
	Loop Until Years <= 5 And Years >= 1 Or Years = -1
	Return Years
End Function

' Alternative solution that accounts for numbers outside of the specified range, non-numerical values, and non-integers within the range:
Function GetHowLongToRun() As Integer
'Additional variable required to check if input it decimal or not.
	Dim Year As String
	Dim Years As Integer
	Dim Valid As Boolean
	Console.WriteLine("Welcome to the Plant Growing Simulation")
	Console.WriteLine()
	Console.WriteLine("You can step through the simulation a year at a time")
	Console.WriteLine("or run the simulation for 0 to 5 years")
	Console.WriteLine("How many years do you want the simulation to run?")
	
	While Valid = False
'Try-Catch validation in case string entered.
		Try
		Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
		Year = Console.ReadLine()
'Validation for decimals.
		If Year = CInt(Year) Then
			Years = Year
		End If
		
		Catch ex As Exception
		Valid = False
		Years = -10
		End Try
		
'Validation if number not in range.
		If Years < -1 Or Years > 5 Or Years = 0 Then
			Console.WriteLine("The entry was not valid. Please try again.")
			Console.WriteLine()
			Valid = False
		Else
			Valid = True
		End If
		End While
		
		Return Years
	End Function

Delphi/Pascal Solution[edit]

Answer:

Procedure CropVirus(var Field: TField);
var
  Row, Column: Integer;

begin
  if random(5) = 1 then
  begin
    // This chooses a random number between 0 and 5 and if it is equal to 1 the virus begins.
    for Row := 0 to FIELDLENGTH-1 do
      for Column := 0 to FIELDWIDTH-1 do
        if Field[Row][Column] = PLANT then
          if random(1) = 1 then
            Field[Row][Column] := SOIL;
    writeln('There has been a virus!');
  end;
end;

Function SimulateSpring(Field: TField): TField;
Var
  PlantCount: Integer;
  Row, Column: Integer;
  Frost: Boolean;
Begin
  For Row := 0 To FIELDLENGTH - 1 Do
    For Column := 0 To FIELDWIDTH - 1 Do
      If Field[Row][Column] = SEED Then
        Field[Row][Column] := PLANT;
  CountPlants(Field);
  // Crop Virus Call Goes here for a Spring Virus
  CropVirus(Field);
  If random(2) = 1 Then

Save File[edit]

Python Solution[edit]

Answer:

## Save File Function By Hasan Moh
def SaveField(Field):
  FileName = input("Enter File Name To Save As: ")
  FileName = FileName + ".txt"
  Handler = open(FileName, "w+")
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      Handler.write(Field[Row][Column])
    Handler.write('|{0:>3}'.format(Row))
    Handler.write("\n")
  Handler.close()
  print("Field saved to " + FileName)

## Edit Simulation
def Simulation():
  YearsToRun = GetHowLongToRun()
  if YearsToRun != 0:
    Field = InitialiseField()
    if YearsToRun >= 1:
      for Year in range(1, YearsToRun + 1):
        SimulateOneYear(Field, Year)
    else:
      Continuing = True                     
      Year = 0
      while Continuing:
        Year += 1
        SimulateOneYear(Field, Year)
        Response = input('Press Enter to run simulation for another Year, Input X to stop: ')
        if Response == 'x' or Response == 'X':
          Continuing = False
    print('End of Simulation')
    if("Y" in input("Save Field [Y/N]?")):
      SaveField(Field)
  input()

ALTERNATIVE

def SaveFile(Field):

 fileName = input('Enter desired file name: ')
 fileWrite = open(fileName,'w')
 count = 0
 for Row in range(FIELDLENGTH):
   for Column in range(FIELDWIDTH):
     fileWrite.write(str(Field[Row][Column]))
   fileWrite.write('| ' + str(count) + '\n')
   count += 1
 fileWrite.close()
    1. edited simulation

def Simulation():

 YearsToRun = GetHowLongToRun()
 if YearsToRun != 0:
   Field = InitialiseField()
   if YearsToRun >= 1:
     for Year in range(1, YearsToRun + 1):
       SimulateOneYear(Field, Year)
   else:
     Continuing = True                     
     Year = 0
     while Continuing:
       Year += 1
       SimulateOneYear(Field, Year)
       Response = input('Press Enter to run simulation for another Year, Input X to stop: ')
       if Response == 'x' or Response == 'X':
         Continuing = False
   writeChoice = input('Do you want to save the file (Y/N): ')#NEW
   if writeChoice == 'Y':#NEW
     SaveFile(Field)#NEW
   print('End of Simulation')
 input()

VB.NET Solution[edit]

Answer :

Answer:

Console.WriteLine("End of Simulation")
           Dim save As Char
           Dim MyFileWriter = New StreamWriter("F:\game.txt")
           Dim Row As Integer
           Dim Column As Integer
           Console.WriteLine("Would you like to save the simulation? y/n?")
           save = Console.ReadLine
           If save = "y" Then
               For Row = 0 To (FIELDLENGTH - 1)
                   For Column = 0 To (FIELDWIDTH - 1)
                       If Field(Row, Column) = SOIL Then
                           MyFileWriter.Write(SOIL)
                       ElseIf Field(Row, Column) = SEED Then
                           MyFileWriter.Write(SEED)
                       ElseIf Field(Row, Column) = PLANT Then
                           MyFileWriter.Write(PLANT)
                       End If
                   Next
                   MyFileWriter.WriteLine()
               Next
               MyFileWriter.Close()
           End If
       End If

Delphi/Pascal Solution[edit]

Answer :

Answer:

Procedure Savefile(Field : TField); //Note : this procedure is very similar to the display procedure
Var
  Row, Column : Integer; filename: string; currentfile: text;
Begin
  Write('Enter the name of the file to save to: ');
  ReadLn(filename);
  assignfile(currentfile, filename);
  rewrite(currentfile);
  For row := 0 To FIELDLENGTH - 1 Do
    Begin
      For Column := 0 To FIELDWIDTH - 1 Do
        Write(currentfile, Field[Row][Column]);
      Writeln(currentfile, '|', Row:3);
    End;
  closefile(currentfile);
  Writeln('File saved as ', filename);
End;

Java Solution[edit]

Answer :call method in simulation

Answer:

static void WriteFile(char[][] Field) {
   try {
       AQAWriteTextFile2017 FileHandle = new AQAWriteTextFile2017("test.txt");
       for (int Row = 0; Row < FIELDLENGTH; Row++) {
           for (int Column = 0; Column < FIELDWIDTH; Column++) {
               String val = Character.toString(Field[Row][Column]);
               FileHandle.writeToTextFile(val, "");
           }
           FileHandle.writeToTextFile(" ");
       }
           FileHandle.closeFile();
   }
   catch(Exception e)
   {
       CreateNewField(Field);
   }
   }

Java Solution 2[edit]

Answer :call method in simulation

Answer:

  static void SaveFile(char[][] Field) {
    String FileName = "Hello";
    Console.print("Enter file name: ");
    FileName = Console.readLine();
    try {
      BufferedWriter out = new BufferedWriter(new FileWriter(FileName));
      for (int Row = 0; Row < FIELDLENGTH; Row++) {
        for (int Column = 0; Column < FIELDWIDTH; Column++) {
          out.write(Field[Row][Column]);        
        }
        out.write("|" + String.format("%3d", Row));
        out.write("\n");
      }
      out.close();
    }
    catch(Exception e) {
      System.out.println("error");
    }
  }
// Inder Panesar

C# Solution[edit]

Answer :

Answer:

// SaveFile C# Solution //
// By Reidan Beachill, 07/04/2017 //

// Below is only a few additions to call the save subroutine //

 private static void Simulation()
        {
            int YearsToRun;
            char[,] Field = new char[FIELDLENGTH, FIELDWIDTH];
            bool Continuing;
            int Year;
            string Response;
            YearsToRun = GetHowLongToRun();
            if (YearsToRun != 0)
            {
                InitialiseField(Field);
                if (YearsToRun >= 1)
                {
                    for (Year = 1; Year <= YearsToRun; Year++)
                    {
                        SimulateOneYear(Field, Year);
                    }
                }
                else
                {
                    Continuing = true;
                    Year = 0;
                    while (Continuing)
                    {
                        Year++;
                        SimulateOneYear(Field, Year);
                        Console.Write("Press Enter to run simulation for another Year, Input X to stop, S = Save: ");
                        Response = Console.ReadLine();
                        if (Response == "x" || Response == "X")
                        {
                            Continuing = false;
                        }
                        else if (Response.ToUpper() == "S")
                        {
                            saveCurrentPositions(Field); // If the user enters 'S', the field is saved
                        }
                    }
                }
                Console.WriteLine("End of Simulation");
            }
            Console.ReadLine();
        }
// END Simulation() //

// Add the following subroutine somewhere in the code, this contains validation on whether the file exists and saves the file//

// START saveCurrentPositions() //

static void saveCurrentPositions(char[,] Field)
        {
            Console.WriteLine("Please enter a FileName to save to: "); 
            string response = Console.ReadLine();
            StreamWriter streamWriter = new StreamWriter(response+".txt");
            string output = "";
            for (int i = 0; i < Field.GetUpperBound(0); i++)
            {
                for (int j = 0; j < Field.GetUpperBound(1); j++)
                {
                    output += Field[i, j].ToString();
                }
                streamWriter.Write(output);
                streamWriter.WriteLine("| " + String.Format("{0,3}", i));
                output = "";
            }

            streamWriter.Close();

            Console.WriteLine("Do you wish to continue or would you like to start again? C = Continue, or S for Start Again");
            string userResponse = Console.ReadLine();
            if (userResponse.ToUpper() != "C")
            {
                Console.Clear();
                Simulation();
            }
        }

// END saveCurrentPositions() //

C# Solution 2 - the better one *if you don't want to load file again ( ͡° ͜ʖ ͡°) *[edit]

Answer :

Answer:

// SaveFile C# Solution 2//

// adds a simple save function without the excess code //
// bundled with free grammatical errors and hardcoded file paths//

                string save;
                Console.WriteLine("End of Simulation");
                Console.Write("would you like to save the simulation? y/n ");
                save = Console.ReadLine();
                if (save == "y")
                {
                    using (System.IO.StreamWriter file =
 new System.IO.StreamWriter(@"C:\Users\pupil\Documents\TestFolder\WriteLines.txt"))
                    {
                        int Row = 0;
                        int Column = 0;
                        for (Row = 0; Row < FIELDLENGTH; Row++)
                        {
                            for (Column = 0; Column < FIELDWIDTH; Column++)
                            {
                                if (Field[Row, Column] == SOIL)
                                {
                                    file.Write(SOIL);
                                }
                                if (Field[Row, Column] == SEED)
                                {
                                    file.Write(SEED);
                                }
                                if (Field[Row, Column] == PLANT)
                                {
                                    file.Write(PLANT);
                                }
                                if (Field[Row, Column] == ROCKS)
                                {
                                    file.Write(ROCKS);
                                }
                            }
                            file.WriteLine();
                        }
                    }

=== Python Solution: ===
'''Answer :'''{{CPTAnswerTab}}
<syntaxhighlight lang="Python">

def SaveFile(Field):
  FileName = input('Enter file name: ')
  if not(FileName.endswith('.txt')):
              FileName = FileName + '.txt'
  try:
    FileHandle = open(FileName, 'w')
    for Row in range(FIELDLENGTH):
      for Column in range(FIELDWIDTH):
        FileHandle.write(Field[Row][Column])
      FileHandle.write('|{0:>3} \n'.format(Row))
    FileHandle.close() #Closes the file
  except:
    print("File save failed")

#Then in simulation the save function must be inserted
def Simulation():
  YearsToRun = GetHowLongToRun()
  if YearsToRun != 0:
    Field = InitialiseField()
    if YearsToRun >= 1:
      for Year in range(1, YearsToRun + 1):
        SimulateOneYear(Field, Year)
        #Save file is inserted here#######################
        Response = input('Press Enter to continue, Input Y to save file: ')
        if Response == 'y' or Response == 'Y':
          SaveFile(Field)
        #############################################
    else:
      Continuing = True                     
      Year = 0
      while Continuing:
        Year += 1
        SimulateOneYear(Field, Year)
        #Save file is also inserted here ######################
        Response = input('Press Enter to continue, Input Y to save file: ')
        if Response == 'y' or Response == 'Y':
          SaveFile(Field)
          ###############################################
        Response = input('Press Enter to run simulation for another Year, Input X to stop: ')
        if Response == 'x' or Response == 'X':
          Continuing = False
    print('End of Simulation')
  input()

Adding Rocks to the Simulation[edit]

Currently the rocks are defined as a constant but not used - how about adding a random number of rocks to the game at the beginning

VB.Console Solution[edit]

Answer:

VB.Console Solution:Function CreateNewField() As Char(,)
        Dim Row As Integer
        Dim Column As Integer
        Dim Field(FIELDLENGTH, FIELDWIDTH) As Char
        Dim rocknumber As Integer

 Console.WriteLine("how many rocks would you like?") 'Get number of rocks for simulation'
        Try
            rocknumber = Console.ReadLine 'validation'
        Catch
            Console.WriteLine("Not a valid entry. Simulation will continue as normal.")
        End Try

        For Row = 0 To FIELDLENGTH - 1
            For Column = 0 To FIELDWIDTH - 1
                Field(Row, Column) = SOIL
            Next
        Next

        Row = FIELDLENGTH \ 2
        Column = FIELDWIDTH \ 2
        Field(Row, Column) = SEED

            For x = 1 To rocknumber
            Row = Int(Rnd() * FIELDLENGTH) 'Gets random integer between 1 and 20'
            Column = Int(Rnd() * FIELDWIDTH) 'gets random Integer between 1 And 35
            Field(Row, Column) = ROCKS 'places rocks in field

        Next
        Return Field
        Console.ReadLine()
    End Function

Java Solution[edit]

Answer:

JAVA: 
static void instertRocks(char[][] Field)
  { Random RandomInt = new Random();
    int Row = 0;
    int Column = 0; 
    int rocknum;
       for (Row = 0; Row < FIELDLENGTH; Row++)
    {
      for (Column = 0; Column < FIELDWIDTH; Column++)
      {
        Field[Row][Column] = SOIL;
      }
    }
   do{
      rocknum=Console.readInteger("Enter the amount of rocks wanted ");
       if (rocknum>(FIELDLENGTH*FIELDWIDTH)){
         Console.println("Enter a valid number");
       }
    }while(rocknum>(FIELDLENGTH*FIELDWIDTH));   
    for(int x=0;x<rocknum;x++){
      do{
        Row = RandomInt.nextInt(FIELDLENGTH);
        Column = RandomInt.nextInt(FIELDWIDTH);
      } while(Field[Row][Column] == ROCKS); 
       Field[Row][Column] = ROCKS;
    }
  }

Java Solution 2[edit]

Answer:

  static void CreateNewField(char[][] Field) {
	int Rocks = 0;
	int RockIntervals = 0;
    Rocks = Console.readInteger("How many rocks do you want to place?");
    int Row = 0;
    int Column = 0;
    for (Row = 0; Row < FIELDLENGTH; Row++)  {
      for (Column = 0; Column < FIELDWIDTH; Column++) {
        Field[Row][Column] = SOIL;
      }
    }
    Row = FIELDLENGTH / 2;
    Column = FIELDWIDTH / 2;
    Field[Row][Column] = SEED;
    while (Rocks > RockIntervals) {
        Random RandomInt = new Random();
        int rowrandom = RandomInt.nextInt(19);
        Random RandomInt2 = new Random();
        int columnrandom = RandomInt2.nextInt(34);
        if(Field[rowrandom][columnrandom] == SEED) {
        	Field[rowrandom][columnrandom] = SEED;
        }
        else {
        	Field[rowrandom][columnrandom] = ROCKS;
        	RockIntervals++;
        }
    }
}
//alternative way of adding rocks
//Inder Panesar

Python Solution[edit]

Answer:

def CreateNewField():
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
###########################################################################################

  AddRocks = str(input("Would you like to add rocks to your game (y/n): "))
  if AddRocks == "y":
      NumRocks = randint(FIELDWIDTH,FIELDLENGTH)
      for _ in range (NumRocks):
          Row = randint(0,FIELDWIDTH-1)
          Column = randint(0,FIELDLENGTH-1)
          Field[Row][Column] = ROCKS
           
###########################################################################################
  Row = FIELDLENGTH // 2
  Column = FIELDWIDTH // 2
  Field[Row][Column] = SEED
  return Field
by Micheal Air Jordan
###You should be a better programmer Balwinder Singh
###It doesn't work, you lied
###You Should have picked IT
###Go back to scratch

Alternate Python Solution[edit]

Answer:

# i find this solution simpler and easier to understand

def CreateNewField():
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
# after this line is where the rock code is added.
  Rock_Choice = input('Would you like to add rocks to the simulation? (Y/N): ')
  if Rock_Choice == 'Y' or Rock_Choice == 'y':
    for Row in range(FIELDLENGTH):
      for Column in range(FIELDWIDTH):
        AddRock = randint(0,25)
# you can change the value in the randint function to whatever
        if AddRock == 1:
          Field[Row][Column] = ROCKS

C# Solution[edit]

Answer:

// written by Patrick Lake //

        static void CreateNewField(char[,] Field)
        {
            int Row = 0;
            int Column = 0;

            Random RandomInt = new Random();

            for (Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (Column = 0; Column < FIELDWIDTH; Column++)
                {
                    if (RandomInt.Next(0, 20) == 0)       // gives 1 in 20 chance
                        Field[Row, Column] = ROCKS;

                    else
                        Field[Row, Column] = SOIL;
                }
            }
            Row = FIELDLENGTH / 2;
            Column = FIELDWIDTH / 2;
            Field[Row, Column] = SEED;
        }

Delphi/Pascal Solution[edit]

Answer:

//The '{}' indicates the lines of code I have added ontop of the vanilla skeleton code
Function CreateNewField() : TField;
Var
  Row, Column, X, Y : Integer;
  Field : TField;
  Answer: Char;

Begin
  For Row := 0 to FIELDLENGTH - 1 Do
    For Column := 0 to FIELDWIDTH - 1 Do
      Field[Row][Column] := SOIL;
  Writeln ('Would you like to spawn rocks? [Y/N]');{}                    //User given the option to choose if they wish to put rocks in
  Readln (Answer);{}                                                     //The program will only proceed with the rock generation
  if (Answer = 'Y') or (Answer = 'y'){}                                  //if the user inputs 'Y' or 'y'
  then begin{}
              For Row := 0 to FIELDLENGTH-1 do{}                         //This line of code will 'scan' the entire 'grid'.
                For Column := 0 to FIELDWIDTH-1 do{}
                    if Field[Row][Column] = SOIL then{}                  //While it is 'scanning' is soil, there is a 1/20 chance
                       if random(20) = 1 then{}                          //that each soil element will be turned into a rock,
                       begin{}                                           //thus creating a random rock generator.
                             X:= Random(FIELDLENGTH);{}
                             Y:= Random(FIELDWIDTH);{}
                             FIELD [X, Y] := ROCKS;{}
                       end;{}
       end;{}
  Row := FIELDLENGTH DIV 2;
  Column := FIELDWIDTH DIV 2;
  Field[Row][Column] := SEED;
  CreateNewField := Field;
End;

Player has the option to choose where the first seed is placed[edit]

TEST FOR QUESTION

C# Solution[edit]

Answer :

Answer:

		static void CreateNewField(char[,] Field){
//added onto the bottom of CreateNewField() Subroutine.
			if (!SpecificSeedPlacement()) {
				Row = FIELDLENGTH / 2;
				Column = FIELDWIDTH / 2;
				Field[Row, Column] = SEED; //places 1 seed in the middle of board.
			}
			else {
				int[] Placement = new int[2];
				SetSeedPlacement(ref Placement); // defines where user wants to place seed.
				Field[Placement[0], Placement[1]] = SEED;
			}
		}

		static bool SpecificSeedPlacement() {
			Console.WriteLine("Would you like to Place the seed in a specific square? Y/N");
			string input = Console.ReadLine().Trim().ToString();
			if (input == "Y" || input == "y") {
				return true;
			}
			else {
				return false;
			}
		}

		static void SetSeedPlacement(ref int[] Placement) {
			Console.WriteLine("Where would you like to place the seed? Enter (X,Y) coordinate");
			bool correct = false;
			do {
				string tempinput = Console.ReadLine().Replace(" ", "").Trim('(', ')'); //removes space and brackets
				string[] input = tempinput.Split(','); //Splits string into an array

				if (Convert.ToInt32(input[0]) >= FIELDLENGTH || Convert.ToInt32(input[0]) < 0 || Convert.ToInt32(input[1]) >= FIELDWIDTH || Convert.ToInt32(input[1]) < 0) { //checks if array is out of bounds
					correct = false;
					Console.WriteLine("You have enter a value that is invalid. Please Try Again.");
				}
				else {
					Placement[0] = Convert.ToInt32(input[0]); //set the referenced 'Placement[]' array to user input
					Placement[1] = Convert.ToInt32(input[1]);
					correct = true;
				}
			} while (!correct);
		}

Answer 2 :

Answer:

i have found a simpler solution that doesn't require much coding
        static void CreateNewField(char[,] Field)
        {
            int Row = 0;
            int Column = 0;
            for (Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (Column = 0; Column < FIELDWIDTH; Column++)
                {
                    Field[Row, Column] = SOIL;
                }
            }
            Console.WriteLine("would you like to choose your first seeds position (Y/N): ");
            string Response = Console.ReadLine();
            if ((Response == "Y") || (Response == "y"))
            {
                Console.WriteLine("Please insert the row number you would like to place your seed. Bearing in mind it is between 0 and {0}: ", FIELDWIDTH);
                Row = System.Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Please insert the column number you would like to place your seed. Bearing in mind it is between 0 and {0}: ", FIELDLENGTH);
                Column = System.Convert.ToInt32(Console.ReadLine());
                Field[Row, Column] = SEED;
            }
            else if ((Response == "N")  || (Response == "n"))
            {
                Row = FIELDLENGTH / 2;
                Column = FIELDWIDTH / 2;
                Field[Row, Column] = SEED;
            }
        }
//side note- There is an isssue when dealing with maximum sizes. as for now i have no solution to this currently.
James Barlow, Bridgwater college, KEK with a head like this I'd run -> [http://i.imgur.com/eTdYQXg.jpg Tool]

VB.Net Solution[edit]

Answer:

Dim seedPos1 As Integer
Dim seedPos2 As Integer
Console.WriteLine("enter X co ordinate for seed")
seedPos1 = Console.ReadLine
Console.WriteLine("enter Y co ordinate for seed")
seedPos2 = Console.ReadLine
Field(seedPos1, seedPos2) = SEED
Return Field

22

Python Solution 1[edit]

Answer:

def CreateNewField(): 
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
  while True:
    SeedPositionRow = int(input("Enter the y position of the first seed: "))
    SeedPositionColumn = int(input("Enter the x value of the first seed: "))
# You want the seed to be able to be placed in 0,0 position meaning it cant be <=0 it has to be <=-1
#Your Welcome
#Chris Owen :) 420 Blaze it
    if SeedPositionRow > FIELDLENGTH or SeedPositionRow <= -1:
      print("You have entered an invalid y position. Try again")
    if SeedPositionColumn > FIELDWIDTH or SeedPositionColumn <= -1:
      print("You have entered an invalid x position. Try again")
    else:
      break
  Field[SeedPositionRow][SeedPositionColumn] = SEED
  return Field

Python Solution 2[edit]

Answer:

# All modifications are made within the CreateNewField function
# All inputs are checked and reasked if an invalid answer was given.
# Capitals mean that's the default 
def CreateNewField(): 
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
  Row = FIELDLENGTH // 2
  Column = FIELDWIDTH // 2
  done=not(input("Do you want to adjust the seed start position?:(y/N)\n>>> ").upper()=="Y")
  while not(done):
    try:
      xCoord = int(input("Choose the x coordinate for the seed: (Default=Centre)\n>>> "))
      yCoord = int(input("Choose the y coordinate for the seed: (Default=Centre)\n>>> "))
      if xCoord > FIELDWIDTH or xCoord <=0:
        print("Incorrect x value entered, please try again.")
      elif yCoord > FIELDWIDTH or yCoord <=0:
        print("Incorrect y value entered, please try again.")
      else:
        done=True
        Row, Column = yCoord-1, xCoord-1
    except ValueError:
      print("Incorrect value entered, please try again.")
      done=False
  Field[Row][Column] = SEED
  return Field

Java Solution[edit]

Answer:

static void CreateNewField(char[][] Field)
 {
   Random RandomInt = new Random();
   int Row = 0;
   int Column = 0;
   for (Row = 0; Row < FIELDLENGTH; Row++)
   {
     for (Column = 0; Column < FIELDWIDTH; Column++)
     {
       Field[Row][Column] = SOIL;
     }
   }
  char option = Console.readChar("Would you like to enter a start position (Y/N) ");
   if ((option=='Y')||(option=='y')){
   do{
    Row=Console.readInteger("Enter row position ");
    if ((Row>=FIELDLENGTH)||(Row<0)){
       Console.println("Please enter a valid row");
       }
   }while((Row>=FIELDLENGTH)||(Row<0));
   do{
    Column=Console.readInteger("Enter Column position ");
    if ((Column>=FIELDWIDTH)||(Column<0)){
       Console.println("Please enter a valid Column");
       }
   }while((Column>=FIELDWIDTH)||(Column<0));
   Field[Row][Column] = SEED;
   }
   else {
   Row = FIELDLENGTH / 2;
   Column = FIELDWIDTH / 2;
   Field[Row][Column] = SEED;
  }
 }

Change the program so when you enter number of years it doesn't accept any character input and returns an error with another chance of input.[edit]

Change the program so when you enter number of years it doesn't accept any character input and returns an error with another chance of input.

C# Solution[edit]

Answer :

Answer:

== This code deals with '1) Make Sure The Number of Years Entered Is Valid' as well as this problem ==
== Code by Zac Murphy ==

        static int GetHowLongToRun() //Function that returns the number of years to run the simulation
        {
            int Years = 0;
            Console.WriteLine("Welcome to the Plant Growing Simulation");
            Console.WriteLine();
            Console.WriteLine("You can step through the simulation a year at a time");
            Console.WriteLine("or run the simulation for 0 to 5 years");
            Console.WriteLine("How many years do you want the simulation to run?");

            //Do loop to check if the character entered is correct
            do
            {
                Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: "); //Write this every time the input is not an integer
            } while (!int.TryParse(Console.ReadLine(), out Years)); //Convert the string to an integer, if it can. When it is successful out Years

            //While loop to check the input is within range
            while (!((Years >= 1 && Years <= 5) || Years == -1))
            {
                //Followed by the do loop again, to make sure it is still an integer
                do
                {
                    Console.WriteLine("Try again");
                    Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ");
                } while (!int.TryParse(Console.ReadLine(), out Years));
            }
            return Years;
        }

Delphi/Pascal Solution[edit]

Answer :

Answer:


Java Solution[edit]

Answer :

Answer:

 static int GetHowLongToRun()
  {
    int Years = 0;
    Console.println("Welcome to the Plant Growing Simulation");
    Console.println();
    Console.println("You can step through the simulation a year at a time");
    Console.println("or run the simulation for 0 to 5 years");
    Console.println("How many years do you want the simulation to run?");
    do {
    try{
    Years = Console.readInteger("Enter a number between 0 and 5, or -1 for stepping mode: ");
    } catch (Exception e) {
    Years = -100;
    }
    } while (Years > 5 || Years < -1); 
    return Years;
  }
//Inder Panesar

Python Solution[edit]

Answer :

Answer:

while (True):
     try:
       Years = int(input('Enter a number between 0 and 5, or -1 for stepping mode: '))
       if Years > 5 or Years < -1:
         raise ValueError
       else:
         break
     except:
       print("You have entered an invalid year")
By iuhiuh (aka. SJP)

Alternate Python solution[edit]

Answer:

def GetHowLongToRun():
  print('Welcome to the Plant Growing Simulation')
  print()
  print('You can step through the simulation a year at a time')
  print('or run the simulation for 0 to 5 years')
  print('How many years do you want the simulation to run?')
  Valid = False
  while Valid == False:
    try:
      Years = int(input('Enter a number between 0 and 5, -1 for stepping mode.'))
      if Years in range (0,6):
        Valid = True
      elif Years == -1:
        Valid = True
      else:
        Valid = False
    except:
      print('An error occurred, try again.')
  return Years

# this solution does not utilize the break function

VB.NET Solution[edit]

Answer :

Answer:

    Function GetHowLongToRun() As Integer
        Dim Years As Integer
        Dim num1 As Boolean
        Console.WriteLine("Welcome to the Plant Growing Simulation")
        Console.WriteLine()
        Console.WriteLine("You can step through the simulation a year at a time")
        Console.WriteLine("or run the simulation for 0 to 5 years")
        Console.WriteLine("How many years do you want the simulation to run?")
        Do
            Try
                Console.Write("Enter a number between 0 and 5, or -1 for stepping mode: ")
                Years = Console.ReadLine()
            Catch
                Console.WriteLine("Enter A valid integer")
                num1 = False
            End Try
            If Years < -2 Or Years > 6 Then
                Console.WriteLine("Please enter a valid number.")
                num1 = False
            ElseIf Years > -2 And Years < 6 Then
                num1 = True
            End If
        Loop Until num1 = True

        Return Years
    End Function
'Big up NewVic mandem ' The Real Swifty

Add functionality for plants that thrive on or require frost[edit]

Add functionality for plants that thrive on or require frost

C# Solution: Adds very frosty plants[edit]

Answer :

Answer:

// Reverse engineered Through pain and lots of energy drinks from python (You had 2 cans? Seriously you are such a lightweight)

//Ps Totally No spelling mistakes this time

//Top Of program
static bool Thrive = false;

// New subroutine
static void FrostPlant()
{
char ThriveInFrost='n';
bool thrive = false;
Console.Write("Does the plant thrive in frost (Y/N): ");
ThriveInFrost = char.Parse(Console.ReadLine());
if (ThriveInFrost == 'Y' || (ThriveInFrost == 'y'))
{
thrive = true;
}
else
{
thrive = false;
}
//can you feel it now Mr Krabs?
Thrive = thrive;
}

// In Simulate Spring
// add in the if(Frost part)

if (Thrive != true)
{
PlantCount = 0;
for (int row = 0; row < FIELDLENGTH; row++)
{
for (int Column = 0; Column < FIELDWIDTH; Column++)
{
if (Field[row, Column] == PLANT)
{
PlantCount++;
if (PlantCount % 3 == 0)
{
Field[row, Column] = SOIL;
}
}
}
//Yes SpongeBob, Im feeling it now
}
}
}
else
{
for (int row = 0; row < FIELDLENGTH; row++)
{
for (int Column = 0; Column < FIELDWIDTH; Column++)
{
if (Field[row, Column] == PLANT)
{
SeedLands(Field, row - 2, Column - 2);
SeedLands(Field, row - 1, Column - 2);
SeedLands(Field, row - 2, Column - 1);
SeedLands(Field, row - 2, Column);
SeedLands(Field, row - 2, Column + 2);
SeedLands(Field, row - 2, Column + 1);
SeedLands(Field, row - 1, Column + 2);
SeedLands(Field, row, Column - 2);
SeedLands(Field, row, Column + 2);
SeedLands(Field, row + 2, Column - 2);
SeedLands(Field, row + 1, Column - 2);
SeedLands(Field, row + 2, Column - 1);
SeedLands(Field, row + 2, Column);
SeedLands(Field, row + 2, Column + 2);
SeedLands(Field, row + 1, Column + 2);
SeedLands(Field, row + 2, Column + 1); 
}
}
}
}
Console.WriteLine("There has been a frost");
CountPlants(Field);
}

C# Solution: Adds frosty plants[edit]

Answer :

Answer:

//Replace the current SimulateSpring sub-routine with this
        //05/05/17
        static void SimulateSpring(char[,] Field)
        {
            int PlantCount = 0;
            bool Frost = false;
            for (int Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (int Column = 0; Column < FIELDWIDTH; Column++)
                {
                    if (Field[Row, Column] == SEED)
                    {
                        Field[Row, Column] = PLANT;
                    }
                }
            }
            Random RandomInt = new Random();
            if (RandomInt.Next(0, 2) == 1)
            {
                Frost = true;
            }
            else
            {
                Frost = false;
            }
            if (Frost)
            {
                PlantCount = 0;
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == PLANT)
                        {
                            PlantCount++;
                            if (PlantCount % 3 == 0)
                            {
                                Field[Row, Column] = SOIL;
                            }
                        }
                    }   
                }
                if(Frost)
                {
                    int amountOfFrost, pos1, pos2;
                    Random rand = new Random();
                    amountOfFrost = rand.Next(0, 10);
                    Console.WriteLine("There has been a frost");
                    CountPlants(Field);
                    for (int i = 0; i < amountOfFrost; i++)
                    {
                        pos1 = rand.Next(0, FIELDLENGTH);
                        pos2 = rand.Next(0, FIELDWIDTH);
                        if (Field[pos1, pos2] == PLANT || Field[pos1, pos2] == SOIL)
                        {
                            Field[pos1, pos2] = FROST;
                        }
                    }
                }
            }
            if (Frost == false)
            {
                for (int Row = 0; Row < FIELDLENGTH; Row++)
                {
                    for (int Column = 0; Column < FIELDWIDTH; Column++)
                    {
                        if (Field[Row, Column] == FROST)
                        {
                            Field[Row, Column] = SOIL;
                        }
                    }
                }
            }
        }

Delphi/Pascal Solution[edit]

Answer :

Answer:


Java Solution[edit]

Answer :

Answer:

class Paper1_ASLv1_2017_Java_Pre
{
  static char SOIL = '.';
  static char SEED = 'S';
  static char PLANT = 'P';
  static char ROCKS = 'X';
  static int FIELDLENGTH = 20;
  static int FIELDWIDTH = 35;
  static Boolean FROST = false; <--

   static void CreateNewField(char[][] Field) {
	boolean frost = false;
	char ThriveInFrost = 'n';
    int Row = 0;
    int Column = 0;
    for (Row = 0; Row < FIELDLENGTH; Row++)  {
      for (Column = 0; Column < FIELDWIDTH; Column++) {
        Field[Row][Column] = SOIL;
      }
    }
    Row = FIELDLENGTH / 2;
    Column = FIELDWIDTH / 2;
    Field[Row][Column] = SEED;
    ThriveInFrost = Console.readChar("Does the plant thrive in frost (Y/N): "); <--
    if (ThriveInFrost == 'Y' || ThriveInFrost == 'y') { <--
    	frost = true; <--
    } <--
    else { <--
    	frost = false; <--
    } <--
    FROST = frost; <--
} <--
 
  static void SimulateSpring(char[][] Field)
  {
    int PlantCount = 0;
    Boolean Frost = false;
    for (int Row = 0; Row < FIELDLENGTH; Row++)
    {
      for (int Column = 0; Column < FIELDWIDTH; Column++)
      {
        if (Field[Row][Column] == SEED)
        {
          Field[Row][Column] = PLANT;
        }
      }
    }
    CountPlants(Field);
    Random RandomInt = new Random();
    if (RandomInt.nextInt(2) == 1)
    {
      Frost = true;
    }
    else
    {
      Frost = false;
    }
    if (Frost && !FROST) <--
    {
      PlantCount = 0;
      for (int Row = 0; Row < FIELDLENGTH; Row++)
      {
        for (int Column = 0; Column < FIELDWIDTH; Column++)
        {
          if (Field[Row][Column] == PLANT)
          {
            PlantCount++;
            if (PlantCount % 3 == 0)
            {
              Field[Row][Column] = SOIL;
            }
          }
        }
      }
      Console.println("There has been a frost");
      CountPlants(Field);
    }
  }
//Inder Panesar

Python Solution[edit]

Answer :

Answer:

(at start of program)

FIELDLENGTH = 20 
FIELDWIDTH = 35
Thrive_in_Frost = input("Does the plant thrive in frost (Y/N): ")
if Thrive_in_Frost == "Y":
  Thrive_in_Frost = True
else:
  Thrive_in_Frost = False

(in Simulate spring Function)

if Frost:
  if not Thrive_in_Frost:
    PlantCount = 0
    for Row in range(FIELDLENGTH):
      for Column in range(FIELDWIDTH):
        if Field[Row][Column] == PLANT:
          PlantCount += 1
          if PlantCount % 3 == 0:
            Field[Row][Column] = SOIL
  else:
    for Row in range(FIELDLENGTH):
      for Column in range(FIELDWIDTH):
        if Field[Row][Column] == PLANT:
          Field = SeedLands(Field, Row - 2, Column - 2)
          Field = SeedLands(Field, Row - 1, Column - 2)
          Field = SeedLands(Field, Row - 2, Column - 1)
          Field = SeedLands(Field, Row - 2, Column)
          Field = SeedLands(Field, Row - 2, Column + 2)
          Field = SeedLands(Field, Row - 2, Column + 1)
          Field = SeedLands(Field, Row - 1, Column + 2)
          Field = SeedLands(Field, Row, Column - 2)
          Field = SeedLands(Field, Row, Column + 2)
          Field = SeedLands(Field, Row + 2, Column - 2)
          Field = SeedLands(Field, Row + 1, Column - 2)
          Field = SeedLands(Field, Row + 2, Column - 1)
          Field = SeedLands(Field, Row + 2, Column)
          Field = SeedLands(Field, Row + 2, Column + 2)
          Field = SeedLands(Field, Row + 1, Column + 2)
          Field = SeedLands(Field, Row + 2, Column + 1)
  print('There has been a frost')
  CountPlants(Field)
return Field

VB.NET Solution[edit]

Answer :

Answer:

'to ask if plants survive frost
    Sub Simulation()
        Dim YearsToRun As Integer
        Dim Continuing, frostsurvive, loops As Boolean
        Dim Response As String
        Dim Year, save As Integer
        Dim Field(FIELDWIDTH, FIELDLENGTH), choice As Char
        YearsToRun = GetHowLongToRun()
        Console.WriteLine("Do the plants thrive in frost. [Y/N]")
        choice = Console.ReadLine()
        If choice = "Y" Then
            frostsurvive = True
        End If
        If YearsToRun <> 0 Then
            Field = InitialiseField()
            If YearsToRun >= 1 Then
                For Year = 1 To YearsToRun
                    SimulateOneYear(Field, Year, frostsurvive)
                Next
'frost thriving
    Function SimulateSpring(ByVal Field As Char(,), ByRef frostsurvive As Boolean)
        Dim Frost As Boolean
        Dim PlantCount As Integer
        For Row = 0 To FIELDLENGTH - 1
            For Column = 0 To FIELDWIDTH - 1
                If Field(Row, Column) = SEED Then
                    Field(Row, Column) = PLANT
                End If
            Next
        Next
        CountPlants(Field)
        If Int(Rnd() * 2) = 1 Then
            Frost = True
        Else
            Frost = False
        End If

        If Frost Then
            If frostsurvive Then
                Console.WriteLine("Your plants thrive in the frost")
                For Row = 0 To FIELDLENGTH - 1
                    For Column = 0 To FIELDWIDTH - 1
                        If Field(Row, Column) = PLANT Then
                            Field = SeedLands(Field, Row - 1, Column - 1)
                            Field = SeedLands(Field, Row - 1, Column)
                            Field = SeedLands(Field, Row - 1, Column + 1)
                            Field = SeedLands(Field, Row, Column - 1)
                            Field = SeedLands(Field, Row, Column + 1)
                            Field = SeedLands(Field, Row + 1, Column - 1)
                            Field = SeedLands(Field, Row + 1, Column)
                            Field = SeedLands(Field, Row + 1, Column + 1)
                        End If
                    Next
                Next
            Else
                PlantCount = 0
                For Row = 0 To FIELDLENGTH - 1
                    For Column = 0 To FIELDWIDTH - 1
                        If Field(Row, Column) = PLANT Then
                            PlantCount += 1
                            If PlantCount Mod 3 = 0 Then
                                Field(Row, Column) = SOIL
                            End If
                        End If
                    Next
                Next
            End If
            Console.WriteLine("There has been a frost")
            CountPlants(Field)
        End If
        Return Field
    End Function

 Sub SimulateOneYear(ByVal Field(,) As Char, ByVal Year As Integer)
        Field = SimulateSpring(Field, frostsurvive:=True)
        simulateplantvirus(Field)
        Display(Field, "spring", Year)

When the program wants to load a file, make it so that the user only needs to input the file name without the ".txt" extension but the program needs to be able to handle if the user does enter the ".txt" extension.[edit]

C# Solution[edit]

Answer :

Answer:

		static void ReadFile(char[,] Field){
			string FileName = "";
			string FieldRow = "";
			Console.Write("Enter file name: ");

// These two lines are the only changes

			FileName = Console.ReadLine().Replace(".txt", ""); 
			FileName = FileName + ".txt";

//-

			try {
				StreamReader CurrentFile = new StreamReader(FileName);
				for (int Row = 0; Row < FIELDLENGTH; Row++) {
					FieldRow = CurrentFile.ReadLine();
					for (int Column = 0; Column < FIELDWIDTH; Column++) {
						Field[Row, Column] = FieldRow[Column];
					}
				}
				CurrentFile.Close();
			}
			catch (Exception) {
				CreateNewField(Field);
			}
		}

Delphi/Pascal Solution[edit]

Answer :

Answer:

Function ReadFile() : TField;
Var
  Row, Column : Integer;
  FileName : String;
  FieldRow : String;
  CurrentFile : Text;
  Field : TField;
Begin
  Write('Enter file name: ');
  Readln(FileName);
  if RightStr(filename,4)<>'.txt' then     //StrUtils must be used
    filename:=filename+'.txt';
  Try
    AssignFile(CurrentFile, FileName);
    Reset(CurrentFile);
    For Row := 0 To FIELDLENGTH - 1 Do
    Begin
      Readln(CurrentFile, FieldRow);
      For Column := 0 To FIELDWIDTH - 1 Do
        Field[Row][Column] := FieldRow[Column + 1];
    End;
    CloseFile(CurrentFile);
  Except
    Field := CreateNewField();
  End;
  ReadFile := Field;
End;

Java Solution[edit]

Answer :

Answer:

  static void ReadFile(char[][] Field) {
    String FileName = "";
    String FieldRow = "";
    Console.print("Enter file name: ");
    FileName = Console.readLine();
    if (FileName.contains(".txt")) {
        FileName = FileName;          
    }
    else {
        FileName = (FileName + ".txt");
    }
    try {
      for (int Row = 0; Row < FIELDLENGTH; Row++) {
        for (int Column = 0; Column < FIELDWIDTH; Column++) {
          Field[Row][Column] = SOIL;
        }
      }
      AQAReadTextFile2017 FileHandle = new AQAReadTextFile2017(FileName); 
      for (int Row = 0; Row < FIELDLENGTH; Row++) {
        FieldRow = FileHandle.readLine();
        for (int Column = 0; Column < FIELDWIDTH; Column++) {
          Field[Row][Column] = FieldRow.charAt(Column);
        }
      }
      FileHandle.closeFile();
    }
    catch(Exception e){
      CreateNewField(Field);
    }
  }
//Inder Panesar 15/03/2017

Python Solution[edit]

Answer :

Answer:

def ReadFile():
  FileName = input('Enter file name: ')
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
  try:
    if ".txt" not in FileName:
        FileName=FileName+".txt"
    FileHandle = open(FileName, 'r')
    for Row in range(FIELDLENGTH):
      FieldRow = FileHandle.readline()
      for Column in range(FIELDWIDTH):
        Field[Row][Column] = FieldRow[Column]
    FileHandle.close()
  except:
    Field = CreateNewField()
  return Field

VB.NET Solution[edit]

Answer :

Answer:

'adds .txt if required, but ignores other file types for now. Add into readfile subroutine (and possibly the saving one too while you're at it)
        If Right(FileName, 4) = ".txt" Then
            FileName = FileName
        Else
            FileName = String.Concat(FileName, ".txt")
        End If

The rows are numbered but not the columns. Fix this columns as letters.[edit]

C# Solution[edit]

Answer :

Answer:

        static void Display(char[,] Field, string Season, int Year)
        {
            //base 62
            char[] alphabet = new char[]
            {
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','l','m','n','m','o','p','q','r','s','t','u','v','w','x','y','z'
            };

            Console.WriteLine("Season: " + Season + " Year number: " + Year);
            for (int Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (int Column = 0; Column < FIELDWIDTH; Column++)
                {
                    Console.Write(Field[Row, Column]);                    
                }
                if (Row <= 9)
                    Console.WriteLine("| " + String.Format("{0,3}", Row));
                else                
                    Console.WriteLine("| " + String.Format("{0,3}", alphabet.GetValue(Row - 10)));               
            }
            
            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                Console.Write("-");
            }
            Console.WriteLine();

            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                if (Column <= 9)
                    Console.Write(Column);
                else
                    Console.Write(alphabet.GetValue(Column - 10));                
            }
            Console.WriteLine();           
        }

C# Solution 2 (an esaier on that requires less work and looks cooler!)[edit]

Answer :

Answer:

  static void Display(char[,] Field, string Season, int Year)
       {
           Console.WriteLine("Season: " + Season + " Year number: " + Year);
           String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHI";
           for (int column = 0; column < FIELDWIDTH; column++)
           {
               Console.Write(alphabet[column]);
           }
           Console.WriteLine();
           for (int Row = 0; Row < FIELDLENGTH; Row++)
           {
               for (int Column = 0; Column < FIELDWIDTH; Column++)
               {
                   Console.Write(Field[Row, Column]);
                   
               }
               Console.WriteLine("| " + String.Format("{0,3}", Row));
            
           }
       }

C# Solution 3 (Solution 1 but uses vertical numbers instead of base 62 *works for field sizes larger than 62)[edit]

Answer :

Answer:

static void Display(char[,] Field, string Season, int Year)
        {
            Console.WriteLine("Season: " + Season + " Year number: " + Year);

            for (int Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (int Column = 0; Column < FIELDWIDTH; Column++)
                {
                    Console.Write(Field[Row, Column]);
                }
                Console.WriteLine("| " + String.Format("{0,3}", Row));
            }

            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                Console.Write("-");
            }
            Console.WriteLine();

            int count = -1;
            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                if (Column % 10 == 0)
                    count++;
                if (Column <= 9)
                    Console.Write(Column);
                else
                    Console.Write(count);
            }
            Console.WriteLine();

            count = 0;
            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                if (Column % 10 == 0)
                    count++;
                if (Column <= 9)
                    Console.Write(" ");
                else
                    Console.Write(Column - (count * 10) + 10);
            }
            Console.WriteLine();
        }

Pascal Solution[edit]

Answer :

 1 Procedure Display(Field : TField; Season : String; Year : Integer);
 2 Var
 3   Row, Column : Integer;
 4   alphabet: String;
 5 Begin
 6   Writeln('Season: ', Season, '  Year number: ', Year);
 7    alphabet := 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv';
 8 
 9    for Column := 1 to FieldWidth  do
10    begin
11      write(alphabet[column]);
12    end;
13    writeln();
14 
15   For row := 0 To FIELDLENGTH - 1 Do
16     Begin
17       For Column := 0 To FIELDWIDTH - 1 Do
18         Write(Field[Row][Column]);
19       Writeln('|', Row:3);
20     End;
21   Writeln;
22 End;

                                     

Java Solution[edit]

Answer :

Answer:

 static void Display(char[][] Field, String Season, int Year)  {
    Console.println("Season: " + Season + "  Year number: " + Year);
    int width = 0;
    while (width != FIELDWIDTH) {
		if (width <= 9) {
            Console.print("  "+width);
		}
        if (width > 9) {
        	Console.print(" "+width);
        }
        width++;
        if(width == FIELDWIDTH){
        	Console.println(" ");
        }
     }

    for (int Row = 0; Row < FIELDLENGTH; Row++) {
      for (int Column = 0; Column < FIELDWIDTH; Column++)  {
        Console.print("  "+Field[Row][Column]);
      }                                                 
      Console.println("|" + String.format("%3d", Row));
    }
    
  }
//Inder Panesar 14/03/2017

Python Solution[edit]

Answer 1:

Answer:

#Edit Display Function

def Display(Field, Season, Year):
  print('Season: ', Season, '  Year number: ', Year)
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      print(Field[Row][Column], end='  ')
    print('|{0:>3}'.format(Row))
  NumberList =""
  for i in range(0,FIELDWIDTH):
    if len(str(i)) < 2:
      i = " " + str(i)
    NumberList = NumberList + str(i) +" "
  print(NumberList)

Answer 2:

Answer:

 
def Display(Field, Season, Year):
  topline = ''
  secondline = ''
  for Column in range(FIELDWIDTH):
    number= Column - int(Column/10)*10
    if number == 0:
      topline += '|'
      secondline += '|'
    elif number == 2:
      topline += str((int(Column/10)*10))
      secondline +='2'
    elif number ==3:
      if int(Column/10)*10 == 0:
        topline+=' '
      secondline += str(number)        
    else:
      topline+= ' '
      secondline += str(number)
  print('Season: ', Season, '  Year number: ', Year)
  print(topline+'|')
  print(secondline+'|')
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      print(Field[Row][Column], end='')
    print('|{0:>3}'.format(Row))
  print()

Answer 3:

Answer:

 
def Display(Field, Season, Year):
  print('Season: ', Season, '  Year number: ', Year)
  x= 0
  y=[]
  while x!=FIELDWIDTH:
    y.append(x)
    x=x+1
  y1 = ''.join(str(e) for e in y)
  print(y1)
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      print(Field[Row][Column], end='')
      
    print('|{0:>3}'.format(Row))
  print()
##By Jack  aka Thugzbunny aka J.drizzle aka millionaires slice
##Git Gud Scrub

Answer 4: Vertical Columns

Answer:

"""This creates Vertical Columns that work for any length between 2 and 99"""
def Display(Field, Season, Year):
  onetoten=list(range(0,10))
  onetotenstr="".join(str(x) for x in onetoten)
  print('Season: ', Season, '  Year number: ', Year)
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      print(Field[Row][Column], end='')
    print('|{0:>3}'.format(Row))
  y=""
  x=0
  while x != FIELDWIDTH:
    if x%10 == 0:
      y=y+onetotenstr
      x +=1
    x+=1
  if y != FIELDWIDTH:
    y = y[0:FIELDWIDTH-len(y)]
  temp= list(y)
  index=[]
  for x in range(len(temp)):
    if  x>=10 and x<=19:
      index.append("1")
    if x>=20 and x<=29:
      index.append("2")
    if x>=30 and x<=39:
      index.append("3")
    if x>=40 and x<=49:
      index.append("4")
    if x>=50 and x<=59:
      index.append("5")
    if x>=60 and x<=69:
      index.append("6")
    if x>=70 and x<=79:
      index.append("7")
    if x>=80 and x<=89:
      index.append("8")
    if x>=90 and x>=99:
      index.append("9")
  indexstr="".join(str(x) for x in index)
  print("-"*FIELDWIDTH)
  print("          " + indexstr)
  print(y)
# By Mr MoneyMan @Moneyman
#Business Email: moneyman@money.co.uk/money
{{CPTAnswerTabEnd}}

Answer 5:

Answer:

"""All you need is a few lines."""
def Display(Field, Season, Year):
    print('Season: ', Season, '  Year number: ', Year)

    char = 65
    for t in range(FIELDWIDTH):
        if char +t> 65+25:
            offset = 6
        else:
            offset = 0

        print(chr(char+t+offset),end="")
    print("")
    for Row in range(FIELDLENGTH):
        for Column in range(FIELDWIDTH):
            print(Field[Row][Column], end='')
        print('|{0:>3}'.format(Row))

    print()
# By Mo

Every year in winter a bird (B) flies down a column and eats all seeds in it.[edit]

C# Solution[edit]

Answer :

Answer:


     const char BIRD = 'B'; // Addition of 'Bird
     static void SimulateWinter(char[,] Field)
       {
           for (int Row = 0; Row < FIELDLENGTH; Row++)
           {
               for (int Column = 0; Column < FIELDWIDTH; Column++)
               {
                   if (Field[Row, Column] == PLANT)
                   {
                       Field[Row, Column] = SOIL;
                   }
               }
           }
           Random rnd = new Random(); // Random variable 'rnd'
           int BirdFlight = rnd.Next(0, FIELDWIDTH);
           for (int Row = 0; Row < FIELDLENGTH; Row++) //Random Column Selected between 0 and FIELDLENGTH
           {
               if (Field[Row, BirdFlight] == SEED) // Change SEED to BIRD
               {
                   Field[Row, BirdFlight] = BIRD;
               }
           }
       }


       static void SimulateOneYear(char[,] Field, int Year)
       {
           SimulateSpring(Field);
           Display(Field, "spring", Year);
           SimulateSummer(Field);
           Display(Field, "summer", Year);
           SimulateAutumn(Field);
           Display(Field, "autumn", Year);
           SimulateWinter(Field);
           Display(Field, "winter", Year);
           Console.WriteLine("A bird has flown down a column! All seeds in this column have been eaten!!"); //Adds a Message
       }
    static void SimulateSpring(char[,] Field)
       {
           int PlantCount = 0;
           bool Frost = false;
           for (int Row = 0; Row < FIELDLENGTH; Row++)
           {
               for (int Column = 0; Column < FIELDWIDTH; Column++)
               {
                   if (Field[Row, Column] == BIRD) // Changes any 'Bird' characters (B) to Soil.
                   {
                       Field[Row, Column] = SOIL;
                   }
                   if (Field[Row, Column] == SEED)
                   {
                       Field[Row, Column] = PLANT;
                   }
               }
           }

Pascal Solution[edit]

Answer :

Answer:


Java Solution[edit]

Answer :

Answer:

static void SimulateBird(char[][] Field)

 {
   Random RandomInt = new Random();
   int PlantCount = 0;
   boolean Bird=false;
 if (RandomInt.nextInt(10) == 1)
    {
      Bird = true;
    } 
    else
    {
      Bird = false;
    }
    if (Bird){
     int Row=RandomInt.nextInt(FIELDWIDTH);
     for (int x=0;x<FIELDLENGTH;x++){
        Field[x][Row] = 'B';
        }
    }
    else{
     int Column=RandomInt.nextInt(FIELDLENGTH);
     for (int x=0;x<FIELDWIDTH;x++){
        Field[Column][x] = 'B';
        }
    }
    CountPlants(Field);
    }

Python Solution[edit]

Answer :

Answer:

 
# Remove 'if randint(0,5) == 1' and unindent for the bird to always perform this task

def BirdEvent(Field):
  if randint(0,5) == 1:
    RandColumn = randint(0, FIELDWIDTH)
    print('A bird has eaten all seeds in column', RandColumn)
    for Column in range(FIELDWIDTH):
      for Row in range(FIELDLENGTH):
        if Column == RandColumn and Field[Row][Column] == SEED:
          Field[Row][Column] = SOIL
    return Field
  else:
    return Field

# Event is to be added in the function 'SimulateWinter'

#################################################
#SOLUTION 2
def BirdEvent(Field):
  Destroyed_Column = randint(0,FIELDWIDTH)-1
  print("One Column of your lovely plants have been eaten by a bird!")
  print("The ",Destroyed_Column," Column has been destoyed!")
  for Row in range(FIELDLENGTH):
    for Column in range(FIELDWIDTH):
      Field[Row][Destroyed_Column] = SOIL
  return Field
#Add BirdEvent to similuate winter
# By Mr MoneyMan @Moneyman
#Business Email: moneyman@money.co.uk/money

#### concerned by both the above solutions for these reasons
#### random ranges incorrect in both cases

## the random ranges can be changed if the question demands it, it is only there if you need 
## it, as this is more of a template of code than a real answer.

#### no need to loop through every column when only one column is being eaten

## the loop i use is scanning the field for the co-ordinates that the desired column is 
## located in.

#### no need to return field on both paths

## I return the field on both paths because of the way i was taught, in the sense that a 
## function must return something, regardless of what path it takes. its also added because 
## its to make sure that it returns something on both paths

#### Jobbins is a bic boi -_-

def BirdEvent(Field):
  RandColumn = randint(0, FIELDWIDTH -1)
  print('A bird has eaten all seeds in column', RandColumn)
  for Row in range(FIELDLENGTH):
    if Field[Row][RandColumn] == SEED:
      Field[Row][RandColumn] = SOIL
  return Field

VB.NET Solution[edit]

Answer :

Answer:

   Function SimulateWinter(ByVal Field As Char(,)) As Char(,)
       Dim bcolumn As Integer
       For Row = 0 To FIELDLENGTH - 1
           For Column = 0 To FIELDWIDTH - 1
               If Field(Row, Column) = PLANT Then
                   Field(Row, Column) = SOIL
               End If
           Next
       Next
       bcolumn = Rnd() * 34
       For row = 0 To 19
           If Field(row, bcolumn) = SEED Then
               Field(row, bcolumn) = SOIL
           End If
       Next
       Return Field
   End Function

'Big up Newvic mandem u get me 'The Real Swifty $IBRAHIM$ THE ROADMAN69

Answer 2:

Answer:

    Function SimulateWinter(ByVal Field As Char(,)) As Char(,)
       Dim AvianFeast As Integer = CInt(Math.Floor((FIELDWIDTH + 1) * Rnd()))
       Console.WriteLine("The birds are eating all the seeds in column " + CStr(AvianFeast + 1) + "!")
       For Row = 0 To FIELDLENGTH - 1
           For Column = 0 To FIELDWIDTH - 1
               If Field(Row, Column) = PLANT Then
                   Field(Row, Column) = SOIL
               End If
               If Field(Row, Column) = SEED And Column = AvianFeast Then
                   Field(Row, Column) = SOIL
               End If
           Next
       Next
       Return Field
   End Function   
    'Like Chilli Memes on Facebook 
    'by THE BIG POKESIE - discord pokesie#2884 add me <3

Implement a 1 in 40 chance of a Meteor Storm occuring, which spawns 2 meteors in the field, and sets the whole field on fire, ending the simulation.[edit]

C# Solution[edit]

Answer :

Answer:

Place a random chance to call this function (I used 1/40 chance, can be adjusted) inside of all of the seasons (optional, can just be one)

Also, if you have placed a validation for getting a response, create a boolean, and place the "End of Simulation, run again or end?" code inside of an if statement, and if there is a meteor shower, set a global variable to True, and it will not allow the option to continue, just end. E.g.

                    if (meteorShower == false)
                            {
                                Console.Write("Press Enter to run simulation for another Year,\nOr input X to stop, or S to save the current field to a file and end: ");
                                Response = Console.ReadLine();
                           ....
                    else
                            {
                                Console.WriteLine("Unfortunately your field burned in the midst of the meteor shower,");
                                Console.WriteLine("The end of the world has ocurred.");
                                Console.WriteLine("You cannot save or continue from this disaster.");
                                goodResp = true;
                                Continuing = false;
                            }

Below is the function for the Meteor Storm:

        static void MeteorStorm(char[,] Field)
        {
            Console.WriteLine("A LARGE METEOR SHOWER HAS CAUSED THE END OF THE WORLD!");
            //Sets the whole field on fire
            for (int Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (int Column = 0; Column < FIELDWIDTH; Column++)
                {
                    Field[Row, Column] = FIRE;
                }
            }

            int FirstPos, SecondPos;
            Random RandomInt = new Random();
            for (int i = 0; i < 2; i++)
            {
                //The following adds METEOR in a 5x5 area, the centre being at (FirstPos, SecondPos)
                FirstPos = RandomInt.Next(4, FIELDLENGTH - 4);
                SecondPos = RandomInt.Next(4, FIELDWIDTH - 4);
                Field[FirstPos, SecondPos] = METEOR;
                Field[FirstPos, SecondPos + 1] = METEOR;
                Field[FirstPos, SecondPos - 1] = METEOR;
                Field[FirstPos, SecondPos + 2] = METEOR;
                Field[FirstPos, SecondPos - 2] = METEOR;
                Field[FirstPos + 1, SecondPos] = METEOR;
                Field[FirstPos + 1, SecondPos + 1] = METEOR;
                Field[FirstPos + 1, SecondPos - 1] = METEOR;
                Field[FirstPos + 1, SecondPos + 2] = METEOR;
                Field[FirstPos + 1, SecondPos - 2] = METEOR;
                Field[FirstPos - 1, SecondPos] = METEOR;
                Field[FirstPos - 1, SecondPos + 1] = METEOR;
                Field[FirstPos - 1, SecondPos - 1] = METEOR;
                Field[FirstPos - 1, SecondPos + 2] = METEOR;
                Field[FirstPos - 1, SecondPos - 2] = METEOR;
                Field[FirstPos + 2, SecondPos] = METEOR;
                Field[FirstPos + 2, SecondPos + 1] = METEOR;
                Field[FirstPos + 2, SecondPos - 1] = METEOR;
                Field[FirstPos + 2, SecondPos + 2] = METEOR;
                Field[FirstPos + 2, SecondPos - 2] = METEOR;
                Field[FirstPos - 2, SecondPos] = METEOR;
                Field[FirstPos - 2, SecondPos + 1] = METEOR;
                Field[FirstPos - 2, SecondPos - 1] = METEOR;
                Field[FirstPos - 2, SecondPos + 2] = METEOR;
                Field[FirstPos - 2, SecondPos - 2] = METEOR;
            } //Use A Loop, this looks disgusting
        }

Java Solution[edit]

Answer:

Answer:

  static void METOR(char[][] Field) {
	  Console.println("The End of the Field is incoming!");
	    for (int Row = 0; Row < FIELDLENGTH; Row++)
	    {
	      for (int Column = 0; Column < FIELDWIDTH; Column++)
	      {
	        if (Field[Row][Column] == PLANT || Field[Row][Column] == SOIL || Field[Row][Column] == SEED || Field[Row][Column] == ROCKS )
	        {
	          Field[Row][Column] = FIRE;
	        }
	      }
	    }	  
  }
  
  private static void Simulation()
  {
    int YearsToRun;
    int Storm = 1;
    char[][] Field = new char[FIELDLENGTH][FIELDWIDTH];
    Boolean Continuing;
    int Year;
    String Response;
    YearsToRun = GetHowLongToRun();

	
    if (YearsToRun != 0)
    {
      InitialiseField(Field);
      if (YearsToRun >= 1)
      {
        for (Year = 1; Year <= YearsToRun; Year++)
        {
          SimulateOneYear(Field, Year);
          Random RandomInt2 = new Random();
      	  int Chance = RandomInt2.nextInt(80);
      	  Console.println(Chance);
          if (Chance < 10) {
       	   Storm = 0;
       	   METOR(Field);
       	   Display(Field, "END", 0);
              Console.println("METEOR STORM, THE FIELD HAS BEEN DESTROYED");
              String exit = Console.readLine("Please enter to leave the program!");
              if (exit == null) {
              	System.exit(0);
              }
       	}
        }
      }
      else
      {
        Continuing = true;
        Year = 0;
        while (Continuing)
        {
          Year++;
          SimulateOneYear(Field, Year);
          if (Storm == 1) {
          Console.print("Press Enter to run simulation for another Year, Input X to stop: ");
          Response = Console.readLine();
          if (Response.equals("x") || Response.equals("X")) {
            Continuing = false;
          }
          }
          
          else {

          }
        }
      }

      Console.println("End of Simulation");
    }
    Console.readLine();
  }
// Inder Panesar

Python Solution[edit]

Answer :

Answer:

def Meteor(Field, Year):

    Continuing = True

    num = randint(0, 39)
    if num == 38:
        print("Oh NO! A meteor has struck")
        for l in range(FIELDLENGTH):
            for j in range(FIELDWIDTH):
                Field[l][j] = "F"

        Field[randint(20)][randint(35)] = "M"
        Field[randint(20)][randint(35)] = "M"

        Continuing = False
        Display(Field, 'winter', Year)

    return Continuing

def Simulation():
    YearsToRun = GetHowLongToRun()
    if YearsToRun != 0:
        Field = InitialiseField()
        if YearsToRun >= 1:
            Continuing = True
            for Year in range(1, YearsToRun + 1):

                SimulateOneYear(Field, Year)
                Continuing = Meteor(Field, Year)
                if Continuing == False:
                    break

        else:
            Continuing = True
            Year = 0
            while Continuing:
                Year += 1
                SimulateOneYear(Field, Year)
                Response = input('Press Enter to run simulation for another Year, Input X to stop: ')
                if Response == 'x' or Response == 'X':
                    Continuing = False
        print('End of Simulation')
    input()
#By Mo

Another Answer :

Answer:

def Meteorites(Field, Year):
  LandRow = randint(0, FIELDLENGTH)
  LandCol = randint(0, FIELDWIDTH)
  print("A meteorite has hit the field at :", LandRow, LandCol, ".")
  Display(Field, "Meteorite Aftermath", Year)
  return Field

def SimulateOneYear(Field, Year):
  Field = SimulateSpring(Field)
  Display(Field, 'spring', Year)
  Chance = randint(0, 41)
  if Chance == 27:
    Meteorites(Field, Year)
    print("The field is dead. Goodbye.")
    time.sleep(5)
    sys.exit()
  Field = SimulateSummer(Field)
  Display(Field, 'summer', Year)
  Chance = randint(0, 41)
  if Chance == 27:
    Meteorites(Field, Year)
    print("The field is dead. Goodbye.")
    time.sleep(5)
    sys.exit()
  Field = SimulateAutumn(Field)
  Display(Field, 'autumn', Year)
  Chance = randint(0, 41)
  if Chance == 27:
    Meteorites(Field, Year)
    print("The field is dead. Goodbye.")
    time.sleep(5)
    sys.exit()
  Field = SimulateWinter(Field)
  Display(Field, 'winter', Year)
  Chance = randint(0, 41)
  if Chance == 27:
    Meteorites(Field, Year)
    print("The field is dead. Goodbye.")
    time.sleep(5)
    sys.exit()

Implement a 10% chance of Tornado in Autumn where Plants are destroyed and Seeds and Rocks are randomly rearranged in a 10x10 grid[edit]

C# Solution[edit]

Answer :

Answer:

Place a random chance to call this function in autumn (or wherever you want to call it)

        static void tornado(char[,] Field)
        {
            Random Rand = new Random();
            int row = Rand.Next(FIELDLENGTH - 10);
            System.Threading.Thread.Sleep(50);
            int col = Rand.Next(FIELDWIDTH - 10);
            Console.WriteLine("tornado at centre " + row + " " + col);
            int rockcount = 0;
            int seedcount = 0;
            for (int i = row; i < row + 10; i++)
            {
                for (int j = col; j < col + 10; j++)
                {
                    if (Field[i, j] == PLANT)
                    {
                        Field[i, j] = SOIL;
                    }
                    else if (Field[i, j] == SEED)
                    {
                        seedcount++;
                        Field[i, j] = SOIL;
                    }
                    else if (Field[i, j] == ROCKS)
                    {
                        rockcount++;
                        Field[i, j] = SOIL;
                    }
                }
            }
            int newRow, newCol;
            for (int i = 0; i < rockcount; i++)
            {
                newRow = row + Rand.Next(0, 10);
                System.Threading.Thread.Sleep(50);
                newCol = col + Rand.Next(0, 10);
                Field[newRow, newCol] = ROCKS;
            }
            for (int i = 0; i < seedcount; i++)
            {
                newRow = row + Rand.Next(0, 10);
                System.Threading.Thread.Sleep(50);
                newCol = col + Rand.Next(0, 10);
                SeedLands(Field, newRow, newCol);
            }
        }
The thread.sleep is there to make sure it is a random number every time
--Brock College <3
--Big Up you Lads
--Edit to correct season by a member of the best CSGO team: https://steamcommunity.com/groups/TeamOgreLords

Pascal Solution[edit]

Answer :

Answer:


Java Solution[edit]

Answer :

Answer:

  static void SimulateSummer(char[][] Field)
  {
    Random RandomInt = new Random();
    //int RainFall = RandomInt.nextInt(3);
    int RainFall = 5;
    int PlantCount = 0;
    int SeedCount = 0;
    if (RainFall == 0) {
      PlantCount = 0;
      for (int Row = 0; Row < FIELDLENGTH; Row++) {
        for (int Column = 0; Column < FIELDWIDTH; Column++) {
          if (Field[Row][Column] == PLANT) {
            PlantCount++;
            if (PlantCount % 2 == 0) {
              Field[Row][Column] = SOIL;
            }
          }
        }
      }
      Console.println("There has been a drought");
      CountPlants(Field);
    }
    else {
    	Random RandomInt1 = new Random();
    	 //int RadomInt = RandomInt1.nextInt(500);
    	int RadomInt = 3;
        if(RadomInt < 20 ) {
            Console.println("ALERT");
            SimulateTornado(Field);
        }
    }
   }

  
  static void SimulateTornado(char[][] Field) {
	  //Console.println(Row + " " + Column);
      Random RandomInt11 = new Random();
      int Row = RandomInt11.nextInt(35);
      Random RandomInt12 = new Random();
      int Column = RandomInt12.nextInt(20);
	  int seednumber = 0;
	  int rocknumber = 0;
	  int spreadseed = 0;
	  int spreadrock = 0;
	  int st = Row - 5;
	  int pst = Row + 7;
	  int ct = Column - 5;
	  int pct = Column + 7;
	  while (st < 0) {
		  st++;
	  }
	  while (ct < 0) {
		  ct++;
	  }
	  while (pst > 20) {
		  pst--;
	  }
	  while (pct > 35) {
		  pct--;
	  }
	  Console.println("Tornado has struck!");
	  for(int i = st; i < pst; i++) {
		  for(int y = ct; y < pct; y++) {
			  if (Field[i][y] == SEED) {
				  seednumber++;
				  Field[i][y] = SOIL;
			  }
			  if (Field[i][y] == PLANT) {
				  Field[i][y] = SOIL;
				  seednumber = seednumber + 2;
			  }
			  if (Field[i][y] == ROCKS) {
				  rocknumber++;
			  }
			  while(spreadseed < seednumber) {
					Random RandomInt3 = new Random();
				    int direction = RandomInt3.nextInt(1);  
				    if (direction == 0) {
						Random RandomInt1 = new Random();
					    int rowrandom = RandomInt1.nextInt(6);
						Random RandomInt2 = new Random();
					    int columnrandom = RandomInt2.nextInt(6);
					    Row = Row - rowrandom;
					    Column = Column - columnrandom;
					    while (Row < 0) {
					    	Row++;
					    }
					    while (Row > 20) {
					    	Row--;
					    }
					    while (Column < 0) {
					    	Column++;
					    }
					    while (Column > 20) {
					    	Column--;
					    }
						    Field[Row][Column] = SEED;
						spreadseed++;
					    
				    }
				    else if (direction == 1) {
						Random RandomInt1 = new Random();
					    int rowrandom = RandomInt1.nextInt(6);
						Random RandomInt2 = new Random();
					    int columnrandom = RandomInt2.nextInt(6);
					    Row = Row + rowrandom;
					    Column = Column + columnrandom;
					    
					    while (Row < 0) {
					    	Row++;
					    }
					    while (Row > 20) {
					    	Row--;
					    }
					    while (Column < 0) {
					    	Column++;
					    }
					    while (Column > 20) {
					    	Column--;
					    }
					    
						    Field[Row][Column] = SEED;
							spreadseed++;
				    }
				    
			  }
			  
			  while(spreadrock < rocknumber) {
					Random RandomInt3 = new Random();
				    int direction = RandomInt3.nextInt(1);  
				    if (direction == 0) {
						Random RandomInt1 = new Random();
					    int rowrandom = RandomInt1.nextInt(6);
						Random RandomInt2 = new Random();
					    int columnrandom = RandomInt2.nextInt(6);
					    Row = Row - rowrandom;
					    Column = Column - columnrandom;
					    while (Row < 0) {
					    	Row++;
					    }
					    while (Row > 20) {
					    	Row--;
					    }
					    while (Column < 0) {
					    	Column++;
					    }
					    while (Column > 20) {
					    	Column--;
					    }
						    Field[Row][Column] = ROCKS;
						spreadseed++;
					    
				    }
				    else if (direction == 1) {
						Random RandomInt1 = new Random();
					    int rowrandom = RandomInt1.nextInt(6);
						Random RandomInt2 = new Random();
					    int columnrandom = RandomInt2.nextInt(6);
					    Row = Row + rowrandom;
					    Column = Column + columnrandom;
					    
					    while (Row < 0) {
					    	Row++;
					    }
					    while (Row > 20) {
					    	Row--;
					    }
					    while (Column < 0) {
					    	Column++;
					    }
					    while (Column > 20) {
					    	Column--;
					    }
					    
						    Field[Row][Column] = ROCKS;
							spreadseed++;
				    }
				    
			  }
			 
		  }
	  }
	  if (seednumber == 0) {
		  System.out.println("No Seeds affected in tornado.");
	  }
	  if (rocknumber == 0) {
		  System.out.println("No Rocks affected in tornado.");
	  }
   }
// Inder Panesar

Python Solution[edit]

Answer 1:

Answer:

def Tornadoify(Field,Row,Column):
  if Column >=0 and Row>=0 and Row<FIELDLENGTH and Column<FIELDWIDTH:
    chance = randint(1,3)
    if chance ==1:
      Field[Row][Column] = SEED
    elif chance ==2:
      Field[Row][Column] = ROCKS
    #elif chance ==3:
    #nothing changes
  return Field

  
def Tornado(Field):
  
  CentreRow = randint(0,FIELDLENGTH-1)
  CentreColumn = randint(0,FIELDWIDTH-1)
  print(CentreRow," and",CentreColumn)

  for Row in range (CentreRow-4,CentreRow+5):
    for Column in range (CentreColumn-5,CentreColumn+5):
      Field = Tornadoify(Field,Row,Column)
  return Field

#Add to summer Function

if randint(1,10) = 10:
   Field=Tornado(Field)

Answer  :

Answer:

# Add to Simulate Summer
  tornado_chance =randint(1,10)
  #print(tornado_chance)
  if tornado_chance == 1:
    print("You have been visited my the great tornado")
    plant_count = 0
    start_grid = randint(0,FIELDLENGTH-10)
    end_grid = randint(0,FIELDWIDTH-10)
    print(start_grid)
    print(end_grid)
    for Row in range(start_grid,start_grid+10):
      for Column in range(end_grid,end_grid+10):
          if Field[Row][Column] == PLANT:
            plant_count +=1
            Field[Row][Column]= SOIL
          if Field[Row][Column] == ROCKS:
             random_row=randint(start_grid,start_grid+10)
             random_column=randint(end_grid,end_grid+10)
             Field[random_row][random_column] = ROCKS
             Field[Row][Column]= SOIL
          if Field[Row][Column] == SEED:
            random_row=randint(start_grid,start_grid+10)
            random_column=randint(end_grid,end_grid+10)
            Field[random_row][random_column] = SEED
            Field[Row][Column]= SOIL   
    print(plant_count,"plants have been killed")

# By Mr MoneyMan @Moneyman
#Business Email: moneyman@money.co.uk/money

VB.NET Solution[edit]

Answer :

Answer:

'to start the tornado

   Function SimulateSummer(ByVal Field(,) As Char) As Char(,)
       Dim RainFall, tornado As Integer
       Dim PlantCount As Integer
       RainFall = Int(Rnd() * 3)
       tornado = Int(Rnd() * 10)
       If tornado = 1 Then
           Console.WriteLine("A tornado occurs")
           Tornadoo(Field)
       End If
       If RainFall = 0 Then
           PlantCount = 0
           For Row = 0 To FIELDLENGTH - 1
               For Column = 0 To FIELDWIDTH - 1
                   If Field(Row, Column) = PLANT Then
                       PlantCount += 1
                       If PlantCount Mod 2 = 0 Then
                           Field(Row, Column) = SOIL
                       End If
                   End If
               Next
           Next
           Console.WriteLine("There has been a severe drought")
           CountPlants(Field)
       End If
       Return Field
   End Function

'how the tornado works

   Sub Tornadoo(ByRef Field(,) As Char)
       Dim column, row, plants, rock, prow, pcolumn, srow, scolumn As Integer
       column = Int(Rnd() * 24 + 5)
       row = Int(Rnd() * 10 + 5)
       For count = row - 5 To row + 5
           For count2 = column - 5 To column + 5
               If Field(count, count2) = PLANT Then
                   Field(count, count2) = SOIL
               ElseIf Field(count, count2) = SEED Then
                   plants = plants + 1
                   Field(count, count2) = SOIL
               ElseIf Field(count, count2) = ROCKS Then
                   rock = rock + 1
                   Field(count, count2) = SOIL
               End If
           Next
       Next
       For count = 0 To plants
           prow = Rnd() * 10 + (row - 5)
           pcolumn = Rnd() * 10 + (column - 5)
           Field(prow, pcolumn) = SEED
       Next
       For count = 0 To pcolumn
           srow = Rnd() * 10 + (row - 5)
           scolumn = Rnd() * 10 + (column - 5)
           Field(srow, scolumn) = ROCKS
       Next
   End Sub

~ 'Big up NewVic man dem 'The Real Swifty ~

Implement a rock wall around the field and make the plants pay for the wall[edit]

Python Solution[edit]

Answer 1:

Answer:

#Edited the existing CreateNewField function, however it's possible to do this in a separate function if the paper requires it#

def CreateNewField(): 
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
  for Column in range(FIELDWIDTH):
      Field[0][Column] = ROCKS
      Field[19][Column] = ROCKS
  for Row in range(FIELDLENGTH):
    Field[Row][0] = ROCKS
    Field[Row][34] = ROCKS
  Row = FIELDLENGTH // 2
  Column = FIELDWIDTH // 2
  Field[Row][Column] = SEED
  return Field

#May not be the most efficient, but it gets the job done. Like I mean how do i get the plants to pay for it. I*'ll have to make my own economy.

Python Solution[edit]

Answer 2:

Answer:

def CreateNewField(): 
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
  Row = FIELDLENGTH // 2
  Column = FIELDWIDTH // 2
  Field[Row][Column] = SEED
  for row in range(FIELDLENGTH):
    Field[row][0], Field[row][-1] = ROCKS, ROCKS
  for col in range(FIELDWIDTH):
    Field[0][col], Field[-1][col] = ROCKS, ROCKS
  return Field

Python Solution[edit]

Answer 3:

Answer:

#Better than Lee-roy's
def CreateNewField(): 
  Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
  Row = FIELDLENGTH // 2
  Column = FIELDWIDTH // 2
  Field[Row][Column] = SEED
  for column in range(FIELDWIDTH):
    Field[0][column],Field[FIELDLENGTH-1][column] = ROCKS,ROCKS  
  for row in range(FIELDLENGTH):
    Field[row][0],Field[row][FIELDWIDTH-1] = ROCKS,ROCKS
  return Field

Java Solution[edit]

Answer:

Answer:

  static void CreateNewField(char[][] Field) {
    int Row = 0;
    int Column = 0;
    for (int i = 0; i < FIELDLENGTH; i++) {
    	Field[i][0] = ROCKS;
    }
    for (int i = 0; i < FIELDLENGTH; i++) {
    	Field[i][34] = ROCKS;
    }
    for (int i = 0; i < FIELDWIDTH; i++) {
    	Field[0][i] = ROCKS;
    }
    for (int i = 0; i < FIELDWIDTH; i++) {
    	Field[19][i] = ROCKS;
    }
    for (Row = 0; Row < FIELDLENGTH; Row++)
    {
      for (Column = 0; Column < FIELDWIDTH; Column++)
      {
    	if (Field[Row][Column] == ROCKS) {
    		Field[Row][Column] = ROCKS;
    	}
    	else {
    		Field[Row][Column] = SOIL;
    	}
        
      }
    }
    Row = FIELDLENGTH / 2;
    Column = FIELDWIDTH / 2;
    Field[Row][Column] = SEED;
  }
//Inder Panesar

C# Solution[edit]

Answer 1:

Answer:

            for(int Row = 0; Row < FIELDLENGTH; Row++)
            {
                Field[Row, 0] = ROCKS;
            }
            for (int Row = 0; Row < FIELDLENGTH; Row++)
            {
                Field[Row, FIELDWIDTH-1] = ROCKS;
            }
            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                Field[0, Column] = ROCKS;
            }
            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                Field[FIELDLENGTH - 1, Column] = ROCKS;
            }

    #By Andrew Dawson

Note - Add this code into 'Initialise Field Void' just under Console.WriteLine("| " + String.Format("{0,3}", Row));

Compact version - The 4 'for' statements can be reduced to 2 as they both carry out the same function.

for (int Row = 0; Row < FIELDLENGTH; Row++)
            {
                Field[Row, 0] = ROCKS;
                Field[Row, FIELDWIDTH - 1] = ROCKS;
            }
            for (int Column = 0; Column < FIELDWIDTH; Column++)
            {
                Field[0, Column] = ROCKS;
                Field[FIELDLENGTH - 1, Column] = ROCKS;
            }

Answer 2:

Answer:

This code is very good and works perfectly, though your comment on where to put it is a  bit off.
I found a way to implement this code in the create new field section
        static void CreateNewField(char[,] Field)
        {
            int Row = 0;
            int Column = 0;
            for (Row = 0; Row < FIELDLENGTH; Row++)
            {
                for (Column = 0; Column < FIELDWIDTH; Column++)
                {
                    Field[Row, Column] = SOIL;
                }
            }
            for (Row = 0; Row < FIELDLENGTH; Row++)
            {
                Field[Row, 0] = ROCKS;
                Field[Row, FIELDWIDTH - 1] = ROCKS;
            }
            for (Column = 0; Column < FIELDWIDTH; Column++)
            {
                Field[0, Column] = ROCKS;
                Field[FIELDLENGTH - 1, Column] = ROCKS;
            }
                Row = FIELDLENGTH / 2;
            Column = FIELDWIDTH / 2;
            Field[Row, Column] = SEED;
        }
James Barlow, Bridgwater college, inb4 messed up by headteacher -> [http://i.imgur.com/eTdYQXg.jpg Tool]

VB.Net Solution[edit]

Answer 1:

Answer:

Function rockWall(ByVal Field(,) As Char) As Char(,)
        Dim firstRow As Integer
        Dim firstColumn As Integer
        Dim secondRow As Integer
        Dim secondColumn As Integer
        Console.Write("Enter the x co-ordinate of the top left of the wall: ")
        firstRow = Console.ReadLine
        Console.Write("Enter the y co-ordinate of the top left of the wall: ")
        firstColumn = Console.ReadLine
        Console.Write("Enter the x co-ordinate of the bottom right of the wall: ")
        secondRow = Console.ReadLine
        Console.Write("Enter the y co-ordinate of the bottom right of the wall: ")
        secondColumn = Console.ReadLine
        For y = firstColumn To secondColumn Step 1
            For x = firstRow To secondRow Step 1
                If x = firstRow Or x = secondRow Then
                    Field(x, y) = ROCKS
                ElseIf y = firstColumn Or y = secondColumn Then
                    Field(x, y) = ROCKS
                End If
            Next
        Next
        Return Field
    End Function
'Made by Jacky Chan of Reed's School
'racism is not funny grow up

Implement Season 0, i.e. show the state of the field when the seed is sown - at the start of Spring[edit]

[i.e. When the simulation starts, the first field shown is the state of the field at the END of Spring. If you start, for example, with the TestCase.txt file, you will not see the field as it is in the TestCase.txt file, but only once Spring has sprung. This amendment requires the simulation to show the point when Spring starts and then continues as before. Thus, any test file used as the starting point will be shown as Season 0 (to confirm that the field state is as it should be when the test file is read, and the simulation then continues. Hope this is a clearer explanation. Apologies if this has simply muddied the water.]

I've read this at least 40 times and I still have no idea what this question means.

I think this will come up - Excellent question.

  --------ARA--------

VB.NET Solution[edit]

Answer :

Answer:

 Sub Simulation()
        Dim YearsToRun As Integer
        Dim Continuing As Boolean
        Dim Response As String
        Dim Year As Integer
        Dim Field(FIELDWIDTH, FIELDLENGTH) As Char
        Dim randomMachine As New Random
        Dim randomNumber As Integer

        YearsToRun = GetHowLongToRun()
        If YearsToRun <> 0 Then
            Field = InitialiseField()
            Display(Field, "Starting Field:", 0)
...
...

Java Solution[edit]

Answer:

Answer:

  private static void Simulation()
  {
    int YearsToRun;
    char[][] Field = new char[FIELDLENGTH][FIELDWIDTH];
    Boolean Continuing;
    int Year;
    String Response;
    YearsToRun = GetHowLongToRun();
    if (YearsToRun != 0)
    {
      InitialiseField(Field);
      Display (Field, "Spring", 0);
      if (YearsToRun >= 1)
      {
        for (Year = 1; Year <= YearsToRun; Year++)
        {
          SimulateOneYear(Field, Year);
        }
      }
      else
      {
        Continuing = true;
        Year = 0;
        while (Continuing)
        {
          Year++;
          SimulateOneYear(Field, Year);
          Console.print("Press Enter to run simulation for another Year, Input X to stop: ");
          Response = Console.readLine();
          if (Response.equals("x") || Response.equals("X"))
          {
            Continuing = false;
          }
        }
      }
      Console.println("End of Simulation");
    }
    Console.readLine();
  }
//Inder Panesar

C# Solution[edit]

Answer :

Answer:

== Add the following line to the beginning of the procedure 'SimulateOneYear' == 
== Code by Zac Murphy ==

Display(Field, "original", Year); //Show the original field, before it is changed

Python Solution[edit]

Answer :

Answer:

{{CPTAnswerTabEnd}}
=== VB.NET Solution ===
'''Answer :'''{{CPTAnswerTab}}

<syntaxhighlight lang="VB.NET">

{{CPTAnswerTabEnd}}

== An antelope comes along each season and eats a seed with a chance of being killed as well as a chance of reproducing: ==
{{CPTsolutionTab}}
=== C# Solution ===
'''Answer :'''{{CPTAnswerTab}}
<syntaxhighlight lang="c#">
// at the beggingng of the code
static int antelopecount = 5;

// before the simulate one year
static void antelope(char[,] Field)
        {       
            int row = 0;
            int column = 0;
            int eaten = 0;
            int died = 0;
            int reproduce = 0;
            bool leave = false;
            Random co = new Random();
            Random co2 = new Random();
            Random cdd2 =new Random();
            int g = 0;
            for (int i = 0; i < antelopecount; i++)
            {
                do
                {
                    g = Convert.ToInt32(cdd2.Next(1, 3));
                    row= Convert.ToInt32(co.Next(1, 20));
                    k = Convert.ToInt32(co2.Next(1, 35));
                    if (Field[row, collum] == SEED)
                    {
                        Field[row, collum] = SOIL;
                        eaten++;
                        leave = false;
                    }
                    if (g == 2)
                    {
                        antelopecount = antelopecount - 1;
                        leave = false;
                        died++;
                    }
                    else
                    { antelopecount = antelopecount + 1;
                        reproduce++;
                            }
                   
                } while (leave == true);

              
                
            }
            Console.WriteLine("{0} antelopes have eaten a seed", eaten);
            Console.WriteLine("{0} antelopes have reproduced", reproduce);
            Console.WriteLine("{0} antelopes have died of starvation", died);
            Console.WriteLine("{0} antelopes are remaining", antelopecount);
        }

static void SimulateOneYear(char[,] Field, int Year)
        {
            SimulateSpring(Field);
            antelope(Field);
            Display(Field, "spring", Year);
            
            SimulateSummer(Field);
            antelope(Field);
            Display(Field, "summer", Year);
            SimulateAutumn(Field);
            antelope(Field);
            Display(Field, "autumn", Year);
            SimulateWinter(Field);
            antelope(Field);
            Display(Field, "winter", Year);
        }
//comments about this code, their is a high chance for the antelopes to not eat a single seed, so i have not based their death around starvation, if you wish to do this you can change the second IF statement in the Antelope procedure so that when an antelope does not eat a seed it will die. be warned as a genocide of antelopes will be casued by this and they will all die if their population is not high enough
{{CPTAnswerTabEnd}}

== Change the size of the width and length of the field ==

=== C# Solution ===
'''Answer :'''{{CPTAnswerTab}}
<syntaxhighlight lang="c#">

== Code by Zac Murphy ==
== Modify the procedure "Main" == so it looks like this ==
== Instead of having a sperate procedure to check if the user wants to change the dimensions, it could be built into here ==

static void Main(string[] args)
        {
            changeSize = changeFieldSize(); //Check to see if the user wants to change the size
            Console.Clear();
            if (!changeSize)
            {
                Simulation(); //Start the program
            }
            else
            {
                changeFieldProportions(); //Change the field proportions
                Console.Clear();
                Simulation(); //Then start the program
            }
        }

== Procedure that asks the user if they want to change the dimensions ==

//Function that asks the user if they want to change the field size
        static bool changeFieldSize()
        {
            //Declare local variables
            char response = ' ';

            Console.WriteLine("Welcome to the Plant Growing Simulation");
            Console.WriteLine();
            Console.WriteLine("Do you want to change the field size from the default? (20x35)");

            //Do loop to check if the user input is a character
            do
            {
                Console.Write("(Y/N): "); //Write this every time the input is not an character
            } while (!char.TryParse((Console.ReadLine()).ToUpper(), out response));

            //While loop 
            while (!(Regex.IsMatch(response.ToString(), @"[Yy]|[Nn]"))) //The range has to be in upper and lower case for it to work
            {
                //Followed by the do loop again, to make sure it is still a character
                do
                {
                    Console.Write("(Y/N): "); //Write this every time the input is not an character
                } while (!char.TryParse((Console.ReadLine()).ToUpper(), out response));
            }

            //If statement to control what happens with the input
            if (response == 'Y' || response == 'y')
            {
                return changeSize = true;
            }
            else
            {
                return changeSize = false;
            }
        }

== Procedure that actually changes the field dimensions ==

//Procedure that actually changes the proportions of the field
        static void changeFieldProportions()
        {
            //Get user input
            Console.WriteLine("Enter the field proportions");

            //Do loop to check if the character entered is correct
            do
            {
                Console.Write("Width (up to 100): "); //Write this every time the input is not an integer
            } while (!int.TryParse(Console.ReadLine(), out FIELDWIDTH));

            //While loop to check the width input is within range
            while (!(FIELDWIDTH > 0 && FIELDWIDTH < 101))
            {
                //Followed by the do loop again, to make sure it is still an integer
                do
                {
                    Console.Write("Width (up to 100): ");
                } while (!int.TryParse(Console.ReadLine(), out FIELDWIDTH));
            }

            Console.WriteLine();

            //Do loop to check if the character entered is correct
            do
            {
                Console.Write("Length (up to 50): "); //Write this every time the input is not an integer
            } while (!int.TryParse(Console.ReadLine(), out FIELDLENGTH));

            //While loop to check the width input is within range
            while (!(FIELDLENGTH > 0 && FIELDLENGTH < 51))
            {
                //Followed by the do loop again, to make sure it is still an integer
                do
                {
                    Console.Write("Length (up to 50): ");
                } while (!int.TryParse(Console.ReadLine(), out FIELDLENGTH));
            }
        }
  1. but why

Python solution[edit]

Answer:

def GetFieldSize():
  while True:
    try:
      FIELDLENGTH = int(input("Please input the LENGTH you would like the field to be (between 5 & 50): ")) #Prompts the user for the bounds for the size
      FIELDWIDTH = int(input("Please input the WIDTH you would like the field to be (between 5 & 50): "))
      if FIELDLENGTH < 5 or FIELDWIDTH < 5 or FIELDLENGTH > 50 or FIELDWIDTH > 50:
        print("Please only enter a value above 5 and below 50") #Error message if above 50 or below 5
      else:
        break #Exits while loop
    except ValueError:
      print("Please only enter a number for the value of width and length") #Error message is character is entered
  return FIELDLENGTH, FIELDWIDTH #Needs to be returned and passed as no longer global variables
# or you could just, you know, make the constants input based 
# (e.g. FIELDWIDTH = int(input('Enter the Width of the field: ')))

#By Ethan Leith (A very not cool kid){{CPTAnswerTabEnd}}

=== Python solution (file loading): ===
{{CPTAnswerTab}}
<syntaxhighlight lang="python">

#This is the code to adjust for loading a file of indefinite size

def ReadFile():   
  FileName = input('Enter file name: ') #Gets the name of the file from the user
  FileName += '.txt' #.txt is added to the file, assuming .txt was not added, unless found otherwise
  txtExec = FileName.split(".") 
  if len(txtExec) == 3: #Since there should only be one '.', if there are multiple .'s, it assumes there was already a .txt added
    FileName = txtExec[0] + "." + txtExec[2] 
  try: #Checks for errors in loading, generating field if file size not loaded correctly
    FileHandle = open(FileName, 'r')
    lWidth = FileHandle.readline()
    FIELDWIDTH = len(lWidth)-1 #Measure length of line, excluding space off the end due to the format of the data file
    lBlank = False
    lNum = 0
    while lBlank == False: #Reads lines of the file until a blank line is read, signifying the end of the file
      tmp = FileHandle.readline()
      if tmp == "":
        lBlank = True
      lNum += 1 #Line number
    FIELDLENGTH = lNum #Saves the line number to the fieldlength value
    FileHandle.close() #Resets the file so the data can be read from the begining
    FileHandle = open(FileName, 'r') 
    Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)] #Reading of file
    for Row in range((FIELDLENGTH)):
      FieldRow = FileHandle.readline()
      for Column in range((FIELDWIDTH-5)):
        Field[Row][Column] = FieldRow[Column]
    FileHandle.close()
  except:
    print("File load error, generating field") 
    FIELDLENGTH = 20 #Creates values in case file reading fails before values assigned
    FIELDWIDTH = 35
    Field = CreateNewField(FIELDLENGTH, FIELDWIDTH) #Generates random field if file load fails
  return Field, FIELDWIDTH, FIELDLENGTH #Need to be returned and passed to each function as no longer global variables

#By Ethan Leith

{{CPTAnswerTabEnd}}For both of these previous solutions as FIELDWIDTH and FIELDLENGTH are no longer global variables, they need to be returned back to the main program and passed to every function that uses them.

== Make seed placing more efficient (using a FOR loop): ==
=== VB.NET Solution : ===
{{CPTAnswerTab}}
<syntaxhighlight lang="VB.net">
Function SimulateAutumn(ByVal Field(,) As Char) As Char(,)
        'wherever a plant is encountered, scatter seeds around it
        For Row = 0 To FIELDLENGTH - 1
            For Column = 0 To FIELDWIDTH - 1
                If Field(Row, Column) = PLANT Then
                    For i = -1 To 1
                        For j = -1 To 1
                            Field = SeedLands(Field, Row + i, Column + j)
                        Next
                    Next
                End If
            Next
        Next
        Return Field
    End Function
'big up daddy programming for the ends, it's rough out here for the mandem