예제 #1
0
        public async Task <IContent> GetContent(string path, IList <MediaTypeHeaderValue>?acceptContentType)
        {
            Rule?rule = null;

            foreach (var r in rules)
            {
                if (path.EndsWith(r.NewExtension, StringComparison.InvariantCultureIgnoreCase))
                {
                    rule = r;
                }
            }

            if (rule == null)
            {
                return(await backend.GetContent(path, acceptContentType));
            }
            else if (rule.Transformer == null)
            {
                path = path.Substring(0, path.Length - rule.NewExtension.Length) + rule.OriginalExtension;
                return(await backend.GetContent(path, acceptContentType));
            }
            else
            {
                path = path.Substring(0, path.Length - rule.NewExtension.Length) + rule.OriginalExtension;
                var content = await backend.GetContent(path, acceptContentType);

                return(new TransformContent(content, rule.Transformer));
            }
        }
예제 #2
0
파일: Rule.cs 프로젝트: NoirFry/AoC2020
 public Rule(int n, Rule r1, Rule?r2, Rule?r3, Rule?r4)
 {
     number      = n;
     subRules[0] = r1;
     subRules[1] = r2;
     subRules[2] = r3;
     subRules[3] = r4;
 }
 private void CreateLocalCss()
 {
     localCheckCoverRule = new Rule
     {
         Selector = new ClassSelector() { SelectorName = "ms-DetailsRow-checkCover" },
         Properties = new CssString() { Css = $"position:absolute;top:-1px;left:0;bottom:0;right:0;display:{(AnySelected ? "block" : "none")};" }
     };
     DetailsRowLocalRules.Add(localCheckCoverRule);
 }
예제 #4
0
        public void run(string Course)
        {
            Rule?triggerRule = inferenceEngine.backwardChaining(workingMemory, workingRules, Course);

            BackwardOutput backwardOutput = new BackwardOutput();

            backwardOutput.updateEligible(triggerRule, Course);
            backwardOutput.Show();
        }
예제 #5
0
        public Rule GetRule(int number)
        {
            Rule?rule = GetRuleNullable(number);

            if (rule == null)
            {
                throw new InvalidOperationException("Rule at " + nameof(number) + " " + number + " was null.");
            }
            return(rule);
        }
        public string MapWeatherInfo(string location, WeatherInfo todayInfo, WeatherInfo yesterdayInfo)
        {
            if (string.IsNullOrEmpty(location) || !HasAnyValue(todayInfo) || !HasAnyValue(yesterdayInfo))
            {
                throw new ArgumentException("All properties must be set");
            }

            Rule?rule = GetRule(todayInfo, yesterdayInfo);

            //If no rules, we set default text
            return(rule != null?string.Format(rule.SuccessEvent, location, todayInfo.Temperature, yesterdayInfo.Temperature)
                       : $"Vejret i {location} er {todayInfo.Conditions} og der er {todayInfo.Temperature} grader. I går var det {yesterdayInfo.Conditions} og {yesterdayInfo.Temperature} grader.");
        }
예제 #7
0
        protected override void OnInitialized()
        {
            msTextRule = new Rule()
            {
                Selector = new ClassSelector()
                {
                    SelectorName = "ms-text"
                },
                Properties = CreateTextStyle()
            };
            CssRules.Add(msTextRule);

            base.OnInitialized();
        }
예제 #8
0
        //DissectChange

        /*
         * Defines a group of operators.
         */
        public Grammar GetOperators(params string[] args)
        {
            this.currentRule      = null;
            this.currentOperators = args;
            foreach (var op in args)
            {
                this.operators.Add(op, new Dictionary <string, int>()
                {
                    { "prec", 1 }, { "assoc", LEFT }
                });
            }

            return(this);
        }
예제 #9
0
            public List <Rule> ParseRuleList()
            {
                List <Rule> rules = new List <Rule>();

                while (true)
                {
                    Rule?rule = ParseRule();
                    if (rule == null)
                    {
                        break;
                    }
                    rules.Add(rule);
                }
                return(rules);
            }
예제 #10
0
        /*
         * Defines an alternative for a grammar rule.
         */
        public Grammar Is(params string[] args)
        {
            this.currentOperators = null;
            if (this.currentNonterminal == null)
            {
                throw new InvalidOperationException("You must specify a name of the rule first.");
            }

            int  num  = this.nextRuleNumber++;
            Rule rule = new Rule(num, this.currentNonterminal, args);

            this.Rules.Add(rule);
            this.currentRule = rule;
            this.GroupedRules.AddNewListIfNotContainsKeyAndAddValueToList(this.currentNonterminal, rule);
            return(this);
        }
        public override async Task <string?> OnSetPropertyValueAsync(string propertyName, string unevaluatedPropertyValue, IProjectProperties defaultProperties, IReadOnlyDictionary <string, string>?dimensionalConditions = null)
        {
            ConfiguredProject?configuredProject = await _project.GetSuggestedConfiguredProjectAsync();

            IPropertyPagesCatalogProvider?catalogProvider = configuredProject?.Services.PropertyPagesCatalog;

            if (catalogProvider == null)
            {
                return(null);
            }

            IPropertyPagesCatalog catalog = await catalogProvider.GetCatalogAsync(PropertyPageContexts.Project);

            Rule?rule = catalog.GetSchema(unevaluatedPropertyValue);

            if (rule == null)
            {
                return(null);
            }

            if (rule.Metadata.TryGetValue("CommandName", out object pageCommandNameObj) &&
                pageCommandNameObj is string pageCommandName)
            {
                _projectThreadingService.RunAndForget(async() =>
                {
                    // Infinite timeout means this will not actually be null.
                    ILaunchSettings?launchSettings = await _launchSettingsProvider.WaitForFirstSnapshot(Timeout.Infinite);
                    Assumes.NotNull(launchSettings);

                    IWritableLaunchSettings writableLaunchSettings = launchSettings.ToWritableLaunchSettings();
                    IWritableLaunchProfile?activeProfile           = writableLaunchSettings.ActiveProfile;
                    if (activeProfile != null)
                    {
                        activeProfile.CommandName = pageCommandName;

                        await _launchSettingsProvider.UpdateAndSaveSettingsAsync(writableLaunchSettings.ToLaunchSettings());
                    }
                },
                                                      options: ForkOptions.HideLocks,
                                                      unconfiguredProject: _project);
            }

            return(null);
        }
예제 #12
0
        public void updateEligible(Rule?triggeredRule, string course)
        {
            string output = "";

            if (triggeredRule != null)
            {
                output += "Yes, " + triggeredRule.Course + " is eligible for the Spring because rule" + triggeredRule.RuleNumber + " and" + Environment.NewLine +
                          "Semester is " + triggeredRule.Semester + Environment.NewLine;
                foreach (string req in triggeredRule.Requirements)
                {
                    output += req + " was passed" + Environment.NewLine;
                }
            }
            else
            {
                output += "No, " + course + " is eligible for the Spring since not all requirements met";
            }

            eligibleTextBox.Text = output;
        }
        private async Task <string> GetPropertyValueAsync()
        {
            // Infinite timeout means this will not actually be null.
            ILaunchSettings?launchSettings = await _launchSettingsProvider.WaitForFirstSnapshot(Timeout.Infinite);

            Assumes.NotNull(launchSettings);

            string?commandName = launchSettings.ActiveProfile?.CommandName;

            if (commandName == null)
            {
                return(string.Empty);
            }

            ConfiguredProject?configuredProject = await _project.GetSuggestedConfiguredProjectAsync();

            IPropertyPagesCatalogProvider?catalogProvider = configuredProject?.Services.PropertyPagesCatalog;

            if (catalogProvider == null)
            {
                return(string.Empty);
            }

            IPropertyPagesCatalog catalog = await catalogProvider.GetCatalogAsync(PropertyPageContexts.Project);

            foreach (string schemaName in catalog.GetPropertyPagesSchemas())
            {
                Rule?rule = catalog.GetSchema(schemaName);
                if (rule != null &&
                    string.Equals(rule.PageTemplate, "CommandNameBasedDebugger", StringComparison.OrdinalIgnoreCase) &&
                    rule.Metadata.TryGetValue("CommandName", out object pageCommandNameObj) &&
                    pageCommandNameObj is string pageCommandName &&
                    pageCommandName.Equals(commandName))
                {
                    return(schemaName);
                }
            }

            return(string.Empty);
        }
        public static IRule CreateFromRule(
            Rule?schema = null,
            IEnumerable <IProperty>?properties = null)
        {
            var rule = new Mock <IRule>();

            if (properties != null)
            {
                rule.Setup(o => o.GetProperty(It.IsAny <string>()))
                .Returns((string propertyName) =>
                {
                    return(properties.FirstOrDefault(p => p.Name == propertyName));
                });
            }

            if (schema != null)
            {
                rule.Setup(o => o.Schema)
                .Returns(schema);
            }

            return(rule.Object);
        }
예제 #15
0
        /// <summary>
        /// Asynchronously gets all rules registered with the bridge.
        /// </summary>
        /// <returns>An enumerable of <see cref="Rule"/>s registered with the bridge.</returns>
        public async Task <IReadOnlyCollection <Rule> > GetRulesAsync()
        {
            CheckInitialized();

            HttpClient client = await GetHttpClient().ConfigureAwait(false);

            string stringResult = await client.GetStringAsync(new Uri(String.Format("{0}rules", ApiBase))).ConfigureAwait(false);

//#if DEBUG
//			//stringResult = "{\"1\": {    \"name\": \"Wall Switch Rule\",    \"lasttriggered\": \"2013-10-17T01:23:20\",    \"creationtime\": \"2013-10-10T21:11:45\",    \"timestriggered\": 27,    \"owner\": \"78H56B12BA\",    \"status\": \"enabled\",    \"conditions\": [        {            \"address\": \"/sensors/2/state/buttonevent\",            \"operator\": \"eq\",            \"value\": \"16\"        },        {            \"address\": \"/sensors/2/state/lastupdated\",            \"operator\": \"dx\"        }    ],    \"actions\": [        {            \"address\": \"/groups/0/action\",            \"method\": \"PUT\",            \"body\": {                \"scene\": \"S3\"            }        }    ]} }";
//			stringResult = "{    \"29\": {        \"name\": \"MotionSensor 13.day-on\",        \"owner\": \"Ftg8b0E4NVk3vVpodvV-Nh-rg8q3XfB0sDUZv3Hy\",        \"created\": \"2016-10-15T12:01:33\",        \"lasttriggered\": \"2016-10-23T08:59:32\",        \"timestriggered\": 5,        \"status\": \"enabled\",        \"recycle\": true,        \"conditions\": [            {                \"address\": \"/config/localtime\",                \"operator\": \"in\",                \"value\": \"T08:00:00/T23:00:00\"            },            {                \"address\": \"/sensors/13/state/presence\",                \"operator\": \"eq\",                \"value\": \"true\"            },            {                \"address\": \"/sensors/13/state/presence\",                \"operator\": \"dx\"            },            {               \"address\": \"/sensors/15/state/status\",                \"operator\": \"lt\",                \"value\": \"1\"            },            {                \"address\": \"/sensors/14/state/dark\",                \"operator\": \"eq\",                \"value\": \"true\"            }        ],        \"actions\": [            {                \"address\": \"/groups/3/action\",                \"method\": \"PUT\",                \"body\": {                    \"scene\": \"kZvpr1yJTqvHyQA\"                }            },            {                \"address\": \"/sensors/15/state\",                \"method\": \"PUT\",                \"body\": {                    \"status\": 1                }            }        ]    }}";
//#endif


            List <Rule> results = new List <Rule>();

            JToken token = JToken.Parse(stringResult);

            if (token.Type == JTokenType.Object)
            {
                //Each property is a scene
                var jsonResult = (JObject)token;

                foreach (var prop in jsonResult.Properties())
                {
                    Rule?rule = JsonConvert.DeserializeObject <Rule>(prop.Value.ToString());
                    if (rule != null)
                    {
                        rule.Id = prop.Name;

                        results.Add(rule);
                    }
                }
            }

            return(results);
        }
예제 #16
0
 public ArgumentCollection(Rule?single)
 {
     Add(single !);
 }
        public void OnSetPropertyValue(string propertyName, string propertyValue, IWritableLaunchProfile launchProfile, ImmutableDictionary <string, object> globalSettings, Rule?rule)
        {
            switch (propertyName)
            {
            case AuthenticationModePropertyName:
                TrySetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteAuthenticationModeProperty, propertyValue, string.Empty);
                break;

            case NativeDebuggingPropertyName:
                TrySetOtherProperty(launchProfile, LaunchProfileExtensions.NativeDebuggingProperty, bool.Parse(propertyValue), false);
                break;

            case RemoteDebugEnabledPropertyName:
                TrySetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteDebugEnabledProperty, bool.Parse(propertyValue), false);
                break;

            case RemoteDebugMachinePropertyName:
                TrySetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteDebugMachineProperty, propertyValue, string.Empty);
                break;

            case SqlDebuggingPropertyName:
                TrySetOtherProperty(launchProfile, LaunchProfileExtensions.SqlDebuggingProperty, bool.Parse(propertyValue), false);
                break;

            default:
                throw new InvalidOperationException($"{nameof(ProjectLaunchProfileExtensionValueProvider)} does not handle property '{propertyName}'.");
            }
        }
        public string OnGetPropertyValue(string propertyName, ILaunchProfile launchProfile, ImmutableDictionary <string, object> globalSettings, Rule?rule)
        {
            string propertyValue = propertyName switch
            {
                AuthenticationModePropertyName => GetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteAuthenticationModeProperty, string.Empty),
                NativeDebuggingPropertyName => GetOtherProperty(launchProfile, LaunchProfileExtensions.NativeDebuggingProperty, false) ? True : False,
                RemoteDebugEnabledPropertyName => GetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteDebugEnabledProperty, false) ? True : False,
                RemoteDebugMachinePropertyName => GetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteDebugMachineProperty, string.Empty),
                SqlDebuggingPropertyName => GetOtherProperty(launchProfile, LaunchProfileExtensions.SqlDebuggingProperty, false) ? True : False,

                _ => throw new InvalidOperationException($"{nameof(ProjectLaunchProfileExtensionValueProvider)} does not handle property '{propertyName}'.")
            };

            return(propertyValue);
        }
예제 #19
0
파일: Day16.cs 프로젝트: htoomik/aoc2020
        public long Solve2(string input)
        {
            var cleaned  = input.Trim().Replace("\r", "");
            var sections = cleaned.Split("\n\n");

            var rules        = sections[0].Split("\n").Select(ParseRule).ToList();
            var myTicket     = sections[1].Split("\n")[1].Split(",").Select(int.Parse).ToList();
            var otherTickets = sections[2].Split("\n").Skip(1).Select(ParseTicket).ToList();

            var validTickets = new List <List <int> >();

            foreach (var ticket in otherTickets)
            {
                var allValid = true;
                foreach (var value in ticket)
                {
                    var foundMatch = false;
                    foreach (var rule in rules)
                    {
                        if (RuleMatchesValue(rule, value))
                        {
                            foundMatch = true;
                            break;
                        }
                    }

                    if (!foundMatch)
                    {
                        allValid = false;
                        break;
                    }
                }

                if (allValid)
                {
                    validTickets.Add(ticket);
                }
            }

            var unmatchedRules    = rules.Select(r => r).ToList();
            var valuesPerPosition = GetValuesPerPosition(myTicket, validTickets);
            var rulePositions     = new Dictionary <Rule, int>();

            var done = false;

            while (!done)
            {
                for (var i = 0; i < valuesPerPosition.Count; i++)
                {
                    var  position     = valuesPerPosition[i];
                    var  rulesMatched = 0;
                    Rule?match        = null;
                    foreach (var rule in unmatchedRules)
                    {
                        if (position.All(value => RuleMatchesValue(rule, value)))
                        {
                            rulesMatched++;
                            match = rule;
                        }
                    }

                    if (rulesMatched == 1)
                    {
                        rulePositions[match.Value] = i;
                        unmatchedRules.Remove(match.Value);
                    }
                }

                done = !unmatchedRules.Any();
            }

            long total = 1;

            foreach (var(rule, position) in rulePositions)
            {
                if (rule.Name.StartsWith("departure"))
                {
                    var value = myTicket[position];
                    total *= value;
                }
            }

            return(total);
        }
 public void OnSetPropertyValue(string propertyName, string propertyValue, IWritableLaunchProfile launchProfile, ImmutableDictionary <string, object> globalSettings, Rule?rule)
 {
     // TODO: Should the result (success or failure) be ignored?
     _ = propertyName switch
     {
         AuthenticationModePropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteAuthenticationModeProperty, propertyValue, string.Empty),
         HotReloadEnabledPropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.HotReloadEnabledProperty, bool.Parse(propertyValue), true),
         NativeDebuggingPropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.NativeDebuggingProperty, bool.Parse(propertyValue), false),
         RemoteDebugEnabledPropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteDebugEnabledProperty, bool.Parse(propertyValue), false),
         RemoteDebugMachinePropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.RemoteDebugMachineProperty, propertyValue, string.Empty),
         SqlDebuggingPropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.SqlDebuggingProperty, bool.Parse(propertyValue), false),
         WebView2DebuggingPropertyName => TrySetOtherProperty(launchProfile, LaunchProfileExtensions.JSWebView2DebuggingProperty, bool.Parse(propertyValue), false),
         _ => throw new InvalidOperationException($"{nameof(ProjectLaunchProfileExtensionValueProvider)} does not handle property '{propertyName}'."),
     };
 }
예제 #21
0
 public VariableRule(Rule path, Rule defaultValue)
 {
     _path         = path;
     _defaultValue = defaultValue;
 }
예제 #22
0
 public VariableRule(Rule path)
 {
     _path = path;
 }
예제 #23
0
 /// <summary>
 /// Sets the rules of the state
 /// </summary>
 /// <param name="notSetRule">Rule for NotSetRule</param>
 /// <param name="setRule">Rule for SetRule</param>
 public void SetRules(Rule notSetRule, Rule setRule)
 {
     NotSetRule = notSetRule;
     SetRule    = setRule;
 }
 public Conflict(int state, string lookahead, Rule rule, int resolution)
     : this(state, lookahead, resolution)
 {
     this.rule = rule;
 }
        public async Task <IRule?> GetBrowseObjectRuleAsync(IDependency dependency, TargetFramework targetFramework, IProjectCatalogSnapshot?catalogs)
        {
            Requires.NotNull(dependency, nameof(dependency));

            IImmutableDictionary <string, IPropertyPagesCatalog> namedCatalogs = await GetNamedCatalogsAsync();

            Requires.NotNull(namedCatalogs, nameof(namedCatalogs));

            if (!namedCatalogs.TryGetValue(PropertyPageContexts.BrowseObject, out IPropertyPagesCatalog browseObjectsCatalog))
            {
                // Issue https://github.com/dotnet/project-system/issues/4860 suggests this code path
                // can exist, however a repro was not found to dig deeper into the underlying cause.
                // For now just return null as the upstream caller handles null correctly anyway.
                return(null);
            }

            string?itemSpec = string.IsNullOrEmpty(dependency.OriginalItemSpec)
                ? dependency.FilePath
                : dependency.OriginalItemSpec;

            var context = ProjectPropertiesContext.GetContext(
                UnconfiguredProject,
                itemType: dependency.SchemaItemType,
                itemName: itemSpec);

            Rule?schema = dependency.SchemaName != null?browseObjectsCatalog.GetSchema(dependency.SchemaName) : null;

            if (schema == null)
            {
                // Since we have no browse object, we still need to create *something* so
                // that standard property pages can pop up.
                Rule emptyRule = RuleExtensions.SynthesizeEmptyRule(context.ItemType);

                return(GetConfiguredProjectExports().PropertyPagesDataModelProvider.GetRule(
                           emptyRule,
                           context.File,
                           context.ItemType,
                           context.ItemName));
            }

            if (dependency.Resolved && !Strings.IsNullOrEmpty(dependency.OriginalItemSpec))
            {
                return(GetConfiguredProjectExports().RuleFactory.CreateResolvedReferencePageRule(
                           schema,
                           context,
                           dependency.OriginalItemSpec,
                           dependency.BrowseObjectProperties));
            }

            return(browseObjectsCatalog.BindToContext(schema.Name, context));

            async Task <IImmutableDictionary <string, IPropertyPagesCatalog> > GetNamedCatalogsAsync()
            {
                if (catalogs != null)
                {
                    return(catalogs.NamedCatalogs);
                }

                if (_namedCatalogs == null)
                {
                    Assumes.NotNull(ActiveConfiguredProject);
                    Assumes.Present(ActiveConfiguredProject.Services.PropertyPagesCatalog);

                    // Note: it is unlikely that we end up here, however for cases when node providers
                    // getting their node data not from Design time build events, we might have OnDependenciesChanged
                    // event coming before initial design time build event updates NamedCatalogs in this class.
                    // Thus, just in case, explicitly request it here (GetCatalogsAsync will acquire a project read lock)
                    _namedCatalogs = await ActiveConfiguredProject.Services.PropertyPagesCatalog.GetCatalogsAsync();
                }

                return(_namedCatalogs);
            }

            ConfiguredProjectExports GetConfiguredProjectExports()
            {
                Assumes.NotNull(ActiveConfiguredProject);

                ConfiguredProject project = targetFramework.Equals(TargetFramework.Any)
                    ? ActiveConfiguredProject
                    : _dependenciesSnapshotProvider.GetConfiguredProject(targetFramework) ?? ActiveConfiguredProject;

                return(GetActiveConfiguredProjectExports(project));
            }
        }
