Message Boards Message Boards

0
|
5764 Views
|
1 Reply
|
0 Total Likes
View groups...
Share
Share this post:

best way to replace element in list with sum of two consecutive elements?

Posted 10 years ago

I am a Mathematica novice - starting learning a couple of weeks ago. Looking for help with hopefully a simple problem. Any help gratefully accepted.

I have a list G[i] recursively defined, starting with

G[2] = {2,4}

G[i_] := Nest[Join[#, G[i - 1]] &, G[i - 1], Prime[i] - 1]

And I would like to replace some pairs of elements in the list (say, the ith and i+1th) with the sum of those two elements.

The criterion is that the sum of all the elements up to i is +1 mod some prime.

so, for example,

G[3] = {2, 4, 2, 4, 2, 4, 2, 4, 2, 4} (just 5 copies of G[2] )

And I want to transform it so that, for example, because the 1st and 2nd elements sum to 6 = 1(mod 5), and the sum of the first 9 elements is 26= 1 (mod 5), the new list should read {2, 6, 4, 2, 4, 2, 4, 6}

I know how to apply the test and sum two consecutive elements, but I don't know how to cleanly remove the element after the two that were summed.

Here's what I have so far:

Hsum[i_] := 
 Table[If[Mod[Sum[G[i][[j]], {j, 1, k}], Prime[i]] == 1, 
   G[i][[k]] + G[i][[k - 1]], G[i][[k]]], {k, 1, Length[G[i]]}]

I've tried various things, like Delete, or ReplacePart etc. but no joy.

Would love to know if someone knows how to do this!

:-)

POSTED BY: p linh

Hi, your spec didn't seem quite consistent, but hopefully the code below will give you some ideas, particularly with the use of Accumulate and TakeWhile.

g[2] = {2, 4};
g[i_] := Nest[Join[#, g[i - 1]] &, g[i - 1], Prime[i] - 1]

hsum[i_] := Module[{g1, sum, p, g2, t},
  g1 = g[i];
  sum = g1[[i - 1]] + g1[[i]];
  p = Prime[i];
  If[Mod[sum, p] == 1,
   g2 = ReplacePart[Delete[g1, i], (i - 1) -> sum];
   t = TakeWhile[Drop[Accumulate[g1], 2], Mod[#, p] != 1 &];
   Take[g2, Length[t] + 1]]]

hsum[3]
POSTED BY: Chris Degnen
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