Skip to content

Instantly share code, notes, and snippets.

@LizardLeliel
Created December 31, 2014 17:34
Show Gist options
  • Save LizardLeliel/35824d9244ef753f5564 to your computer and use it in GitHub Desktop.
Save LizardLeliel/35824d9244ef753f5564 to your computer and use it in GitHub Desktop.
Ruby class for 2x2 matrices, plus a section that rotates around a grid
# Our class
class Matrix2by2
# Initialize with a 2x2 list
def initialize(x, y)
if not (x.is_a? Array and y.is_a? Array) then
throw(:notArray)
end
if (x.length != 2 and y.length != 2) then
throw(:notEqual)
end
@x = x
@y = y
end
# Overload access operator
def [](n)
return @x if n == 0
return @y if n == 1
throw(:OutOfBounds!)
end
# Overload addition operator
def +(a)
@x[0] += a[0][0]
@x[1] += a[0][1]
@y[0] += a[1][0]
@y[1] += a[1][1]
end
# Overload multiplicaiton operator
def *(a)
z = [Array.new(2), Array.new(2)]
z[0][0] = @x[0]*a[0][0] + @x[1]*a[1][0]
z[0][1] = @x[0]*a[0][1] + @x[1]*a[1][1]
z[1][0] = @y[0]*a[0][0] + @y[1]*a[1][0]
z[1][1] = @y[0]*a[0][1] + @y[1]*a[1][1]
return Matrix2by2.new(z[0], z[1])
end
# Print matrix
def printContents()
puts("| #{@x[0]} #{@x[1]} |")
puts("| #{@y[0]} #{@y[1]} |")
end
# Print matrix
def printAsGrid(maxDim)
midway = maxDim/2
grid = Array.new(maxDim)
0.upto maxDim-1 do |n|
grid[n] = " "*79
end
0.upto maxDim-1 do |n|
grid[n][midway] = "|"
grid[midway][n] = "-"
end
grid[midway][midway] = " "
grid[midway - @x[0]][midway + @x[1]] = "*"
grid[midway - @y[0]][midway + @y[1]] = "*"
for line in grid do
puts line
end
end
end
#Make a new matrix
z = Matrix2by2.new([1, 5], [2, 8])
#double the matrix
z *= Matrix2by2.new([2,0],[0,2])
#print info
puts("The matrix we're going to rotate a whole 360 degrees" +
" in 15 degree steps:")
z.printContents
#converts degrees to radians
def degToRad(deg)
return deg*Math.acos(-1)/180
end
#the variable named "deg" is such a lie
(0..360).step(15) do |n|
deg = degToRad(n)
(z * [[Math.cos(deg), -Math.sin(deg)],
[Math.sin(deg), Math.cos(deg)]]).printAsGrid(37)
puts("="*80)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment