Saturday, July 10, 2021

 Question: Given two decimal numbers represented as Strings, write a function to add those two and return the result

Assumptions: 

1. The input will be having only numbers, will not be having any alphabets or symbols

2. Both the numbers will be positive numbers.

3. One or both numbers might not be having decimal point also is a valid scenario 

eg:

1.    "1.2" + "2.3" = 3.5

2.    "3" + "5" = "8"

3. "3648698147689.368147698" + "6848634.687469717776897811189" = "3648704996324.055617415776897811189"



My Solution:

public static String addStrings(String number1, String number2){
int i=0;
int lengthOfFirstPartOfFirstString = number1.substring(0, number1.contains(".") ? number1.indexOf(".") : number1.length()).length();
int lengthOfFirstPartOfSecondString = number2.substring(0, number2.contains(".") ? number2.indexOf(".") : number2.length()).length();
int lengthOfSecondPartOfFirstString = number1.contains(".") ? number1.substring(number1.indexOf(".")+1).length() : 0;
int lengthOfSecondPartOfSecondString = number2.contains(".") ? number2.substring(number2.indexOf(".")+1).length() : 0;
if(lengthOfFirstPartOfFirstString != lengthOfFirstPartOfSecondString){
StringBuilder padZeroes = new StringBuilder();
while(i++ != Math.abs(lengthOfFirstPartOfFirstString - lengthOfFirstPartOfSecondString)){
padZeroes.append("0");
}
i=0;
if(lengthOfFirstPartOfFirstString > lengthOfFirstPartOfSecondString){
number2 = padZeroes.toString() + number2;
} else{
number1 = padZeroes.toString() + number1;
}
}
if(lengthOfSecondPartOfFirstString != lengthOfSecondPartOfSecondString){
StringBuilder padZeroes = new StringBuilder();
while(i++ != Math.abs(lengthOfSecondPartOfFirstString - lengthOfSecondPartOfSecondString)){
padZeroes.append("0");
}
if(lengthOfSecondPartOfFirstString > lengthOfSecondPartOfSecondString){
if(!number2.contains(".")){
number2 = number2 + ".";
}
number2 = number2 + padZeroes.toString();
} else{
if(!number1.contains(".")){
number1 = number1 + ".";
}
number1 = number1 + padZeroes.toString();
}
}
String number1Rev = strrev(number1);
String number2Rev = strrev(number2);
String output = "";
int carry = 0;
for(int j=0; j<number1Rev.length(); j++){
if(number1Rev.charAt(j) != '.'){
int sum = Integer.parseInt(number1Rev.substring(j, j+1)) + Integer.parseInt(number2Rev.substring(j, j+1)) + carry;
carry = 0;
if(sum > 9){
carry = 1;
sum = sum - 10;
}
output = output + String.valueOf(sum);
} else {
output = output + ".";
}
}
return strrev(output);
}

public static String strrev(String str){
StringBuilder number1StrBld = new StringBuilder(str);
return number1StrBld.reverse().toString();
}

Wednesday, January 12, 2011

Things to keep in mind while upgrading a project

Things to keep in mind while upgrading a project

Upgrading a project has two meanings

1. The project is being upgraded from a previous version of the same programming language to the newer versoin.
2. The project is converted from an older programming language to a different programming language which is new.

This blog is all about the second point. This blog is also applicable if we are converting a project from one programming language to another.

Do not just convert:- The first point to remember if you are converting a project from one programming language to another is that you SHOULD NOT just convert. It is very easy to copy the code from the application, paste it to the IDE of the second language and just convert. But it should be the last thing which is expected from you as a programmer. If you are doing exactly this, you are not a good programmer (in my personal opinion).

First thing that you should keep in your mind when you are converting a project is that, the meaning of the task in your hand is very simple – You are going to write a software which is already written. You can run the old running application and see how it works. But don’t look into the code. Understand the business and follow the style of the new language. Apply whatever framework which is apt for the software, which is applicable to the language.

Reason for my argument for not JUST CONVERT:- The way a particular application can be written in two different programming language will be in two different ways. I will state one simple example –

Consider you are converting an application written ages back in C++ to .NET. Also consider that no table in the database that the application has a primary key (WTF?). If you want to do an update operation in the database, you will have inbuilt method called Post() which the framework provides you which handles the update process smoothly so that you may not want to worry about it, in C++. But if you are using .NET, you will have to write query to update – a query which takes care of everything that no duplication will occur and you need to take care of a long list of columns to make a row unique. If the update process consists of multiple rows, you might find yourself in trouble if you are using .NET and dealing with multiple columns to find a unique row. If anything goes wrong, the DB won’t allow you to save the info and there you can find yourself in trouble.

The above stated is just a single example. Different operations handled in an older programming language might not be safe to apply in the same way in our current language. The new language will have greater security measures to ensure that nothing goes wrong and to keep everything in control.

