Java Closing AWT Window without Implementing WindowListener

Closing AWT Window without Implementing WindowListener:

This code is extension or continuation of this code adding button to AWT window. Why do this? Shorter code, no need implement unnecessary methods.

Register window listener to the frame and pass in WindowAdapter Object as shown below. Here we just implement windowClosing method but if we need others we could also add them inside WindowAdapter.

Code AWT GUI window Closing without WindowListener Implementation:

import java.awt.*;
import java.awt.event.*;

/**
 * Created by asif on 8/13/2015.
 */
public class SimpleAwtGui {

    // Declare a Frame type variable
    Frame frame;
    Button button;

    public SimpleAwtGui() {
        // Create Frame Object and pass in the Frame Name / title
        frame = new Frame("AWT GUI EXAMPLE");
        button = new Button("I am here Click Me");
    }

    public static void main(String[] args) {

        // Create an instance of SimpleAwtGui
        SimpleAwtGui window = new SimpleAwtGui();

        // call the showFrame() function to display the window
        window.showFrame();

    }

    // Not necessary but good practice all codes inside this can be written inside main
    public void showFrame() {
        // set the size of the window
        frame.setSize(400, 400);

        // set the layout for the window
        frame.setLayout(new FlowLayout());

        // Add the button component to frame otherwise button won't show
        frame.add(button);

        // Register window listener event to the frame without implementing WindowListener
        frame.addWindowListener(
                new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        System.exit(0);
                    }
                }
        );

        // set the frame visible otherwise nothing will be shown
        frame.setVisible(true);
    }
}
Advertisements

UVA Problem 299 – Train Swapping Solution

UVA Problem 299 – Train Swapping Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

The problem specifically asks to “find the least number of swaps of two adjacent carriages necessary to order the train”. That’s it.

It is a sorting problem and we have to count the number of swap between adjacent carriages. So a stable must be applied. Here I have provided three codes with insertion sort, bubble sort, merge sort.

Even though merge sort is O(n lg n) because input size is so small ( 0 <= L <= 50 ) it doesn’t make much difference. For Bubble sort though no need to perform swaps 🙂 just count it. A hybrid between insertion and merge sort me be a slight performance booster. I will try to include it later.

The problem UVA 11462 age sort is solved also with merge sort among other sort algorithms. A commented version merge sort can be found there.

Important:  Be sure to add or print a new line after each output unless otherwise specified. The outputs should match exactly because sometimes even a space character causes the answer to be marked as wrong answer.


Input:

3
3
1 3 2
4
4 3 2 1
2
2 1

Output:

Optimal train swapping takes 1 swaps.
Optimal train swapping takes 6 swaps.
Optimal train swapping takes 1 swaps.

Code ( Bubble Sort No Swap ):

/**
 * @author  Quickgrid ( Asif Ahmed )
 * @link    https://quickgrid.wordpress.com
 * Problem: UVA 299 Train Swapping (Bubble Sort No Swap)
 */

#include<stdio.h>

/**
 * c is swap count
 */
static int A[64], c;

int main(){
    int n, i, j, m;
    scanf("%d", &n);

    while(n--){
        scanf("%d", &m);
        for(i = c = 0; i < m; ++i)
            scanf("%d", &A[i]);

        /**
         * Bubble Sort
         */
        for(i = 0; i < m - 1; ++i){
            for(j = i + 1; j < m; ++j){
                /**
                 * No need to swap elements
                 * This code may be moved input loop
                 */
                if(A[i] > A[j])
                    ++c;
            }
        }

        printf("Optimal train swapping takes %d swaps.\n", c);
    }
    return 0;
}

Code ( Insertion Sort ):

/**
 * @author  Quickgrid ( Asif Ahmed )
 * @link    https://quickgrid.wordpress.com
 * Problem: UVA 299 Train Swapping (Insertion Sort)
 */

#include<stdio.h>

static int A[64], c;

int main(){
    register int n, i, j;
    int m, key;
    scanf("%d", &n);
    while(n--){
        scanf("%d", &m);
        for(i = c = 0; i < m; ++i)
            scanf("%d", &A[i]);

        /**
         * Insertion sort using inner for loop
         */
        for(i = 1; i < m; ++i){
            key = A[i];
            for(j = i - 1; j >= 0 && A[j] > key; --j){
                A[j + 1] = A[j];
                ++c;
            }
            A[j + 1] = key;
        }

        printf("Optimal train swapping takes %d swaps.\n", c);
    }
    return 0;
}

Code ( Merge Sort Swap Count ):

/**
 * @author  Quickgrid ( Asif Ahmed )
 * @link    https://quickgrid.wordpress.com
 * Problem: UVA 299 Train Swapping (Merge Sort)
 */

#include<stdio.h>
#include<limits.h>

static int A[64], c;

void Merge(int front, int mid, int rear){
    int n1 = mid-front+1;
    int n2 = rear - mid;

    int *L = new int[n1 + 1];
    int *R = new int[n2 + 1];

    register unsigned i = 0;
    for(; i < n1; ++i)
        L[i] = A[front + i];

    register unsigned j = 0;
    for(; j < n2; ++j)
        R[j] = A[mid + 1 + j];

    L[n1] = INT_MAX;
    R[n2] = INT_MAX;
    i = j = 0;

    /**
     * Might work without swaps by just incrementing index counters
     */
    register unsigned k = front;
    for(; k <= rear; ++k){
        if(L[i] <= R[j]){
            A[k] = L[i++];
            c += j;
        }
        else
            A[k] = R[j++];
    }
}

void Mergesort(int front, int rear){
    if(front < rear){
       int mid = (rear + front) >> 1;
       Mergesort(front, mid);
       Mergesort(mid + 1, rear);
       Merge(front, mid, rear);
    }
}

int main(){
    int n, i, j, m;
    scanf("%d", &n);
    while(n--){
        scanf("%d", &m);
        for(i = c = 0; i < m; ++i)
            scanf("%d", &A[i]);

        /**
         * To understand Merge sort see my UVA solution age sort 11462
         */
        Mergesort(0, m - 1);

        printf("Optimal train swapping takes %d swaps.\n", c);
    }
    return 0;
}

UVA Problem 11462 – Age Sort Solution

UVA Problem 11462 – Age Sort Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

First of all a warning. This is going to be a very very very long post. For this problem i will use various divide and conquer algorithms ( Ex: quick sort, merge sort etc ) & techniques to solve.

The best Solution here takes 0.502 s ( 502 ms ) . If you are looking for a very fast solution this is not the right place. But these code can be optimized to create a very fast solution.  Also sorts such as bubble sort, selection sort, insertion sort, replacement sort won’t be able to sort in time. So you’ll get TLE if you use these sort.

Lets begin:

This is a sorting problem. The only trouble here is the huge count of test cases. But there’s very important line most miss including me. That is ” no individual in that country lives for 100 or more years “. So we may have many many test cases but no input age is more than 100. 🙂

Now lets look at our solution menu,

1. Counting sort ( Just count occurrence of each values, then print them 0 to 100 for ascending order).

2. Binary Merge sort ( 2 partition ).

3. Ternary Merge sort ( 3 partition ).

4. Quick sort ( 2 partition ).

5. Quick sort ( 3 partition ).


The first solution code here ( counting sort ) runs the fastest since it just count elements at each index and prints them. This solution may be made faster by using combination of fread, fwrite, strtok, atoi, stringstream ( <sstream> ) . Although i haven’t used them. If i get time I will try to implement them in future.

I used the other sorts here just demonstrate implementation of merge sort and quick sort algorithms. I may include more sorting algorithms for this problem in future. All codes are well commented take a look below and try to understand their logic.

Important:  Be sure to add or print a new line after each output unless otherwise specified. The outputs should match exactly because sometimes even a space character causes the answer to be marked as wrong answer.


Input:

5
3 4 2 1 5
5
2 3 2 3 1
0

Output:

1 2 3 4 5
1 2 2 3 3

Counting Sort Code:

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 11462 ( Age sort )
 * Solution Method: Counting Sort
 */

#include<stdio.h>
#include<string.h>

static unsigned A[128];

int main(){
    register unsigned n, i, c;
    unsigned num;
    while(scanf("%u", &n) && n){             /* Test cases */
        memset(A, 0, sizeof A);              /* Clear memory for each test case */
        for(i = n; i; --i){                  /* Exits Loop when i is 0 */
            scanf("%u", &num);
            ++A[num];                        /* Since input is never greater than 100, we can use that as index and count occurrence of that index */
        }
        c = i = 1;                           /* i starts from 1 since i is never 0  */
        for(; i<100; ++i){
            while(A[i]--){                   /* Decrease number count at that index */
                if(c == n) printf("%u", i);  /* For the last item in sorted output there is no space */
                else{
                    printf("%u ", i);        /* Just print the index since that was our original input */
                    ++c;                     /* Counter to check if the last element is reached */
                }
            }
        }
        printf("\n");                        /* Print a new line for each test case */
    }
    return 0;
}

 Counting Sort Code ( Usage of stringstream, *slower ):

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 11462 ( Age sort )
 * Description: stringstream demo
 */

#include<iostream>
#include<cstdio>
#include<cstring>
#include<sstream>

using namespace std;

static unsigned A[128];

int main(){
    register unsigned n, c, i;
    unsigned num;
    string B;
    while(1){
        scanf("%u", &n); getchar();
        if(!n) return 0;

        memset(A, 0, sizeof A);
        getline(cin, B);

        stringstream ss;
        ss << B;
        while(ss >> num)
            ++A[num];


        c = i = 1;
        for(; i < 100; ++i){
            while(A[i]--){
                if(c == n) printf("%u", i);
                else{
                    printf("%u ", i);
                    ++c;
                }
            }
        }
        printf("\n");
    }
    return 0;
}

 Binary Merge Sort Code ( 2 Partition ):

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 11462 ( Age sort )
 * Solution Method: Binary Merge Sort ( 2 Partition )
 */

#include<stdio.h>
#include<limits.h>

#define SIZE 2000002
static unsigned A[SIZE];

void Merge(register unsigned front, register unsigned mid, register unsigned rear){
    register unsigned n1 = mid-front+1;         /* Calculate size of left half of the array */
    register unsigned n2 = rear - mid;          /* Calculate size of right half of the array */

    unsigned *L = new unsigned[n1 + 1];     /* Dynamically create and allocate calculated amount of memory */
    unsigned *R = new unsigned[n2 + 1];     /* plus 1 to hold Infinity or A Very large value for which any input can't be larger than */

    register unsigned i = 0;
    for(; i < n1; ++i)
        L[i] = A[front+i];                          /* Copy elements from given original array to left sub array */

    register unsigned j = 0;
    for(; j < n2; ++j)
        R[j] = A[mid + 1 + j];                          /* Copy elements from given original array to right sub array */


    L[n1] = INT_MAX;                                /* In the last position of sub array set a very large value */
    R[n2] = INT_MAX;
    i = j = 0;

    register unsigned k = front;                /* Instead of wasting space creating a new array, we can use the original large array since we have already copied all items to sub arrays */
    for(; k <= rear; ++k){
        if(L[i] <= R[j])
            A[k] = L[i++];             /* Compare and copy smaller elements of sub arrays onto original array */
        else
            A[k] = R[j++];
    }
}

void Mergesort(register unsigned front, register unsigned rear){
    if(front < rear){
       register unsigned mid = (rear+front) >> 1;  /* Find the mid point of the array */
                                                    /* Shift bits to right once, equivalent of divided by TWO */

       Mergesort(front, mid);                       /* Recursively divide array in left portion */
       Mergesort(mid+1, rear);                      /* Recursively divide array in right portion */

       Merge(front, mid, rear);                     /* Merge the divided array back again in sorted order */
    }
}

int main(){
    register unsigned n, i;
    while(scanf("%u", &n) && n){
        for(i=0; i<n; ++i)
            scanf("%u", &A[i]);

        Mergesort(0, n-1);                          /* Call merge sort function for each test case */

        for(i = 0; i<n; ++i){
            printf("%u", A[i]);
            if(i != n - 1)
                printf(" ");                 /* Do not print a space after last sorted item */
        }
        printf("\n");
    }
    return 0;
}

 Ternary Merge Sort Code ( 3 Partition ):

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 11462 ( Age sort )
 * Solution Method: Ternary Merge Sort ( 3 Partition )
 */

