Weekly Challenge #3 – Sentence Repetition – Solutions

A test of your arithmetic and list operation skills.

Note: This contains answers to the Sentence Repetition challenge. Have a go at the challenge before coming here!

Bronze

Console.Write("Please enter a sentence: ");
string sentence = Console.ReadLine();

string[] sentenceArray = sentence.Split(' ');

sentence += " " + sentenceArray[0];

Console.WriteLine(sentence);
sentence = input("What is the sentence? ")

sentenceArray = sentence.split(" ")

sentence = sentence + " " + sentenceArray[0]

print(sentence)

Silver

Console.Write("Please enter a sentence: ");
string sentence = Console.ReadLine();

string[] sentenceArray = sentence.Split(' ');

sentence += " " + sentenceArray[0] + " " + sentenceArray[sentenceArray.Length - 1];

Console.WriteLine(sentence);
sentence = input("What is the sentence? ")

sentenceArray = sentence.split(" ")

sentence = sentence + " " + sentenceArray[0] + " " + sentenceArray[-1]

print(sentence)

Gold

string[] words = new string[20] {"BRUSH", "CHUBBY", "BOARD", "LOAD", "PRODUCE",
        "DESERVE", "HURRIED", "ROT", "CHICKEN", "ABRUPT", "WHISTLE", "SHOP", "MAN",
        "JINGLE", "FORGETFUL", "STARK", "CRICKET", "FIXED", "HILL", "EARTHY"};

Random rnd = new Random();
string sentence = "";
for (int i = 0; i < 5; i++)
{
        sentence += words[rnd.Next(0, words.Length)] + " ";
}
Console.WriteLine(sentence);
Console.WriteLine("After typing the sentence, repeat the first word followed by the last word.");
Console.Write("Please enter the sentence following the rules: ");
string userGuess = Console.ReadLine().ToUpper();

string[] sentenceArray = sentence.Split(' ');

// Subtract two as the final value is empty
string correctAnswer = sentence + sentenceArray[0] + " " + sentenceArray[sentenceArray.Length - 2];

if(userGuess == correctAnswer)
{
       Console.WriteLine("Correct!");
} else
{
       Console.WriteLine("Incorrect. Correct answer: {0}", correctAnswer);
}
import random

words = ["BRUSH", "CHUBBY", "BOARD", "LOAD", "PRODUCE",
        "DESERVE", "HURRIED", "ROT", "CHICKEN", "ABRUPT", "WHISTLE", "SHOP", "MAN",
        "JINGLE", "FORGETFUL", "STARK", "CRICKET", "FIXED", "HILL", "EARTHY"]

# Generates a list made up of five random elements from the words list
sentenceList = random.sample(words, 5)

# Converts the sentenceList into a string, separated by spaces
sentence = " ".join(sentenceList)
print(sentence)

print("After typing the sentence, repeat the first word followed by the last word.")
userGuess = input("Please enter the sentence following the rules: ").upper()

correctAnswer = sentence + " " + sentenceList[0] + " " + sentenceList[-1]

if userGuess == correctAnswer:
    print("Correct!")
else:
    print("Incorrect!")
    print("The correct answer:", correctAnswer)

As always, there are many different ways of solving these problems. If you’re unsure about any part of these solutions, feel free to get in touch (Or use Google!).