Thursday, 12 July 2018

How to write a program to find the permutations of a given string in C#(coding interview question)


I really feel challenged in solving this problem. Basically the term permutations means arranging in an unique order(I don't know anything more). I tried finding permutations on a piece of paper, quite easy to think and note them down. Then I tried to write a program for it to find permutations for as many character as we like. I figured to solve the problem in the following way. Hope it will help you learn something. There is fiddle link below. Run it and know how it works.



using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var stringText = "ABCD";
        var possibilities = GetPossibilities(stringText);
        Console.WriteLine("The permutations of *{0}* are as shown below:", stringText);
        foreach (var pos in possibilities)
        {
            Console.WriteLine(">>>>>>>>>>>>>>" + pos + "<<<<<<<<<<<<<<");
        }
    }

    private static List<string> GetPossibilities(string text)
    {
        bool reached = false;
        List<string> possibleStrings = new List<string>();
        List<int> possibleInts = new List<int>();
        var textArray = text.ToArray();
        string prev = string.Empty;
        string dummy = string.Empty;
        int preIndexNum = 1;
        while (!reached)
        {
            var indexes = GetDigitsList(preIndexNum);
            foreach (var index in indexes)
            {
                dummy = dummy + textArray[index - 1];
            }
            bool isPermutation = CheckPermutation(dummy, text);
            if (isPermutation)
            {
                possibleStrings.Add(dummy);
                possibleInts.Add(preIndexNum);
            }
            dummy = string.Empty;
            reached = checkReached(preIndexNum, textArray.Length);
            preIndexNum = GetNumberBasedOnTextLength(textArray.Length, preIndexNum);
        }
        var distinctStrings = possibleStrings.Distinct().ToList();
        return distinctStrings;
    }


    private static bool CheckPermutation(string dummy, string text)
    {
        if (dummy.Count() != text.Length)
            return false;
        else
        {
            foreach (var t in dummy)
            {
                if (dummy.Count(x => x == t) == text.Count(x => x == t))
                    continue;
                else
                    return false;
            }
            return true;
        }
    }

    private static int GetNumberBasedOnTextLength(int length, int number)
    {
        var digitsList = GetDigitsList(number);
        digitsList.Reverse();
        var digitsArray = digitsList.ToArray();
        var dummyIntList = new int[digitsArray.Length + 1];
        for (int i = 0; i < digitsArray.Length; i++)
        {
            dummyIntList[i] = digitsArray[i];
        }
        for (int i = 0; i < dummyIntList.Length; i++)
        {
            if (dummyIntList[i] < length)
            {
                dummyIntList[i] = dummyIntList[i] + 1;
                break;
            }
            if (dummyIntList[i] == length)
            {
                for (int j = i; j < dummyIntList.Length; j++)
                {
                    if (dummyIntList[j] < length)
                    {
                        dummyIntList[j] = dummyIntList[j] + 1;
                        break;
                    }
                    else
                        dummyIntList[j] = 1;
                }
                break;
            }
        }
        var list = dummyIntList.ToList();
        list.Reverse();
        number = GenrateNumber(list.ToArray());
        return number;
    }
    private static int GenrateNumber(int[] digitsArray)
    {
        int sum = 0;
        for (int i = 0; i < digitsArray.Length; i++)
        {
            if (digitsArray[i] == 0)
                continue;
            sum = sum * 10 + digitsArray[i];
        }
        return sum;
    }
    private static List<int> GetDigitsList(int number)
    {
        List<int> digitsList = new List<int>();
        while (number > 0)
        {
            digitsList.Add(number % 10);
            number = number / 10;
        }
        digitsList.Reverse();
        return digitsList;
    }
    private static bool checkReached(int preIndexNum, int length)
    {
        var digitsList = GetDigitsList(preIndexNum);
        if (digitsList.Count() == length)
        {
            foreach (var digit in digitsList)
            {
                if (digit < length)
                    return false;
            }
            return true;
        }
        else
        {
            return false;
        }
    }
}

To know the how the code works check this link: PermutationsOfString(.net fiddle)

Saturday, 7 July 2018

Amazons coding interview question on possible ways of reaching to top of a stair case with N steps with N step overs

Actually I came across a video in youtube giving an overview on this coding interview question by amazon. I have gone through the question and started coding in c#. Here I solved the problem in my own way to test my skills in programming.

The question is about to find possible number of ways from starting point, all the way to the end with a set of possible step overs. To get a quick understanding I provided an image.

The code I have pasted below is basically a console app created in visual studio. You can create a new console app in your local and paste this code there and run it. If you can refactor the code just refactor it and paste it in the comment below.


To know the how the code works check this link: StairNWays(.net fiddle)


using System;
using System.Collections.Generic;
using System.Linq;

namespace stairNways
{
    class Program
    {
        static void Main(string[] args)
        {
            int noOfPossibilities;
            int noOfSteps;
            List<int> combinationsList = new List<int>();
            List<int> noOfWaysList = new List<int>();
            bool reached = false;
            Console.Write("Enter the number of steps: ");
            noOfSteps = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the number of possible step overs that you want to make: ");
            noOfPossibilities = Convert.ToInt32(Console.ReadLine());
            if (noOfPossibilities > 0)
            {
                Console.WriteLine("Enter the step over values: ");
                for (int i = 0; i < noOfPossibilities; i++)
                {
                    Console.Write("> ");
                    combinationsList.Add(Convert.ToInt32(Console.ReadLine()));
                }
                Console.WriteLine("You can reach your destination in following possible ways");
                do
                {
                    noOfWaysList = GetArray(noOfWaysList, combinationsList, noOfSteps);
                    reached = checkReached(noOfWaysList, noOfSteps);
                } while (!reached);
                Console.WriteLine(">>>>>>>>>>>>>>>>{0}<<<<<<<<<<<<<<<", noOfWaysList.Count());
            }
            else
            {
                Console.WriteLine("you entered an invalid nuber");
            }
            Console.ReadKey();
        }

        private static bool checkReached(List<int> noOfWaysList, int noOfSteps)
        {
            bool reached = true;
            foreach (var nwl in noOfWaysList)
            {
                if (nwl != noOfSteps)
                    reached = false;
            }
            return reached;
        }

        private static List<int> GetArray(List<int> possibleWaysList, List<int> stepOvers, int noOfSteps)
        {
            if (possibleWaysList == null || possibleWaysList.Count() == 0)
            {
                foreach (var stepOver in stepOvers)
                {
                    possibleWaysList.Add(stepOver);
                }
            }
            else
            {
                List<int> dummyList = new List<int>();
                foreach (var pwl in possibleWaysList)
                {
                    if (pwl == noOfSteps)
                    {
                        dummyList.Add(pwl);
                        continue;
                    }

                    foreach (var so in stepOvers)
                    {
                        if ((pwl + so) <= noOfSteps)
                        {
                            dummyList.Add(pwl + so);
                        }
                    }
                }
                return dummyList;
            }
            return possibleWaysList;
        }
    }
}




Saturday, 13 May 2017

Understanding "USING" keyword in c# programming

The keyword USING is similar to #INCLUDE in c programming to add the namespaces into the program which we are going to execute. We can write programs without using this keyword too. The bellow two example show how the code is changed with and without including the "USING" keyword in the program.

The program with "USING" keyword:

using System;
class SimpleHelloWorld
{
    static void Main()
    {
        Console.WriteLine("Hello World!");
    }
}




The program without "USING" keyword:

class WithoutUsing
{
    static void Main()
    {
        System.Console.WriteLine("Hello World!");
    }
}



Simple Hello World Program

The program is as follows:


using System;
class SimpleHelloWorld
{
    static void Main()
    {
        Console.WriteLine("Hello World!");
    }
}

The output is as follows:






Thursday, 4 May 2017

Creating a Sample WPF Application in Visual Studio 2015 using Visual Basic WPF

What is WPF(Windows Presentation Foundation) application?

It is a graphical subsystem in windows to render user interface in windows-based applications. WPF works on the base of DirectX which is a set of API's.  


1.Open visual studio 2015 and create a new WPF application with the name Hello:



2.Create two radio buttons:

         To create radio button double click on Radio Button control in toolbox. If the toolbox is hidden, select view menu and click on toolbox (or) use a shortcut "Ctrl+Alt+X".  You can create a radio button on double clicking on radio button which is listed in "Common Wpf Controls".



3.Again create another radio button. And place them by dragging. After dragging and placing both the radio buttons the main window will appear like this.



4.The names behind the radio buttons is "RadioButton" by default. The name of the button can be changed as per our requirement of its use in the application. To change the name of radiobutton select the radiobutton to access the properties of it. And then edit the name in "Content Property" as shown in the figure below.




5.Select each radio button and change the font size and its style as shown in the figure below.



6.Then add a button into the main window by double clicking on the "Button" in the toolbox window. And then change its name is "Display". Adjust the size of the button to look apt to the window size.



7.Double click on the "Display Button" to write the code. The code is about to generate a message box when you click the button in the main window. The message box display different messages based on the selection of hello and goodbye radio buttons. The code is as follows:


Class MainWindow
    Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
        If radioButton.IsChecked = True Then
            MessageBox.Show("Hello")
        Else radiobutton.IsChecked = True
            MessageBox.Show("GoodBye")
        End If
    End Sub
End Class



Then click debug to run the application. 



Wednesday, 3 May 2017

How to change the color theme into dark in visual studio 2015

Steps:-

1.First open the visual studio 2015.
2.Select the Tools on the Menu bar.
3.Select Options
4.After selecting the options in the tools menu.
5.In the option window Change the color theme into Dark.
6.Set the color theme into dark and click OK.

You can follow the above steps with the below images.

1.First open the visual studio 2015.



2.Select the Tools on the Menu bar.