Things to communicate to the client:- Identify the areas in the existing code base which can be considered as obsolete. An example being – the above mentioned case of not having a primary key. In this case, a change in the DB design should be there. Identify those areas. Suggest new implementations. Convince the client that this is the right way to do things, now. Make the application most robust in every sense.

Time frame calculation:- Also the time frame calculation to complete this type of project is very crucial. It is utterly absurd to calculate the time based on the assumption that we have a code base, whatever be the programming language. It is always better to calculate the time frame by treating the application as a new one. In my personal opinion, calculate the time based on the requirements, and design and the initial stuffs, solely. Never ever assume that this is an existing application and a code base is also there.
Happy Coding.
  

Monday, January 3, 2011

Being Empathetic to others - What religions and science has to say...

Why should we help others? Is it mandatory that we need to help the needy? Well, the answer is, even if you don’t do this, nobody will kill you. But think deeply. I am presenting here my thought in this topic. There are a bunch of religions all over the world. When considering all these religions in a broader perspective, as all speakers around the world and religious leaders say all these leads to the same point – The eternal truth. Being religious is not bad. However, being religious to that point which blurs our vision from having a clear picture of what happens around us is dangerous. In my opinion, there will be no scripture in this world, which does not mention about being empathetic to our fellow beings.



In bible, Jesus Christ urges everyone to love every other person the same way you love yourself. We all love our self the most dearly. We will eat the food we like the most, buy clothes we like, and will live our life the way we like – mostly, in the most beautiful way. We all will try to make our life as smooth and happy as possible. Why cant we do this to others as well? Why cant we help the needy, feed those who are hungry? What will we do if God himself comes to us and ask us to give him some food and clothe? Wont we provide him with what he want? I am sure that we all will try our level best to make him happy.


I know my above paragraph is a cliché one – All might have read this or heard this from various speakers who come across our life.



But when I thought about various incidents that mentioned in bible, one incident caught my attention – God created Man in his own resemblance. Now the question is why it is mentioned like that in the bible? Does God really have a shape like ours? Is God really a He or a She? From a religious perspective, God is a He if we consider Christianity or Islam and God can be He or She if we consider Hinduism. Now the question comes again, why did it mentioned like that in bible? Now try to combine the two statements from bible – “Love every other person the same way you love yourself” and “God created Man in his own resemblance”. Doesn’t it mean that God is urging us to find God in our fellow beings? This gives other statements from bible a perfect sense –“ If you do anything to them (poor people), you are doing it to me”, “If you cant love your brother who is with you and visible to you, then how can you love God, whom you cannot see?”



In Hindu mythology also, there are two statements – “Aham Brahmasmi” and Tathwamasi” which means that “God is in you” when you are trying to find him elsewhere. Doesn’t this also agree with the point that we should find God in ourselves and our fellow beings and love and help others like we love our self?



Here we can find that various religions – even though has different mode of worshipping and all – aims at the well being of the entire humanity.



Now take the case of Science. What does science has to say in this? The most widely accepted theory about the origin of universe is “The Big Bang Theory”. According to that, this universe is formed as a result of a big bang. So before Big Bang, what might have been the state? Some scientists say a chain of Big Bangs have happened and some say a very dense form of energy was there. Most of the scientists agrees with the intervention of a force – something external, to trigger these. And they have given that force or that source of energy a name – God. So we can say, according to science, God is a source of energy which fills the entire universe and anything beyond that also, if there is any. String theory is the most modern theory which explains the universe and its origin. As you all know, every matter is made up of molecules, which in turn by atoms, which consists of electrons and protons. If we go further inside, we can find particles called quarks. According to String theory, if we go deeper level into the quarks, we can find strings of energy vibrating in certain frequencies inside it. That means we can see God (energy, according to science), deep inside us. When I discussed this with one of my friends, he told me the beauty is that the further understand science, the greater we understand God. We can find his signature in each and everything around us. That means God is in us and in our fellow beings.



This is the real beauty where we can see religion and science agrees upon the concept of God being inside us. So treating our fellow beings with compassion is the great thing that we can do. A smile, a consolation, a helping hand to the needy will make small changes. And don’t forget the saying – “Little things make perfection. But perfection is not a little thing”.


Sunday, August 8, 2010

How to make a WPF Popup "Find control" - draggable


WPF – Windows Presentation Foundation offers a control called Popup which can be used to "Pop up" some texts or information whenever we need it. Also, this control can be customized so that it performs some specified function we need.

One instance when we can use Popup to create a custom control is when we have a requirement to create a "Find Control" box of our own. The reason behind using a Popup control rather than going for another window to design a Popup control is that, since the Popup is linked with that page where the information is shown (from which some text needs to be found out using the Find Control box), the communication between the Popup and the Window containing the content is easy.

So here we go...

First, create a UserControl to create a custom control for the TextArea where the text needs to be displayed...

Here is the xaml code:

   <Grid>
        <RichTextBox IsDocumentEnabled="True"
                     VerticalScrollBarVisibility="Visible"
                     HorizontalScrollBarVisibility="Visible" x:Name="uxRichTextBox" IsReadOnly="True"/>
    Grid>

Now write the code beside for this file.

public partial class CustomRichText : UserControl
    {
        private FindAndReplaceManager manager;
        public CustomRichText()
        {
            InitializeComponent();

            this.Loaded += delegate(object sender, RoutedEventArgs args)
            {
                if (!string.IsNullOrEmpty(FilePath))
                {
                    ProcessFile(FilePath,uxRichTextBox);
                }
            };
        }



        public string FilePath
        {
            get { return (string)GetValue(FilePathProperty); }
            set { SetValue(FilePathProperty, value); }
        }

        // Using a DependencyProperty as the backing store for FilePath.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FilePathProperty =
            DependencyProperty.Register("FilePath", typeof(string), typeof(CustomRichText), new UIPropertyMetadata(new PropertyChangedCallback(FilePathChangeCallBack)));


        private static  void FilePathChangeCallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            CustomRichText cRichTxtBx = d as CustomRichText;
            if (!String.IsNullOrEmpty(cRichTxtBx.FilePath))
            {
                ProcessFile(cRichTxtBx.FilePath, cRichTxtBx.uxRichTextBox);
            }
        }

        private static void ProcessFile(string filePath, RichTextBox richTextBox)
        {
            StreamReader file = new System.IO.StreamReader(filePath);
            richTextBox.Document = new FlowDocument();
            Paragraph p = new Paragraph();;
            while (!file.EndOfStream)
            {               
                p.Inlines.Add(file.ReadLine());
                p.Inlines.Add(new LineBreak());
            }
            richTextBox.Document.Blocks.Add(p);
        }              

        public void FindText(string searchText, FindOptions findOptions)
        {
            String findText = searchText;
            if (String.IsNullOrEmpty(findText))
            {
                return;
            }

            if (manager == null)
            {
                manager = new FindAndReplaceManager(uxRichTextBox.Document);
            }

            manager.CurrentPosition = uxRichTextBox.CaretPosition;

            TextRange textRange = manager.FindNext(findText, findOptions);
            if (textRange != null)
            {
                uxRichTextBox.Focus();
                uxRichTextBox.Selection.Select(textRange.Start, textRange.End);
            }
            else
            {
                if (manager.CurrentPosition.CompareTo(uxRichTextBox.Document.ContentEnd) == 0)
                {
                    MessageBox.Show("You've been reached to the end of the document!");
                    uxRichTextBox.CaretPosition = uxRichTextBox.Document.ContentStart;
                    manager.CurrentPosition = uxRichTextBox.CaretPosition;
                }
            }
        }      
    }

Now comes our original page where we are going to use this custom control.

The xaml goes like this...

<controls:CustomRichText FilePath="{Binding FilePath}"
                                 Grid.Row="2"
                                 x:Name="uxRichText" />
        <Popup x:Name="uxFind"
               AllowsTransparency="False"
               Width="363"
               Height="111"                                            
               StaysOpen="True" >
            <Border BorderThickness="2"
                    BorderBrush="#FFE8E6E2" BitmapEffect="{StaticResource popupShadow}">
                <Grid FocusManager.IsFocusScope="True"
                      HorizontalAlignment="Left"
                      Background="#FFD4D0C8"
                      Width="360"
                      Height="126"
                      >
                    <Grid.RowDefinitions>
                        <RowDefinition Height="21" />
                        <RowDefinition Height="30" />
                        <RowDefinition Height="30" />
                        <RowDefinition Height="30" />
                    Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="85" />
                    Grid.ColumnDefinitions>
                    <DockPanel Background="#FF274383"
                               Grid.Row="0"
                               Grid.Column="0"
                               Grid.ColumnSpan="2">
                        <TextBlock Text="Find"
                                   Height="16"
                                   Margin="2,2,0,2"
                                   Foreground="White"
                                   FontWeight="Bold" />
                        <Button x:Name="Close" Content="X"
                                Width="17"
                                Height="17.5"
                                HorizontalAlignment="Right" Click="Close_Click" />
                    DockPanel>
                    <StackPanel Orientation="Horizontal"
                                Grid.Column="0"
                                Grid.Row="1">
                        <TextBlock Text="Find what:"
                                   Margin="4,0,0,0"
                                   VerticalAlignment="Center" />
                        <TextBox  x:Name="uxSearchText"
                                  Width="192"
                                  Height="20"
                                  Margin="10,0,0,0" />
                    StackPanel>
                    <Button x:Name="Find" Content="Find Next"
                            Grid.Column="1"
                            Grid.Row="1"
                            Height="25"
                            Width="75" Click="Find_Click" />
                    <CheckBox x:Name="MatchCase" Content="Find match case only"
                              Grid.Row="2"
                              Margin="4,0,0,0" Click="FindOptions_Click"  />
                    <CheckBox x:Name="WholeWord" Content="Find whole word"
                              Grid.Row="3"
                              Margin="4,0,0,0" Click="FindOptions_Click" />
                    <Button x:Name="Cancel" Content="Cancel"
                            Grid.Row="2"
                            Grid.Column="1"
                            Height="25"
                            Width="75" Click="Close_Click" IsEnabled="{Binding ElementName=uxSearchText, Converter={StaticResource nullToVisibility}}" />
                Grid>
            Border>
        Popup>

In the code beside of this, we can set the "FilePath" property which is binded in the CustomRichText control to contain the full path of the file. You can define this property as a DependencyProperty like this

 public static readonly DependencyProperty FilePathProperty =
            DependencyProperty.Register("FilePath", typeof(string), typeof(FileViewer), new UIPropertyMetadata(string.Empty));

Now assume that we are showing this Find Control on the click of a Menu item called "Find". So inside the click event of the "Find" Menu item, add this code:

            uxFind.IsOpen = true;
         uxFind.StaysOpen = true;

Add the following code to Find a particular word and to close the Find control:-

  private void Close_Click(object sender, RoutedEventArgs e)
        {
            uxFind.IsOpen = false;
        }

        private void Find_Click(object sender, RoutedEventArgs e)
        {
            uxRichText.FindText(uxSearchText.Text, findOptions);
        }

        private void FindOptions_Click(object sender, RoutedEventArgs e)
        {
            if (WholeWord.IsChecked == true && MatchCase.IsChecked == true)
            {
                findOptions = FindOptions.MatchCaseAndWholeWord;
            }
            else if (WholeWord.IsChecked == false && MatchCase.IsChecked == true)
            {
                findOptions = FindOptions.MatchCase;
            }
            else if (WholeWord.IsChecked == true && MatchCase.IsChecked == true)
            {
                findOptions = FindOptions.MatchWholeWord;
            }
            else
            {
                findOptions = FindOptions.None;
            }
        }

Now everything is set and we have our find control in our hand. But this control has a problem. It is not draggable. The problem is that if we want to find a word, and if the word comes under this control, we cant move this to see the word. But dont worry, we have a solution for you...

The whole logic behind dragging a window lies in finding it’s initial position, find the initial mouse position by listening to MouseLeftButtonDown event. Also, find the last Mouse position by listening to the MouseLeftButtonUp event. Find the delta, add it to the initial TopLeft of the Find Control and there you can see your Find Control is re-located.

See the code for it below:-

First, add the following code to your “Find” menu item click event


MouseLeftButtonDown += new MouseButtonEventHandler(Window1_MouseLeftButtonDown);
            MouseLeftButtonUp += new MouseButtonEventHandler(Window1_MouseLeftButtonUp);
            s = new Size(363, 111);
            uxFind.Placement = PlacementMode.AbsolutePoint;
            uxFind.PlacementRectangle = new Rect(new Point(450, 450), s);
            initialPosOfPopup.X = Convert.ToInt32(uxFind.PlacementRectangle.Left);
            initialPosOfPopup.Y = Convert.ToInt32(uxFind.PlacementRectangle.Top);

Then write the handler methods:- for getting the first mouse position

      void Window1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
      {
          firstClickPoint = System.Windows.Forms.Cursor.Position;

      }

For getting the last mouse position, calculating delta, and applying it.

      void Window1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
      {
          lastClickPoint = System.Windows.Forms.Cursor.Position;
          int deltaX = lastClickPoint.X - firstClickPoint.X;
          int deltaY = lastClickPoint.Y - firstClickPoint.Y;

          if ((initialPosOfPopup.X < firstClickPoint.X) && (firstClickPoint.X < initialPosOfPopup.X + 200) && (initialPosOfPopup.Y < firstClickPoint.Y) && (firstClickPoint.Y < initialPosOfPopup.Y + 200))
              uxFind.PlacementRectangle = new Rect(new Point(Convert.ToDouble(deltaX) + initialPosOfPopup.X, Convert.ToDouble(deltaY) + initialPosOfPopup.Y), s);

          initialPosOfPopup.X = Convert.ToInt32(uxFind.PlacementRectangle.Left);
          initialPosOfPopup.Y = Convert.ToInt32(uxFind.PlacementRectangle.Top);
      }

Also, declare these variables as global:-

        System.Drawing.Point firstClickPoint;
        System.Drawing.Point lastClickPoint;
        System.Drawing.Point initialPosOfPopup;

        Size s;

Done!! Now you have a Find Control box which you can re-position.

Happy Coding…