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

From Wikibooks, open books for an open world
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

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

This is a simple question that may be in section 2. It is adding validation to the number of years entered.

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
		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 :

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

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?')
  while True:
    try:
      Years = int(input('Enter a number between 0 and 5, or -1 for stepping mode: '))
    except ValueError:
      print("You must enter a value between -1 and 5, excluding 0")
      continue
    if Years > 0 and Years <= 5 or Years == -1:
      break
    else:
      print("You must enter a value between -1 and 5, excluding 0")
  return Years

By David Matthews
#Come back when you don't need to copy my code

Add a crop virus[edit]

TEST FOR QUESTION

C# Solution:[edit]

Answer :

Answer :

Delphi/Pascal Solution[edit]

Answer :

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

Java Solution[edit]

Answer :

Answer :

Python Solution:[edit]

Answer 1:

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)

By David Matthews
#Come back when you don't need to copy my code

Answer :

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 :

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

Put a maximum field size[edit]

TEST FOR QUESTION

C# Solution:[edit]

Answer :

Answer :

Delphi/Pascal Solution[edit]

Answer :

Answer :

Java Solution[edit]

Answer :

Answer :

while(FIELDLENGTH<1){
		try{
		FIELDLENGTH = Console.readInteger("What field length would you like?");
		}
		catch(NumberFormatException e ){
			FIELDLENGTH = Console.readInteger("What field length would you like?");
		}
		}
		while(FIELDWIDTH<1){
			try{
			FIELDWIDTH = Console.readInteger("What field width would you like?");
			}
			catch(NumberFormatException e ){
				FIELDWIDTH = Console.readInteger("What field width would you like?");
			}
			}

Python Solution:[edit]

Answer :

Answer :

 
while True:
  try:
    FIELDLENGTH = int(input("How long do you want the field to be? "))
    if FIELDLENGTH < 1:
      print("You can't have a field that small!")
    elif FIELDLENGTH > 0:
      break
  except ValueError:
    print("Please insert a valid number.")

while True:
  try:
    FIELDWIDTH = int(input("How wide do you want the field to be? "))
    if FIELDWIDTH < 1:
      print("You can't have a field that small!")
      continue
    elif FIELDWIDTH > 0:
      break
  except ValueError:
    print("Please insert a valid number.")

#Made by Misc

VB.NET Solution[edit]

Answer :

Answer :

Save game function[edit]

TEST FOR QUESTION

VB.Net Solution:[edit]

Answer :

Dim save As String
           Dim fileName As String
           Console.WriteLine("Would you like to save results? Y/N")
           save = Console.ReadLine
           If save.ToLower = "Y" Then
               Console.WriteLine("Please enter the file name:")
               fileName = Console.ReadLine
               Dim StreamWriter As New StreamWriter(fileName & ".txt")
               For row = 0 To FIELDLENGTH - 1
                   For Colum = 0 To FIELDLENGTH - 1
                       StreamWriter.Write(Field(row, Colum))
                   Next
                   StreamWriter.Write(") " & row)
                   StreamWriter.WriteLine()
               Next
               StreamWriter.Close()
           End If
       End If
       Console.ReadLine()
   End Sub

'Alternative similar idea 
 Sub WriteField(ByVal Field(,) As Char)

        Dim StringToWrite As String = ""

        Dim filename As String
        Console.WriteLine(" Enter a filename for the new file")
        filename = Console.ReadLine()   'get the filename from the user
        filename = CurDir() & "\" & filename & ".txt"       'Add the path to the filename gained from the user
        Dim FileHandle As New System.IO.StreamWriter(filename)
        'build the string to write 
        Dim row, column As Integer
        For row = 0 To FIELDLENGTH - 1 'step through the array rows / columns
            For column = 0 To FIELDWIDTH - 1
                StringToWrite = StringToWrite & Field(row, column)  'add the contents of Field at row,column to the string
            Next
            StringToWrite = StringToWrite & "| " & row & vbCrLf 'when you get to the end of the columns 
        Next                                                    'Write a  line and then the row - then add a newline
        FileHandle.Write(StringToWrite)  'Write the string to the file
        FileHandle.Close()
    End Sub

'Then adding to the simulation method
 Sub Simulation()
        Dim YearsToRun As Integer
        Dim Continuing As Boolean
        Dim Response As String
        Dim Year As Integer
        Dim Field(FIELDWIDTH, FIELDLENGTH) As Char
        YearsToRun = GetHowLongToRun()
        If YearsToRun <> 0 Then
            Field = InitialiseField()
            If YearsToRun >= 1 Then
                For Year = 1 To YearsToRun
                    SimulateOneYear(Field, Year)
                Next
            Else
                Continuing = True
                Year = 0
                While Continuing
                    Year += 1
                    SimulateOneYear(Field, Year)
                    Console.Write("Press Enter to run simulation for another Year, Input X to stop: OR S to Save ") 'added to Save
                    Response = Console.ReadLine()
                    If Response = "x" Or Response = "X" Then
                        Continuing = False
                    End If
                    If Response = "S" Or Response = "s" Then    'This allows for saving while the continuous sim is running
                        Call WriteField(Field)
                    End If
                End While
            End If
            Dim SaveFile As Char    'this code added to save the results at the end of the sim
            Console.WriteLine("Do you want to save these results Y or N")
            SaveFile = UCase(Console.ReadLine())    'capture the answer from the user
            If SaveFile = "Y" Then
                WriteField(Field)   'Write field creates and writes a sring to a text file
            End If
            Console.WriteLine("End of Simulation")
        End If
        Console.ReadLine()
    End Sub

Java Solution[edit]

Answer :

Answer :

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

Delphi/Pascal Solution[edit]

Answer :

Answer :

Java Solution[edit]

Answer :

Answer :

 static void ReadFile(char[][] Field)
  {
    String FileName = "";
    String FieldRow = "";
    boolean error=false;
   
    
     do{
    Console.print("Enter file name: ");
    FileName = Console.readLine();
    error=false;
    
     if(FileName.contains(".txt")){
     }
     else {
         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)
    {
        error=true;
        Console.println("Invalid file, please reenter file name");
    }
   } while(error);
 }

Python Solution:[edit]

Answer :

Answer :

#place this subroutine before the main program
def savegame(Field):
  save_q = input("Would you like to save? (Y/N): ")
  if save_q == 'Y':
    filename = input("Please enter a name for your save file: ")
    filename = filename+'.txt'
    file = open(filename, 'w+')
    data = file.read().replace('\n', '')
    for Row in range(FIELDLENGTH):
      for Column in range(FIELDWIDTH):
        file.write(Field[Row][Column])
      file.write('|{0:>3}'.format(Row))
      file.write('\n')    
    file.close()
  elif save_q == 'N':
    print()
  else:
    print("Invalid input")

#and call it here:
def Simulation():
  YearsToRun = GetHowLongToRun()
  if YearsToRun != 0:
    Field = InitialiseField()
    if YearsToRun >= 1:
      for Year in range(1, YearsToRun + 1):
        SimulateOneYear(Field, Year)
      savegame(Field)
    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
          savegame(Field)
    print('End of Simulation')
  input()

VB.NET Solution

Answer :

Answer :

Adding Rocks to the Sim[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.Net Solution[edit]

Answer :

VB.Net Solution: Dim numberOfRocks As Integer

       Dim randomGen As New Random
       numberOfRocks = randomGen.Next(1, 5)
       Console.WriteLine("ROCKS" & numberOfRocks)
       For i = 0 To numberOfRocks
           Row = randomGen.Next(0, FIELDLENGTH)
           Column = randomGen.Next(0, FIELDWIDTH)
           Field(Row, Column) = ROCKS
       Next
       Return Field
   End Function
Alt vb.net solution Adding rocks to the simulation Function CreateNewField() As Char(,)

       Randomize()
       Dim Row As Integer
       Dim Column As Integer
       Dim Field(FIELDLENGTH, FIELDWIDTH) As Char
       Dim rocknumber As Integer
       Do
           Console.WriteLine("how many rocks would you like?") 'Get number of rocks for simulation'
           Try
               rocknumber = Console.ReadLine 'validation'
           Catch
           End Try
       Loop Until rocknumber > -1
       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 = CInt(Rnd() * FIELDLENGTH) 'Gets random integer between 1 and 20'
           Column = CInt(Rnd() * FIELDWIDTH) 'gets random integer between 1 and 35'
           Field(Row, Column) = ROCKS 'places rocks in field 
       Next
       Return Field
   End Function

Java Solution[edit]

Answer :

JAVA: 
static void insterRocks(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;
    }
  }

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

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

TEST FOR QUESTION

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

Python Solution:[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: "))

    if SeedPositionRow > FIELDLENGTH or SeedPositionRow <= 0:
      print("You have entered an invalid y position. Try again")
    if SeedPositionColumn > FIELDWIDTH or SeedPositionColumn <= 0:
      print("You have entered an invalid x position. Try again")
    else:
      break
  Field[SeedPositionRow][SeedPositionColumn] = 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 :

Validate input for number of years (what happens if 6 is entered?)

Between seasons there is no pause.  Change it so that Enter must be pressed to advance the season. 
 
What happens if an incorrect file name is entered?  Change it so that an error message is displayed and the user is again prompted for the filename.  

The rows are numbered but not the columns.  Fix this.  

Create option to plant a seed in a specified location.  This should only be possible at the start.  

Create a method called DisplayMenu.  It should be displayed at the start and should contain options for 1) Load a file 2) Set seed location 3) Random seed.  

Adapt the option for random seed so that the number of seeds can be set be the user.  

Validate that the seed location selected is on the board.  

Validate that the number of seeds picked is valid.  

Every year in Spring a caterpillar (C) appears at a random location and eats all seeds surrounding it for a radius of 1.  

Every year in Summer a bird (B) flies down a column and eats all seeds in it. 

1Add code to have Severe Snow in SimulateWinter

Add code to have Severe Flood in SimulateAutumn

Add an option to save the simulation at at point to a file​

== Randomly generate the location of rocks​ ==

Delphi/Pascal Solution[edit]

Answer :

Answer :

Java Solution[edit]

Answer :Template:CPT4AnswerTab

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")

VB.NET Solution[edit]

Answer :

Answer :

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

Add functionality for plants that thrive on or require frost

C# Solution:[edit]

Answer :

Answer :

Delphi/Pascal Solution[edit]

Answer :

Answer :

Java Solution[edit]

Answer :

Answer :

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 :

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 :

Delphi/Pascal Solution[edit]

Answer :

Answer :

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 :

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

C# Solution[edit]

Answer :

Answer :

Pascal Solution[edit]

Answer :

Answer :

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 (The Better One) :

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)

By David Matthews and Ben Dawson (a little)

Answer 2 (Its Ok):

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 (simplest best)

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[edit]

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

VB.NET Solution[edit]

Answer :

Sub Display(ByVal Field(,) As Char, ByVal Season As String, ByVal Year As Integer)

        Dim Row As Integer
        Dim Column As Integer
        Console.WriteLine("Season: " & Season & "  Year number: " & Year)
        For i = 0 To FIELDWIDTH - 1
            Console.Write(i.ToString.PadLeft(3))
        Next
        Console.WriteLine()

        For Row = 0 To FIELDLENGTH - 1
            For Column = 0 To FIELDWIDTH - 1
                Console.Write("  " & Field(Row, Column))
            Next
            Console.WriteLine("|" & Str(Row).PadLeft(3))
        Next
        Console.WriteLine()
    End Sub

'highcliffeSchoolComputing
'NoAdvertisingThankYou

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
       }

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 you 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

VB.NET Solution[edit]

Answer :

Answer :

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

C# Solution[edit]

Answer :

Answer :

Pascal Solution[edit]

Answer :

Answer :

Java Solution[edit]

Answer :

Answer :

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)

By David Matthews

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 :