# Nim Practice Exercises: Essential Techniques for Mastering the Framework

Here’s a short practice exercise to help you get started with Nim:

1. Write a program that calculates the factorial of a number: Factorial is defined as the product of all positive integers up to a given number. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120. Here’s an example program in Nim that calculates the factorial of a number:
```phpCopy code```proc factorial(n: int): int =
if n <= 1:
return 1
else:
return n * factorial(n - 1)

echo factorial(5) # prints 120
``````
1. Implement a simple game of rock-paper-scissors: Rock-paper-scissors is a classic game where two players each choose one of three options: rock, paper, or scissors. The winner is determined by a simple set of rules: rock beats scissors, scissors beats paper, and paper beats rock. Here’s an example program in Nim that allows the user to play against the computer:
```csharpCopy code```import random

proc playRPS(): string =
let options = ["rock", "paper", "scissors"]
let computerChoice = options[random(3)]
if playerChoice == computerChoice:
return "It's a tie!"
elif (playerChoice == "rock" and computerChoice == "scissors") or
(playerChoice == "scissors" and computerChoice == "paper") or
(playerChoice == "paper" and computerChoice == "rock"):
return "You win!"
else:
return "You lose!"

echo playRPS()
``````

This program imports the “random” module to generate a random choice for the computer. It then prompts the user to enter their choice and compares it to the computer’s choice to determine the winner.

These practice exercises should help you get started with Nim and give you a sense of the language’s capabilities. As you become more familiar with Nim, you can explore more advanced features and build more complex programs.

Tags: No tags