Return last number in sub-sequences in a list of integersFind subsequences of consecutive integers inside a listappending element to sub listPartition list into a given number of sub-listsDelete String sub listHow to select a number from all the integers list?Partitioning a number into consecutive integersHow do I graph only integers using the list function?Selecting integers which are not a member in an ordered list of integersNative function that gives sequential sub-sequences of a list?Select sub-sequences in lists?How to concatenate list of integers into a single number

IBM mainframe classic executable file formats

How to derive trigonometric Cartesian equation from parametric

Novel - Accidental exploration ship, broadcasts a TV show to let people know what they find

How can flights operated by the same company have such different prices when marketed by another?

Which service could I use to train my networks?

Can living where magnetic ore is abundant provide any protection from cosmic radiation?

How to get Planck length in meters to 6 decimal places

A game of red and black

Best Ergonomic Design for a handheld ranged weapon

Oath of redemption: Does Emmissary of Peace reflect damage taken from Aura of the Guardian?

Were there any unmanned expeditions to the moon that returned to Earth prior to Apollo?

Constant Scan spooling

"Fewer errors means better products" or "Fewer errors mean better products"?

May a hotel provide accommodation for fewer people than booked?

Should 2FA be enabled on service accounts?

How to crop this photo of water drops on a leaf to improve the composition?

UX writing: When to use "we"?

What does the USDA zone range mean?

The Enigma Machine (CLI) in Java

How did Biff return to 2015 from 1955 without a lightning strike?

Guidelines for writing a chord progression

Skipping same old introductions

Using Python in a Bash Script

Russian pronunciation of /etc (a directory)



Return last number in sub-sequences in a list of integers


Find subsequences of consecutive integers inside a listappending element to sub listPartition list into a given number of sub-listsDelete String sub listHow to select a number from all the integers list?Partitioning a number into consecutive integersHow do I graph only integers using the list function?Selecting integers which are not a member in an ordered list of integersNative function that gives sequential sub-sequences of a list?Select sub-sequences in lists?How to concatenate list of integers into a single number






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








6












$begingroup$


Given a list of integers like this:



z = 113, 117, 118, 119, 120, 121, 475, 476, 529, 538, 542, 543, 544


I want a function that returns:



113, 121, 476, 529, 538, 544


here's the pedestrian version:



LastinSequence[a_] := Module[
n,
n = ;
Do[
If[
a[[i]] > (1 + a[[i - 1]]),
n = Append[n, a[[i - 1]]]
];
, i, 2, Length@a
];
n = Append[n, Last@a];
n
]


Horrible.



Can I have some suggestions to do this elegantly (and quickly!) in Wolfram language?



Also, a variation FirstinSequence[a_] that would return:



113 117, 475, 529, 538, 542


Thanks.










share|improve this question











$endgroup$









  • 2




    $begingroup$
    Closely related: mathematica.stackexchange.com/questions/23607/…, with some of the same techniques we see in the answers that have already been posted.
    $endgroup$
    – Michael E2
    6 hours ago

















6












$begingroup$


Given a list of integers like this:



z = 113, 117, 118, 119, 120, 121, 475, 476, 529, 538, 542, 543, 544


I want a function that returns:



113, 121, 476, 529, 538, 544


here's the pedestrian version:



LastinSequence[a_] := Module[
n,
n = ;
Do[
If[
a[[i]] > (1 + a[[i - 1]]),
n = Append[n, a[[i - 1]]]
];
, i, 2, Length@a
];
n = Append[n, Last@a];
n
]


Horrible.



Can I have some suggestions to do this elegantly (and quickly!) in Wolfram language?



Also, a variation FirstinSequence[a_] that would return:



113 117, 475, 529, 538, 542


Thanks.










share|improve this question











$endgroup$









  • 2




    $begingroup$
    Closely related: mathematica.stackexchange.com/questions/23607/…, with some of the same techniques we see in the answers that have already been posted.
    $endgroup$
    – Michael E2
    6 hours ago













6












6








6





$begingroup$


Given a list of integers like this:



z = 113, 117, 118, 119, 120, 121, 475, 476, 529, 538, 542, 543, 544


I want a function that returns:



113, 121, 476, 529, 538, 544


here's the pedestrian version:



LastinSequence[a_] := Module[
n,
n = ;
Do[
If[
a[[i]] > (1 + a[[i - 1]]),
n = Append[n, a[[i - 1]]]
];
, i, 2, Length@a
];
n = Append[n, Last@a];
n
]


Horrible.



Can I have some suggestions to do this elegantly (and quickly!) in Wolfram language?



