Saturday, October 13, 2018

First 5k run experience without training


There had been a modest amount of buzz at the office when couple of co-workers had signed up for their first 5k social run sponsored by a local car dealership. They started sharing experiences of their training now and then, that inspired few others of us to sign up for the event. When signing up, I had roughly 3 weeks to prepare for the run. As guilty as accused, for pushing the training to run a couple of miles, to test the level of energy I possessed at that time, the day already arrived.

I have been walking pushing my two-year old on a stroller for several months daily. But, the total distance I covered might be around a mile. Going uphill that is modestly steep to a nearby community park, I had some basic cardio done each day. Apart from that, a year ago, I had been regularly hitting the gym with twenty minutes of intense running and walking which served as a supplement for the weight training I did at that time. So, the maximum distance I had covered in the past was not more than two miles on any given run. The day arrived without waiting for me to get know whether a 5k run is sweet or sour.

The run was on a beautiful calm trail near a lake. I couldn’t have betted on a better weather than that evening! My manager was the one who aspired the team members to run. He who had already completed several half marathons and few full marathons in different parts of the US and the country, was present on that day to encourage us and to do his own piece of running as well.

Before starting the run, my mind was blank because I was skeptical how I would feel upon finishing. It was a straight trail, where, there will be an orange code after 1.5 miles and we must have to run around that and return to complete the reminder of the run which tallies to 3 miles or otherwise 5k.  Never nervous or afraid, I started the run along with the crowd (almost 150 people). My colleagues and I were running together at the same, slow and steady pace. Few minutes and what seemed to be 0.4 miles roughly, I started slowing down and my friends started disappearing on the visage of the trial as it convoluted like a snake. There were also some untrained runners from my office, a few of them were behind me as well. I determined not to stop running at least until the first half of the race, which indeed was hard.

My speed was reducing which was evident by the number of people who overtook me. Running with the dog. Pushing twin girls on a stroller. Running with kids. Running with a partner hand in hand. I witnessed several other running ahead of me and soon vanishing from the sight. Several times, the thoughts of stopping to run and walk, peeped the mind. I was gritty not to give up though. Tenacity and the zeal are absolutely required for anything to be achieved anywhere. However, it cannot help you drive a car that is running out of gas. In this case, I was both the car and the driver. The engine was boiling and denied running further.

My legs slowed down and started walking. But the arms were still swinging as if I was running. I gasped for more oxygen which was there in abundant with countless number of trees around the trail. A few more steps forward, there was a middle-aged father who was telling his daughter that it is almost a mile and encouraged her to run forward. I was surprised that I still haven’t reached a mile. When asked, he said it was 0.95 miles.

Not even half the distance and I am already sucking the air.

I walked forward thinking I will start running after regaining the breath when an untrained colleague of mine overtook me slowly. Regaining breath and some momentum, I started running again. My steps were little longer than his. I overtook him slowly this time.

I stopped. He overtook. I ran forward pushing him behind. I stopped again. He overtook. This continued as we ran into the other friends who were on their way back, waving hands at us. Running around the orange cone, I started running back to where it all started to complete the run. On the way back, found one of the best things that happened to the universe. Water! Grabbed the small bottle of water and drank a mouthful. It felt extremely good. On resuming the run after the few seconds hiatus, I could feel the water juggling inside my belly.

The stopping and overtaking game between me and the other colleague continued until I had to stop running for an extended period of two to three minutes and walked. He started disappearing from the sight as well. On resumption, there was a lady who must be in her late forties was running with some gadgets wrapped around her arm and hip. Every minute, her gadget, presumably a phone, said out loud how much time has elapsed, and distance covered. 2.1 miles, 2.2 miles, 2.43 miles, 2.5 miles, 2.7 miles, 2.8 miles in 35 minutes. Almost there. But, not quite. My heart was begging for me to sit (or lie down) and rest. The gadget lady disappeared too.

I slowly strolled down to the finish line and was glad that I finished the race which I was doubtful at the beginning.  I was even more glad that I don’t have to run anymore. I found where my friends were standing, and I knew each one of them had a story to exchange with others. I reached them slowly and tried to speak. The spot between the lower part of the throat until the lungs, felt like as if it was on fire. The heart did not realize that I had finished the run and was still beating faster. Excusing myself from the others, I had to go sit and let the heart beats to slow down. Ten more minutes, I was alright. My thighs and calf muscles were little sore but manageable.

It was indeed a great achievement and I was proud of myself then. Went to a restaurant to treat myself with some good carb rich food. When I reached home, my family was already asleep. I had to consume more and more water since I was feeling thirsty repeatedly within an hour. I was not able to sleep probably because my heart did not come out of the panic mode.

Next couple of days, my thighs and right foot felt awful. I had to allow myself of not doing anything that required too much walking or standing to get back into shape.

Now, I am much more interested in training and running a 5k. The goal I am going for is to not to stop even once during the run.

Friday, September 12, 2014

Maximum subsequence sum


import java.util.ArrayList;

/**
 * Created by Arun on 9/11/14.
 */
public class SequenceResult
{
    public static void maximumContSubSeq(int[] a) {
        int sum[] = new int[a.length]; // Sum at every element
        sum[0] = a[0];
        int max = 0;
        for (int i = 1; i < a.length; i++) {
            sum[i] = Math.max(sum[i - 1] + a[i], a[i]);
            if(sum[i-1]+a[i]>a[i]){
                sum[i] = sum[i - 1] + a[i];
            }
            if (max < sum[i]) {
                max = sum[i];
            }
        }
        System.out.println(max);
    }


    public static void main(String args[]){
        int x[] = {-2, 3, -16, 100, -4, 5, 21 };
        maximumContSubSeq(x);
    }

}

Program to find whether a number is a perfect square or not


You can write an algorithm in linear time something like below

for(int i=1; i<numberToCheck; i++) {
    if(i*i==numberToCheck) {
        return true;
        break;
    }
    return false;
}

The above code can be optimized as follows, since we are sure that the number of times it has to be traversed is less than or equal to half the size of the input number we can divide it by 2.

for(int i=1; i<numberToCheck/2; i++) {
    if(i*i==numberToCheck) {
        return true;
        break;
    }
    return false;
}

Optimized? Not quite... We can still optimize it to <=sqrt(input) number of times!
/**
 * Created by Arun on 9/12/14.
 */
public class Square {

    public static boolean findPerfectSquare(int a) {
        int currentSquare = 1;
        for(int i=1;currentSquare<a;i++) {
            System.out.println(i);
            if(i*i==a) {
                return true;
            }
            currentSquare = i * i;
        }
        return false;
    }

    public static void main(String args[]) {
        System.out.println(findPerfectSquare(1222));

    }
}

Monday, August 11, 2014

Given a sorted array arr[] and a value X, find the k closest elements to X in arr[]. Examples: Input: K = 4, X = 35 arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 56} Output: 30 39 42 45


import java.util.Arrays;

/**
 * Created by Arun on 8/11/14.
 */
public class ClosestArray {
    private static int[] getClosest(int num, int element, int arr[]){
        int elementIndex = -1;
        int closeArray [] = new int[num];
        for(int i=0;i<arr.length;i++) {
            if(arr[i]==element){
                elementIndex = i;
            }
        }
        for(int i=0, j=elementIndex-1, k=elementIndex+1;i<num;i++){
            int diff1 = element-arr[j];
            int diff2  = arr[k]-element;
            if(diff1<diff2){
                closeArray[i]=arr[j];
                j--;
            }
            else if(diff1>diff2) {
                closeArray[i]=arr[k];
                k++;
            }
            else{
                closeArray[i]=arr[j];
                if(i<num){
                    i++;
                    closeArray[i]=arr[k];
                    j--;
                    k++;
                }
                else {
                    break;
                }
            }
        }
        return closeArray;
    }

    public static void main(String args[]) {
        int arr[] = {12, 16, 22, 31, 35, 39, 42, 45, 48, 50, 53, 55, 56};
        getClosest(4, 35, arr);
    }
}

Saturday, August 9, 2014

Given an array of integers. This array denotes ‘our’ own ascending order of the elements. So if the array is {2,3,1,4}, by mathematics we can say that 2<3<1<4. Given another array, sort this new array in ‘our’ ascending order.
Let’s say the new array is {1,2,4,3,5,4,9,2}, output will be {2,2,3,1,4,4,5,9}. Note that since 5 and 9 do not occur, they are sorted by actual ascending order at the end.



import java.util.*;

/**
 * Created by Arun on 8/9/14.
 */
public class CustomizedSort {
    public static ArrayList<Integer> sort(int customSortList[], Integer arr[]){
        Map<Integer, Integer> mp = new LinkedHashMap<Integer, Integer>();
        for(int i=0;i<customSortList.length;i++) {
            mp.put(customSortList[i], i);
        }
        System.out.println(mp);
        List<Integer> a = Arrays.asList(arr);
        Collections.sort(a);
        arr = a.toArray(new Integer[arr.length]);
        ArrayList<Integer> newArr = new ArrayList<Integer> (arr.length);

        Iterator it = mp.entrySet().iterator();
        while (it.hasNext()){
            Map.Entry pairs = (Map.Entry)it.next();
            int key = (Integer)pairs.getKey();
            for(int i=0;i<a.size();i++){
                if(a.get(i)==key){
                    newArr.add(key);
                }
            }
        }
        for(int i=0;i<a.size();i++){
            if (!newArr.contains(a.get(i))){
                newArr.add(a.get(i));
            }
        }
        return newArr;
    }
    public static void main(String args[]){
        int customSortList[] = {2,3,1,4};
        Integer arr [] = {1,2,4,3,5,4,9,2};
        System.out.println(sort(customSortList, arr));
    }
}

Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] and its permutations (or anagrams) in txt[]. You may assume that n > m.E.g. : I/p : txt[] = “BACDGABCDA” pat[] = “ABCD”o/p :0,5,6

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Arun on 8/9/14.
 */
public class PatternMatching {
    public static boolean isPrime(int n) {
        if (n <= 1) {
            return false;
        }
        for (int i = 2; i < Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    public static ArrayList<Integer> getPrimes() {
        ArrayList<Integer> arr = new ArrayList<Integer>();
        for(int i=0, j=0;j<26;i++){
            if(isPrime(i)){
                arr.add(i);
                j++;
            }
        }
        return arr;
    }

    private static ArrayList<Integer> matchPattern(String str, String pattern) {
        ArrayList<Integer> a = getPrimes();
        String alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Map<String, Integer> valMap = new HashMap<String, Integer>();
        int patternProduct = 1;
        for(int i=0;i<alphabets.length();i++) {
            valMap.put(String.valueOf(alphabets.charAt(i)), a.get(i));
        }
        for(int i=0;i<pattern.length();i++) {
            patternProduct = patternProduct * valMap.get(String.valueOf(pattern.charAt(i)));
        }
        for(int i=0;i<=str.length()-pattern.length();i++) {
            int tempVal=1;
            for(int j=i, k=0;k<pattern.length();k++,j++){
                tempVal = tempVal * valMap.get(String.valueOf(str.charAt(j)));
            }
            if(tempVal==patternProduct) {
                System.out.println(i);
            }
        }
        return null;
    }
    public static void main(String args[]) {
        matchPattern("BACDGABCDABCD", "ABCD");
    }
}


Given an array of integers. Segregate all the non-zero numbers at the beginning. Print the number of non-zero integers and the minimum number of swaps required for these operations.Eg. : I/p : 1, 0, 0, -6, 2, 0o/p : Number of non-zero integers : 3

import java.util.ArrayList;

/**
 * Created by Arun on 8/9/14.
 */
public class ArrayNonZero {
    public static void main(String args[]) {
        int arr []  = {1, 0, 0, -6, 2, 0};
        ArrayList<Integer> nonZero = new ArrayList<Integer>();
        ArrayList<Integer> zero = new ArrayList<Integer>();
        int i=0;
      //get the indexes of the zero and non zero elements
        for(int val: arr) {
            if(val!=0) {
                nonZero.add(i);
            }
            else {
                zero.add(i);
            }
            i++;
        }
        int newArr [] = new int[arr.length];
        i=0;
       //put the non-zero elements at the end and zero element at the beginning
        for(int val: nonZero){
            newArr[i]=arr[val];
            i++;
        }
        for(int val: zero) {
            newArr[i] = arr[val];
            i++;
        }
        for(int val: newArr){
            System.out.println(val);
        }
    }
}