Category talk:Wren-math: Difference between revisions

Added Nums.plot method.
(→‎Source code: Nums.barChart method now allows for left or right alignment of labels,)
(Added Nums.plot method.)
Line 972:
barChart(title, width, labels, data, true, "■", "◧", "□")
}
 
// Plots a sequence of points 'pts' on x/y axes of lengths 'lenX'/'lenY' on the
// terminal automatically scaling them to those lengths. 'symbol' marks each point.
static plot(title, pts, lenX, lenY, symbol) {
var px = pts.map { |p| p[0] }
var py = pts.map { |p| p[1] }
var maxX = max(px).ceil
var minX = min(px).floor
var maxY = max(py).ceil
var minY = min(py).floor
var cy = max([maxY.toString.count, minY.toString.count, 5])
pts = pts.map { |p|
var q = [0, 0]
q[0] = Math.lerp(1, lenX, (p[0] - minX) / (maxX - minX)).round
q[1] = Math.lerp(1, lenY, (p[1] - minY) / (maxY - minY)).round
return q
}.toList
pts.sort { |p, q| p[1] != q[1] ? p[1] > q[1] : p[0] < q[0] }
System.print(title)
System.print("-" * (lenX + cy + 3))
var pc = 0
for (line in lenY..1) {
var s = ""
if (line == lenY) {
s = maxY.toString
} else if (line == 1) {
s = minY.toString
}
System.write("|")
if (s.count < cy) System.write(" " * (cy - s.count))
System.write(s + "|")
var xs = []
while (pc < pts.count && pts[pc][1] == line) {
xs.add(pts[pc][0])
pc = pc + 1
}
if (xs.isEmpty) {
System.print(" " * lenX + "|")
} else {
var lastX = 0
for (x in xs) {
if (x == lastX) continue
if (x - lastX > 1) System.write(" " * (x - lastX - 1))
System.write(symbol)
lastX = x
}
if (lenX > lastX) System.write(" " * (lenX - lastX))
System.print("|")
}
}
System.print("|" + "-" * (lenX + cy + 1) + "|")
var minL = minX.toString.count
var maxL = maxX.toString.count
System.write("| y/x" + " " * (cy - 4) + "|")
System.print(minX.toString + " " * (lenX - minL - maxL) + maxX.toString + "|")
System.print("-" * (lenX + cy + 3))
}
 
// As above method but uses a default symbol.
static plot(title, pts, lenX, lenY) { plot(title, pts, lenX, lenY, "▮") }
}
 
9,477

edits