Arrays of Int arrays. Storing duplicates in order only











up vote
9
down vote

favorite
1












I need to store an array of Int array for ordered duplicates (which are in a Array).



Example:




  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]


Now i need to create a 2D array of int Array.

Example:



Array  = [
[7, 7],
[3],
[2, 2, 2],
[1],
[7],
[5, 5]
]


Here is what I have:



for var i = 0; i < val.count; i++ {
var columnArray = Array<Int>()
for var j in 0...9 {
if oldNum == val[j]{
columnArray.append(val[j])
}
else {
array.append(columnArray);
//j += 1
break;
}
oldNum = val[j];
j += 1
}
}









share|improve this question




















  • 1




    I like how the question is asked. Little text and straight to the point.
    – Eendje
    Feb 11 '16 at 0:32










  • Note that the OP doesn't want an array of uniques as most answers (me included) are trying to do.
    – Eendje
    Feb 11 '16 at 1:04















up vote
9
down vote

favorite
1












I need to store an array of Int array for ordered duplicates (which are in a Array).



Example:




  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]


Now i need to create a 2D array of int Array.

Example:



Array  = [
[7, 7],
[3],
[2, 2, 2],
[1],
[7],
[5, 5]
]


Here is what I have:



for var i = 0; i < val.count; i++ {
var columnArray = Array<Int>()
for var j in 0...9 {
if oldNum == val[j]{
columnArray.append(val[j])
}
else {
array.append(columnArray);
//j += 1
break;
}
oldNum = val[j];
j += 1
}
}









share|improve this question




















  • 1




    I like how the question is asked. Little text and straight to the point.
    – Eendje
    Feb 11 '16 at 0:32










  • Note that the OP doesn't want an array of uniques as most answers (me included) are trying to do.
    – Eendje
    Feb 11 '16 at 1:04













up vote
9
down vote

favorite
1









up vote
9
down vote

favorite
1






1





I need to store an array of Int array for ordered duplicates (which are in a Array).



Example:




  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]


Now i need to create a 2D array of int Array.

Example:



Array  = [
[7, 7],
[3],
[2, 2, 2],
[1],
[7],
[5, 5]
]


Here is what I have:



for var i = 0; i < val.count; i++ {
var columnArray = Array<Int>()
for var j in 0...9 {
if oldNum == val[j]{
columnArray.append(val[j])
}
else {
array.append(columnArray);
//j += 1
break;
}
oldNum = val[j];
j += 1
}
}









share|improve this question















I need to store an array of Int array for ordered duplicates (which are in a Array).



Example:




  • Given array:
    mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]


Now i need to create a 2D array of int Array.

Example:



Array  = [
[7, 7],
[3],
[2, 2, 2],
[1],
[7],
[5, 5]
]


Here is what I have:



for var i = 0; i < val.count; i++ {
var columnArray = Array<Int>()
for var j in 0...9 {
if oldNum == val[j]{
columnArray.append(val[j])
}
else {
array.append(columnArray);
//j += 1
break;
}
oldNum = val[j];
j += 1
}
}






ios arrays swift algorithm






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 10 '17 at 21:40

























asked Feb 11 '16 at 0:02









Shank

821519




821519








  • 1




    I like how the question is asked. Little text and straight to the point.
    – Eendje
    Feb 11 '16 at 0:32










  • Note that the OP doesn't want an array of uniques as most answers (me included) are trying to do.
    – Eendje
    Feb 11 '16 at 1:04














  • 1




    I like how the question is asked. Little text and straight to the point.
    – Eendje
    Feb 11 '16 at 0:32










  • Note that the OP doesn't want an array of uniques as most answers (me included) are trying to do.
    – Eendje
    Feb 11 '16 at 1:04








1




1




I like how the question is asked. Little text and straight to the point.
– Eendje
Feb 11 '16 at 0:32




