6
$\begingroup$

How to transform list wherein position of the symbol encoded by number at second position

{{a,6},{z,1},{g,2},{y,12}} 

to string

zg---a-----y
$\endgroup$
5
$\begingroup$
list = {{a, 6}, {z, 1}, {g, 2}, {y, 12}};

#2 -> ToString[#] & @@@ list // Append[_ -> "-"] // SparseArray // StringJoin

"zg---a-----y"

$\endgroup$
  • $\begingroup$ SparseArray is very clever. (+1) $\endgroup$ – Edmund Dec 27 '16 at 15:56
5
$\begingroup$

One more alternative, using StringReplacePart[]:

l = {{"a", 6}, {"z", 1}, {"g", 2}, {"y", 12}};
str = StringJoin[ConstantArray["-", Max[l[[All, -1]]]]];
Fold[StringReplacePart[#1, Sequence @@ #2] &, str,
     MapAt[ConstantArray[#, 2] &, l, {All, -1}]]
$\endgroup$
3
$\begingroup$

Pre-processing:

str = {{a, 6}, {z, 1}, {g, 2}, {y, 12}};
len = Max@Last@Transpose@str
out = StringRepeat["-", len]

String manipulations:

repl = {ToString /@ #1, Transpose@{#2, #2}} & @@ (Transpose@str)
StringReplacePart[out, #1, #2] & @@ repl

"zg---a-----y"

$\endgroup$
2
$\begingroup$

Modify a string of "-"s with the correct length:

list = {{a,6},{z,1},{g,2},{y,12}};
len = Max[list[[All, 2]]];
chars = ConstantArray["-", len];
Do[chars[[s[[2]]]] = ToString @ s[[1]], {s, list}];
StringJoin[chars]
$\endgroup$
2
$\begingroup$

Like the first answer, this keeps list as a list until the end:

list = {{a, 6}, {z, 1}, {g, 2}, {y, 12}}; 
Fold[ ReplacePart[ #1, #2[[2]] -> ToString @ #2[[1]] ] &
    , Table["-", 12], list] // StringJoin
$\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.