@somtum, please use ```ruby as your opening code line, so the code is lexed correctly as Ruby code.
It appears like this when you add the language name …
# Get determinant of 3x3 matrix a
def determinant(a)
determ = a[0][0] * a[1][1] * a[2][2] + a[0][1] * a[1][2] * a[2][0] + a[0][2] * a[1][0] * a[2][1] - a[0][2] * a[1][1] * a[2][0] - a[0][1] * a[1][0] * a[2][2] - a[0][0] * a[1][2] * a[2][1]
determ
end
# Get unit normal vector of plane defined by points a, b, and c
def unit_normal(a, b, c)
x = determinant([[1, a[1], a[2]], [1, b[1], b[2]],
[1, c[1], c[2]]])
y = determinant([[a[0], 1, a[2]],
[b[0], 1, b[2]],
[c[0], 1, c[2]]])
z = determinant([[a[0], a[1], 1],
[b[0], b[1], 1],
[c[0], c[1], 1]])
magnitude = (x ** 2 + y ** 2 + z ** 2) ** 0.5
normal = [x / magnitude, y / magnitude, z / magnitude]
normal
end
def polygon_area(poly)
if poly.length < 3
return 0
end
total = [0, 0, 0]
poly.each_with_index do |vertex, index|
v1 = Geom::Vector3d.new(vertex)
v2 = Geom::Vector3d.new(poly[index - 1])
prod = v1.cross(v2)
total[0] += prod[0]
total[1] += prod[1]
total[2] += prod[2]
end
# General formula for area of polygon in 3D space
sum_of_crosses_vector = Geom::Vector3d.new(total)
unit_normal_vector = Geom::Vector3d.new(unit_normal(poly[0], poly[1], poly[2]))
double_area = sum_of_crosses_vector.dot(unit_normal_vector)
area = (double_area / 2).abs
area
end
(Off-topic) Alternate indents for method calls, using unit_normal method as an example ... (click to view)
Basically all style guides encourage only 2 space indents, so indenting all the way (many spaces) over to a method call’s first argument is poor form. (But I’ve even seen some of the core Ruby code that does use these “giant” indents.)
Here is an example of adhering to the 2 space indent rule:
# Get unit normal vector of plane defined by points a, b, and c
def unit_normal(a, b, c)
x = determinant([
[1, a[1], a[2]],
[1, b[1], b[2]],
[1, c[1], c[2]]
])
y = determinant([
[a[0], 1, a[2]],
[b[0], 1, b[2]],
[c[0], 1, c[2]]
])
z = determinant([
[a[0], a[1], 1],
[b[0], b[1], 1],
[c[0], c[1], 1]
])
magnitude = (x ** 2 + y ** 2 + z ** 2) ** 0.5
normal = [x / magnitude, y / magnitude, z / magnitude]
normal
end
Some might say that even this example is wrong, that the outer array should be the first indent and the inner array one indent more like:
x = determinant(
[
[1, a[1], a[2]],
[1, b[1], b[2]],
[1, c[1], c[2]]
]
)
Yea, I do this but only if it is a much more complex or very large array.