예제 #26
0
 public SubstrRule(Rule input, Rule start, Rule count)
 {
     _input = input;
     _start = start;
     _count = count;
 }
예제 #27
0
        static void Part2(StreamReader streamReader)
        {
            bool test   = false;
            long result = 0;

            string line = streamReader.ReadLine();

            if (line.StartsWith("result:"))
            {
                WriteLine("Stand down - it's a test!");
                test   = true;
                result = Int64.Parse(line.Substring(8).Trim()); // accounts for space after :
                line   = streamReader.ReadLine();
            }

            List <Rule>        rules         = new List <Rule>();
            List <List <int> > nearbytickets = new List <List <int> >();
            var yourticket = readFile(line, streamReader, rules, nearbytickets);

            List <List <int> > validnearbytickets = new List <List <int> >();

            foreach (var ticket in nearbytickets)
            {
                bool allok = true;
                foreach (var val in ticket)
                {
                    allok = allok && matchAllConstraints(rules, val);
                }
                if (allok)
                {
                    validnearbytickets.Add(ticket);
                }
            }

            // ok, we have our valid nearby tickets, so for each field, we collect the rules
            // that work for that field, whittling them down.
            int numfields = validnearbytickets[0].Count;

            HashSet <Rule>[] rulesperposition = new HashSet <Rule> [numfields];
            for (int i = 0; i < numfields; i++)
            {
                rulesperposition[i] = new HashSet <Rule>();
                foreach (var rule in rules)
                {
                    rulesperposition[i].Add(rule);
                }
            }

            // this is going to be a memory carnage, but hey ho!
            int counter = 0;

            foreach (var ticket in validnearbytickets)
            {
                for (int i = 0; i < numfields; i++)
                {
                    HashSet <Rule> remainingrules = new HashSet <Rule>();
                    foreach (var rule in rules)
                    {
                        if (matchConstraints(rule, ticket[i]))
                        {
                            remainingrules.Add(rule);
                        }
                    }
                    rulesperposition[i].IntersectWith(remainingrules);
                }
                //WriteLine($"After {counter} goes we have {rulesperposition[i].Count} rules remaining.");
                //if (rulesperposition[i].Count == 0) WriteLine($"Our current value is {ticket[i]}");
                counter++;
            }

            // let's get jiggy with the remaining rules, ruling out those that are already gone.
            // This is resolving the rules.  Any position that has only one rule must be just that
            // rule.  We remove that rule from any other position.  We repeat this until all positions
            // only have a single rule, or in other words, we stop making changes.
            bool done = false;

            while (!done)
            {
                bool changes = false;
                for (int i = 0; i < numfields; i++)
                {
                    if (rulesperposition[i].Count == 1)
                    {
                        Rule?ourrule = null;
                        foreach (var r in rulesperposition[i])
                        {
                            ourrule = r;
                        }
                        if (ourrule != null)
                        {
                            for (int j = 0; j < numfields; j++)
                            {
                                if (i != j && rulesperposition[j].Contains(ourrule))
                                {
                                    changes = true;
                                    rulesperposition[j].Remove(ourrule);
                                }
                            }
                        }
                    }
                }
                done = !changes;
            }

            // makesure there's one rule for each position.
            for (int i = 0; i < numfields; i++)
            {
                if (rulesperposition[i].Count != 1)
                {
                    WriteLine($"Position {i} has {rulesperposition[i].Count} rules left.");
                }
                else
                {
                    Rule x = null;
                    foreach (var rule in rulesperposition[i])
                    {
                        x = rule;
                    }
                    // if we claim this rule, then no one else can have it!
                    for (int j = i + 1; j < numfields; j++)
                    {
                        rulesperposition[j].Remove(x);
                    }
                    WriteLine($"Position {i} is rule {x.name}");
                }
            }

            // find the 'departure' rule positions.
            List <int> positions = new List <int>();

            for (int i = 0; i < numfields; i++)
            {
                Rule x = null;
                foreach (var rule in rulesperposition[i])
                {
                    x = rule;
                }
                if (x != null && x.name.StartsWith("departure"))
                {
                    positions.Add(i);
                }
            }

            long sum = 1;

            foreach (var i in positions)
            {
                sum *= yourticket[i];
            }

            WriteLine($"Sum of the departure fields is {sum}");
            if (test)
            {
                WriteLine($"We expected to see {result}");
            }
        }
예제 #28
0
 public LessThanRule(Rule a, Rule b, Rule c)
 {
     _a = a;
     _b = b;
     _c = c;
 }