Solved

c# small array

Posted on 2011-09-27
7
226 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 74

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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 74

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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
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…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

746 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

12 Experts available now in Live!

Get 1:1 Help Now