• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by DarkSlash · Aug 05, 2015 at 07:59 PM · c#arrayarraysalgorithm

Check times a value is next to the same value in an array

Lets say I have this array on C#:

int myList = {1,4,6,8,3,3,3,3,8,9,0}

I want to know if a value (lets say from 0-9) is next to itself in the list and how many times. In this case, the value 3 is next to itself and it has 4 repetitions. If I have a list {0,1,2,3,4,5,5,6,7} the value 5 is next to itself and has 2 repetitions.

Repetitions have a limit of 5. No value can be repeated more than 5 times. The far I went is making if statements, but I know there's a better way of doing it.

Comment
NeverHopeless

People who like this

1 Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image fafase · Aug 05, 2015 at 08:45 PM 0
Share

You need more constrains or it will break. For instance, your first example, 3 is next to itself, ok. What about the last one? Isn't it next to 8? Also, what is next? Is it before or after?

4 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by cjdev · Aug 05, 2015 at 09:08 PM

You could use a function like this:

 public int GetRepetitions(int[] myList, int value)
 {
     int repetitions = 0;
     for (int i = 0; i < myList.Length; i++)
     {
         if ((myList[i] == value) && ((i == 0 ? false : myList[i - 1] == value) ||
              (i == myList.Length - 1 ? false : myList[i+1] == value)))
         {
             repetitions++;
         }
     }
     return repetitions;
 }

In case you haven't seen it, the a ? b : c operator just means if a then b else c.

Edit: hehe, too slow, either will work.

Comment
DarkSlash

People who like this

1 Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DarkSlash · Aug 05, 2015 at 09:27 PM 0
Share

This doesn't work well if the list is {1,2,3,3,4,5,6,3,3,3} it prints 5 when it should print or 2 or 3.

Nevertheless I think I can change to make it work as I need! THANK YOU!!!

Can you explain me better the if? it checks the previous value if not the first and the next value if not the last?

avatar image cjdev · Aug 05, 2015 at 09:46 PM 0
Share

The ? : thing is called a ternary operator. Basically it's just an inline if then else statement, so if the first part before the question mark is true then you use the statement on the left of the colon, otherwise you use the statement on the right of the colon if it's false.

avatar image DarkSlash · Aug 05, 2015 at 09:48 PM 0
Share

I know the ?, just the if, but i get it! Thanks! :)

avatar image

Answer by IgorAherne · Aug 05, 2015 at 08:59 PM

basic forloop will do

 using System;

 void Start(){
     int[] myArray = new int[]{1,1,1,3,3,3,3};
     Debug.Log(howManyRepetitionsAfterFirstOccurance(ref myArray, 3) );
 }


 int howManyRepetitionsAfterFirstOccurance(ref int[] array2Inspect, int value2Check){ //pass array by reference (don't copy it over, just point your finger at the one to work with
    startingPos = Array.IndexOf(array2Inspect, value2Check) //get the index of the first occurance of the number you need
    int repetitions = 0;

       for(int i = startingPos; i < array2Inspect.Length; i++){  //see if its present once or more in the array
         int value_at_cell = array2Inspect[ i ];      

         if (startingPos == -1 ||  value_at_cell != value2Check) break;

         repetitions++;
    }


    return  repetitions;
 }

Comment

People who like this

0 Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image DarkSlash · Aug 05, 2015 at 09:03 PM 0
Share

Thanks! That should work in the case the list isn't something like {3,1,2,3,3,3,3,3} how do you fix that?

avatar image NoseKills · Aug 05, 2015 at 09:15 PM 0
Share

To "fix" that you'd first need to design how you want it to work in that case. Return the length of the longest set, last set, first found, length of all sets combined ...

avatar image IgorAherne · Aug 05, 2015 at 09:18 PM 0
Share

return 0 if the startingPos is not -1

iterate through the array starting from the startingPos and keep bumping the number of repetitions. If suddenly the value does not equal to the one you wanted, then the repetition has ended.

Store this accumulated result in a biggestRepetitions if it is smaller than the current repetitions. reset repetitions back to zero keep going until you reach the end of the array and return biggestRepetitions.

avatar image

Answer by NoseKills · Aug 05, 2015 at 09:58 PM

Already answered, but i'll just leave this here for fun :)

 void countNumber(int[] array, int value, out int longest, out int cumulative, out int first, out int last)
 {
     cumulative = longest = first = last = 0;
 
     int lastIndex = array.Length - 1;
     int currentStreak = 1;
     bool wasMatch = false;
 
     for(int i = 0; i <= lastIndex; i++)
     {  
         bool isMatch = array[i] == value;
 
         if (wasMatch)
         {
             if (isMatch)
             {
                 currentStreak++;
             }
 
             bool endOfStreak = !isMatch || i == lastIndex;
 
             if (endOfStreak && currentStreak > 1)
             {
                 if (currentStreak > longest) longest = currentStreak;
 
                 if (first == 0) first = currentStreak;
 
                 last = currentStreak;
                 cumulative += currentStreak;
                 currentStreak = 1;
             }
         }
         wasMatch = isMatch;
     }
 }
Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image

Answer by NeverHopeless · Aug 05, 2015 at 10:09 PM

I have this solution which can pick the consecutive repeated elements (even if they are repeated itself too).

e.g., cases like:

{ 1, 4, 3, 6, 6, 8, 3, 3, 3, 3, 8, 9, 0 }; // Here 6 and 3 are repeated

{ 1, 4, 3, 3, 6, 6, 8, 3, 3, 3, 3, 8, 9, 0 }; // Here 6 repeated once and 3 repeated twice

Sample Code:

 int[] myList = new int[] { 1, 4, 3, 3, 6, 6, 8, 3, 3, 3, 3, 8, 9, 0 };
 Dictionary<int, List<int>> groupDict = new Dictionary<int, List<int>>();
 string characters = string.Join("", myList.ToArray());
 
 for (int i = 0; i < characters.Length; i++)
 {
     int cInt = int.Parse(characters[i].ToString());
     MatchCollection mColl = Regex.Matches(characters.Substring(i), "^" + characters[i] + "{2,}");
     if (mColl.Count > 0)
     {
            if (!groupDict.Keys.Contains(cInt))
            {
                 groupDict.Add(cInt, new List<int>());
            }
 
            groupDict[cInt].Add(mColl[0].Length);
            i += mColl[0].Length - 1;
           }
      }
  }

For first case it will show you: (in-memory result)

 6 -> 2
 3 -> 4

For second case it will show you: (in-memory result)

 6 -> 2
 3 -> 2, 4


Hope it is useful for you.

Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Update about the future of Unity Answers

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta later in June. Please note, we are aiming to set Unity Answers to read-only mode on the 31st of May in order to prepare for the final data migration.

For more information, please read our full announcement.

Follow this Question

Answers Answers and Comments

26 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Conceptual Question on Creating Arrays at Runtime 1 Answer

Array not updating in inspector 0 Answers

Array index is out of range 0 Answers

Inspector Doesn't Update Array Elements When Updated In Array Constructor 1 Answer

Null reference when editing an array in a for loop 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges