Saturday, August 29, 2015

Copy From Text Editor to Visual Studio IDE Command Prompt

Visual Studio IDE does not come with a Console View or Console Window to interact with a running Console application as in Eclipse IDE.

When you start your Console Application in Visual Studio IDE a Command Prompt appears and disappears as expected.

In order send parameters to a running Console Application's Main() method from the Visual Studio Command Prompt you need to follow the following steps :

1- Right Click on the Visual Studio Command Prompt Window Header
2- Select Edit
3- Choose your operation from the drop-down-list such as Mark-Copy-Paste






Max Common Array Slice in C#

You are given a sequence of n integers a0, a1, . . . , an−1 and the task is to find the maximum slice of the array which contains no more than two different numbers.

Input 1 :

[1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8]

Result 1 : Answer is 10 because the array slice of (0, 9) is the largest slice of the array with no more than two different numbers.

- There are 10 items in this slice which are "1, 1, 1, 2, 2, 2, 1, 1, 2, 2".
- 2 different numbers for this slice are 1 and 2.


Input 2:

[53, 800, 0, 0, 0, 356, 8988, 1, 1]

Result 2: Answer is because the slice of (1, 4) is the largest slice of the array with no more than two different numbers. The slice (2, 5) would also be valid and would still give a result of 4.

- There are 4 items in this slice which are "800,0,0,0".
- 2 different numbers for this slice are 800 and 0.

Maximum common array slice of the array which contains no more than two different numbers implementation in C# takes a comma delimited array of numbers from STDIN and the output is written back to console.

Important thing here is that the usage of the Dictionary data structure from "System.Collections.Generic" namespace.

Sample implementation uses Add, ContainsKey and Clear methods of the Dictionary class of the .Net framework.

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

namespace MaxCommonArraySlice
{
    class Program
    {

        public static int maxCommonArraySlice(int[] array)
        {
            Dictionary<int, int> items = new Dictionary<int, int>();
            int result = 0;
            int startIndex = 0;
            int uniqueItemCount = 0;
            while (startIndex < array.Length)
            {
                items.Add(array[startIndex], startIndex);
                uniqueItemCount = uniqueItemCount + 1;
                for (int j = startIndex + 1; j < array.Length; j++)
                {
                    if (items.ContainsKey(array[j]) == false)
                    {
                        if (uniqueItemCount != 2)
                        {
                            items.Add(array[j], j);
                            uniqueItemCount = uniqueItemCount + 1;
                            if (j == array.Length - 1)
                            {
                                result = Math.Max(result, j - startIndex + 1);
                                startIndex = array.Length;
                                break;
                            }
                        }
                        else if (uniqueItemCount == 2)
                        {
                            result = Math.Max(result, j - startIndex);
                            int item = array[j - 1];
                            int firstFoundIndex = 0;
                            for (int k = j - 1; k >= 0; k--)
                            {
                                if (array[k] != item)
                                {
                                    firstFoundIndex = k + 1;
                                    break;
                                }
                            }
                            startIndex = firstFoundIndex;
                            items.Clear();
                            uniqueItemCount = 0;
                            break;
                        }
                    }
                    else if (items.ContainsKey(array[j]) != false)
                    {
                        if (j == array.Length - 1)
                        {
                            result = Math.Max(result, j - startIndex + 1);
                            startIndex = array.Length;
                            break;
                        }
                    }
                }
            }

            return result;
        }

        static void Main(string[] args)
        {

            string line = Console.ReadLine();
            if (!line.Equals(""))
            {
                if (line.Length == 1)
                {
                    Console.WriteLine("1");
                }
                else
                {
                    try
                    {
                        line = Regex.Replace(line, @"\s+", "");
                        String[] items = line.Split(',');
                        int N = items.Length;
                        int[] input = new int[N];

                        for (int i = 0; i < N; i++)
                            input[i] = Int32.Parse(items[i]);

                        if (input.Length == 1)
                        {
                            Console.WriteLine("1");
                        }
                        else
                        {
                            int result1 = maxCommonArraySlice(input);
                            Console.WriteLine(result1);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
        }
    }
}

When you create a new Program.cs file and put the above code inside it with a Main() method, application waits you to enter some input from the console.

Following is the console input and output :


Another console input and output of the above program :



Another console input and output of the above program :



Another console input and output of the above program :



Another console input and output of the above program :


Max Common Array Slice in Java

You are given a sequence of n integers a0, a1, . . . , an−1 and the task is to find the maximum slice of the array which contains no more than two different numbers.

Input 1 :

[1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8]

Result 1 : Answer is 10 because the array slice of (0, 9) is the largest slice of the array with no more than two different numbers.

- There are 10 items in this slice which are "1, 1, 1, 2, 2, 2, 1, 1, 2, 2".
- 2 different numbers for this slice are 1 and 2.


Input 2:

[53, 800, 0, 0, 0, 356, 8988, 1, 1]

Result 2: Answer is 4 because the slice of (1, 4) is the largest slice of the array with no more than two different numbers. The slice (2, 5) would also be valid and would still give a result of 4.

- There are 4 items in this slice which are "800,0,0,0".
- 2 different numbers for this slice are 800 and 0.

Maximum common array slice of the array which contains no more than two different numbers implementation in Java takes a comma delimited array of numbers from STDIN and the output is written back to console.

Important thing here is that we used HashMap data structure from "java.util.HashMap" package.

package com.arrayutilities;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class MaxCommonArraySlice {

 public static int maxCommonArraySlice(int[] array) {
  Map<Integer, Integer> items = new HashMap<Integer, Integer>();
  int result = 0;
  int startIndex = 0;
  int uniqueItemCount = 0;
  while (startIndex < array.length) {
   items.put(array[startIndex], startIndex);
   uniqueItemCount = uniqueItemCount + 1;
   for (int j = startIndex + 1; j < array.length; j++) {
    if (items.get(array[j]) == null) {
     if (uniqueItemCount != 2) {
      items.put(array[j], j);
      uniqueItemCount = uniqueItemCount + 1;
      if (j == array.length - 1) {
       result = Math.max(result, j - startIndex + 1);
       startIndex = array.length;
       break;
      }
     } else if (uniqueItemCount == 2) {
      result = Math.max(result, j - startIndex);
      int item = array[j-1];
      int firstFoundIndex = 0;
      for( int k=j-1; k>=0; k-- )
      {
       if( array[k] != item )
       {
        firstFoundIndex = k+1;
        break;
       }
      }
      startIndex = firstFoundIndex;
      items.clear();
      uniqueItemCount = 0;
      break;
     }
    } else if (items.get(array[j]) != null) {
     if (j == array.length - 1) {
      result = Math.max(result, j - startIndex + 1);
      startIndex = array.length;
      break;
     }
    }
   }
  }

  return result;
 }

 public static void main(String[] args) {

  Scanner in = new Scanner(System.in);
  String line = in.nextLine();
  if (!line.equals("")) {
   if (line.length() == 1) {
    System.out.println("1");
   } else {
    try {
     line = line.replaceAll("\\s+", "");
     String[] items = line.split(",");
     int N = items.length;
     int[] input = new int[N];

     for (int i = 0; i < N; i++)
      input[i] = Integer.valueOf(items[i]);

     if (input.length == 1) {
      System.out.println("1");
     } else {
      int result1 = maxCommonArraySlice(input);
      System.out.println(result1);
     }
    } catch (Exception ex) {
     System.out.println(ex.toString());
    }
   }
  }
  in.close();
 }
}

When you create a new MaxCommonArraySlice.java file and put the above code inside it with a main() method, application waits you to enter some input from the console.

Following is the console input and output :



Another console input and output of the above program :



Another console input and output of the above program :



Another console input and output of the above program :



Another console input and output of the above program :


Friday, August 28, 2015

Compare Two Singly Linked Lists in Java

Singly linked list is a very common data structure which consists of different nodes.

There are some basic operations can be performed on singly linked lists such as add, insert, delete, remove from tail or head.

In addition to above operations a comparison method for two different singly linked lists can be implemented.

In the following sample there two different singly linked lists which are SinglyLinkedList1 and SinglyLinkedList2.

SinglyLinkedList1 consists of nodes node1, node2, node3 and node4 with a head node of headA.

SinglyLinkedList2 consists of nodes node11, node21, node31 and a head node of headB.




For this CompareLists method implementation, following design restrictions applied :

1-) Method takes just the head references for different singly linked lists.
2-) In order to be equal number of nodes in singly linked lists must be the same.
3-) In order to be equal data in each node for different singly linked lists must be the same.
4-) In order to be equal order of nodes in each singly linked lists must be the same.

If the above conditions apply then CompareLists method returns 1 otherwise returns 0.

Package contains following classes.


SinglyLinkedList.java contains Node and SinglyLinkedList classes.


package datastructures.linkedlists;

class Node
{
 int data;
 Node next;
}

public class SinglyLinkedList {

 Node head; 
 public SinglyLinkedList() {
  head = null;
 }
}


SinglyLinkedListUtility.java contains CompareLists method.


package datastructures.linkedlists;


public class SinglyLinkedListUtility {

 public int CompareLists(Node headA, Node headB) {

     if( headA == null || headB == null ) return 0;
     Node walkA = headA;
     Node walkB = headB;
     while( walkA != null )
     {
      if( walkA.data != walkB.data ) return 0;
         walkA = walkA.next;
         walkB = walkB.next;
         if( walkA==null && walkB!=null ) return 0;
         if( walkA!=null && walkB==null ) return 0;
     }
     return 1;
 }
 
}

TestSinglyLinkedListUtility is the unit test class including testCompareLists unit test method.


package datastructures.linkedlists;

import static org.junit.Assert.*;
import org.junit.Test;

public class TestSinglyLinkedListUtility {

 @Test
 public void testCompareLists() {
  
  Node node4 = new Node();
  node4.data = 4;
  
  Node node3 = new Node();
  node3.data = 3;
  node3.next = node4;
  
  Node node2 = new Node();
  node2.data = 2;
  node2.next = node3;
  
  Node node1 = new Node();
  node1.data = 1;
  node1.next = node2;
  
  Node headA = node1;
  
  Node node31 = new Node();
  node31.data = 3;
  node31.next = null;
  
  Node node21 = new Node();
  node21.data = 2;
  node21.next = node31;
  
  Node node11 = new Node();
  node11.data = 1;
  node11.next = node21;
  
  Node headB = node11;

  SinglyLinkedListUtility linkedListUtility = new SinglyLinkedListUtility();
  assertEquals( linkedListUtility.CompareLists(headA, headB), 0 );

 }

}

JUnit execution result is :


Tuesday, August 11, 2015

const pointer to const data in c++

A pointer is a variable and it has got a value as other variable types. A pointer can be declared as a constant.

It is allowed to dereference a constant pointer and assign a new value to the pointed address under suitable conditions.

1-) const pointer to data :

In the following function "constPtrToData()" ptr is initially pointing to the address of the val1 which is holding the value of 10. Later constant pointer ptr is dereferenced and the value at the pointed address changed.

Therefore, the value of val1 and val2 variables becomes the same at the end of the "constPtrToData()" function call.

However, it is not allowed to directly change the address where the constant pointer points to.

If the constant pointer is assigned to the address of the second variable then a compile time error arises.

If you try to assign a new address to the const ptr then the following compile-time error is generated :

error: assignment of read-only variable 'ptr'

This means that you can not change the address assigned to the const pointer.

Terminal output of the "constPtrToData()" function shows that the initial address const ptr holds does not change, but the value stored at this address changes.


#include <iostream>
using namespace std;

void constPtrToData()
{
    //not allowed to change where the ptr points to
    int val1 = 10, val2 = 20;
    int *const ptr = &val1;

    cout << "\n";
    cout << "ptr value = " << *ptr << " address = "<< ptr << "\n";

    *ptr = val2;
    cout << "\n";
    cout << "ptr value = " << *ptr << " address = "<< ptr << "\n";
    cout << "\n";
    cout << "val1 value = " << val1 << " val2 value = " << val2 << "\n";

    // can not assign to constant ptr a new address
    // ptr = &val2;  // error: assignment of read-only variable 'ptr'
}

int main()
{
    constPtrToData();
    cout << "\n";

    return 0;
}



2-) pointer to const data

A pointer can point to constant data. At this time, the address that the pointer points to can be changed but the value can not.

Following compile-time error generated when you try to dereference a pointer which points to const data.

error: assignment of read-only location '* ptr2' 

Main aim of using pointer to const data is to protect the data being pointed to instead of the address of the pointer itself.

In the following "ptrToConstantData()" function, ptr2 is declared as a normal pointer which points to constant data.

For this case, it is allowed to change the address which pointer points to.


#include <iostream>
using namespace std;


void ptrToConstantData()
{
    //protect the value of the variable pointed to
    double val3 = 32, val4 = 45;
    const double *ptr2 = &val3;
    cout << "\n";
    cout << "ptr2 value = " << *ptr2 << " address = " << ptr2 << "\n";

    // can not change the value at the address ptr2 points to
    // *ptr2 = val4;   error: assignment of read-only location '* ptr2'

    // allowed to change the address of the ptr2 points to
    ptr2 = &val4;
    cout << "\n";
    cout << "ptr2 value = " << *ptr2 << " address = " << ptr2 << "\n";
    cout << "\n";
    cout << "val3 value = " << val3 << " val4 value = " << val4 << "\n";
}

int main()
{
    ptrToConstantData();
    cout << "\n";

    return 0;
}


Output of the function call is :



3-) const pointer to const data

Declaring a constant pointer which is pointing to constant data means that you are aiming to protect both the pointer and the data at the pointed address from being modified.

In this case, if you try to change the address of the pointer or dereference the pointer following error messages generated respectively :

error: assignment of read-only variable 'ptr3'

error: assignment of read-only location '*(const int*)ptr3'

Following "constPtrToConstData()" declares ptr3 as a const pointer to const int .


#include <iostream>

using namespace std;


void constPtrToConstData()
{
    //protect both pointer and the data from being modified
    int val1 = 10, val2 = 20;
    const int *const ptr3 = &val1;

    cout << *ptr3 << "\n";

    // ptr3 = &val2;  // error: assignment of read-only variable 'ptr3'
    // *ptr3 = val2;  // error: assignment of read-only location '*(const int*)ptr3'
}

int main()
{    
    constPtrToConstData();
    cout << "\n";

    return 0;
}

When the "constPtrToConstData()" function executed it just prints "10" as expected to the terminal.