Solved

c# small array

Posted on 2011-09-27
7
228 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
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…

832 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