A-level Computing/AQA/Paper 1/Skeleton program/AS2017
This is the skeleton code for the AQA AS Paper from 2017. This code is useful for those retaking, and can also be used as a practise for those taking a newer paper.
This is where suggestions can be made about what some of the questions might be, and how they can be solved in different programming languages. If you see that a solution to a question is missing in a language you use, be bold and add it!
Please be respectful and do not vandalise or tamper with the page, as this would affect students' preparation for their exams!
Add Wind
[edit | edit source]C#
[edit | edit source]Answer:
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);
}
}
}
}
}
Python
[edit | edit source]Answer:
def SimulateAutumn(Field):
windTranslate = ["", "No wind", "North", "South", "East", "West",
"Northwest", "Northeast", "Southeast", "Southwest"]
WindDirection = randint(1,9)
print("Wind direction: " + windTranslate[WindDirection])
for Row in range(FIELDLENGTH):
for Column in range(FIELDWIDTH):
if Row >= 0 and Row < FIELDLENGTH and Column >= 0 and Column < FIELDWIDTH:
if Field[Row][Column] == PLANT:
if WindDirection == 1: # Direction: No Wind
pass
elif WindDirection == 2: # Direction: North
Row -= 1
elif WindDirection == 3: # Direction: South
Row += 1
elif WindDirection == 4: # Direction: East
Column -= 1
elif WindDirection == 5: # Direction: West
Column += 1
elif WindDirection == 6: # Direction: Northwest
Row -= 1
Column += 1
elif WindDirection == 7: # Direction: Northeast
Row -= 1
Column -= 1
elif WindDirection == 8: # Direction: Southeast
Row += 1
Column -= 1
elif WindDirection == 9: # Direction: Southwest
Row += 1
Column += 1
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)
return Field
Make Sure The Number of Years Entered Is Valid
[edit | edit source]VB.NET
[edit | edit source]Answer:
Function GetHowLongToRun() As Integer
Dim Years As Integer
Dim Valid As Boolean = False
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()
Try
If Years > -2 And Years < 6 Then
Valid = True
Else
Console.WriteLine("Invalid input: {0} is not accepted. You may only enter a value from 0-5 or -1", Years)
End If
Catch ex As Exception
Console.WriteLine("That's not a number! Please try again.")
End Try
Loop Until Valid
Return Years
End Function
Fire
[edit | edit source]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 | edit source]Answer:
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 | edit source]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 | edit source]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 | edit source]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 | edit source]C# Solution
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 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
Delphi/Pascal Solution
[edit | edit source]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 | edit source]Python Solution
[edit | edit source]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()
- 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 | edit source]Answer:
Sub SaveToFile(ByVal Field As Char(,))
Dim Row, Column As Integer
Dim ToSave As Boolean = False
Dim Save, FileName, RowEnding As String
Dim FileHandler As IO.StreamWriter
Do
Console.Write("Do you want to save the file? Y/N: ")
Save = UCase(Console.ReadLine())
If Save = "Y" Then
ToSave = True
Console.Write("Please enter the file name: ")
FileName = Console.ReadLine()
If Right(FileName, 4) = ".txt" Then
FileName = FileName
Else
FileName = String.Concat(FileName, ".txt")
End If
Try
FileHandler = New IO.StreamWriter(FileName)
For Row = 0 To FIELDLENGTH - 1
For Column = 0 To FIELDWIDTH - 1
FileHandler.Write(Field(Row, Column))
Next
RowEnding = String.Format("| {0}", Row)
FileHandler.Write(RowEnding)
FileHandler.WriteLine()
Next
FileHandler.Close()
Catch ex As Exception
Console.WriteLine("An error occured whilst writing the file; the program will now exit.")
Console.WriteLine(ex)
End Try
Else If Save = "N" Then
ToSave = True
Else
Console.WriteLine("Invalid input, please try again.")
End If
Loop Until ToSave = True
Console.WriteLine("The program will now exit.")
End Sub
Delphi/Pascal Solution
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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:
[edit | edit source]Answer :
Answer:
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 | edit source]Currently the rocks are defined as a constant but not used - we can either allow the user to enter a number of rocks to be randomly placed, or add a random number of rocks to the field.
VB.NET Solution
[edit | edit source]Answer:
Function CreateNewField() As Char(,)
Dim Row As Integer
Dim Column As Integer
Dim Field(FIELDLENGTH, FIELDWIDTH) As Char
Dim AmountOfRocks As Integer = 0
Console.Write("How many rocks should be in the field: ") 'Ask user for input
Try 'Try/Catch to ensure correct datatype
AmountOfRocks = Console.ReadLine()
Catch ex As Exception
Console.WriteLine("Invalid entry: simulation will continue without rocks.")
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 AmountOfRocks
Row = Int(Rnd() * FIELDLENGTH)
Column = Int(Rnd() * FIELDWIDTH)
If Field(Row, Column) = SOIL Then
Field(Row, Column) = ROCKS
Else
Console.WriteLine("Rock #{0} wasn't placed as it would have replaced the seed!", x)
End If
Next
Return Field
End Function
Java Solution
[edit | edit source]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 | edit source]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 | edit source]Answer:
def CreateNewField():
Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
AddRocks = input("How many rocks should be added? ")
try:
if AddRocks <= 0:
pass
else:
for r in range(AddRocks):
Row = randint(0, FIELDWIDTH-1)
Column = randint(0, FIELDWIDTH-1)
if Field[Row][Column] = SOIL:
Field[Row][Column] = ROCKS
else:
print("A rock wasn't added at ({}, {}) because doing so would've removed a seed!".format(Row, Column))
except TypeError as e:
print("Oh no, an error occured whilst trying to add rocks to the field!\nE: The input {} is not a number.".format(AddRocks))
return Field
C# Solution
[edit | edit source]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 | edit source]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;
Changing the seed position
[edit | edit source]This includes either allowing the player to set exact coordinates of the seed (which should also implement column letters), or spawn the seed in a random position.
C# Solution
[edit | edit source]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 | edit source]Answer:
Within Function CreateNewField()
, below the code that selects the number of rocks if that is in use.
Console.Write("Should the seed position be centre (C), random (R), or at specific coordinates (S)? C/R/S: ")
SeedPosition = Console.ReadLine()
Field = PlantFirstSeed(Field, SeedPosition)
Adding a new function:
Function PlantFirstSeed(ByVal Field As Char(,), ByVal SeedPosition As Char) As Char(,)
Dim Row, Column As Integer
Dim RowValid, ColumnValid As Boolean
Select SeedPosition
Case "C":
Console.WriteLine("Planting seed in the centre of the field!")
Case "R":
Console.WriteLine("Planting the seed in a random location")
Row = Int(Rnd() * FIELDLENGTH)
Column = Int(Rnd() * FIELDWIDTH)
Field(Row, Column) = SEED
Return Field
Case "S":
Do
Console.Write("Enter the X coordinate: ")
Row = Console.ReadLine()
If Row >= 0 And Row <= FIELDWIDTH Then
RowValid = True
Else
Console.WriteLine("Invalid input, please try again.")
End If
Loop Until RowValid = True
Do
Console.Write("Enter the Y coordinate: ")
Column = Console.ReadLine()
If Column >= 0 And Column <= FIELDLENGTH Then
ColumnValid = True
Else
Console.WriteLine("Invalid input, please try again.")
End If
Loop Until ColumnValid = True
Field(Row, Column) = SEED
Return Field
Case Else:
Console.WriteLine("Invalid input, defaulting to centre position")
End Select
Row = FIELDLENGTH \ 2
Column = FIELDWIDTH \ 2
Field(Row, Column) = SEED
Return Field
End Function
Python Solution
[edit | edit source]Answer:
This solution will require that you add import random
to the start of the program.
def CreateNewField():
Field = [[SOIL for Column in range(FIELDWIDTH)] for Row in range(FIELDLENGTH)]
Row = FIELDLENGTH // 2
Column = FIELDWIDTH // 2
Valid = False
while not Valid:
SelectPosition = input("Do you want the starting seed position to be the centre (C), random (R) or coordinates you select (S)?\nC/R/S: ")
if SelectPosition == "C":
Valid = True
print("The seed will be planted in the centre")
elif SelectPosition == "R":
Valid = True
Row = random.randint(0, FIELDWIDTH)
Column = random.randint(0, FIELDLENGTH)
print("The seed will be planted at the random coordinates ({}, {})".format(Row, Column))
elif SelectPosition == "S":
try:
x = int(input("Enter the x coordinate: "))
y = int(input("Enter the y coordinate: "))
if x > FIELDWIDTH or x <= 0:
print("Invalid x coordinate entered, please try again.")
elif y > FIELDLENGTH or y <=0:
print("Invalid y coordinate entered, please try again.")
else:
Valid = True
Row, Column = y-1, x-1
except ValueError:
print("An invalid value was entered, please try again.")
Field[Row][Column] = SEED
return Field
Java Solution
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]Answer :
Answer:
Java Solution
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]Add functionality for plants that thrive on or require frost
C# Solution: Adds very frosty plants
[edit | edit source]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 | edit source]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 | edit source]Answer :
Answer:
Java Solution
[edit | edit source]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 | edit source]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 | edit source]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)
Intelligent File Opening
[edit | edit source]When the program loads a file, if the user does not include the ".txt" extension, ensure that it is automagically added.
C# Solution
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 | edit source]C# Solution
[edit | edit source]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 easier on that requires less work and looks cooler!)
[edit | edit source]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 | edit source]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 | edit source]Answer :
Answer:
Procedure Display(Field : TField; Season : String; Year : Integer);
Var
Row, Column : Integer;
alphabet: String;
Begin
Writeln('Season: ', Season, ' Year number: ', Year);
alphabet := 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv';
for Column := 1 to FieldWidth do
begin
write(alphabet[column]);
end;
writeln();
For row := 0 To FIELDLENGTH - 1 Do
Begin
For Column := 0 To FIELDWIDTH - 1 Do
Write(Field[Row][Column]);
Writeln('|', Row:3);
End;
Writeln;
End;
Java Solution
[edit | edit source]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 | edit source]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()
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)
{{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
Answer 6:
Answer:
def Display(Field, Season, Year):
print('Season: ', Season, ' Year number: ', Year)
#Displaying column letters
alphabet = ["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"]
display = ""
counter = -1
secondaryCounter = -1
for i in range(FIELDWIDTH):
counter += 1
if counter > 25:
secondaryCounter += 1
display = display + (alphabet[secondaryCounter]).upper()
else:
display = display + alphabet[counter]
print(display)
#END
for Row in range(FIELDLENGTH):
for Column in range(FIELDWIDTH):
print(Field[Row][Column], end='')
print('|{0:>3}'.format(Row))
print()
VB.NET Solution
[edit | edit source]Answer:
Sub Display(ByVal Field(,) As Char, ByVal Season As String, ByVal Year As Integer)
Dim Row As Integer
Dim Column As Integer
Dim Alphabet As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHI"
If Season = "S" Then
Console.WriteLine("Field at the start of simulation")
Else
Console.WriteLine("Season: " & Season & " Year number: " & Year)
End If
For Each Letter In Alphabet
Console.Write(Letter)
Next
Console.WriteLine()
For Column = 0 To FIELDWIDTH - 1
Console.Write("_")
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
Every year in winter a bird (B) flies down a column and eats all seeds in it.
[edit | edit source]C# Solution
[edit | edit source]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 | edit source]Answer :
Answer:
Java Solution
[edit | edit source]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 | edit source]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 simulate 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 | edit source]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 | edit source]C# Solution
[edit | edit source]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 | edit source]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 | edit source]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 | edit source]C# Solution
[edit | edit source]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 | edit source]Answer :
Answer:
Java Solution
[edit | edit source]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 | edit source]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 | edit source]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
[edit | edit source]Python Solution
[edit | edit source]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 | edit source]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 | edit source]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
Python Solution
[edit | edit source]Answer 4:
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):
for length in range(FIELDWIDTH):
if row == 0 or length == 0 or row == FIELDLENGTH - 1 or length == FIELDWIDTH - 1:
Field[row][length] = ROCKS
return Field
Java Solution
[edit | edit source]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 | edit source]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 | edit source]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 Rowan Bangar 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 | edit source][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 | edit source]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 | edit source]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 | edit source]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 | edit source]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 caused 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));
}
}
Python solution
[edit | edit source]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