#include<stdio.h>
#include<limits.h>

#define SIZE 2000002
static unsigned A[SIZE];

void Merge(register unsigned front, register unsigned mid1, register unsigned mid2, register unsigned rear){
    /*
     * Calculate size for creating sub array
     * In this case calculate size for three sub arrays
     */
    unsigned n1 = mid1 - front + 1;
    unsigned n2 = mid2 - mid1;
    unsigned n3 = rear - mid2;

    /*
     * Dynamically allocate memory for three sub arrays
     * Here Plus One because we will set a very large value for last position of the array
     */
    unsigned *L = new unsigned[n1 + 1];
    unsigned *R = new unsigned[n2 + 1];
    unsigned *X = new unsigned[n3 + 1];

    /*
     * Copy 1/3 of original array to sub arrays
     * First 1/3 to L array, next 1/3 to R array, last 1/3 to X array
     */
    register  int i = 0;
    for(; i<n1; ++i)
        L[i] = A[front + i];

    for(i=0; i<n2; ++i)
        R[i] = A[mid1 + 1 + i];

    for(i = 0; i < n3; ++i)
        X[i] = A[mid2 + 1 + i];

    /*
     * INT_MAX is found in <limits.h>
     * Instead of traversing the whole array increasing runtime
     * We can compare every element again a very large value which will always be grater than or equal to any input
     */
    L[n1] = INT_MAX;
    R[n2] = INT_MAX;
    X[n3] = INT_MAX;

    /*
     * Reset index counter for sorting
     */
    i = 0;
    register unsigned p = 0, j = 0, k = front;

    /*
     * Sort:
     * Compare items of each array against each other
     * Copy back the smaller item from the comparison to original array
     */
    for(; k <= rear; ++k){
        if(L[i] <= R[j] && L[i] <= X[p]){
            A[k] = L[i];
            ++i;
        }else if(R[j] <= X[p]){
            A[k] = R[j];
            ++j;
        }else{
            A[k] = X[p];
            ++p;
        }
    }
}

void Mergesort(register int front, register int rear){
    /*
     * Check if there is only One element in array
     */
    if(front < rear){
        /*
         * calculate the size of 1/3 of array
         * Now calculate two mid points since it is 3 way partition
         */
        register int dist = (rear - front + 1) / 3;
        int mid1 = front + dist;
        int mid2 = mid1 + dist;

        /*
         * Recursively call this array cutting down original array by 1/3 ( One Third )
         */
        Mergesort(front, mid1);
        Mergesort(mid1 + 1, mid2);
        Mergesort(mid2 + 1, rear);

        /*
         * Merge divided elements back into original array
         */
        Merge(front, mid1, mid2, rear);
    }
}

int main(){
    register int n, i;
    while(scanf("%u", &n) && n){
        for(i = 0; i < n; ++i)
            scanf("%u", &A[i]);

        /*
         * Merge sort from index 0 to index n-1
         */
        Mergesort(0, n - 1);

        for(i = 0; i < n; ++i){
            printf("%u", A[i]);
            /*
             * For the last sorted element do not print a space
             */
            if(i != n-1)
                printf(" ");
        }
        printf("\n");
    }
    return 0;
}

 Quick Sort Code ( 2 Partition ):

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 11462 ( Age sort )
 * Solution Method: Quick Sort ( 2 Partition )
 */
#include<cstdio>
#include<iostream>

#define SIZE 2000002

static int A[SIZE];

void quicksort (int *a, register int n) {
    register int i, j, mid;
    if (n < 2) return;

    mid = a[n >> 1];

    for (i = 0, j = n - 1; ; i++, j--) {
        while (a[i] < mid)
            i++;
        while (mid < a[j])
            j--;

        if (i >= j) break;
        std::swap(a[i], a[j]);
    }
    quicksort(a, i);
    quicksort(a + i, n - i);
}

