Message Boards Message Boards

0
|
3249 Views
|
3 Replies
|
1 Total Likes
View groups...
Share
Share this post:
GROUPS:

Problem creating a list manipulating function

Posted 11 years ago

I'm trying to create a function that takes grouped data, represented as such: list2 = {{0, 3}, {1, 7}, {2, 6}, {3, 4}, {4, 1}} and convert it into ungrouped data like this: list2new = {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4}.

I've written a code block that produces the result I'm after:

n = 0;
string = "{";
While[n != Length[list2],
 n = n + 1;
 For[i = 0, i < list2[[n, 2]], i++,
  string = string <> ToString[list2[[n, 1]]] <> ", ";]]
string = StringDrop[string, -2] <> "}";
ToExpression[string]

However, now when I try to assign this to a variable or define it as a function it develops errors. For example this code doesn't work:

UngroupList[in_List] := (
  n = 0;
  string = "{";
  While[n != Length[in],
     n = n + 1;
     For[i = 0, i < in[[n, 2]], i++,
      string = string <> ToString[in[[n, 1]]] <> ", ";]]
    string = StringDrop[string, -2] <> "}";
  ToExpression[string])

UngroupList[list2]

Hoping someone can see what I'm doing wrong here. Thanks for your time.

POSTED BY: Miles Ford
3 Replies
Posted 11 years ago

Ah, yes, much simpler. I feel stupid now. Oh well, live and learn.

Thanks for the help guys, really appreciate it.

POSTED BY: Miles Ford

David's solution is the better one, but just to show another way

      Flatten @ (Table[ First@#, {Last@#}] & /@ list2)
POSTED BY: Nasser M. Abbasi

First off, I would suggest that you invest a bit of time in getting familiar with the functional and pattern-based programming paradigms that are what make Mathematica so very powerful. Very often newcomers to Mathematica start out programming in ways that are more familiar to them coming from procedural languages like C and so on.

That said, here is a program that does what you want:

In[1]:= list2 = {{0, 3}, {1, 7}, {2, 6}, {3, 4}, {4, 1}} 

Out[1]= {{0, 3}, {1, 7}, {2, 6}, {3, 4}, {4, 1}}

In[2]:= Flatten[Apply[ConstantArray, list2, 1]]

Out[2]= {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 4}

Rather more straightforward no? ;-)

POSTED BY: David Reiss
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract