Solved

c# small array

Posted on 2011-09-27
7
227 Views
Last Modified: 2013-12-17
I want an array that is 4 elements long.  I want to have a function where I can add the item to the beginning of the array.  If it exists in the array, remove it from where it is, and add it to the beginning.

array in beginning
cat
dog
llama
tiger

add llama becomes
llama
cat
dog
tiger

add bird
bird
llama
cat
dog
0
Comment
Question by:jackjohnson44
  • 3
  • 2
  • 2
7 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
ID: 36713271
You might find working with a List a tad easier. You can even pass your array in as data and get an array back. For example:

string[] myArr = { "cat", "dog", "llama", "tiger" };
System.Collections.Generic.List<string> myList = new System.Collections.Generic.List<string>(myArr);

string newAnimal = "llama";

if (myList.Contains(newAnimal))
{
    myList.Remove(newAnimal);
    myList.Insert(0, newAnimal);
}
else
{
    myList.RemoveAt(myList.Count - 1);
    myList.Insert(0, newAnimal);
}

myArr = myList.ToArray();

Open in new window


Putting that into a function, you might have:

static string[] InsertAnimal(string animal, string[] animals)
{
    System.Collections.Generic.List<string> myList = new System.Collections.Generic.List<string>(animals);

    if (myList.Contains(animal))
    {
        myList.Remove(animal);
        myList.Insert(0, animal);
    }
    else
    {
        myList.RemoveAt(myList.Count - 1);
        myList.Insert(0, animal);
    }

    return myList.ToArray();
}

Open in new window


If you'd rather avoid the List, then you could do something like:

static string[] InsertAnimal(string animal, string[] animals)
{
    int i = 0;

    // Loop through animals looking for existing occurrence
    for (; i < animals.Length; i++)
    {
        // If we find an existing animal, shift
        //   everything to the right and insert
        //   the new animal at the beginning.
        if (animals[i] == animal)
        {
            for (int j = i; j > 0; j--)
            {
                animals[j] = animals[j - 1];
            }

            animals[0] = animal;
            break;
        }
    }

    // If i is the length of the array, then we didn't find an
    //  existing occurrence, so shift everything to the right;
    //  then insert the new animal at the beginning.
    if (i == animals.Length)
    {
        for (i = animals.Length - 1; i > 0 ; i--)
        {
            animals[i] = animals[i - 1];
        }

        animals[0] = animal;
    }

    return animals;
}

Open in new window

0
 

Expert Comment

by:ezdrt
ID: 36713609
Check out this website
Lists
http://www.dotnetperls.com/list

ArrayList
http://www.dotnetperls.com/arraylist

very good resource

i agree with kaufmed, use a list or arraylist, it would be easier

0
 
LVL 29

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 250 total points
ID: 36713622
OK, I also have some code including testing code.

Output:
bear
cat
dog
llama
==============
llama
bear
cat
dog
==============
cat
llama
bear
dog
==============
cat
llama
bear
dog
==============
private void printArray(string[] arr)
        {
            foreach (string s in arr)
            {
                System.Diagnostics.Debug.WriteLine(s);
            }
            System.Diagnostics.Debug.WriteLine("==============");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string[] myArr = {"cat","dog","llama","tiger"};
            string newStr = "bear";
            myArr = addToBeginning(myArr, newStr);
            printArray(myArr);
            newStr = "llama";
            myArr = addToBeginning(myArr, newStr);
            printArray(myArr);
            newStr = "cat";
            myArr = addToBeginning(myArr, newStr);
            printArray(myArr);
            newStr = "cat";
            myArr = addToBeginning(myArr, newStr);
            printArray(myArr);
        }

        private string[] addToBeginning(string[] arr, string str)
        {
            int foundIndex = -1;// index of a searched entry
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == str)
                    foundIndex = i;
            }
            int shiftIndex = -1;// index to what we shift array elements
            if (foundIndex >= 0)
                shiftIndex = foundIndex - 1;
            else
                shiftIndex =  arr.Length - 2;

            for (int j = shiftIndex; j >= 0; j--)
            {
                arr[j + 1] = arr[j];
            }
            arr[0] = str;
            return arr;
        }

Open in new window

0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 36713630
About lists here. These arrays are very short. Lists have quite big overhead. Does not really think lists have any benefits here. And not really simpler in this specific scenario!
Don'r stone me! :)
0
 

Expert Comment

by:ezdrt
ID: 36713653
well what if he one day decides to expand his software to include all the animals in the world? Like a noahs arc program ;) Lists!
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 36713715
Pls don't take mosquito on the ark! :)
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 36713849
Lists have quite big overhead. Does not really think lists have any benefits here. And not really simpler in this specific scenario!
True, there is more overhead with a list, but the benefit here is ease of understanding. Lines like

myList.Remove(animal);
myList.Insert(0, animal);

are more intuitive/readable than lines like:

for (; i < animals.Length; i++)
{
    // If we find an existing animal, shift
    //   everything to the right and insert
    //   the new animal at the beginning.
    if (animals[i] == animal)
    {
        for (int j = i; j > 0; j--)
        {
            animals[j] = animals[j - 1];
        }

        animals[0] = animal;
        break;
    }
}

Open in new window


The benefit is self-documentation and code simplicity = )
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Delivering innovative fully-managed cloud services for mission-critical applications requires expertise in multiple areas plus vision and commitment. Meet a few of the people behind the quality services of Concerto.

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now