Also, a variation FirstinSequence[a_] that would return:



113 117, 475, 529, 538, 542


Thanks.










share|improve this question











$endgroup$




Given a list of integers like this:



z = 113, 117, 118, 119, 120, 121, 475, 476, 529, 538, 542, 543, 544


I want a function that returns:



113, 121, 476, 529, 538, 544


here's the pedestrian version:



LastinSequence[a_] := Module[
n,
n = ;
Do[
If[
a[[i]] > (1 + a[[i - 1]]),
n = Append[n, a[[i - 1]]]
];
, i, 2, Length@a
];
n = Append[n, Last@a];
n
]


Horrible.



Can I have some suggestions to do this elegantly (and quickly!) in Wolfram language?



Also, a variation FirstinSequence[a_] that would return:



113 117, 475, 529, 538, 542


Thanks.







list-manipulation performance-tuning integer-sequence






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 6 hours ago









Michael E2

157k13 gold badges215 silver badges509 bronze badges




157k13 gold badges215 silver badges509 bronze badges










asked 8 hours ago









Jonathan KinlayJonathan Kinlay

2361 silver badge10 bronze badges




2361 silver badge10 bronze badges










  • 2




    $begingroup$
    Closely related: mathematica.stackexchange.com/questions/23607/…, with some of the same techniques we see in the answers that have already been posted.
    $endgroup$
    – Michael E2
    6 hours ago












  • 2




    $begingroup$
    Closely related: mathematica.stackexchange.com/questions/23607/…, with some of the same techniques we see in the answers that have already been posted.
    $endgroup$
    – Michael E2
    6 hours ago







2




2




$begingroup$
Closely related: mathematica.stackexchange.com/questions/23607/…, with some of the same techniques we see in the answers that have already been posted.
$endgroup$
– Michael E2
6 hours ago




$begingroup$
Closely related: mathematica.stackexchange.com/questions/23607/…, with some of the same techniques we see in the answers that have already been posted.
$endgroup$
– Michael E2
6 hours ago










5 Answers
5






active

oldest

votes


















5












$begingroup$

Use a "background" element of the desired difference in SparseArray on the differences, and "AdjacencyLists" will pick out what you desire:



Last in sequence:



positions = Append[SparseArray[Differences@z, Automatic, 1], 0]["AdjacencyLists"]
(* 1, 6, 8, 9, 10, 13 *)

z ~Part~ positions // Normal
(* 113, 121, 476, 529, 538, 544 *)


More efficient version:



Append[
z ~Part~
SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],
Last@z]


First in sequence:



Prepend[
Reverse@z ~Part~
Reverse[SparseArray[Rest@z - Most@z, Automatic, 1]]["AdjacencyLists"],
First@z]
(* 113, 117, 475, 529, 538, 542 *)


My answer is similar to Mr.Wizard's answer to Find subsequences of consecutive integers inside a list, which asks for the essentially same thing as the OP but with the output in a different form.






share|improve this answer











$endgroup$














  • $begingroup$
    +1 This seems to be the fastest approach so far.
    $endgroup$
    – rhermans
    6 hours ago







  • 1




    $begingroup$
    @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
    $endgroup$
    – Michael E2
    6 hours ago










  • $begingroup$
    @Shadowray Really?: i.stack.imgur.com/KVWea.png
    $endgroup$
    – Michael E2
    4 hours ago






  • 1




    $begingroup$
    Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
    $endgroup$
    – Shadowray
    3 hours ago










  • $begingroup$
    @Shadowray Awesome! I knew that but had forgotten. Thanks!
    $endgroup$
    – Michael E2
    3 hours ago


















6












$begingroup$

You can use Split:



Last /@ Split[z, #2 == # + 1&]



113, 121, 476, 529, 538, 544




First /@ Split[z, #2 == # + 1&]



113, 117, 475, 529, 538, 542







share|improve this answer









$endgroup$














  • $begingroup$
    Very elegant indeed.
    $endgroup$
    – Jonathan Kinlay
    5 hours ago


















5












$begingroup$

Pick in combination with vectorized arithmetic is as fast as SparseArray:



myLastInSequenceV3[z_] := Join[Pick[Most[z], Unitize[Rest[z]-Most[z]-1], 1], Last[z]]


Alternative version. Shorter, but slower:



myLastInSequence[z_] := Pick[z, Join[Differences[z], 0], Except[1, _Integer]]


Test:



LastinSequence[z] == myLastInSequence[z] == myLastInSequenceV3[z]



True




Timing for SparseArray-based solution:



data = NestList[(# + RandomInteger[9]) &, 1, 100000];

lastInSequenceSparseUpd[z_] := Append[z ~Part~SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],Last@z]
First@RepeatedTiming[lastInSequenceSparseUpd[data];]



0.0018




This method:



First@RepeatedTiming[myLastInSequenceV3[data];]



0.0019







share|improve this answer











$endgroup$














  • $begingroup$
    Very fast and elegant. Superb!
    $endgroup$
    – Jonathan Kinlay
    5 hours ago


















4












$begingroup$

Solutions



This is actually twice as fast as fast as kglr's but three times slower than Shadowray's . MichaelE2 has provided the fastest answer by far.



LastInSequenceRH2[d_] := Pick[d, Inner[Unequal, d, RotateLeft[d - 1], List]]


This was my previous attempt



FirstInSequenceRH1[z_] := With[n = Length[z],
Pick[z, Array[(z[[#]] != z[[Max[# - 1, 1]]] + 1) &, n]]
];
LastInSequenceRH1[z_] := With[n = Length[z],
Pick[z, Array[(z[[Min[# + 1, n]]] != z[[#]] + 1) &, n]]
]


FirstInSequence[data]
(* 113, 117, 475, 529, 538, 542 *)

LastInSequence[data]
(* 113, 121, 476, 529, 538, 544 *)


Benchmark



data = NestList[(# + RandomInteger[9]) &, 1, 100000]; (* Large data *)

First@RepeatedTiming[FirstInSequenceRH1[data];] (* My first answer *)
(* 0.242 *)

First@RepeatedTiming[FirstInSequencekglr[data];] (* kglr's answer *)
(* 0.0913 *)

First@RepeatedTiming[LastInSequenceOP[data];] (* OP question *)
(* 11.57 *)

First@RepeatedTiming[LastInSequenceRH2[data];] (* My second answer *)
(* 0.049 *)

First@RepeatedTiming[LastInSequenceShadowray[data];] (* Shadowray's *)
(* 0.016 *)

First@RepeatedTiming[LastInSequenceMichaelE2[data];] (* MichaelE2 *)
(* 0.0038 *)





share|improve this answer











$endgroup$






















    1












    $begingroup$

    Some great solutions here. I borrowed Shadowray's code and created this:



     FirstInSequence[z_] := 
    Join[First[z], Pick[Rest[z], Unitize[Differences[z] - 1], 1]]

    FirstInSequence[113, 117, 118, 119, 120, 121, 475, 476, 529, 538,
    542, 543, 544]

    113, 117, 475, 529, 538, 542





    share|improve this answer









    $endgroup$

















      Your Answer








      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "387"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f203174%2freturn-last-number-in-sub-sequences-in-a-list-of-integers%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5












      $begingroup$

      Use a "background" element of the desired difference in SparseArray on the differences, and "AdjacencyLists" will pick out what you desire:



      Last in sequence:



      positions = Append[SparseArray[Differences@z, Automatic, 1], 0]["AdjacencyLists"]
      (* 1, 6, 8, 9, 10, 13 *)

      z ~Part~ positions // Normal
      (* 113, 121, 476, 529, 538, 544 *)


      More efficient version:



      Append[
      z ~Part~
      SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],
      Last@z]


      First in sequence:



      Prepend[
      Reverse@z ~Part~
      Reverse[SparseArray[Rest@z - Most@z, Automatic, 1]]["AdjacencyLists"],
      First@z]
      (* 113, 117, 475, 529, 538, 542 *)


      My answer is similar to Mr.Wizard's answer to Find subsequences of consecutive integers inside a list, which asks for the essentially same thing as the OP but with the output in a different form.






      share|improve this answer











      $endgroup$














      • $begingroup$
        +1 This seems to be the fastest approach so far.
        $endgroup$
        – rhermans
        6 hours ago







      • 1




        $begingroup$
        @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
        $endgroup$
        – Michael E2
        6 hours ago










      • $begingroup$
        @Shadowray Really?: i.stack.imgur.com/KVWea.png
        $endgroup$
        – Michael E2
        4 hours ago






      • 1




        $begingroup$
        Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
        $endgroup$
        – Shadowray
        3 hours ago










      • $begingroup$
        @Shadowray Awesome! I knew that but had forgotten. Thanks!
        $endgroup$
        – Michael E2
        3 hours ago















      5












      $begingroup$

      Use a "background" element of the desired difference in SparseArray on the differences, and "AdjacencyLists" will pick out what you desire:



      Last in sequence:



      positions = Append[SparseArray[Differences@z, Automatic, 1], 0]["AdjacencyLists"]
      (* 1, 6, 8, 9, 10, 13 *)

      z ~Part~ positions // Normal
      (* 113, 121, 476, 529, 538, 544 *)


      More efficient version:



      Append[
      z ~Part~
      SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],
      Last@z]


      First in sequence:



      Prepend[
      Reverse@z ~Part~
      Reverse[SparseArray[Rest@z - Most@z, Automatic, 1]]["AdjacencyLists"],
      First@z]
      (* 113, 117, 475, 529, 538, 542 *)


      My answer is similar to Mr.Wizard's answer to Find subsequences of consecutive integers inside a list, which asks for the essentially same thing as the OP but with the output in a different form.






      share|improve this answer











      $endgroup$














      • $begingroup$
        +1 This seems to be the fastest approach so far.
        $endgroup$
        – rhermans
        6 hours ago







      • 1




        $begingroup$
        @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
        $endgroup$
        – Michael E2
        6 hours ago










      • $begingroup$
        @Shadowray Really?: i.stack.imgur.com/KVWea.png
        $endgroup$
        – Michael E2
        4 hours ago






      • 1




        $begingroup$
        Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
        $endgroup$
        – Shadowray
        3 hours ago










      • $begingroup$
        @Shadowray Awesome! I knew that but had forgotten. Thanks!
        $endgroup$
        – Michael E2
        3 hours ago













      5












      5








      5





      $begingroup$

      Use a "background" element of the desired difference in SparseArray on the differences, and "AdjacencyLists" will pick out what you desire:



      Last in sequence:



      positions = Append[SparseArray[Differences@z, Automatic, 1], 0]["AdjacencyLists"]
      (* 1, 6, 8, 9, 10, 13 *)

      z ~Part~ positions // Normal
      (* 113, 121, 476, 529, 538, 544 *)


      More efficient version:



      Append[
      z ~Part~
      SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],
      Last@z]


      First in sequence:



      Prepend[
      Reverse@z ~Part~
      Reverse[SparseArray[Rest@z - Most@z, Automatic, 1]]["AdjacencyLists"],
      First@z]
      (* 113, 117, 475, 529, 538, 542 *)


      My answer is similar to Mr.Wizard's answer to Find subsequences of consecutive integers inside a list, which asks for the essentially same thing as the OP but with the output in a different form.






      share|improve this answer











      $endgroup$



      Use a "background" element of the desired difference in SparseArray on the differences, and "AdjacencyLists" will pick out what you desire:



      Last in sequence:



      positions = Append[SparseArray[Differences@z, Automatic, 1], 0]["AdjacencyLists"]
      (* 1, 6, 8, 9, 10, 13 *)

      z ~Part~ positions // Normal
      (* 113, 121, 476, 529, 538, 544 *)


      More efficient version:



      Append[
      z ~Part~
      SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],
      Last@z]


      First in sequence:



      Prepend[
      Reverse@z ~Part~
      Reverse[SparseArray[Rest@z - Most@z, Automatic, 1]]["AdjacencyLists"],
      First@z]
      (* 113, 117, 475, 529, 538, 542 *)


      My answer is similar to Mr.Wizard's answer to Find subsequences of consecutive integers inside a list, which asks for the essentially same thing as the OP but with the output in a different form.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 3 hours ago

























      answered 6 hours ago









      Michael E2Michael E2

      157k13 gold badges215 silver badges509 bronze badges




      157k13 gold badges215 silver badges509 bronze badges














      • $begingroup$
        +1 This seems to be the fastest approach so far.
        $endgroup$
        – rhermans
        6 hours ago







      • 1




        $begingroup$
        @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
        $endgroup$
        – Michael E2
        6 hours ago










      • $begingroup$
        @Shadowray Really?: i.stack.imgur.com/KVWea.png
        $endgroup$
        – Michael E2
        4 hours ago






      • 1




        $begingroup$
        Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
        $endgroup$
        – Shadowray
        3 hours ago










      • $begingroup$
        @Shadowray Awesome! I knew that but had forgotten. Thanks!
        $endgroup$
        – Michael E2
        3 hours ago
















      • $begingroup$
        +1 This seems to be the fastest approach so far.
        $endgroup$
        – rhermans
        6 hours ago







      • 1




        $begingroup$
        @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
        $endgroup$
        – Michael E2
        6 hours ago










      • $begingroup$
        @Shadowray Really?: i.stack.imgur.com/KVWea.png
        $endgroup$
        – Michael E2
        4 hours ago






      • 1




        $begingroup$
        Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
        $endgroup$
        – Shadowray
        3 hours ago










      • $begingroup$
        @Shadowray Awesome! I knew that but had forgotten. Thanks!
        $endgroup$
        – Michael E2
        3 hours ago















      $begingroup$
      +1 This seems to be the fastest approach so far.
      $endgroup$
      – rhermans
      6 hours ago





      $begingroup$
      +1 This seems to be the fastest approach so far.
      $endgroup$
      – rhermans
      6 hours ago





      1




      1




      $begingroup$
      @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
      $endgroup$
      – Michael E2
      6 hours ago




      $begingroup$
      @rhermans Thanks. "AdjacencyLists" and "NonzeroPositions" can be found in efficient solution to many similar problems on this site. (I couldn't find a duplicate, though, which surprises me.)
      $endgroup$
      – Michael E2
      6 hours ago












      $begingroup$
      @Shadowray Really?: i.stack.imgur.com/KVWea.png
      $endgroup$
      – Michael E2
      4 hours ago




      $begingroup$
      @Shadowray Really?: i.stack.imgur.com/KVWea.png
      $endgroup$
      – Michael E2
      4 hours ago




      1




      1




      $begingroup$
      Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
      $endgroup$
      – Shadowray
      3 hours ago




      $begingroup$
      Note also that for vector of integers, Differences[z] may be noticably slower than Rest[z]-Most[z]
      $endgroup$
      – Shadowray
      3 hours ago












      $begingroup$
      @Shadowray Awesome! I knew that but had forgotten. Thanks!
      $endgroup$
      – Michael E2
      3 hours ago




      $begingroup$
      @Shadowray Awesome! I knew that but had forgotten. Thanks!
      $endgroup$
      – Michael E2
      3 hours ago













      6












      $begingroup$

      You can use Split:



      Last /@ Split[z, #2 == # + 1&]



      113, 121, 476, 529, 538, 544




      First /@ Split[z, #2 == # + 1&]



      113, 117, 475, 529, 538, 542







      share|improve this answer









      $endgroup$














      • $begingroup$
        Very elegant indeed.
        $endgroup$
        – Jonathan Kinlay
        5 hours ago















      6












      $begingroup$

      You can use Split:



      Last /@ Split[z, #2 == # + 1&]



      113, 121, 476, 529, 538, 544




      First /@ Split[z, #2 == # + 1&]



      113, 117, 475, 529, 538, 542







      share|improve this answer









      $endgroup$














      • $begingroup$
        Very elegant indeed.
        $endgroup$
        – Jonathan Kinlay
        5 hours ago













      6












      6








      6





      $begingroup$

      You can use Split:



      Last /@ Split[z, #2 == # + 1&]



      113, 121, 476, 529, 538, 544




      First /@ Split[z, #2 == # + 1&]



      113, 117, 475, 529, 538, 542







      share|improve this answer









      $endgroup$



      You can use Split:



      Last /@ Split[z, #2 == # + 1&]



      113, 121, 476, 529, 538, 544




      First /@ Split[z, #2 == # + 1&]



      113, 117, 475, 529, 538, 542








      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered 8 hours ago









      kglrkglr

      208k10 gold badges241 silver badges476 bronze badges




      208k10 gold badges241 silver badges476 bronze badges














      • $begingroup$
        Very elegant indeed.
        $endgroup$
        – Jonathan Kinlay
        5 hours ago
















      • $begingroup$
        Very elegant indeed.
        $endgroup$
        – Jonathan Kinlay
        5 hours ago















      $begingroup$
      Very elegant indeed.
      $endgroup$
      – Jonathan Kinlay
      5 hours ago




      $begingroup$
      Very elegant indeed.
      $endgroup$
      – Jonathan Kinlay
      5 hours ago











      5












      $begingroup$

      Pick in combination with vectorized arithmetic is as fast as SparseArray:



      myLastInSequenceV3[z_] := Join[Pick[Most[z], Unitize[Rest[z]-Most[z]-1], 1], Last[z]]


      Alternative version. Shorter, but slower:



      myLastInSequence[z_] := Pick[z, Join[Differences[z], 0], Except[1, _Integer]]


      Test:



      LastinSequence[z] == myLastInSequence[z] == myLastInSequenceV3[z]



      True




      Timing for SparseArray-based solution:



      data = NestList[(# + RandomInteger[9]) &, 1, 100000];

      lastInSequenceSparseUpd[z_] := Append[z ~Part~SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],Last@z]
      First@RepeatedTiming[lastInSequenceSparseUpd[data];]



      0.0018




      This method:



      First@RepeatedTiming[myLastInSequenceV3[data];]



      0.0019







      share|improve this answer











      $endgroup$














      • $begingroup$
        Very fast and elegant. Superb!
        $endgroup$
        – Jonathan Kinlay
        5 hours ago















      5












      $begingroup$

      Pick in combination with vectorized arithmetic is as fast as SparseArray:



      myLastInSequenceV3[z_] := Join[Pick[Most[z], Unitize[Rest[z]-Most[z]-1], 1], Last[z]]


      Alternative version. Shorter, but slower:



      myLastInSequence[z_] := Pick[z, Join[Differences[z], 0], Except[1, _Integer]]


      Test:



      LastinSequence[z] == myLastInSequence[z] == myLastInSequenceV3[z]



      True




      Timing for SparseArray-based solution:



      data = NestList[(# + RandomInteger[9]) &, 1, 100000];

      lastInSequenceSparseUpd[z_] := Append[z ~Part~SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],Last@z]
      First@RepeatedTiming[lastInSequenceSparseUpd[data];]



      0.0018




      This method:



      First@RepeatedTiming[myLastInSequenceV3[data];]



      0.0019







      share|improve this answer











      $endgroup$














      • $begingroup$
        Very fast and elegant. Superb!
        $endgroup$
        – Jonathan Kinlay
        5 hours ago













      5












      5








      5





      $begingroup$

      Pick in combination with vectorized arithmetic is as fast as SparseArray:



      myLastInSequenceV3[z_] := Join[Pick[Most[z], Unitize[Rest[z]-Most[z]-1], 1], Last[z]]


      Alternative version. Shorter, but slower:



      myLastInSequence[z_] := Pick[z, Join[Differences[z], 0], Except[1, _Integer]]


      Test:



      LastinSequence[z] == myLastInSequence[z] == myLastInSequenceV3[z]



      True




      Timing for SparseArray-based solution:



      data = NestList[(# + RandomInteger[9]) &, 1, 100000];

      lastInSequenceSparseUpd[z_] := Append[z ~Part~SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],Last@z]
      First@RepeatedTiming[lastInSequenceSparseUpd[data];]



      0.0018




      This method:



      First@RepeatedTiming[myLastInSequenceV3[data];]



      0.0019







      share|improve this answer











      $endgroup$



      Pick in combination with vectorized arithmetic is as fast as SparseArray:



      myLastInSequenceV3[z_] := Join[Pick[Most[z], Unitize[Rest[z]-Most[z]-1], 1], Last[z]]


      Alternative version. Shorter, but slower:



      myLastInSequence[z_] := Pick[z, Join[Differences[z], 0], Except[1, _Integer]]


      Test:



      LastinSequence[z] == myLastInSequence[z] == myLastInSequenceV3[z]



      True




      Timing for SparseArray-based solution:



      data = NestList[(# + RandomInteger[9]) &, 1, 100000];

      lastInSequenceSparseUpd[z_] := Append[z ~Part~SparseArray[Rest@z - Most@z, Automatic, 1]["AdjacencyLists"],Last@z]
      First@RepeatedTiming[lastInSequenceSparseUpd[data];]



      0.0018




      This method:



      First@RepeatedTiming[myLastInSequenceV3[data];]



      0.0019








      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited 3 hours ago

























      answered 6 hours ago









      ShadowrayShadowray

      5,9571 gold badge9 silver badges34 bronze badges




      5,9571 gold badge9 silver badges34 bronze badges














      • $begingroup$
        Very fast and elegant. Superb!
        $endgroup$
        – Jonathan Kinlay
        5 hours ago
















      • $begingroup$
        Very fast and elegant. Superb!
        $endgroup$
        – Jonathan Kinlay
        5 hours ago















      $begingroup$
      Very fast and elegant. Superb!
      $endgroup$
      – Jonathan Kinlay
      5 hours ago




      $begingroup$
      Very fast and elegant. Superb!
      $endgroup$
      – Jonathan Kinlay
      5 hours ago











      4












      $begingroup$

      Solutions



      This is actually twice as fast as fast as kglr's but three times slower than Shadowray's . MichaelE2 has provided the fastest answer by far.



      LastInSequenceRH2[d_] := Pick[d, Inner[Unequal, d, RotateLeft[d - 1], List]]


      This was my previous attempt



      FirstInSequenceRH1[z_] := With[n = Length[z],
      Pick[z, Array[(z[[#]] != z[[Max[# - 1, 1]]] + 1) &, n]]
      ];
      LastInSequenceRH1[z_] := With[n = Length[z],
      Pick[z, Array[(z[[Min[# + 1, n]]] != z[[#]] + 1) &, n]]
      ]


      FirstInSequence[data]
      (* 113, 117, 475, 529, 538, 542 *)

      LastInSequence[data]
      (* 113, 121, 476, 529, 538, 544 *)


      Benchmark



      data = NestList[(# + RandomInteger[9]) &, 1, 100000]; (* Large data *)

      First@RepeatedTiming[FirstInSequenceRH1[data];] (* My first answer *)
      (* 0.242 *)

      First@RepeatedTiming[FirstInSequencekglr[data];] (* kglr's answer *)
      (* 0.0913 *)

      First@RepeatedTiming[LastInSequenceOP[data];] (* OP question *)
      (* 11.57 *)

      First@RepeatedTiming[LastInSequenceRH2[data];] (* My second answer *)
      (* 0.049 *)

      First@RepeatedTiming[LastInSequenceShadowray[data];] (* Shadowray's *)
      (* 0.016 *)

      First@RepeatedTiming[LastInSequenceMichaelE2[data];] (* MichaelE2 *)
      (* 0.0038 *)





      share|improve this answer











      $endgroup$



















        4












        $begingroup$

        Solutions



        This is actually twice as fast as fast as kglr's but three times slower than Shadowray's . MichaelE2 has provided the fastest answer by far.



        LastInSequenceRH2[d_] := Pick[d, Inner[Unequal, d, RotateLeft[d - 1], List]]


        This was my previous attempt



        FirstInSequenceRH1[z_] := With[n = Length[z],
        Pick[z, Array[(z[[#]] != z[[Max[# - 1, 1]]] + 1) &, n]]
        ];
        LastInSequenceRH1[z_] := With[n = Length[z],
        Pick[z, Array[(z[[Min[# + 1, n]]] != z[[#]] + 1) &, n]]
        ]


        FirstInSequence[data]
        (* 113, 117, 475, 529, 538, 542 *)

        LastInSequence[data]
        (* 113, 121, 476, 529, 538, 544 *)


        Benchmark



        data = NestList[(# + RandomInteger[9]) &, 1, 100000]; (* Large data *)

        First@RepeatedTiming[FirstInSequenceRH1[data];] (* My first answer *)
        (* 0.242 *)

        First@RepeatedTiming[FirstInSequencekglr[data];] (* kglr's answer *)
        (* 0.0913 *)

        First@RepeatedTiming[LastInSequenceOP[data];] (* OP question *)
        (* 11.57 *)

        First@RepeatedTiming[LastInSequenceRH2[data];] (* My second answer *)
        (* 0.049 *)

        First@RepeatedTiming[LastInSequenceShadowray[data];] (* Shadowray's *)
        (* 0.016 *)

        First@RepeatedTiming[LastInSequenceMichaelE2[data];] (* MichaelE2 *)
        (* 0.0038 *)





        share|improve this answer











        $endgroup$

















          4












          4








          4





          $begingroup$

          Solutions



          This is actually twice as fast as fast as kglr's but three times slower than Shadowray's . MichaelE2 has provided the fastest answer by far.



          LastInSequenceRH2[d_] := Pick[d, Inner[Unequal, d, RotateLeft[d - 1], List]]


          This was my previous attempt



          FirstInSequenceRH1[z_] := With[n = Length[z],
          Pick[z, Array[(z[[#]] != z[[Max[# - 1, 1]]] + 1) &, n]]
          ];
          LastInSequenceRH1[z_] := With[n = Length[z],
          Pick[z, Array[(z[[Min[# + 1, n]]] != z[[#]] + 1) &, n]]
          ]


          FirstInSequence[data]
          (* 113, 117, 475, 529, 538, 542 *)

          LastInSequence[data]
          (* 113, 121, 476, 529, 538, 544 *)


          Benchmark



          data = NestList[(# + RandomInteger[9]) &, 1, 100000]; (* Large data *)

          First@RepeatedTiming[FirstInSequenceRH1[data];] (* My first answer *)
          (* 0.242 *)

          First@RepeatedTiming[FirstInSequencekglr[data];] (* kglr's answer *)
          (* 0.0913 *)

          First@RepeatedTiming[LastInSequenceOP[data];] (* OP question *)
          (* 11.57 *)

          First@RepeatedTiming[LastInSequenceRH2[data];] (* My second answer *)
          (* 0.049 *)

          First@RepeatedTiming[LastInSequenceShadowray[data];] (* Shadowray's *)
          (* 0.016 *)

          First@RepeatedTiming[LastInSequenceMichaelE2[data];] (* MichaelE2 *)
          (* 0.0038 *)





          share|improve this answer











          $endgroup$



          Solutions



          This is actually twice as fast as fast as kglr's but three times slower than Shadowray's . MichaelE2 has provided the fastest answer by far.



          LastInSequenceRH2[d_] := Pick[d, Inner[Unequal, d, RotateLeft[d - 1], List]]


          This was my previous attempt



          FirstInSequenceRH1[z_] := With[n = Length[z],
          Pick[z, Array[(z[[#]] != z[[Max[# - 1, 1]]] + 1) &, n]]
          ];
          LastInSequenceRH1[z_] := With[n = Length[z],
          Pick[z, Array[(z[[Min[# + 1, n]]] != z[[#]] + 1) &, n]]
          ]


          FirstInSequence[data]
          (* 113, 117, 475, 529, 538, 542 *)

          LastInSequence[data]
          (* 113, 121, 476, 529, 538, 544 *)


          Benchmark



          data = NestList[(# + RandomInteger[9]) &, 1, 100000]; (* Large data *)

          First@RepeatedTiming[FirstInSequenceRH1[data];] (* My first answer *)
          (* 0.242 *)

          First@RepeatedTiming[FirstInSequencekglr[data];] (* kglr's answer *)
          (* 0.0913 *)

          First@RepeatedTiming[LastInSequenceOP[data];] (* OP question *)
          (* 11.57 *)

          First@RepeatedTiming[LastInSequenceRH2[data];] (* My second answer *)
          (* 0.049 *)

          First@RepeatedTiming[LastInSequenceShadowray[data];] (* Shadowray's *)
          (* 0.016 *)

          First@RepeatedTiming[LastInSequenceMichaelE2[data];] (* MichaelE2 *)
          (* 0.0038 *)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 6 hours ago

























          answered 7 hours ago









          rhermansrhermans

          23.6k4 gold badges42 silver badges110 bronze badges




          23.6k4 gold badges42 silver badges110 bronze badges
























              1












              $begingroup$

              Some great solutions here. I borrowed Shadowray's code and created this:



               FirstInSequence[z_] := 
              Join[First[z], Pick[Rest[z], Unitize[Differences[z] - 1], 1]]

              FirstInSequence[113, 117, 118, 119, 120, 121, 475, 476, 529, 538,
              542, 543, 544]

              113, 117, 475, 529, 538, 542





              share|improve this answer









              $endgroup$



















                1












                $begingroup$

                Some great solutions here. I borrowed Shadowray's code and created this:



                 FirstInSequence[z_] := 
                Join[First[z], Pick[Rest[z], Unitize[Differences[z] - 1], 1]]

                FirstInSequence[113, 117, 118, 119, 120, 121, 475, 476, 529, 538,
                542, 543, 544]

                113, 117, 475, 529, 538, 542





                share|improve this answer









                $endgroup$

















                  1












                  1








                  1





                  $begingroup$

                  Some great solutions here. I borrowed Shadowray's code and created this:



                   FirstInSequence[z_] := 
                  Join[First[z], Pick[Rest[z], Unitize[Differences[z] - 1], 1]]

                  FirstInSequence[113, 117, 118, 119, 120, 121, 475, 476, 529, 538,
                  542, 543, 544]

                  113, 117, 475, 529, 538, 542





                  share|improve this answer









                  $endgroup$



                  Some great solutions here. I borrowed Shadowray's code and created this:



                   FirstInSequence[z_] := 
                  Join[First[z], Pick[Rest[z], Unitize[Differences[z] - 1], 1]]

                  FirstInSequence[113, 117, 118, 119, 120, 121, 475, 476, 529, 538,
                  542, 543, 544]

                  113, 117, 475, 529, 538, 542






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 5 hours ago









                  Jonathan KinlayJonathan Kinlay

                  2361 silver badge10 bronze badges




                  2361 silver badge10 bronze badges






























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Mathematica Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      Use MathJax to format equations. MathJax reference.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmathematica.stackexchange.com%2fquestions%2f203174%2freturn-last-number-in-sub-sequences-in-a-list-of-integers%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                      Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                      In Tikz, how to set a node's label alignment to the left?Rotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?Numerical conditional within tikz keys?TikZ/ERD: node (=Entity) label on the insideLine up nested tikz enviroments or how to get rid of themVertically align a tikzpicture and forestDrawing tikz line in the margin for multiple pagesLongtable, contained tikz, padding, custom columns, and an alignment issueTikZ: define arrow starting position based on style and format node labelAlign node name in Tikz