sorted list and shifting

Hi;

This is a .net question but i also added in java section.

I have a sorted list that can contain some values in it (integer values) and i have a content; 2,3,1 which i tokenize.

my aim is that i want to validate the content against sortedlist values.

E.g.

If sorted list has the following values:
2
Then it is a valid value according to content as the content starts with 2

If sorted list has the following values:
2, 3
Then it is a valid value according to content as the content starts with 2 and continue with 3

If sorted list has the following values:
2, 1
Then it is NOT a valid value according to content as the content starts with 2 but does not continue with 1

If sorted list has the following values:
3
Then it is NOT a valid value according to content as the content does NOT start with 3

I tried to do that but i think i couldn't make up the logic, can you help me?

    public bool validateOrder()
    {
        if(SortedList.Count > 0)
        {
            string templateOrder = GetNodeValue("/behavior/order"); // content
            string [] orders = templateOrder.Split(',');

         
                foreach (var i in SortedList)
                {
                    foreach (var order in orders)
                    {
                        if (int.Parse(order) != i.Value)
                            return false;
                    }
                }
                return true;
            }
            return true;                
    }

Open in new window


Br.
LVL 12
jazzIIIloveAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Hi jazzIIIlove;

Try the code like this to see if it gives you what you need.
public bool validateOrder()
{
    bool isvalid = false;

    if (SortedList.Count > 0)
    {
        string templateOrder = GetNodeValue("/behavior/order"); // content
        string[] orders = templateOrder.Split(',');

        for (int i = 0; i < orders.Count(); i++)
        {
            if (SortedList[i] == int.Parse(orders[i]))
            {
                isvalid = true;
            }
            else
            {
                isvalid = false;
                break;
            }
        }
    }
    return isvalid;
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
it_saigeDeveloperCommented:
Might I recommend using the SequenceEqual Enumerable method:
static class Extensions
{
	public static bool IsValidToken(this SortedList<string, int> source, string token)
	{
		bool result = true;
		try
		{
			int comparer = -1;
			var orders = token.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
			var values = (from order in orders where int.TryParse(order, out comparer) select comparer);
			result = source.Values.SequenceEqual(values);
		}
		catch (Exception)
		{
			result = false;
		}
		return result;
	}
}

Open in new window

Which could be condensed down to:
static class Extensions
{
	public static bool IsValidToken(this SortedList<string, int> source, string token)
	{
		bool result = true;
		try
		{
			int comparer = -1;
			result = source.Values.SequenceEqual((from order in token.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) where int.TryParse(order, out comparer) select comparer));
		}
		catch (Exception)
		{
			result = false;
		}
		return result;
	}
}

Open in new window

In either case the following tests show the expected output -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28717265
{
	class Program
	{
		static SortedList<string, int> values = new SortedList<string, int>() { { "A", 2 }, { "B", 3 }, { "C", 1 } };
		static void Main(string[] args)
		{
			string token1 = "ONE, 1, THREE, 3, TWO, 2";
			string token2 = "TWO, 2, ONE, 1, THREE, 3";
			string token3 = "TWO, 2, THREE, 3, ONE, 1";

			Console.WriteLine("Token 1 is valid? {0}", values.IsValidToken(token1));
			Console.WriteLine("Token 2 is valid? {0}", values.IsValidToken(token2));
			Console.WriteLine("Token 3 is valid? {0}", values.IsValidToken(token3));
			Console.ReadLine();
		}
	}

	static class Extensions
	{
		public static bool IsValidToken(this SortedList<string, int> source, string token)
		{
			bool result = true;
			try
			{
				int comparer = -1;
				result = source.Values.SequenceEqual((from order in token.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) where int.TryParse(order, out comparer) select comparer));
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-
MlandaTCommented:
This algorithm basically boils down to a StartsWith string comparison:
void Main()
{

	List<long> sorted = new List<long>() {2,3,1};
	List<long> compare = null;

	IsValid(sorted, new List<long>() {2,3,1});
	IsValid(sorted, new List<long>() {2});
	IsValid(sorted, new List<long>() {2,3});
	IsValid(sorted, new List<long>() {3});
	IsValid(sorted, new List<long>() {2,1});
	
}

bool IsValid(List<long> sorted, List<long> compare)
{
	string sorted_str = string.Join(@",", sorted.Select(l => l.ToString()).ToArray()) + ",";
	string compare_str = string.Join(@",", compare.Select(l => l.ToString()).ToArray()) + ",";
	
	bool result = sorted_str.StartsWith(compare_str);
	return result;
}

Open in new window

Which in LinqPad gives the output:LinqPad output
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

jazzIIIloveAuthor Commented:
Thanks. Your code sample is fine except for one thing. I fall into this exception, "the given key was not present in the dictionary."

I can suppress this error by an empty catch which i don't really prefer. How can we iterate this so that it can be robust?

Br.

Edit; oh there are too many comments now :)

Actually my comment was for the first expert.:)
Fernando SotoRetiredCommented:
Hi jazzIIIlove;;

In order to not exceed the number of values in the SortedList I placed an additional if statement. Try this version.
public bool validateOrder()
{
    bool isvalid = false;

    if (SortedList.Count > 0)
    {
        string templateOrder = GetNodeValue("/behavior/order"); // content
        string[] orders = templateOrder.Split(',');
        if (orders.Count() > SortedList.Count())
        {
            for (int i = 0; i < orders.Count(); i++)
            {
                if (SortedList[i] == int.Parse(orders[i]))
                {
                    isvalid = true;
                }
                else
                {
                    isvalid = false;
                    break;
                }
            }
        }
    }
    return isvalid;
}

Open in new window

it_saigeDeveloperCommented:
After reviewing your requirements with finer detail, I need to take into account one small detail (the difference in set sizes).  

The source set (the list) may only have 1 item.  So you want all tokens that match that one item as their starting value.  On the other hand, you may have a source set that has 5 items.  In this case, you want to include all tokens that have the same sequence up to the source size.

With that in mind, the extension method can be updated as such:
static class Extensions
{
	public static bool IsTokenValid(this SortedList<string, int> source, string token)
	{
		bool result = true;
		try
		{
			int comparer = -1;

			// Get the values to compare against in the SortedList from the token.
			var comparers = (from order in token.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) where int.TryParse(order, out comparer) select comparer);

			result = source.Values.Count() >= comparers.Count() ?
				// We take only the number of values from the source values that equal the number of values in the comparers values.
				(source.Values.Take(comparers.Count()).SequenceEqual(comparers)) :
				// We take only the number of values from the comparers values that equal the number of values in the source values.
				(comparers.Take(source.Values.Count()).SequenceEqual(source.Values));
		}
		catch (Exception)
		{
			result = false;
		}
		return result;
	}
}

Open in new window

Here is an example implementation -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28717265
{
	class Program
	{
		readonly static SortedList<string, int> setA = new SortedList<string, int>() { { "A", 2 }, { "B", 3 }, { "C", 1 } };
		readonly static SortedList<string, int> setB = new SortedList<string, int>() { { "A", 2 } };
		readonly static SortedList<string, int> setC = new SortedList<string, int>() { { "A", 2 }, { "B", 3 } };
		readonly static SortedList<string, int> setD = new SortedList<string, int>() { { "A", 3 } };
		readonly static SortedList<string, int> setE = new SortedList<string, int>() { { "A", 2 }, { "B", 1 } };
		readonly static SortedList<string, int> setF = new SortedList<string, int>() { { "A", 2 }, { "B", 3 }, { "C", 1 }, { "D", 4 } };

		readonly static List<string> tokens = new List<string>() 
		{ 
			"2,3,1", 
			"2,4",
			"2"
		};

		static void Main(string[] args)
		{
			TestTokens(setA);
			TestTokens(setB);
			TestTokens(setC);
			TestTokens(setD);
			TestTokens(setE);
			TestTokens(setF);
			Console.ReadLine();
		}

		static void TestTokens(SortedList<string, int> set)
		{
			Console.WriteLine("Getting matches for {{{0}}}", String.Join(",", Array.ConvertAll(set.Values.ToArray(), x => x.ToString())));
			var matches = (from token in tokens where set.IsTokenValid(token) select token);
			if (matches.Count() != 0)
			{
				foreach (var match in matches)
					Console.WriteLine("Token - {0}; matches.", match);
			}
			else
				Console.WriteLine("There are no matches for this set.");
			Console.WriteLine();
		}
	}

	static class Extensions
	{
		public static bool IsTokenValid(this SortedList<string, int> source, string token)
		{
			bool result = true;
			try
			{
				int comparer = -1;

				// Get the values to compare against in the SortedList from the token.
				var comparers = (from order in token.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) where int.TryParse(order, out comparer) select comparer);

				result = source.Values.Count() >= comparers.Count() ?
					// We take only the number of values from the source values that equal the number of values in the comparers values.
					(source.Values.Take(comparers.Count()).SequenceEqual(comparers)) :
					// We take only the number of values from the comparers values that equal the number of values in the source values.
					(comparers.Take(source.Values.Count()).SequenceEqual(source.Values));
			}
			catch (Exception)
			{
				result = false;
			}
			return result;
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-
jazzIIIloveAuthor Commented:
Oh.. what a lovely contribution. Just as in the old days of EE.

Best regards.
Fernando SotoRetiredCommented:
Have any of the post above answered you question?
jazzIIIloveAuthor Commented:
Sorry for delay guys
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.