?
Solved

c# small array

Posted on 2011-09-27
7
Medium Priority
?
233 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 1000 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 30

Assisted Solution

by:anarki_jimbel
anarki_jimbel earned 1000 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
Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

 
LVL 30

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 30

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

PowerShell Core for Advanced Linux Administrators

Understand advanced principals around Powershell Core with a focus on the Linux Administrator.  This course covers how to administer numerous environments across multiple platforms including Linux, Azure, AWS, and Google Cloud from a single shell instance.

Question has a verified solution.

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

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 aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
Suggested Courses

741 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