4
$\begingroup$

I would like to reverse the effect of Counts, i.e., starting with

x = <|a -> 4, b -> 2, c -> 1|>

I would like to reconstruct a sorted list

y = {a, a, a, a, b, b, c}

such that Counts[y] == x. I have come up with

y = Join @@ ConstantArray @@@ Normal @ x

but I'd like to know if there's anything more elegant than this, with less intermediary expressions.

$\endgroup$
  • $\begingroup$ Essentially a duplicate on Stack Overflow: (763915) $\endgroup$ – Mr.Wizard Apr 26 '17 at 16:27
  • $\begingroup$ Wow, I would never find that question in search for relateds, @Mr.Wizard. But what I take from your answer there is that the method I'm suggesting is about as good as it gets, right? $\endgroup$ – The Vee Apr 26 '17 at 17:31
  • $\begingroup$ Well, it's what I would use, still; you can take that for what it's worth. :-) $\endgroup$ – Mr.Wizard Apr 26 '17 at 19:17
5
$\begingroup$
Catenate @ KeyValueMap[ConstantArray] @ x

Related topics:

Reverse DeleteDuplicates using Information from Tally

Generating repeated elements in a list

Replicate sublist in new list

List creation/manipulation

| improve this answer | |
$\endgroup$
  • 2
    $\begingroup$ Catenate @ KeyValueMap[Table] @ x ought to work as well. $\endgroup$ – J. M.'s discontentment Apr 19 '17 at 11:16
  • 1
    $\begingroup$ @J.M. yep, I think ConstantArray has better performance but I don't remember where to find benchmarks, I just use it by default. p.s. any idea why only the first link is automatically formatted? $\endgroup$ – Kuba Apr 19 '17 at 11:18
  • $\begingroup$ I changed your links to use https://. $\endgroup$ – J. M.'s discontentment Apr 19 '17 at 11:25
  • 1
    $\begingroup$ @Kuba A little and I think we even can ignored it. $\endgroup$ – yode Apr 26 '17 at 11:28
  • 1
    $\begingroup$ @Kuba I believe the key difference is that if it is numeric input, ConstantArray generates packed arrays. But, Catenate doesn't respect packed arrays, so you instead have to use Join @@ KeyValueMap[ConstantArray]@<|1 -> 4, 2 -> 2, 3 -> 1|>, instead. $\endgroup$ – rcollyer Apr 26 '17 at 16:23
2
$\begingroup$
KeyValueMap[Table /* Apply[Sequence], x]

{a, a, a, a, b, b, c}

| improve this answer | |
$\endgroup$
1
$\begingroup$

Multiplication of Matrices

In:

xs = <|a -> 4, b -> 2, c -> 1|>;
A = Table[1, #] & /@ Values[xs]
B = Keys[xs]
A B // Flatten

Out:

{{1, 1, 1, 1}, {1, 1}, {1}}
{a, b, c}
{a, a, a, a, b, b, c}
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.