Coding Concepts 1
Coding Concepts 1
can define a
`Vector` class that encapsulates vector operations like addition, subtraction, dot product, etc. Below is a basic implementation of a 2D vector
class in C#:
```csharp
using System;
// Vector addition
public static Vector2 operator +(Vector2 v1, Vector2 v2)
{
return new Vector2(v1.X + v2.X, v1.Y + v2.Y);
}
// Vector subtraction
public static Vector2 operator -(Vector2 v1, Vector2 v2)
{
return new Vector2(v1.X - v2.X, v1.Y - v2.Y);
}
// Scalar multiplication
public static Vector2 operator *(Vector2 v, float scalar)
{
return new Vector2(v.X * scalar, v.Y * scalar);
}
// Dot product
public static float Dot(Vector2 v1, Vector2 v2)
{
return v1.X * v2.X + v1.Y * v2.Y;
}
class Program
{
static void Main(string[] args)
{
Vector2 v1 = new Vector2(3, 4);
Vector2 v2 = new Vector2(1, 2);
Console.WriteLine($"v1: {v1}");
Console.WriteLine($"v2: {v2}");
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Scaled v1: {scaled}");
Console.WriteLine($"Dot Product: {dotProduct}");
Console.WriteLine($"Normalized v1: {normalized}");
}
}
```
### Explanation:
- **Vector2 Class:** This represents a 2D vector with `X` and `Y` components.
- **Operator Overloading:** The `+`, `-`, and `*` operators are overloaded to support vector addition, subtraction, and scalar multiplication.
- **Dot Product:** A static method to calculate the dot product of two vectors.
- **Magnitude:** This method returns the length of the vector.
- **Normalize:** Returns a unit vector (vector with a magnitude of 1) in the same direction.
### Usage:
- You can create instances of the `Vector2` class, perform operations like addition, subtraction, scaling, etc., and easily print the results.
This can be extended to 3D vectors by adding a `Z` component and modifying the methods accordingly.