Solved

c# small array

Posted on 2011-09-27
7
229 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
MIM Survival Guide for Service Desk Managers

Major incidents can send mastered service desk processes into disorder. Systems and tools produce the data needed to resolve these incidents, but your challenge is getting that information to the right people fast. Check out the Survival Guide and begin bringing order to chaos.

 
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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
SQL Help 27 57
VB.NET 2008 Winforms Signing 13 33
SSIS On fail action 5 38
How to repeat the data 4 20
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

820 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