3.Select Options


4.After selecting the options in the tools menu.




5.In the option window Change the color theme into Dark.



6.Set the color theme into dark and click OK.



7.After changing the color theme you can view the visual studio like this.


Monday, 3 April 2017

Finding the given number is Armstrong number or not using C programming(c programming examples)(c program examples)

If you want to see this code with a perfect indentation, copy the code into "sublime text editor" and make sure that the type of code is set to 'c' at the bottom right of the window. After pasting the code press the command "ctrl+shift+P", you get a search box. Type "indentation" you get an option like this below the search box "Indentation: Reindent lines". Clink on that to get the code with indentation.(c programming examples)

The program is as follows:


#include <stdio.h>
main()
{
 int num, i, sum=0, cube;
 printf("enter the number to verify is it armstrong or not\n");
 scanf("%d", &num);
 i=num;
 while(num>0)
 {
  cube=(num%10)*(num%10)*(num%10);
  sum=sum+cube;
  num=num/10;
 }
 if(num!=0)
  sum=sum+(num*num*num);
 if (sum==i)
  printf("the entered number is armstrong number\n");
 else
  printf("the entered number is not armstrong number\n");
return 0;
}


The output is as follows:

C is a general-purpose programming language. It has been closely associated with the UNIX system where is was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language” because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains.(c programming examples)(c program examples)
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP-7.(c programming examples)
BCPL and B are “typeless” languages. By contrast, C provides a variety of data types. The fundamental types are characters, and integers and floating point numbers of several sizes. In addition, there is a hierarchy of derived data types created with pointers, arrays, structures, and unions. Expressions are formed from operators and operands; any expression, including an assignment or a function call, can be a statement. Pointers provide for machine-independent address arithmetic.(c programming examples)(c program examples)
C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible cases (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).(c programming examples)(c program examples)
Functions may return values of basic types, structures, unions, or pointers. Any function may be called recursively. Local variables are typically “automatic,” or created anew with each invocation. Function definitions may not be nested but variables may be declared in a block-structured fashion. The functions of a C program may exist I separate source files that are compiled separately. Variables may be internal to a function, external but know only within a single source file, or visible to the entire program.(c programming examples)(c program examples)
A preprocessing step performs macro substitution on program text, inclusion of other source files, conditional compilation.(c programming examples)(c program examples)
C  is a relatively “low level” language. This characterization is not pejorative; it simply means that C deals with the same sort of object that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines.(c programming examples)(c program examples)
C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is n heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions.(c programming examples)(c program examples)



Finding the list of Armstrong numbers upto given input number using C programming(c programming examples)(c program examples)

If you want to see this code with a perfect indentation, copy the code into "sublime text editor" and make sure that the type of code is set to 'c' at the bottom right of the window. After pasting the code press the command "ctrl+shift+P", you get a search box. Type "indentation" you get an option like this below the search box "Indentation: Reindent lines". Clink on that to get the code with indentation.

The program is as follows:

#include <stdio.h>
main()
{
 int num, i, sum=0, cube, upto;
 printf("enter the number upto which u need tha armstrong numbers list\n");
 scanf("%d", &upto);
 i=num=1;
 printf("the list of armstrong numbers are:\n");
 printf("%d\t", 0 );
 while(i<=upto)
 {
  sum=0;
 while(num>0)
 {
  cube=(num%10)*(num%10)*(num%10);
  sum=sum+cube;
  num=num/10;
 }
 if(num!=0)
  sum=sum+(num*num*num);
 if (sum==i)
  printf("%d\t", i);
 i++;
 num=i;
 }
return 0;
}


The output is as follows:




C is a general-purpose programming language. It has been closely associated with the UNIX system where is was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language” because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains.(c programming examples)(c program examples)
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP-7.(c programming examples)
BCPL and B are “typeless” languages. By contrast, C provides a variety of data types. The fundamental types are characters, and integers and floating point numbers of several sizes. In addition, there is a hierarchy of derived data types created with pointers, arrays, structures, and unions. Expressions are formed from operators and operands; any expression, including an assignment or a function call, can be a statement. Pointers provide for machine-independent address arithmetic.(c programming examples)(c program examples)
C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible cases (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).(c programming examples)(c program examples)
Functions may return values of basic types, structures, unions, or pointers. Any function may be called recursively. Local variables are typically “automatic,” or created anew with each invocation. Function definitions may not be nested but variables may be declared in a block-structured fashion. The functions of a C program may exist I separate source files that are compiled separately. Variables may be internal to a function, external but know only within a single source file, or visible to the entire program.(c programming examples)(c program examples)
A preprocessing step performs macro substitution on program text, inclusion of other source files, conditional compilation.(c programming examples)(c program examples)
C  is a relatively “low level” language. This characterization is not pejorative; it simply means that C deals with the same sort of object that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines.(c programming examples)(c program examples)
C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is n heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions.(c programming examples)(c program examples)