Posted 3 days ago

C# LINQ Tip – Read console inputs in one single line of code

Hi, here in C# LINQ Tip – Read console inputs in one single line of code, I will explain a little tip to save some lines of code in competitive programming.

If you use C# in a normal way, and in some problem you need to read from console a single line of integers, for example, “1 2 3 4 5 6 7 8 9 10″, you first will split this line in a string[] array and parse them to int using some for loop and another int[] array.

- Here a little tip to do it in a single line of code using LINQ.

int[] input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray();

As you can see, we read from console the whole line, then using Split() method, split the whole text in small pieces with each element in string, and then with Select(), using int.Parse(), we parse to int each element, then, store in an array.

- You can specify at the end the type of the array, like in this example:

int[] input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToArray<int>();

- You can do the same using a List, like here:

List<int> input = Console.ReadLine().Split(' ').Select(x => int.Parse(x)).ToList();

- Another cool thing you can do using LINQ, is to split a single word and convert in a string[] array or in a List<string> in a single line of code.
1
//string[] array
string[] input = Console.ReadLine().Select(x => x.ToString()).ToArray<string>();

//List<string>
List<string> input = Console.ReadLine().Select(x => x.ToString()).ToList();

This way is a simple way to read the majority of the inputs in a single line of code using C#.
This could save some seconds, and avoid the use of some for loop.

I hope that you found this helpful ;)
Thanks for read!

Posted 5 days ago

Codeforces C# Problem A Password Check

Hi, here a new problem I´ve solved right now!

Github Codeforces C# Problem A Password Check
Codeforces Problem Statement

Here, I hace created three string to help, one with Large letters, one with Small letters and one with Numbers, then I need only to check if all this three contains any of the letters in text and the text itself contains more than 5 chars.

Here my code:

using System;
using System.Linq;

namespace ProblemAPasswordCheck
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = Console.ReadLine();
            string abc = "abcdefghijklmnopqrstuvwxyz";
            string ABC = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            string numbers = "0123456789";
            if (text.Any(x => abc.Contains(x)) && text.Any(x => ABC.Contains(x)) && text.Any(x => numbers.Contains(x)) && text.Length >= 5)
                Console.WriteLine("Correct");
            else
                Console.WriteLine("Too weak");
            Console.ReadLine();
        }
    }
}

Thank you very much

Posted 5 days ago

TopCoder C# Practice Room SRM 280 DIV 2, Problem 500

Hi, here a new problem I’ve solved right now!!

Github TopCoder C# Practice Room SRM 280 DIV 2, Problem 500
TopCoder Problem Statement

Here I have done this problem in two parts, first, with “[", with a for loop, if after this exists some "]“, remove both until the end, and then repeat with “]” starting at the end, removing the “[" in pairs. Then, count the number of "[" and the number of "]” sepparately, and then, while “[" still remains, add "]” at the ned, and viceversa.

Here my code:

public class CompletingBrackets
    {
        public string complete(string text)
        {
            List<string> lefts = text.Select(x => x.ToString()).ToList();
            List<string> rights = text.Select(x => x.ToString()).ToList();
            for (int i = 0; i < lefts.Count - 1; i++)
            {
                if (lefts[i] == "[")
                {
                    for (int a = i + 1; a < lefts.Count; a++)
                    {
                        if (lefts[a] == "]")
                        {
                            lefts.RemoveAt(a);
                            lefts.RemoveAt(i);
                            i--;
                            break;
                        }
                    }
                }
            }
            for (int i = rights.Count - 1; i > 0; i--)
            {
                if (rights[i] == "]")
                {
                    for (int a = i - 1; a >= 0; a--)
                    {
                        if (rights[a] == "[")
                        {
                            rights.RemoveAt(i);
                            rights.RemoveAt(a);
                            i--;
                            break;
                        }
                    }
                }
            }
            int left = lefts.Count(x => x == "[");
            int right = rights.Count(x => x == "]");
            StringBuilder sb = new StringBuilder(text);
            while (left > 0)
            {
                sb.Append("]");
                left--;
            }
            while (right > 0)
            {
                sb = sb.Insert(0, "[");
                right--;
            }
            return sb.ToString();
        }
    }

Thank you very much

Posted 5 days ago

TopCoder C# Practice Room SRM 277 DIV 2, Problem 500

Hi, here a new problem I’ve solved right now!

Github TopCoder C# Practice Room SRM 277 DIV 2, Problem 500
TopCoder Problem Statement

Here only need to get the first mean, then with a for loop, check if the first list has more than 1 element, if it is, then with a for loop, in each iteration, create a new list with all the elements and exchange one of them, get the new mean, and if both are bigger than the initial ones, then add +1 to result. repeat this with all the elements, and the same with the second list.

Here my code:

public class RogersPhenomenon
    {
        public int countTriggers(int[] set1, int[] set2)
        {
            double[] s1 = set1.Select(x => double.Parse(x.ToString())).ToArray<double>();
            double[] s2 = set2.Select(x => double.Parse(x.ToString())).ToArray<double>();
            double final1 = s1.Sum() / s1.Length;
            double final2 = s2.Sum() / s2.Length;
            int result = 0;
            if (s1.Length > 1)
            {
                for (int i = 0; i < s1.Length; i++)
                {
                    List<double> list1 = s1.ToList();
                    List<double> list2 = s2.ToList();
                    list2.Add(list1[i]);
                    list1.RemoveAt(i);
                    double temp1 = list1.Sum() / list1.Count;
                    double temp2 = list2.Sum() / list2.Count;
                    if (temp1 > final1 && temp2 > final2)
                        result++;
                }
            }
            if (s2.Length > 1)
            {
                for (int i = 0; i < s2.Length; i++)
                {
                    List<double> list1 = s1.ToList();
                    List<double> list2 = s2.ToList();
                    list1.Add(list2[i]);
                    list2.RemoveAt(i);
                    double temp1 = list1.Sum() / list1.Count;
                    double temp2 = list2.Sum() / list2.Count;
                    if (temp1 > final1 && temp2 > final2)
                        result++;
                }
            }
            return result;
        }
    }

Thank you very much

Posted 1 week ago

TopCoder C# Practice Room SRM 274 DIV 2, Problem 500

Hi, here a new problem I´ve solved right now!

Github TopCoder C# Practice Room SRM 274 DIV 2, Problem 500
TopCoder Problem Statement

Here we need to do step by step. First, check if the length of baseString is 1, if it is, return baseString. Otherwise, first, create a couple of StringBuilder, called left and right. Then we need to get the times each letter appear in baseString, and then with a for loop going through the times array, while times[i] > 1, Append() this letter to left and Insert in the index 0 this leter to right, then substract 2 and repeat the same with all the letters. This way we will be sure that we are taking the lexicographically first possible string. Then, after this, if left.Length is bigger than 0, get the first letter in the array and Append to left. Then join left and right, and check, if the length of the result is equal to the lenght of the baseString, return the result, otherwise, return an empty string.

Here my code:

public class PalindromeMaker
    {
        public string make(string baseString)
        {
            if (baseString.Length == 1)
                return baseString;
            string abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            int[] times = new int[26];
            StringBuilder left = new StringBuilder();
            StringBuilder right = new StringBuilder();
            for (int i = 0; i < baseString.Length; i++)
                times[abc.IndexOf(baseString[i])]++;
            for (int i = 0; i < times.Length; i++)
            {
                while (times[i] > 1)
                {
                    left.Append(abc[i]);
                    right.Insert(0, abc[i]);
                    times[i] -= 2;
                }
            }
            if (left.Length > 0)
            {
                for (int i = 0; i < times.Length; i++)
                {
                    if (times[i] > 0)
                    {
                        left.Append(abc[i]);
                        break;
                    }
                }
            }
            string result = string.Join("", left, right);
            if (result.Length != baseString.Length)
                return string.Empty;
            else
                return result;
        }
    }

Thank you very much

Posted 2 weeks ago

TCO 14 C# Round 1A Problem 250

Hi, here the 250 problem in the TCO 14 in TopCoder.

Github TCO 14 C# Round 1A Problem 250

Here the problem statement:
Elly has a string S of uppercase letters and a magic device that can modify the string. The strength of the device is an int L. The device is used in the following way. The user enters a 0-based index i such that 0 <= i <= length(S)-L. The device then performs the following changes:
It leaves the first i characters (i.e., characters with indices 0 through i-1) untouched.
It rearranges the next L characters (i.e., characters with indices i through i+L-1) into alphabetical order.
It erases all the remaining characters (i.e., characters with indices i+L and more). Note that for i=length(S)-L no characters are erased.
The girl can use this "sorting trimmer" as many times as she likes. After each use she is left with the new version of the string. In the examples below we use brackets to highlight the region that shall be sorted. For example, "ABRA[CADAB]RA" means that L=5 and Elly chose i=4. The device keeps the letters in front of the brackets, sorts the letters in the brackets, and throws away the rest. Here is one way how Elly could have used a device with L = 5, starting with the string S = "ABRACADABRA":
"ABRAC[ADABR]A" -> “ABRACAABDR”
“ABR[ACAAB]DR” -> “ABRAAABC”
“A[BRAAA]BC” -> “AAAABR”
You are given the string S and the int L. Return the lexicographically smallest string Elly can obtain.

Here my code:

public class EllysSortingTrimmer
    {
        public string getMin(string S, int L)
        {
            List<string> word = S.Select(x => x.ToString()).ToList<string>();
            int i = 0;
            while (word.Count - i > L)
            {
                int j = word.Count - L;
                string sorted = string.Join("", word.Skip(word.Count - L).Take(L).OrderBy(x => x).ToArray<string>());
                S = S.Insert(word.Count - L - i, sorted);
                S = S.Remove(word.Count - L - i + sorted.Length, sorted.Length);
                for (int a = 0; a < sorted.Length; a++)
                {
                    word[j] = sorted[a].ToString();
                    j++;
                }
                word = word.Take(word.Count - 1).ToList();
            }
            return string.Join("", word.OrderBy(x => x).ToArray<string>());
        }
    }

Thank you very much

Posted 2 weeks ago

Google Code Jam Qualification Round 2014 Passed!

Hi!!
I would like to congratulate to everyone who have passed the Google Code Jam Qualification Round 2014 :)

Google Code Jam 2014

For second consecutive year, I have passed the qualification round! I tried to do the C problem, but some tricky case was giving me wrong answer hehehe

You can check my Google Code Jam solutions following this links:

Problem A Magic trick

Problem B Cookie Clicker Alpha

Well… I hope to see you in the first round! ;)

If you want, give me your Code Jam id and I will follow you ;)

Mine is Alethor

Good luck to everyone!

Posted 2 weeks ago

Google Code Jam 14 C# Problem B Cookie Clicker Alpha

Hi, here my solution to the problem B in the Google Code Jam 2014.

Github Google Code Jam 14 C# Problem B Cookie Clicker Alpha
Google Code Jam Problem Statement

Here, first create a List to store all the times. Create too a variable called totalTempTime, initialized to 0.0, and a variable too to store the totalCookiesYouNeed / costOfEachFarm, called farmsLeft. Then, using a for loop, from 0 to 200000 (don´t ask why 200000) haha I put it to enter in time. get first the costOfTheFarm / cookiesPerSecond and store in a variable called timeToFarm. Then, add to the list, totalTempTime + (timeToFarm + farmsLeft). Then, add to totalTempTime the timeToFarm. Now, get the (totalCookies / cookiesPerSecond) + totaltempTime and add to the list. At the end of each iteration, add the cookies that the new farm gives, to the cookiesPerSecond, and repeat. At the end, you will have a list with all the possible times. You only need to return the Min() of all this times.

Here my code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using System.IO;

namespace _2
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"C:\GCJ\B-large.in");
            StreamWriter sw = new StreamWriter(@"C:\GCJ\B-OutputLarge.txt");
            string line = string.Empty;
            int cases = int.Parse(sr.ReadLine());
            for (int i = 0; i < cases; i++)
            {
                double cookiesPerSecond = 2.0;
                string[] text = sr.ReadLine().Split(' ').Select(x => x.Replace('.', ',')).ToArray<string>();
                double[] input = new double[3];
                for (int a = 0; a < text.Length; a++)
                    input[a] = Convert.ToDouble(text[a]);
                double costOfFarm = input[0];
                double totalTempTime = 0.0;
                List<double> times = new List<double>();
                double farmsLeft = input[2] / costOfFarm;
                for (int a = 0; a < 200000; a++)
                {
                    double timeToFarm = costOfFarm / cookiesPerSecond;
                    times.Add(totalTempTime + (timeToFarm * farmsLeft));
                    totalTempTime += timeToFarm;
                    double leftTimeCookies = (input[2] / cookiesPerSecond) + totalTempTime;
                    times.Add(leftTimeCookies);
                    cookiesPerSecond += input[1];
                }
                string result = Convert.ToString(times.Min()).Replace(',', '.');
                sw.WriteLine(string.Format("Case #{0}: {1}", i + 1, result));
            }
            sr.Close();
            sw.Close();
        }
    }
}

Thank you very much

Posted 2 weeks ago

Google Code Jam 14 C# Problem A Magic Trick

Hiii!!! Good news, Google Code Jam qualification Round passed! ;)

Congrats to all of you that have passed too!

Here my solution to the problem A.

Github Google Code Jam 14 C# Problem A Magic Trick
Google Code Jam Problem Statement

Here the idea is to go checking all the numbers in the first row the volunteer said against all the numbers in the second row the volunteer said, then if the number is in both, add to a list. At the end only, check if the number has 0, 1 or more elements and return what you need to each case.

Here my code:

using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.IO;

namespace _1
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamReader sr = new StreamReader(@"C:\GCJ\A-small-attempt0.in");
            StreamWriter sw = new StreamWriter(@"C:\GCJ\A-Output.txt");
            string line = string.Empty;
            int cases = int.Parse(sr.ReadLine());
            for (int i = 0; i < cases; i++)
            {
                int answerFirst = int.Parse(sr.ReadLine()) - 1;
                string[] firstBoard = new string[4];
                for (int a = 0; a < 4; a++)
                {
                    firstBoard[a] = sr.ReadLine();
                }
                int secondFirst = int.Parse(sr.ReadLine()) - 1;
                string[] secondBoard = new string[4];
                for (int a = 0; a < 4; a++)
                {
                    secondBoard[a] = sr.ReadLine();
                }
                List<int> list = new List<int>();
                int[] firstRow = firstBoard[answerFirst].Split(' ').Select(x => int.Parse(x)).ToArray<int>();
                int[] secondRow = secondBoard[secondFirst].Split(' ').Select(x => int.Parse(x)).ToArray<int>();
                for (int a = 0; a < firstRow.Length; a++)
                {
                    if (secondRow.Contains(firstRow[a]))
                        list.Add(firstRow[a]);
                }
                if (list.Count == 0)
                    sw.WriteLine(string.Format("Case #{0}: {1}", i + 1, "Volunteer cheated!"));
                if (list.Count == 1)
                    sw.WriteLine(string.Format("Case #{0}: {1}", i + 1, list[0]));
                if (list.Count > 1)
                    sw.WriteLine(string.Format("Case #{0}: {1}", i + 1, "Bad magician!"));
            }
            sr.Close();
            sw.Close();
        }
    }
}

Thank you very much

Posted 2 weeks ago

TopCoder C# SRM 616 Performance!

Hi, here my performance in the SRM 616.

I solve the 250, and tried the 500, but failed system test. Then I did two challenges, one successfully and the other one no.

Final points -> 266.68
Final position -> #504 of 1206
Points earned -> 10
New rating -> 830 -> 840

Github TopCoder C# SRM 616 Performance!

Here the problem statement:
Alex is sleeping soundly. At any moment, his sleepiness can be characterized by an integer. You are given an int S that represents Alex’s initial sleepiness. Unfortunately, several alarms are going to disturb him. These alarms will be ringing in a cyclic order. Each alarm is characterized by its volume. You are given a list of alarm volumes in a int[] volume in the order in which the alarms are going to ring. Every minute the first alarm on the list rings, and Alex’s sleepiness instantly decreases by its volume. The alarm is then moved to the end of the alarm list. While Alex’s sleepiness is positive, he’s still sleeping. Once it becomes less than or equal to zero, Alex immediately wakes up. Return the number of alarms after which Alex will wake up.

Here how I did:
With a while loop checking that S > 0, check if i == values.Length, in this case, put i = 0 and continue, otherwise, substract values[i] to S, add +1 to the results and add +1 to i. At the end, return result.

Here my code:

public class WakingUpEasy
    {
        public int countAlarms(int[] volume, int S)
        {
            int i = 0;
            int result = 0;
            while (S > 0)
            {
                if (i == volume.Length)
                {
                    i = 0;
                    continue;
                }
                S -= volume[i];
                result++;
                i++;
            }
            return result;
        }
    }

Thank you very much

Follow

Get every new post on this blog delivered to your Inbox.

Join other followers:

Visit Us On TwitterVisit Us On FacebookVisit Us On LinkedinCheck Our Feed