int main () {
    register unsigned n, i;
    while(scanf("%u", &n) && n){
        for(i = 0; i < n; ++i)
            scanf("%d", &A[i]);

        quicksort(A, n);

        for (i = 0; i < n; i++)
            printf("%d%s", A[i], i == n - 1 ? "\n" : " ");

    }
    return 0;
}

 Quick Sort Code ( 3 Partition ):

/* To Do */

UVA Problem 488 – Triangle Wave Solution

UVA Problem 488 – Triangle Wave Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

This is one of the easiest problems but requires some thinking. But getting accepted in not enough we also need to optimize the code to improve timing, memory, ranking.

Here I have solved this problem in two ways. The first took 0.042 s ( 42 ms ) and ranked 254 at the time of writing. The second solution took 0.122 s ( 122 ms ). Both codes take a different approach. The first one is a little bit cheating. Since running the second code I have found out that amplitude input is never greater than 9. Why? because running the second code it outputs garbage for any amplitude greater than 9 and it got accepted.

I will explain the first code logic here. The second ( slower ) code is commented for easier understanding. Please refer below for the solutions.

Since I know amplitude is never greater than 9 so I created constant string array in C. Also possible in C++ by using

const std::string a[] = {"1", "22", .....}

Now just print the predefined string array amplitude times and print in reverse order amplitude minus one times. That’s it. Please note, you should not print a blank line after last wave form. It quite easy,

if(times || n){
    printf("\n");
}

This works because both times and n variables are decremented and for the last loop when they become 0, the if condition does not execute. So for last waveform there is no newline.

Time to write a better solution and get that 1st rank :).

Important:  Be sure to add or print a new line after each output unless otherwise specified. The outputs should match exactly because sometimes even a space character causes the answer to be marked as wrong answer.


Input:

2

4
5

3
2

Output:

1
22
333
4444
333
22
1

1
22
333
4444
333
22
1

1
22
333
4444
333
22
1

1
22
333
4444
333
22
1

1
22
333
4444
333
22
1

1
22
333
22
1

1
22
333
22
1

Code ( Faster ):

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 488 ( Triangle Wave )
 */
#include<stdio.h>

/* For this problem amplitude does not exceed 9, so you can cheat <span class="wp-smiley wp-emoji wp-emoji-smile" title=":)">:)</span> */
const char *a[] = {"", "1", "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"};

int main(){
    register unsigned n, i, j, k;
    scanf("%u", &n);

    while(n--){
        unsigned amp, times;
        scanf("%u%u", &amp, &times);

        while(times--){
            for(i = 1; i < amp; ++i)
                /* Just print the predefined strings */
                printf("%s\n", a[i]);

            for(k = i; k; --k)
                printf("%s\n", a[k]);

            if(times || n)
                printf("\n");
        }
    }
    return 0;
}

Another Solution ( Slower ):

This code also solves the problem but relatively slower. It took 0.122 s for my run. Still have look to learn something new. Please refer to this code for a better explanation of C array of strings.

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 488 ( Triangle Wave )
 */

#include<stdio.h>
#include<string.h>

int main(){
    register unsigned n, i, j, k;
    scanf("%u", &n);

    while(n--){
        unsigned amp, times;
        scanf("%u%u", &amp, &times);

        while(times--){
            /* Allocate memory for string array, allocates memory for string count */
            char **a = new char*[amp + 1];

            for(i = 1; i <= amp; ++i){
                /* Allocate memory for the string */
                a[i] = new char[i + 1];
                /* Reset the array */
                memset(a[i], 0, sizeof a[i]);

                for(j = 0; j < i; ++j)
                    /* Populate the string with numbers */
                    a[i][j] = i + 48;

                /* Print the generated strings */
                printf("%s\n", a[i]);
            }

            for(k = amp - 1; k > 0; --k)
                /* Print the rest in reverse */
                printf("%s\n", a[k]);

            if(times || n)
                /* For the last loop do not print new line */
                printf("\n");
        }
    }
    return 0;
}

Another using C++:

This one is also accepted but slower. Here instead of printing i keep adding all things to one string and only print when program is terminated. Although this works and will work but it is not a very good idea.