I like how the question is asked. Little text and straight to the point.
– Eendje
Feb 11 '16 at 0:32












Note that the OP doesn't want an array of uniques as most answers (me included) are trying to do.
– Eendje
Feb 11 '16 at 1:04




Note that the OP doesn't want an array of uniques as most answers (me included) are trying to do.
– Eendje
Feb 11 '16 at 1:04












6 Answers
6






active

oldest

votes

















up vote
8
down vote



accepted










You can use the reduce method.



let result = numbers.reduce([[Int]]()) { (var result, num) -> [[Int]] in
if var lastSequence = result.last where lastSequence.first == num {
result[result.count-1].append(num)
} else {
result.append([num])
}
return result
}


How does the reduce work?



reduce does apply the logic in the closure to an empty 2D array of integers ([[Int]]) and the first elm of numbers.



Then it is applied again to the result of the previous iteration and the second array of integers... and so on.



What does happen in the closure?



The if does check whether the number in the last array added to the result is equals to the integer currently examined. If so that integer is added to that array.



Otherwise a new array containing only the new integer is added to the result.



Test



[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





share|improve this answer



















  • 1




    Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
    – Eendje
    Feb 11 '16 at 0:45










  • @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
    – Luca Angeletti
    Feb 11 '16 at 0:48












  • A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
    – Eendje
    Feb 11 '16 at 0:51










  • @Eendje: yep I am reading it now, thanks!
    – Luca Angeletti
    Feb 11 '16 at 0:51






  • 1




    Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
    – Eendje
    Feb 11 '16 at 1:00




















up vote
2
down vote













Another approach extending collections where elements are equatable



extension Collection where Element: Equatable {
var grouped: [[Element]] {
var result: [[Element]] =
for element in self {
if element == result.last?.last {
result[result.index(before: result.endIndex)].append(element)
} else {
result.append([element])
}
}
return result
}
}




let array = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

array.grouped // [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





share|improve this answer






























    up vote
    1
    down vote













    This is a programming logic problem problem. Your current code is totally wrong.



    Here's one way you could solve it:



    Start out by sorting your starting array. call that inputArray.



    Create new, empty output "outerArray" and "innerArray" variables. Then loop through the entries in inputArray, testing for changes in value. If the value is the same as the last value, add that value to "innerArray". If the value has changed, save the previous innerArray to the outerArray and create a new, empty array and save it to innerArray.






    share|improve this answer




























      up vote
      1
      down vote













      The following code will give you what you need...



      let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
      var newArray: [[Int]] =

      for var i=0; i < mainArray.count; i++ {
      let element = mainArray[i]
      if mainArray.indexOf(element) == i {
      var subArray = mainArray.filter({ $0 == element })
      newArray.append(subArray)
      }
      }

      print(newArray) // -> [[7, 7, 7], [3], [2, 2, 2], [1], [5, 5]]





      share|improve this answer




























        up vote
        1
        down vote













        Here's the most boring iterative answer I can imagine. On the other hand it's easy to understand and doesn't suffer from potential complexity problems like reduce based solutions allegedly do:



        var result: [[Int]] = 
        var inner: [Int] =

        for i in mainArray {
        if i == inner.last {
        inner.append(i)
        } else {
        result.append(inner)
        inner = [i]
        }
        }
        result.append(inner)
        // result == [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





        share|improve this answer




























          up vote
          1
          down vote













          You can use the forEach and keep the value of the last element to keep adding to your array while it's not different like in this way:



          let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

          func filterTo2DArray(list: [Int] ) -> [[Int]] {

          var resultList = [[Int]]()

          list.forEach { x -> () in
          if let lastValue = resultList.last?.last where lastValue == x {
          resultList[resultList.count - 1].append(x)
          }
          else{
          resultList.append([x])
          }
          }
          return resultList
          }


          let t = filterTo2DArray(mainArray) //[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]


          I hope this help you.






          share|improve this answer























          • Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
            – Luca Angeletti
            Feb 11 '16 at 15:22










          • Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
            – Victor Sigler
            Feb 11 '16 at 15:40











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          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',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          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%2fstackoverflow.com%2fquestions%2f35328405%2farrays-of-int-arrays-storing-duplicates-in-order-only%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          8
          down vote



          accepted










          You can use the reduce method.



          let result = numbers.reduce([[Int]]()) { (var result, num) -> [[Int]] in
          if var lastSequence = result.last where lastSequence.first == num {
          result[result.count-1].append(num)
          } else {
          result.append([num])
          }
          return result
          }


          How does the reduce work?



          reduce does apply the logic in the closure to an empty 2D array of integers ([[Int]]) and the first elm of numbers.



          Then it is applied again to the result of the previous iteration and the second array of integers... and so on.



          What does happen in the closure?



          The if does check whether the number in the last array added to the result is equals to the integer currently examined. If so that integer is added to that array.



          Otherwise a new array containing only the new integer is added to the result.



          Test



          [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





          share|improve this answer



















          • 1




            Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
            – Eendje
            Feb 11 '16 at 0:45










          • @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
            – Luca Angeletti
            Feb 11 '16 at 0:48












          • A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
            – Eendje
            Feb 11 '16 at 0:51










          • @Eendje: yep I am reading it now, thanks!
            – Luca Angeletti
            Feb 11 '16 at 0:51






          • 1




            Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
            – Eendje
            Feb 11 '16 at 1:00

















          up vote
          8
          down vote



          accepted










          You can use the reduce method.



          let result = numbers.reduce([[Int]]()) { (var result, num) -> [[Int]] in
          if var lastSequence = result.last where lastSequence.first == num {
          result[result.count-1].append(num)
          } else {
          result.append([num])
          }
          return result
          }


          How does the reduce work?



          reduce does apply the logic in the closure to an empty 2D array of integers ([[Int]]) and the first elm of numbers.



          Then it is applied again to the result of the previous iteration and the second array of integers... and so on.



          What does happen in the closure?



          The if does check whether the number in the last array added to the result is equals to the integer currently examined. If so that integer is added to that array.



          Otherwise a new array containing only the new integer is added to the result.



          Test



          [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





          share|improve this answer



















          • 1




            Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
            – Eendje
            Feb 11 '16 at 0:45










          • @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
            – Luca Angeletti
            Feb 11 '16 at 0:48












          • A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
            – Eendje
            Feb 11 '16 at 0:51










          • @Eendje: yep I am reading it now, thanks!
            – Luca Angeletti
            Feb 11 '16 at 0:51






          • 1




            Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
            – Eendje
            Feb 11 '16 at 1:00















          up vote
          8
          down vote



          accepted







          up vote
          8
          down vote



          accepted






          You can use the reduce method.



          let result = numbers.reduce([[Int]]()) { (var result, num) -> [[Int]] in
          if var lastSequence = result.last where lastSequence.first == num {
          result[result.count-1].append(num)
          } else {
          result.append([num])
          }
          return result
          }


          How does the reduce work?



          reduce does apply the logic in the closure to an empty 2D array of integers ([[Int]]) and the first elm of numbers.



          Then it is applied again to the result of the previous iteration and the second array of integers... and so on.



          What does happen in the closure?



          The if does check whether the number in the last array added to the result is equals to the integer currently examined. If so that integer is added to that array.



          Otherwise a new array containing only the new integer is added to the result.



          Test



          [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





          share|improve this answer














          You can use the reduce method.



          let result = numbers.reduce([[Int]]()) { (var result, num) -> [[Int]] in
          if var lastSequence = result.last where lastSequence.first == num {
          result[result.count-1].append(num)
          } else {
          result.append([num])
          }
          return result
          }


          How does the reduce work?



          reduce does apply the logic in the closure to an empty 2D array of integers ([[Int]]) and the first elm of numbers.



          Then it is applied again to the result of the previous iteration and the second array of integers... and so on.



          What does happen in the closure?



          The if does check whether the number in the last array added to the result is equals to the integer currently examined. If so that integer is added to that array.



          Otherwise a new array containing only the new integer is added to the result.



          Test



          [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Feb 11 '16 at 9:26

























          answered Feb 11 '16 at 0:43









          Luca Angeletti

          39.9k565115




          39.9k565115








          • 1




            Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
            – Eendje
            Feb 11 '16 at 0:45










          • @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
            – Luca Angeletti
            Feb 11 '16 at 0:48












          • A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
            – Eendje
            Feb 11 '16 at 0:51










          • @Eendje: yep I am reading it now, thanks!
            – Luca Angeletti
            Feb 11 '16 at 0:51






          • 1




            Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
            – Eendje
            Feb 11 '16 at 1:00
















          • 1




            Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
            – Eendje
            Feb 11 '16 at 0:45










          • @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
            – Luca Angeletti
            Feb 11 '16 at 0:48












          • A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
            – Eendje
            Feb 11 '16 at 0:51










          • @Eendje: yep I am reading it now, thanks!
            – Luca Angeletti
            Feb 11 '16 at 0:51






          • 1




            Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
            – Eendje
            Feb 11 '16 at 1:00










          1




          1




          Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
          – Eendje
          Feb 11 '16 at 0:45




          Heh @appzYourLife, seems you love reduce :) Like I last said, creating arrays / dictionary will decrease the performance greatly. (anyway I wanted to ask the link of your question about reduce the last time :).
          – Eendje
          Feb 11 '16 at 0:45












          @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
          – Luca Angeletti
          Feb 11 '16 at 0:48






          @Eendje: ahah :D I really like Functional Programming indeed! This is the question about the reduce
          – Luca Angeletti
          Feb 11 '16 at 0:48














          A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
          – Eendje
          Feb 11 '16 at 0:51




          A very interesting read! Also you might want to read the link I've posted in my answer about creating arrays / dictionaries with reduce :p
          – Eendje
          Feb 11 '16 at 0:51












          @Eendje: yep I am reading it now, thanks!
          – Luca Angeletti
          Feb 11 '16 at 0:51




          @Eendje: yep I am reading it now, thanks!
          – Luca Angeletti
          Feb 11 '16 at 0:51




          1




          1




          Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
          – Eendje
          Feb 11 '16 at 1:00






          Seems like this is the only answer that gives the result OP wants. +1 from me. The others made the same mistake I did. Gotta find a way to make it a one liner! :)
          – Eendje
          Feb 11 '16 at 1:00














          up vote
          2
          down vote













          Another approach extending collections where elements are equatable



          extension Collection where Element: Equatable {
          var grouped: [[Element]] {
          var result: [[Element]] =
          for element in self {
          if element == result.last?.last {
          result[result.index(before: result.endIndex)].append(element)
          } else {
          result.append([element])
          }
          }
          return result
          }
          }




          let array = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

          array.grouped // [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





          share|improve this answer



























            up vote
            2
            down vote













            Another approach extending collections where elements are equatable



            extension Collection where Element: Equatable {
            var grouped: [[Element]] {
            var result: [[Element]] =
            for element in self {
            if element == result.last?.last {
            result[result.index(before: result.endIndex)].append(element)
            } else {
            result.append([element])
            }
            }
            return result
            }
            }




            let array = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

            array.grouped // [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





            share|improve this answer

























              up vote
              2
              down vote










              up vote
              2
              down vote









              Another approach extending collections where elements are equatable



              extension Collection where Element: Equatable {
              var grouped: [[Element]] {
              var result: [[Element]] =
              for element in self {
              if element == result.last?.last {
              result[result.index(before: result.endIndex)].append(element)
              } else {
              result.append([element])
              }
              }
              return result
              }
              }




              let array = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

              array.grouped // [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





              share|improve this answer














              Another approach extending collections where elements are equatable



              extension Collection where Element: Equatable {
              var grouped: [[Element]] {
              var result: [[Element]] =
              for element in self {
              if element == result.last?.last {
              result[result.index(before: result.endIndex)].append(element)
              } else {
              result.append([element])
              }
              }
              return result
              }
              }




              let array = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

              array.grouped // [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 21 at 22:21

























              answered Feb 11 '16 at 5:22









              Leo Dabus

              128k30261338




              128k30261338






















                  up vote
                  1
                  down vote













                  This is a programming logic problem problem. Your current code is totally wrong.



                  Here's one way you could solve it:



                  Start out by sorting your starting array. call that inputArray.



                  Create new, empty output "outerArray" and "innerArray" variables. Then loop through the entries in inputArray, testing for changes in value. If the value is the same as the last value, add that value to "innerArray". If the value has changed, save the previous innerArray to the outerArray and create a new, empty array and save it to innerArray.






                  share|improve this answer

























                    up vote
                    1
                    down vote













                    This is a programming logic problem problem. Your current code is totally wrong.



                    Here's one way you could solve it:



                    Start out by sorting your starting array. call that inputArray.



                    Create new, empty output "outerArray" and "innerArray" variables. Then loop through the entries in inputArray, testing for changes in value. If the value is the same as the last value, add that value to "innerArray". If the value has changed, save the previous innerArray to the outerArray and create a new, empty array and save it to innerArray.






                    share|improve this answer























                      up vote
                      1
                      down vote










                      up vote
                      1
                      down vote









                      This is a programming logic problem problem. Your current code is totally wrong.



                      Here's one way you could solve it:



                      Start out by sorting your starting array. call that inputArray.



                      Create new, empty output "outerArray" and "innerArray" variables. Then loop through the entries in inputArray, testing for changes in value. If the value is the same as the last value, add that value to "innerArray". If the value has changed, save the previous innerArray to the outerArray and create a new, empty array and save it to innerArray.






                      share|improve this answer












                      This is a programming logic problem problem. Your current code is totally wrong.



                      Here's one way you could solve it:



                      Start out by sorting your starting array. call that inputArray.



                      Create new, empty output "outerArray" and "innerArray" variables. Then loop through the entries in inputArray, testing for changes in value. If the value is the same as the last value, add that value to "innerArray". If the value has changed, save the previous innerArray to the outerArray and create a new, empty array and save it to innerArray.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Feb 11 '16 at 0:20









                      Duncan C

                      91.4k13114194




                      91.4k13114194






















                          up vote
                          1
                          down vote













                          The following code will give you what you need...



                          let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
                          var newArray: [[Int]] =

                          for var i=0; i < mainArray.count; i++ {
                          let element = mainArray[i]
                          if mainArray.indexOf(element) == i {
                          var subArray = mainArray.filter({ $0 == element })
                          newArray.append(subArray)
                          }
                          }

                          print(newArray) // -> [[7, 7, 7], [3], [2, 2, 2], [1], [5, 5]]





                          share|improve this answer

























                            up vote
                            1
                            down vote













                            The following code will give you what you need...



                            let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
                            var newArray: [[Int]] =

                            for var i=0; i < mainArray.count; i++ {
                            let element = mainArray[i]
                            if mainArray.indexOf(element) == i {
                            var subArray = mainArray.filter({ $0 == element })
                            newArray.append(subArray)
                            }
                            }

                            print(newArray) // -> [[7, 7, 7], [3], [2, 2, 2], [1], [5, 5]]





                            share|improve this answer























                              up vote
                              1
                              down vote










                              up vote
                              1
                              down vote









                              The following code will give you what you need...



                              let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
                              var newArray: [[Int]] =

                              for var i=0; i < mainArray.count; i++ {
                              let element = mainArray[i]
                              if mainArray.indexOf(element) == i {
                              var subArray = mainArray.filter({ $0 == element })
                              newArray.append(subArray)
                              }
                              }

                              print(newArray) // -> [[7, 7, 7], [3], [2, 2, 2], [1], [5, 5]]





                              share|improve this answer












                              The following code will give you what you need...



                              let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]
                              var newArray: [[Int]] =

                              for var i=0; i < mainArray.count; i++ {
                              let element = mainArray[i]
                              if mainArray.indexOf(element) == i {
                              var subArray = mainArray.filter({ $0 == element })
                              newArray.append(subArray)
                              }
                              }

                              print(newArray) // -> [[7, 7, 7], [3], [2, 2, 2], [1], [5, 5]]






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Feb 11 '16 at 0:28









                              Michael

                              7,49612036




                              7,49612036






















                                  up vote
                                  1
                                  down vote













                                  Here's the most boring iterative answer I can imagine. On the other hand it's easy to understand and doesn't suffer from potential complexity problems like reduce based solutions allegedly do:



                                  var result: [[Int]] = 
                                  var inner: [Int] =

                                  for i in mainArray {
                                  if i == inner.last {
                                  inner.append(i)
                                  } else {
                                  result.append(inner)
                                  inner = [i]
                                  }
                                  }
                                  result.append(inner)
                                  // result == [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





                                  share|improve this answer

























                                    up vote
                                    1
                                    down vote













                                    Here's the most boring iterative answer I can imagine. On the other hand it's easy to understand and doesn't suffer from potential complexity problems like reduce based solutions allegedly do:



                                    var result: [[Int]] = 
                                    var inner: [Int] =

                                    for i in mainArray {
                                    if i == inner.last {
                                    inner.append(i)
                                    } else {
                                    result.append(inner)
                                    inner = [i]
                                    }
                                    }
                                    result.append(inner)
                                    // result == [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





                                    share|improve this answer























                                      up vote
                                      1
                                      down vote










                                      up vote
                                      1
                                      down vote









                                      Here's the most boring iterative answer I can imagine. On the other hand it's easy to understand and doesn't suffer from potential complexity problems like reduce based solutions allegedly do:



                                      var result: [[Int]] = 
                                      var inner: [Int] =

                                      for i in mainArray {
                                      if i == inner.last {
                                      inner.append(i)
                                      } else {
                                      result.append(inner)
                                      inner = [i]
                                      }
                                      }
                                      result.append(inner)
                                      // result == [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]





                                      share|improve this answer












                                      Here's the most boring iterative answer I can imagine. On the other hand it's easy to understand and doesn't suffer from potential complexity problems like reduce based solutions allegedly do:



                                      var result: [[Int]] = 
                                      var inner: [Int] =

                                      for i in mainArray {
                                      if i == inner.last {
                                      inner.append(i)
                                      } else {
                                      result.append(inner)
                                      inner = [i]
                                      }
                                      }
                                      result.append(inner)
                                      // result == [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Feb 11 '16 at 3:34









                                      Michael Kohl

                                      56.9k10112138




                                      56.9k10112138






















                                          up vote
                                          1
                                          down vote













                                          You can use the forEach and keep the value of the last element to keep adding to your array while it's not different like in this way:



                                          let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

                                          func filterTo2DArray(list: [Int] ) -> [[Int]] {

                                          var resultList = [[Int]]()

                                          list.forEach { x -> () in
                                          if let lastValue = resultList.last?.last where lastValue == x {
                                          resultList[resultList.count - 1].append(x)
                                          }
                                          else{
                                          resultList.append([x])
                                          }
                                          }
                                          return resultList
                                          }


                                          let t = filterTo2DArray(mainArray) //[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]


                                          I hope this help you.






                                          share|improve this answer























                                          • Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
                                            – Luca Angeletti
                                            Feb 11 '16 at 15:22










                                          • Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
                                            – Victor Sigler
                                            Feb 11 '16 at 15:40















                                          up vote
                                          1
                                          down vote













                                          You can use the forEach and keep the value of the last element to keep adding to your array while it's not different like in this way:



                                          let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

                                          func filterTo2DArray(list: [Int] ) -> [[Int]] {

                                          var resultList = [[Int]]()

                                          list.forEach { x -> () in
                                          if let lastValue = resultList.last?.last where lastValue == x {
                                          resultList[resultList.count - 1].append(x)
                                          }
                                          else{
                                          resultList.append([x])
                                          }
                                          }
                                          return resultList
                                          }


                                          let t = filterTo2DArray(mainArray) //[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]


                                          I hope this help you.






                                          share|improve this answer























                                          • Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
                                            – Luca Angeletti
                                            Feb 11 '16 at 15:22










                                          • Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
                                            – Victor Sigler
                                            Feb 11 '16 at 15:40













                                          up vote
                                          1
                                          down vote










                                          up vote
                                          1
                                          down vote









                                          You can use the forEach and keep the value of the last element to keep adding to your array while it's not different like in this way:



                                          let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

                                          func filterTo2DArray(list: [Int] ) -> [[Int]] {

                                          var resultList = [[Int]]()

                                          list.forEach { x -> () in
                                          if let lastValue = resultList.last?.last where lastValue == x {
                                          resultList[resultList.count - 1].append(x)
                                          }
                                          else{
                                          resultList.append([x])
                                          }
                                          }
                                          return resultList
                                          }


                                          let t = filterTo2DArray(mainArray) //[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]


                                          I hope this help you.






                                          share|improve this answer














                                          You can use the forEach and keep the value of the last element to keep adding to your array while it's not different like in this way:



                                          let mainArray = [7, 7, 3, 2, 2, 2, 1, 7, 5, 5]

                                          func filterTo2DArray(list: [Int] ) -> [[Int]] {

                                          var resultList = [[Int]]()

                                          list.forEach { x -> () in
                                          if let lastValue = resultList.last?.last where lastValue == x {
                                          resultList[resultList.count - 1].append(x)
                                          }
                                          else{
                                          resultList.append([x])
                                          }
                                          }
                                          return resultList
                                          }


                                          let t = filterTo2DArray(mainArray) //[[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]]


                                          I hope this help you.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Feb 11 '16 at 15:38

























                                          answered Feb 11 '16 at 0:35









                                          Victor Sigler

                                          17.9k86687




                                          17.9k86687












                                          • Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
                                            – Luca Angeletti
                                            Feb 11 '16 at 15:22










                                          • Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
                                            – Victor Sigler
                                            Feb 11 '16 at 15:40


















                                          • Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
                                            – Luca Angeletti
                                            Feb 11 '16 at 15:22










                                          • Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
                                            – Victor Sigler
                                            Feb 11 '16 at 15:40
















                                          Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
                                          – Luca Angeletti
                                          Feb 11 '16 at 15:22




                                          Only adjacent values with the same value should be grouped. Given the provided test input, the output should be [[7, 7], [3], [2, 2, 2], [1], [7], [5, 5]] as indicated in the OP.
                                          – Luca Angeletti
                                          Feb 11 '16 at 15:22












                                          Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
                                          – Victor Sigler
                                          Feb 11 '16 at 15:40




                                          Uhmm @appzYourLife Yes you're right my mistake I misunderstood the question I fixed now, thanks
                                          – Victor Sigler
                                          Feb 11 '16 at 15:40


















                                          draft saved

                                          draft discarded




















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • 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.


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





                                          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                          Please pay close attention to the following guidance:


                                          • 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.


                                          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%2fstackoverflow.com%2fquestions%2f35328405%2farrays-of-int-arrays-storing-duplicates-in-order-only%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

                                          Contact image not getting when fetch all contact list from iPhone by CNContact

                                          count number of partitions of a set with n elements into k subsets

                                          A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks