Output the following sequence in c# (DaniWeb problem)

On December year 2013, a question was posted on DaniWeb asking to print out the following result

Using loop print the following output on console.
1
121
12321
1234321
123454321
1234321
12321
121
1

The question (and the results) seems pretty easy to reproduce but once you start thinking (without knowing the best solution) you get stuck a bit.

Although at DaniWeb you are not allowed to give answers if the OP (original poster) hasn’t made any effort. Frequent problem solvers including myself decided to show the art of programming (knowledge and creativity).

My solution


static void Main(string[] args)
{
    string number = "12345";
    int counter = -1;
    string output = "";
    int counter2 = 0;
    int pad = (2 * (number.Length - 1)) + 1;
    List list = new List();
    for (int i = 0; i = 0; j--)//   reverse concatenation
        {
            counter2 = output.Length;
            output = output + number[j];
            if (output[output.Length - 1] == number[0])
            {
                Console.WriteLine(output.PadLeft(pad));
                list.Add(output);
                output = output.Remove(counter + 2);
            }
        }
        counter++;
    }
    list.RemoveAt(list.Count - 1);
    list.Reverse();
    foreach (var item in list)
    {
        Console.WriteLine(item.PadLeft(pad));
    }
    Console.ReadLine();
}

Here is how this should be done (trick revealed) code. As you can see the Math.Pow() gives the desired sequence.

static void Main(string[] args)
        {
            double powValue = 0;
            double sqrtvalue = 0;
            int NumberOfValues = 9;
            for (int i = 1; i  0; i = (i - 1) / 10)
            {
                sqrtvalue = Math.Pow(i, 2);
                Console.WriteLine(sqrtvalue.ToString().PadLeft(NumberOfValues));
            }
            Console.ReadKey();
        }

And here is the final solution that was given by a guy called Ketsuekiama which is a awesome C# problem solver (he made the solution using only one line of code with LINQ)

 static void Main(string[] args)
        {
Enumerable.Range(1,5).Select(x => new string('1', x)).Concat(Enumerable.Range(1,4).Reverse().Select(x => new string('1', x))).Select(int.Parse).ToList().ForEach(y => Console.WriteLine("{0,9}", y*y));
            Console.ReadKey();
        }

and here is his evaluation of the code that he wrote (many of us were interested how this actually works)

Okay, so the Enumerable.Range(start, count) generates a sequence of numbers. When you do the select on this it will perform the lambda of the select for each number in the sequence. I’m not really that interested in the number that the Enumerable outputs, that’s a means to an end. This is because, as we know already, the sequence can be nicely calculated using a series of 1s squared.

The string constructor allows you to tell it to repeat a character x amount of times. The lambda, is essentially building the sequence of “1” for me. A common misconception with LINQ is that you have to get out what you put in, but this isn’t true. So I put in an integer (3 for example) and get out a string (for 3 would be “111”)

The Select method builds a new List of strings for me.

Unfortunately, you can’t make Enumerable.Range count down, I tried experimenting with TakeWhile but simply using .Reverse().Select() gave better output, simpler. So to join the two currently non-existent lists together I had to use Concat. If you were to execute this query now, you’d get a list out that looked like

“1”
“11”
“111”
“1111”
“11111”
“1111”
“111”
“11”
“1”
So now we have the string of 1s that can be used for the calculation. As the easiest way to generate them was as strings, they needed to be parsed back to int so I could work on them mathematically, so input list of strings and select the integer back out (Select(int.Parse)). So my list of strings is now a list of ints, the last one is pretty self explanatory, for each of those ints, write out the value of that int squared.

DaniWeb problem

Count number of words in text

Quite a while ago, my friend had a task to write a program which would count how many words does a text contain. He was unsure how to tackle the problem. He wasn’t allowed to use any system function. He had to write all of the code by himself. As I love problems, I decided to do it for him.

The code is written in C# although he had to write in C.

static void Main(string[] args)
        {
            char[] polje;
            string recenica = "";
            string path = "C:\\Users\\some\\Desktop\\sample_file.txt";
            try
            {
                StreamReader str = new StreamReader(path);
                int counter = 0;

                while (!str.EndOfStream)
                {

                    recenica = str.ReadLine();
                    Console.WriteLine(recenica);
                    polje = recenica.ToCharArray();
                    for (int i = 0; i = 97 && (int)polje2[index + 1] = 64 && (int)polje2[index + 1] = 32 && (int)polje2[index] = 58 && (int)polje2[index] <= 64))
            {
                return true;
            }
            return false;
        }

Programming every day usage differences PART 2

Difference between name-spaces and classes?

Namespaces represent scopes {} where variables, classes, structs and other types reside. Classes are just types which also have to reside inside of a scope and this scope is called namespace. If you want to look at it as a hierarchy, namespaces go first here after that all the other elements/types go, in this case classes.

Other thing which should be mentioned are:

– You can reopen namespaces unlike classes

– You can create an instance of classes unlike with namespaces

– Namespaces can be unnamed unlike with classes which must have a name.

Difference between classes and objects?

Classes and objects are the “same thing”. Basically this is a parameter-argument problem. Classes can be considered as when writing a function. Once you call that class (instantiate) the class becomes an Object.

Difference between arrays and lists?

Both of them can store multiple values and that’s their purpose, to store multiple values. Arrays, however have a fixed storage, so once you declare them you cannot add more cells to it whereas lists are re-sizable.  The other important thing is that arrays are more efficient since they are primitive types and do not need a wrapper around them. List’s represents interfaces (not primitive types) and interfaces have therefore multiple implementations.

Difference between inheritance and interfaces?

Inheritance assumes having an existing class (let’s say a base class, general class like human) which will then be adopted by the newly created class which is related to the base (existing) class and therefore the new class as now access to all properties and methods from the inherited class. It is easier to build the new class or just extend it so it serves to its purpose.

Interface can be seen as blocks or scopes which contain unimplemented variables and methods. A class can inherit multiple interfaces whereas only one class can be inherited. There is no method implementation inside an interface. This is done inside the class once the interface is inherited by it.

Note: The reason why you can’t inherit multiple classes is because you could get a collision between two elements, for example methods. Let’s assume that you can inherit two classes and let the first be “Automobile” class and the second “Robot” class. Suppose both methods have a same method called Run(); When you try to call the method Run() which one should be called? Robots class method or Automobile class method. Because of such problem (which was quite expressed/conspicuous in c++ language) code engineers of languages C# and Java ect. decided not to allow multiple inheritance.

Difference between switch statement, if statements and ternary operators?

There isn’t any better performance in any of the above. Use whatever you like. However it is advised to use switch statement if there are more than 6 if’s. Ternary operators just give a concise syntax and it looks better.

Difference between multidimensional array and jagged array?

Multidimensional arrays are fixed arrays. Once you declare it you are done. Jagged arrays are arrays which contain arrays. This can be also said for the multidimensional array but every row has a same size as does column. Jagged arrays row and column do not have to have same sizes.

Jagged arrays are faster than multidimensional arrays.