Category talk:Wren-math: Difference between revisions
Content added Content deleted
(→Source code: Removed some redundant lines.) |
(→Source code: Added Nums.barChart method.) |
||
Line 930: | Line 930: | ||
// Converts a numeric list to a corresponding string list. |
// Converts a numeric list to a corresponding string list. |
||
static toStrings(a) { a.map { |n| n.toString }.toList } |
static toStrings(a) { a.map { |n| n.toString }.toList } |
||
// Draws a horizontal bar chart on the terminal representing a list of numerical 'data' |
|||
// which must be non-negative. 'labels' are the corresponding text for each bar. |
|||
// When printed 'labels' are always right justified within their maximum length. |
|||
// 'width' is the total width of the chart in characters to which the labels/data will |
|||
// automatically be scaled. 'symbol' is the character to be used to draw each bar |
|||
// and 'symbol2' is the character to be used to represent non-zero data which would |
|||
// otherwise be blank. The actual data is printed at the end of each bar. |
|||
static barChart (title, width, labels, data, symbol, symbol2) { |
|||
var barCount = labels.count |
|||
if (data.count != barCount) Fiber.abort("Mismatch between labels and data.") |
|||
var maxLabelLen = max(labels.map { |l| l.count }) |
|||
labels = labels.map { |l| (" " * (maxLabelLen - l.count)) + l }.toList |
|||
var maxData = max(data) |
|||
var maxLen = width - maxLabelLen - maxData.toString.count - 2 |
|||
var scaledData = data.map { |d| (d * maxLen / maxData).floor }.toList |
|||
System.print(title) |
|||
System.print("-" * Math.max(width, title.count)) |
|||
for (i in 0...barCount) { |
|||
var bar = symbol * scaledData[i] |
|||
if (bar == "") bar = data[i] > 0 ? symbol2 : "\b" |
|||
System.print(labels[i] + " " + bar + " " + data[i].toString) |
|||
} |
|||
System.print("-" * Math.max(width, title.count)) |
|||
} |
|||
// Convenience version of the above method which uses default symbols. |
|||
static barChart(title, width, labels, data) { |
|||
barChart(title, width, labels, data, "■", "◧") |
|||
} |
|||
} |
} |
||