/*
 * Author: Quickgrid ( Asif Ahmed )
 * Site: https://quickgrid.wordpress.com
 * Problem: UVA 488 ( Triangle Wave )
 */
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

const string a[] = {"", "1", "22", "333", "4444", "55555", "666666", "7777777", "88888888", "999999999"};

int main(){
    register unsigned n, i, j, k;
    string output, total = "";
    scanf("%u", &n);

    while(n--){
        unsigned amp, times;
        scanf("%u%u", &amp, &times);
        output = "";

        while(times--){
            for(i = 1; i < amp; ++i)
                output += a[i] + "\n";
            for(k = i; k; --k)
                output += a[k] + "\n";
            if(times || n)
                output += "\n";
        }
        total += output;
    }

    cout << total;
    return 0;
}

UVA Problem 12700 – Banglawash Solution

UVA Problem 12700 – Banglawash Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

This article gives some good code optimization tips.

First of all don’t get confused by the poorly formatted output ( But i have not tried if it works without newline ) . There is a newline after each output.

Now ( except for the last paragraph ) anything above the input label is not necessary to solve this problem.

The first input is number of test cases. Next input is the size of the string ( meaning how many matches have been played ). Next input is a string. There only 4 types of letters in the string. Also we know the number of test cases ( T < 101 ) and array size ( N < 11 ).

These letters will be either `B’ or `W’ or `T’ or `A’. Here, `B’ means the match was won by Bangladesh, `W’ means the match was won by WWW, `T’ means the match was a tie and `A’ means the match was abandoned.

In order to solve this we can just count the number of characters.

Below is just the steps to solve not the expected output:

If all character are A then match is Abandoned.

if Bangladesh won more then print Bangladesh and Bangladesh win count then WWW win count.

if WWW won more then print WWW and WWW win count then Bangladesh win count.

If win count for both team are same or all matches are tied then print Draw then print win count for any team then print tie count.

If Bangladesh won all matches except for the Abandoned matches then print Banglawash.

If WWW won all matches except for the Abandoned matches then print Whitewash.

Important:  Be sure to add or print a new line after each output. The outputs should match exactly because sometimes even a space character causes the answer to be marked as wrong answer.


Input:

6
3
BBB
3
WWW
3
BWB
4
BWWT
3
BTW
2
AA

Output:

Case 1: BANGLAWASH
Case 2: WHITEWASH
Case 3: BANGLADESH 2 - 1
Case 4: WWW 2 - 1
Case 5: DRAW 1 1
Case 6: ABANDONED

Code:

/*
 * @author  Quickgrid ( Asif Ahmed )
 * @link    https://quickgrid.wordpress.com
 */

#include<stdio.h>

static char s[16];

int main(){
    register unsigned n, c = 1;
    scanf("%u", &n);

        while (n--){
            register unsigned m, i;
            unsigned A = 0, B = 0, T = 0, W = 0;
            scanf("%u%s", &m, &s);

            for (i = 0; i < m; ++i){
                switch(s[i]){
                case 65:    /* or use 'A' instead of 65 (ASCII) but using 65 is faster */
                    ++A;
                    break;
                case 66:    /* or use 'B' instead of 66 (ASCII) but using 66 is faster */
                    ++B;
                    break;
                case 84:    /* or use 'T' instead of 84 (ASCII) but using 84 is faster */
                    ++T;
                    break;
                case 87:    /* or use 'W' instead of 87 (ASCII) but using 87 is faster */
                    ++W;
                    break;
            }
        }

        if (A == m)                             /* All matches are abandoned */
            printf("Case %u: ABANDONED\n",c);
        else if (B + A == m)                    /* If Bangladesh won all the matches, except for Abandoned ones */
            printf("Case %u: BANGLAWASH\n",c);
        else if (W + A == m)                    /* If WWW won all the matches, except for Abandoned ones */
            printf("Case %u: WHITEWASH\n",c);
        else if (B > W)                         /* Bangladesh won more matches then WWW */
            printf("Case %u: BANGLADESH %u - %u\n",c,B,W);
        else if (B < W)                         /* WWW won more matches then Bangladesh */
            printf("Case %u: WWW %u - %u\n",c,W,B);
        else                                   /* Win count for both team is tied */
            printf("Case %u: DRAW %u %u\n",c,B,T);

        ++c;
    }
    return 0;
}

UVA Problem 458 (The Decoder) Solution

UVA Problem 458 (The  Decoder) Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

Run time 15 ms ( 0.015 s ), Rank 377

This problem is really easy. The description is quite straight forward. The codes are scrambled based on simple arithmetic manipulation in ASCII value. From comparing input and output we can find the value of how much we need to shift ( add or subtract ) the ASCII value to match the output. In this problem if we subtract all character of given sentence by 7 then we get the correct output. Here I have first modified all the character of the string with 7 less than given character ASCII value.

Here I have modified the string inline in the for loop increment portion. It is rather short.

Important: No extra space or blank lines. Also one can modify and keep printing characters one by one. But that process is really slow.


Input:

1JKJ'pz'{ol'{yhklthyr'vm'{ol'Jvu{yvs'Kh{h'Jvywvyh{pvu5
1PIT'pz'h'{yhklthyr'vm'{ol'Pu{lyuh{pvuhs'I|zpulzz'Thjopul'Jvywvyh{pvu5
1KLJ'pz'{ol'{yhklthyr'vm'{ol'Kpnp{hs'Lx|pwtlu{'Jvywvyh{pvu5

Output:

*CDC is the trademark of the Control Data Corporation.
*IBM is a trademark of the International Business Machine Corporation.
*DEC is the trademark of the Digital Equipment Corporation.

Code:

/*
 * @author Quickgrid ( Asif Ahmed )
 * @link https://quickgrid.wordpress.com
 * Problem: UVA 458 ( The Decoder )
 */

#include<stdio.h>

static char t[1024];

int main(){
    register unsigned i;
    while(gets(t)){
        for(i = 0; t[i]; t[i] -= 7, ++i);
        puts(t);
    }
    return 0;
}

UVA Problem 272 (TEX QUOTES) Solution

UVA Problem 272 (TEX QUOTES) Solution:


Click here to go to this problem in uva Online Judge.

Solving Technique:

This problem is relatively easy. In this problem we are asked to replace a pair of quotes. The first quote replaced with two ( ` ) character and next quote replaced with two ( ‘ ) character. Besides testing with given inputs we should also test with other inputs such as inputs given below before submission.

We can also solve this problem by printing characters one by one when they are found. But that process is really slow. We should consider first creating a string for the things we want to print then print them altogether using only one printf.

Also consider making loop counter variables register. This doesn’t guarantee that variables will be stored on register but if they are then our program runs a lot faster.

Another thing is we need some kind of ON OFF switch, or Flip Flop to check when we get Grave Caret ( ` ) or when we get a single quote ( ). Here in my code the variable ( c ) is doing that job.

ASCII values instead of characters,

' 39     /* Single Quote */
` 96     /* Grave Caret */
" 34     /* Double Quote */

Important: The quotes should be considered for the whole input not line by line.


Critical Input:

""
"""
""""

Critical Output:

``''
``''``
''``''``

Code:

#include<stdio.h>

static char t[256];

int main(){
    register unsigned i, k, c = 0;

    while(gets(t)){
        char inp[256] = {'\0'};

        for (i = k = 0; t[i]; ++i){
            /*
             * ASCII decimal value of " (Double Quotes) is 34
             */
            if (t[i] == 34 && !c){
                /*
                 * ASCII decimal value of ` (Grave Caret) is 96
                 */
                inp[k] = inp[k+1] = 96;
                /*
                 * We added TWO characters
                 */
                k += 2;
                /*
                 * Flag or ON OFF
                 */
                c = 1;
            }else if(c && t[i] == 34){
                /*
                 * ASCII decimal value of ' (Single Quote) is 39
                 */
                inp[k] = inp[k+1] = 39;
                k += 2;
                c = 0;
            }else{
                /*
                 * If neither single or Double Quote found
                 */
                inp[k] = t[i];
                ++k;
            }
        }
        printf("%s\n", inp);
    }
    return 0;
}