1
$\begingroup$

I'm tring to write a little bit of code that adds a missing element to a list. In specific: given a numbered data set such as:

{{0, 1}, {1, 6}, {2, 9}, {3, 29}, {4, 62}, {5, 97}, {6, 107}, {7, 162}, 
 {8, 178}, {9, 173}, {10, 119}, {11, 109}, {12, 49}, {13, 45},
 {14, 26}, {15, 17}, {16, 9}, {17, 6}, {18, 2}, {20, 1}}

If there is a value missing (such as {19,0} here), I want Mathematica to add that element. So I've written this piece of code:

i = 1;
While[list[[i, 1]] <= max,
 If[list[[i, 1]] != i - 1,
   Insert[list, {i - 1, 0}, i];
   ++i,
   ++i
   ];
 ]

Which apparently prefers not working over working. The problem I'm having is that the element does not actually get added to the list, while if I change the insert command to a print command, I get the output {19,0}. I'm then using this code:

i = 1;
While[list[[i, 1]] <= max,
 If[list[[i, 1]] != i - 1,
   Print[{i - 1, 0}];
   ++i,
   ++i
   ];
 ]

Is anyone able to understand why my function isn't working and what I can do to solve it?

$\endgroup$
1
  • $\begingroup$ See specifically: (19804) $\endgroup$
    – Mr.Wizard
    Dec 1, 2016 at 23:55

3 Answers 3

2
$\begingroup$

A non-procedural approach.

list = {{0, 1}, {1, 6}, {2, 9}, {4, 62}, {5, 97}, {6, 107}, {7, 
    162}, {8, 178}, {9, 173}, {10, 119}, {11, 109}, {12, 49}, {13, 
    45}, {14, 26}, {15, 17}, {16, 9}, {17, 6}, {18, 2}, {20, 1}};

I deleted the {3, 29} element for a better illustration.

max = Max@list[[All, 1]]
missing = Complement[Range@max, list[[All, 1]]]

20

{3, 19}

insert = {#, 0} & /@ missing

{{3, 0}, {19, 0}}

list~Join~insert // Sort

{{0, 1}, {1, 6}, {2, 9}, {3, 0}, {4, 62}, {5, 97}, {6, 107}, {7, 162}, {8, 178}, {9, 173}, {10, 119}, {11, 109}, {12, 49}, {13, 45}, {14, 26}, {15, 17}, {16, 9}, {17, 6}, {18, 2}, {19, 0}, {20, 1}}

$\endgroup$
2
$\begingroup$

Aaaand as always you figure it out just after you ask the question. The problem is that you have to re-define the list, so the code should read:

i = 1;
While[list[[i, 1]] <= max,
 If[list[[i, 1]] != i - 1,
   list = Insert[list, {i - 1, 0}, i];
   ++i,
   ++i
   ];
 ]

Thanks anyway!

$\endgroup$
0
$\begingroup$

Perhaps it is better not to make up data?

lst = {{0, 1}, {1, 6}, {2, 9}, {3, 29}, {4, 62}, {5, 97}, {6, 
   107}, {7, 162}, {8, 178}, {9, 173}, {10, 119}, {11, 109}, {12, 
   49}, {13, 45}, {14, 26}, {15, 17}, {16, 9}, {17, 6}, {18, 2}, {20, 
   1}}
a = Association[Rule @@@ lst]
Lookup[a, 19, 0]
$\endgroup$

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