TopCoder Alogirithm System Test Failure - c#

I am doing a problem from Top-Coder.The problem statement is-
One day, Jamie noticed that many English words only use the letters A
and B. Examples of such words include "AB" (short for abdominal),
"BAA" (the noise a sheep makes), "AA" (a type of lava), and "ABBA" (a
Swedish pop sensation).
Inspired by this observation, Jamie created a simple game. You are
given two Strings: initial and target. The goal of the game is to find
a sequence of valid moves that will change initial into target. There
are two types of valid moves:
Add the letter A to the end of the string. Reverse the string and then
add the letter B to the end of the string. Return "Possible" (quotes
for clarity) if there is a sequence of valid moves that will change
initial into target. Otherwise, return "Impossible".
Below is my solution of the problem which passed all the tests in the Panel but failed in system test.But,I did not get any specific information about which test case failed.Please check if my code will not work in some scenario.
class ABBA
{
public string canObtain(string initial,string target)
{
string s = "Impossible";
if (initial.Length > target.Length)
return "Impossible";
if (initial.Equals(target))
return "Possible";
if (CheckFirstWay(target,initial))
{
s=canObtain(initial+"A",target);
}
if (s.Equals("Impossible") && CheckSecondWay(target,initial))
{
s=canObtain(ReverseStringDirect(initial) + "B",target);
}
return s;
}
public static string ReverseStringDirect(string s)
{
char[] array = new char[s.Length];
int forward = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
array[forward++] = s[i];
}
return new string(array);
}
private static bool CheckSecondWay(string final, string initial)
{
if (final.Contains(ReverseStringDirect(initial) + "B") || final.Contains("B"+initial))
{
return true;
}
else
{
return false;
}
}
private static bool CheckFirstWay(string final1, string initial)
{
if (final1.Contains(initial + "A") || final1.Contains(ReverseStringDirect(initial+"A")))
{
return true;
}
else
{
return false;
}
}
}

You can check on which test failed by following procedure,
Go to the specified room.
Open the problem.
Compile.
Submit it.
Then go to run system test.
you will see the error test there.
OR
Select the match from here.
Then in the page as shown you will see set of blue coders and red coders who topped the match.
Select any one player as per your division. [.] --> this logo beside name.
Then check their solution you will see those tests.
Here are the test cases..check it out.
You have to type system tests here. You can check the image below. Image credit : Google

Related

Make a method that contains a linear search?

I'm new to programmning and I'm taking a course to learn the basics in c#.
Right now I'm doing a console application that are supposed to work as a blog. In the application the user should be able to write a new post, show written posts and search for written posts. The application is supposed to be a list that contains arrays.
I'm almost finished with the application but I want to make a method for the linear search that searches for the written blogposts but I cant get it to work.
Here's the code for the linear search:
case 3:
Console.Write("Write the title for the post you are searching for: ");
string searchedWord = Console.ReadLine();
bool search = false;
for (int i = 0; i < myBlog.Count; i++)
{
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
{
search = true;
Console.WriteLine("\nHe post you are looking for exists in the blog:");
Console.WriteLine("\nTitle: " + myBlog[i][0] +
"\nPost: " + myBlog[i][1] +
"\n\nPress enter to return to the menu...");
}
}
if (search == false)
{
Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
break;
I made a try creating a method for it but I'm doing wrong, can somebody please tell me how to do it?
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
for (int i = 0; i < myBlog; i++)
{
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
return i;
}
return -1;
}
If you are allowed to use Linq, you can do
using System.Linq;
//....
static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
// "give me from myBlog ...
// the first element, that fits the criteria OR
// default if such an element is not in the list"
return myBlog.FirstOrDefault(x => x[0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase));
}
See it in action in a Fiddle
Mind that this returns default(string) (which is null) if the searchedWord is not found.
I guess you are using string[] because your class (pun intended) has not come across the concept of classes, yet. So I won't go into that. Just so much: usually, you would model your blog data into a class with specific properties. And later on, you would probably want to keep the data in a Database instead of memory ... but all that is not really related to the problem at hand.
If you are NOT allowed to use Linq:
static string[] BlogSearch(List<string[]> myBlog, string searchedWord)
{
for( int i = 0; i < myBlog.Count; i++ )
{
if( myBlog[i][0].Contains(searchedWord, StringComparison.OrdinalIgnoreCase))
{
return myBlog[i];
}
}
return null;
}
Which is basically the same as the Linq version just coded out explicitly.
See it in action in a Fiddle.
Usage
// ... case 3: ...
var result = BlogSearch(myBlog, searchedWord);
if( result is null )
{
Console.WriteLine("The searched word wasn't found. Press enter to return to the menu...");
}
else
{
Console.WriteLine("\nThe post you are looking for exists in the blog:");
Console.WriteLine("\nTitle: " + result[0] +
"\nPost: " + result[1] +
"\n\nPress enter to return to the menu...");
}
break;
Some hints for you concerning your code:
// You expect to be returning `string`
// but all return statements return `int`.
// vv What you actually need is `string[]`, though.
static string BlogSearch(List<string[]> myBlog, string searchedWord)
{
// vv that's a `List<T>`, so you need `myBlog.Count` here
for (int i = 0; i < myBlog; i++)
{
// Two caveats:
// 1. _Exact_ match
// 2. `ToUpper` does not always work correctly.
// It is advised to use overloads with `StringComparison` argument
if (searchedWord.ToUpper() == myBlog[i][0].ToUpper())
return i;
}
return -1;
}

How to parse a string and a bool array to a method, modifying the string in the method and verifying that the string fulfills all conditions in C#?

I've been doing C# now for about two months. And I want to create a method that does the following:
Takes a string.
Takes an array with conditions that needs to be applied to the string.
Modifies the string within the called method.
Checks if the modified string fulfills all boolean conditions.
Then "returns"(using the ref) string to the caller method.
So for example, if I wanted the user to input their first and last name. I'd do:
GetStringLine(out string name, new bool[] { name.Length > 1, name.Split(' ').Length > 1})
I've been trying several different ways at this point, I believe I am simply missing something. It feels like there should be some way to tell the method that the bool condition being passed into the method should be applied to the actively modified string.
Anyways, as I don't have a whole lot of experience with C#, or programming, I am hoping that the following code block will explain or hint further to what I am trying to achieve. Really hoping to get some more understanding of this. So keep in mind, I don't need to do it exactly as I am showing, if there would be a another way of accomplishing my goals, I'd be happy to do that instead.
Best regards!
static void Main(string[] args) {
string str = "test";
GetStringLine(ref str,
new bool[] {
str.Length > 1,
str.Length < 3
}
);
}
public static void GetStringLine(ref string str, bool[] conditions) {
while (!conditions.All(condition => condition)) {
str = Console.ReadLine();
Console.WriteLine("");
}
}
Edit:
After #pm100 's solution, I applied it as such and it works as expected:
public static void GetStringLine(out string output, Predicate<string>[] conditions) {
string input = "";
while (!conditions.All(condition => condition(input))) {
input = Console.ReadLine();
Console.WriteLine("");
}
output = input;
}
Although, I feel like it's a bit abundant due to the string input = "" and output = input. My first attempt was to do it like this:
public static void GetStringLine(out string output, Predicate<string>[] conditions) {
while (!conditions.All(condition => condition(output))) {
output = Console.ReadLine();
Console.WriteLine("");
}
}
Sadly, this yields me naught but two errors:
First:
CS1628 Cannot use ref, out, or in parameter 'output' inside an anonymous method,
lambda expression, query expression, or local function
Second:
CS0177 The out parameter 'output' must be assigned to before control
leaves the current method
I'll add that my actual code contains more fluff, I.e. error prompts and other things that are needed, but I deemed it not relevant to the current question at hand.
I leave out the looping to reprompt and just show the check against arbitrary conditions (since thats the tricky bit)
static bool CheckString(string input, Predicate<string>[] conditions) {
conditions.All(c => c(input))
}
now to use
var conditions = new Predicate<string>[] {
(s)=>s.Length > 3,
(s)=>s.Contains("a")
};
CheckString("abcdef", conditions); // true
CheckString("ab", conditions); // false
the hard part for you will be to tell the user on each reprompt what the conditions are. You cannot (easily) get a string representation of the predicates, probably should pass in a prompt string
Like this
static string ReadCheckedString(string prompt, Predicate<string>[] conditions) {
while (true) {
Console.WriteLine(prompt);
var input = Console.ReadLine();
if (input == null || input.Length == 0)
return null;
if (conditions.All(c => c(input))) {
return input;
}
}
}
and
var conditions = new Predicate<string>[] {
(s)=>s.Length > 3,
(s)=>s.Contains("a")
};
var ans = ReadCheckedString("longer than 3 chars and contains 'a'", conditions);

Counting a string to ensure the input is within a min/max boundary

For a part of my project, I want to enforce the rule that the user input can only be within a min/max word boundary. With a minimum of 1 word, and a maximum of 50 words. The boolean isn't changing from the default set value of false. Here is my code:
bool WordCount_Bool = false;
//Goto the method that handles the calculation of whether the users input is within the boundary.
WordCount_EH(WordCount_Bool);
//Decide whether to continue with the program depending on the users input.
if (WordCount_Bool == true)
{
/*TEMP*/MessageBox.Show("Valid input");/*TEMP*/
/*Split(split_text);*/
}
else
{
MessageBox.Show("Please keep witin the Min-Max word count margin.", "Error - Outside Word Limit boundary");
}
Method handling the array and the change of the boolean:
private bool WordCount_EH(bool WordCount_Bool)
{
string[] TEMPWordCount_Array = input_box.Text.Split(' ');
int j = 0;
int wordcount = 0;
for (int i = 100; i <=0; i--)
{
if (string.IsNullOrEmpty(TEMPWordCount_Array[j]))
{
//do nothing
}
else
{
wordcount++;
}
j++;
}
if (wordcount >= 1)
{
WordCount_Bool = true;
}
if (wordcount < 1)
{
WordCount_Bool = false;
}
return WordCount_Bool;
}
Thank you all in advance.
Side note: I realize that the for loop will throw an exception or at least is not optimal for its purpose so any advice will be much appreciated.
Extra Side note: Sorry I should have said that the reason i haven't used length is that wherever possible I should do my own code instead of using built-in functions.
The short answer is you should just return a true or false value from your WordCount_EH method like others have said
But just to clear up why it doesn't work. C# by default passes arguments by value. With Value types such as Boolean the actual value of true or false is stored in the variable. So when you pass your Boolean value into your method all you are doing is saying please put this bool value into my new variable (the method parameter). When you make changes to that new variable it only changes that variable. It has no relation to the variable that it was copied from. This is why you don't see a change in original bool variable. You may have named the variables the same but they are infact two different variables.
Jon Skeet explains it fantastically here http://jonskeet.uk/csharp/parameters.html
Here you go this should solve it:
if(input_box.Text.Split(' ').Length>50)
return false;
else
return true;
You need to pass WordCount_Bool by ref if you want to change it in WordCount_EH:
private bool WordCount_EH(ref bool WordCount_Bool) { ... }
bool WordCount_Bool = false;
WordCount_EH(ref WordCount_Bool);
although in this case you might as well use the return value:
bool WordCount_Bool = false;
WordCount_Bool = WordCount_EH(WordCount_Bool);
If you want to pass argument by reference, you need to do as per #Lee suggestion.
For your logic implementation, you can use following code to avoid array indexing.
// It would return true if you word count is greater than 0 and less or equal to 50
private bool WordCount_EH()
{
var splittedWords = input_box.Text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList();
return (splittedWords.Count > 0 && splittedWords.Count <= 50);
}

C# dynamic logic gate

I am working on a program that would allow the user to build digital circuits from virtual logic gates. Every gate would be an instance of a class that represents particular gate type, for example here's how AND class looks:
public class andgate
{
public andgate()
{
inputs = new bool[7];
for (int i = 0; i < 7; i++) inputs[i] = true;
output = (inputs[0] && inputs[1] && inputs[2] && inputs[3] && inputs[4] && inputs[5] && inputs[6]);
}
public bool[] inputs;
public bool output;
}
Every gate has seven inputs but not all of them have to be used (i.e. for a gate with three imputs the remaining four will just be "1" which is AND's neutral element anyway). Each input is a reference to an output of another gate or to an element of bool array (which stores the input vector) so that signal generated by one gate automatically is sent to the following gate. The problem is I also need the signal to be transmitted dynamically within the gate, i.e. if one of the input signals in AND gate is set to 0 then the output automatically has a 0 value. Therefore when you feed a binary vector to the inputs of the cirtuit, it changes the values of the circuit's outputs. Or maybe there's an easier way to simulate a circuit than building it from individual gates? I need it for test pattern generating.
Make the output property read-only:
public bool output
{
get
{
return inputs.All(i => i);
}
}
Instead of ANDing all the inputs, just check if there is any input that is false.
Of course you have to remove the assignment to output in the constructor. This should make your output property "dynamic".
You may also want to change the inputs to bool?[] instead, so that a null value would signify that there is no signal. You will then have to remove the initialization of the input array to all true and change the output return to:
return inputs.All(i => i.GetValueOrDefault(true));
Edited with Tim S's suggestions in the comments
For this, you should use a properties to set/get the inputs, as you can perform additional computations in a property. The state variables you're holding should be private.
public bool[] Inputs {
set {
inputs = value;
}
}
public bool Output {
get {
return inputs[0] && inputs[1] ...
}
}
I would avoid doing this for the Inputs property, since exposing arrays is really exposing information about how the class stores things, which should be avoided where possible for good OOP. A ReadOnlyCollection might be more suitable, for example.
However, I would rethink the design in general, and avoid having some arbitrary # of inputs, 7. Where have you conjured that value from?
A more simplistic approach would be to assume that a gate takes 2 values - A and B, for which you can set the values in the constructor or individual properties.
You then take advantage of the fact that operations on binary logic gates are associative, so an AND gate taking a, b, c, is equivalent to one taking a, b, feeding it's output to another which also takes c. This is how you'd build a circuit in practice anyway - the issue you need to consider is the latency of the gate though.
It sounds like you should add events into your gates, such that when their state changes they're able to notify dependant objects; something like this:
public class AndGate
{
private bool[] inputs;
private bool output;
public bool[] Inputs
{
get
{
return this.inputs;
}
set
{
this.inputs = value;
UpdateOutput();
}
}
public bool Output
{
get
{
return this.output;
}
}
public AndGate()
{
inputs = new bool[7];
for (int i = 0; i < 7; i++) inputs[i] = true;
UpdateOutput();
}
private void UpdateOutput()
{
bool original = output;
output = true;
for(int i=0; i<inputs.Length; i++)
{
output = output && inputs[i];
}
if (original != output)
{
OnChanged(EventArgs.Empty);
}
}
public event GateStateChangedEventHandler StateChanged;
protected virtual void OnChanged(EventArgs e)
{
if (StateChanged != null)
{
StateChanged(this, e);
}
}
}

TPIN number validation in java, c++ or c#

I have small requirement for TPIN validation in my college project, The requirement is, we should not allow the user to set his TPIN in the below scenarios .
TPIN should not be in sequence. (either ascending or descending ex: 123456, 456789, 987654 or 654321)
TPIN should not start from Zero (ex: 0127865, 098764)
TPIN should not be repetitive digit (ex: 888888,222222 etc.)
For the third one my idea is to divide the number by 11 and check for the reminder..
Any ideas plz..
public class Validate
{
public static void main(String[] args)
{
int iTpin = Integer.parseInt(args[0]); // Converted string to int
System.out.println("The entered TPIN is:"+iTpin);
boolean flag = validate(iTpin);
if (flag== true)
System.out.println("The entered TPIN is valid");
else
System.out.println("The entered TPIN is Invalid");
}
public static boolean validate(int passedTpin)
{
if (passedTpin == 0)
return false;
else if ( passedTpin%11 == 0)
return false;
else
return true;
}
}
Finally created code for the sequence of digits. It might be useful for others
private static boolean containsRepetitiveDigits(String tpin) {
char firstChar = tpin.charAt(0);
for (int i = 1; i < tpin.length(); i++) {
char nextChar = tpin.charAt(i);
if ((Character.valueOf(nextChar)).compareTo(Character
.valueOf(firstChar)) != 0) {
return false;
}
}
System.out.println("Error:TPIN contains repetitive digits");
return true;
}
For start, using Int32 to store a number means it shouldn't exceed 2,147,483,647. And apart from this, you won't be able to check for the leading zero once you have converted to a number, since leading zeros obviously disappear once you get a number.
This means you should keep the input as a string during validation. This actually makes your job easier, since you can index individual characters, without the need to use arithmetic operations.
Since you are working with strings, you should also check if the input string contains invalid (non-digit) characters before anything else:
bool ContainsInvalidCharacters(string input)
{
// check if there is a non-digit character
foreach (char c in input)
if (!char.IsDigit(c))
return true;
return false;
}
Then you can continue adding individual rules. For example, to check if characters are repeating, you will do something like:
bool ContainsRepetitiveDigits(string input)
{
if (input.Length == 0)
return false;
// get the first character
char firstChar = input[0];
// check if there is a different character
foreach (char c in input)
if (c != firstChar)
return false;
// if not, it means it's repetitive
return true;
}
bool StartsWithZero(string input)
{
if (input.Length == 0)
return false;
return (input[0] == '0');
}
To detect sequences, the most straightforward way is to get the difference of first two characters, and then check if it changes through the entire string:
bool IsSequence(string input)
{
// we need at least two characters
// for a sequence
if (input.Length < 2)
return false;
// get the "delta" between first two
// characters
int difference = input[1] - input[0];
// allowed differences are:
// -1: descending sequence
// 0: repetitive digits
// 1: ascending sequence
if (difference < -1 || difference > 1)
return false;
// check if all characters are equally
// distributed
for (int i = 2; i < input.Length; i++)
if (input[i] - input[i - 1] != difference)
return false;
// this is a sequence
return true;
}
Once you've defined all of your rules, you can create a single method which will test them one by one:
bool Validate(string input)
{
// list of all predicates to check
IEnumerable<Predicate<string>> rules = new Predicate<string>[]
{
ContainsInvalidCharacters,
ContainsRepetitiveDigits,
StartsWithZero,
IsSequence
};
// check if any rule matches
foreach (Predicate<string> check in rules)
if (check(input))
return false;
// if no match, it means input is valid
return true;
}
Note that IsSequence detects repetitive digit patterns also (when character difference is zero). If you want to explicitly prevent this, alter the condition where allowed differences are checked. Alternatively, you can remove the ContainsRepetitiveDigits rule altogether.
[Edit]
Since I see you are using Java instead of C#, I will try to provide a better example.
Disclaimer: I don't usually program in Java, but from what I know, Java doesn't support delegates the way C# does. So I will try to provide a Java example (hope it will work), which expresses my "composite validation" intent better.
(Suspicious Java code follows)
First, define an interface which all validation rules will implement:
// (java code)
/**
* Defines a validation rule.
*/
public interface IValidationRule
{
/**
* Returns a description of this
* validation rule.
*/
String getDescription();
/**
* Returns true if this rule
* is matched.
*/
boolean matches(String tpin);
}
Next, define each rule in a separate class, implementing both getDescription and matches methods:
// (java code)
public class RepetitiveDigitsRule implements IValidationRule
{
public String getDescription()
{
return "TPIN contains repetitive digits";
}
public boolean matches(String tpin)
{
char firstChar = tpin.charAt(0);
for (int i = 1; i < tpin.length(); i++)
if (tpin.charAt(i) != firstChar)
return false;
return true;
}
}
public class StartsWithZeroRule implements IValidationRule
{
public String getDescription()
{
return "TPIN starts with zero";
}
public boolean matches(String tpin)
{
if (tpin.length() < 1)
return false;
return tpin.charAt(0) == '0';
}
}
You can see that matches method does not print anything to console. It simply returns true if rule is matched, and leaves to its caller to decide whether to print its description (to console, a message box, web page, whatever).
Finally, you can instantiate all known rules (implementations of IValidationRule) and check them one by one:
// (java code)
public class Validator
{
// instantiate all known rules
IValidationRule[] rules = new IValidationRule[] {
new RepetitiveDigitsRule(),
new StartsWithZeroRule()
};
// validate tpin using all known rules
public boolean validate(String tpin)
{
System.out.print("Validating TPIN " + tpin + "... ");
// for all known rules
for (int i = 0; i < rules.length; i++)
{
IValidationRule rule = rules[i];
// if rule is matched?
if (rule.matches(tpin))
{
// print rule description
System.out.println("Error: " + rule.getDescription());
return false;
}
}
System.out.println("Success.");
return true;
}
}
I recommend trying to follow this pattern. You will end up with code much easier to reuse and maintain.
You can generate sequetial tpin (ascending & decending) based on the first digit then compare it to the inputted tpin. If it matches then it is invalid.
public static bool IsSequential(string pin, bool descending)
{
int p = Convert.ToInt32(pin.Substring(0,1));
string tpin = string.Empty;
for (int i = 0; i < 6; i++)
{
tpin += descending ? (p--).ToString() : (p++).ToString();
}
return pin.Equals(tpin);
}
For item 3, you cannot just divide by 11 because some pin will have remainder 0. (i.e. 221199 is a valid one but the remainder is 0). You can get the first digit and use a loop to compare to the remaining digits.

Categories