From f5595c1d81afd629225d9e89fce878b25e84bc12 Mon Sep 17 00:00:00 2001 From: John Darrington Date: Tue, 18 Aug 2020 11:52:57 +0200 Subject: [PATCH] barchart.c: Sort the categories before displaying them. Partial fix for bug #58968 --- src/output/charts/barchart.c | 26 +++++++++++++++++++++++++- tests/language/stats/graph.at | 4 ++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/output/charts/barchart.c b/src/output/charts/barchart.c index 1b7e83ca4f..eb252d4811 100644 --- a/src/output/charts/barchart.c +++ b/src/output/charts/barchart.c @@ -43,6 +43,19 @@ compare_category_3way (const void *a_, const void *b_, const void *bc_) } +static int +compare_category_by_index_3way (const void *a_, const void *b_, + const void *unused UNUSED) +{ + const struct category *const*a = a_; + const struct category *const*b = b_; + + if ( (*a)->idx < (*b)->idx) + return -1; + + return ((*a)->idx > (*b)->idx); +} + static unsigned int hash_freq_2level_ptr (const void *a_, const void *bc_) { @@ -97,10 +110,21 @@ barchart_dump (const struct barchart *bc, FILE *fp) fprintf (fp, "Categories:\n"); struct category *cat; + struct category **cats = XCALLOC (hmap_count (&bc->primaries), struct category *); + int i = 0; HMAP_FOR_EACH (cat, struct category, node, &bc->primaries) { - fprintf (fp, " %d \"%s\"\n", cat->idx, ds_cstr(&cat->label)); + cats[i++] = cat; + } + /* HMAP_FOR_EACH is not guaranteed to iterate in any particular order. So + we must sort here before we output the results. */ + sort (cats, i, sizeof (struct category *), compare_category_by_index_3way, bc); + for (i = 0; i < hmap_count (&bc->primaries); ++i) + { + const struct category *c = cats[i]; + fprintf (fp, " %d \"%s\"\n", c->idx, ds_cstr (&c->label)); } + free (cats); if (bc->ss) { diff --git a/tests/language/stats/graph.at b/tests/language/stats/graph.at index ddabe6c987..750c192be9 100644 --- a/tests/language/stats/graph.at +++ b/tests/language/stats/graph.at @@ -395,9 +395,9 @@ Categorical Variables: Var: "penalty_favopp_x" Categories: 0 " 1.00" + 1 " 2.00" 2 " 4.00" 3 " 5.00" - 1 " 2.00" All Categories: Count: 53.1634; Cat: " 1.00" Count: 18.7756; Cat: " 2.00" @@ -416,9 +416,9 @@ Categorical Variables: Var: "XYdem_racethW8" Categories: 0 " 1.00" + 1 " 2.00" 2 " 4.00" 3 " 5.00" - 1 " 2.00" Sub-categories: 0 " .00" 1 " 1.00" -- 2.30.2