Pages

Gin Rummy Indian Rummy Nine Men's Morris and more Air Attack

Sunday 25 February 2018

A simple shuffle implementation

There are two phases in the algorithm, first we shuffle from the beginning of the array and after that from the end of the array.

First we are going to start from the beginning of the array iterating over all the element. In each iteration we are going to get a random index from current index to the index to the last element.
After getting the random index we are going to swap current element with the element at the random selected index.

In the second phase we are going to do the same thing, but this time we start from the end of the array.

The shuffle implementation is given below,

using System;
using System.Collections.Generic;

class MainClass {
       
    public static void shuffle(List<int> values) {
        Random random = new Random();


        // shuffle by swapping elements from beginning of the list
        for (int i = 0; i < values.Count - 2; ++i) {

            // get a random position from i to end of the list
            int index = random.Next (i, values.Count);

            // swap i th element with the element at position retrieved above, index
            int temp = values [i];
            values [i] = values [index];
            values [index] = temp;
        }

        // shuffle by swapping elements from end of the list
        for (int i = values.Count - 1; i > 2; --i) {
            // get a random position from 0 to i-1 from the list
            int index = random.Next (0, i-1);

            // swap i th element with the element at position retrieved above, index
            int temp = values [i];
            values [i] = values [index];
            values [index] = temp;
        }
    }
   
    public static void Main (string[] args) {
        List<int> values = new List<int>();
        for (int i=0; i<50; ++i) {
            values.Add(i);
        }

        shuffle(values);
        for (int i=0; i<values.Count; ++i) {
            Console.Write(values[i] + ", ");
        }

    }
}



Saturday 4 November 2017

Native Android UI with Unity 5.6

In Unity 5.6 the surface view object that it uses to render its graphics element is set as on top of all other views.
Due to this if you are going to add Android Views using addContentView it will not be getting displayed. For some reason it gets clickable events, so your callback will be fired.

Google ads uses PopupWindow to overcome this issue(a transparent PopupWindow with views added into it), you can see their implementation at https://github.com/googleads/googleads-mobile-unity/tree/master/source/android-library/app/src/main/java/com/google/unity/ads

It will work for you as well if your views only covers part of the window and you need not pass the click event through the PopupWindow.
Suppose you have views at the top and bottom of the window and you create a full screen PopupWindow then Unity's SurfaceView will not receive click events.

Another appraoch, maybe a little dirty, is to find the SurfaceView in the view hierarchy, remove it, set
setZOrderOnTop(false) and add it back. See the code block below,
/**
 * @param view This is the view that you want to add on top of Unity's SurfaceView
 * @param activity Unity applications Activity
 */
void addUIView(View view, Activity activity) {
        ViewGroup viewGroup = (ViewGroup)activity.findViewById(android.R.id.content);
        SurfaceView surfaceView = getSurfaceView(viewGroup);
        if (surfaceView != null) {
            ((ViewGroup)surfaceView.getParent()).removeView(surfaceView);
        }
        surfaceView.setZOrderOnTop(false);  // This should help us in getting our view displayed
        activity.setContentView(surfaceView);
        activity.addContentView(view, new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT));
}
/**
 * Get SurfaceView object by traversing the View heirarchy
 */
private SurfaceView getSurfaceView(ViewGroup parentView) {
        int numChildViews = parentView.getChildCount();
        for (int i = 0; i < numChildViews; i++) {
            View childView = parentView.getChildAt(i);
            if (childView instanceof ViewGroup) {
                SurfaceView surfaceView = getSurfaceView((ViewGroup)childView);
                if (surfaceView != null) {
                    return surfaceView;
                }
            }
            else if (childView instanceof SurfaceView) {
                return (SurfaceView)childView;
            }
        }
        return null;
}

Tuesday 30 August 2016

Finding size of an array in C/C++

It is not a good idea to hard code the size of an array. Instead we would like to somehow retrieve the size from it.

In some cases we will just initialize the array without specifying its size. In this we don't want to hard code the size as in future we might want to add more values to it.

An old way(the C way) of retrieving the size is to calculate the size of the whole array and then divide it with the size of an element in the array. This can be done as,
int i[] = {1, 2, 3};
int size = sizeof(i)/sizeof(i[0]);

// Usually please will write a macro to do this
#define ARRAY_SIZE(a) (sizeof((a))/sizeof((a[0])))


In C++ there is a way to retrieve the size of an array using templates.
template<typename T, std::size_t size>
std::size_t arrSize(T(&)[size]) {
    return size;
}

int i[] = { 1, 2, 3, 4 };
int size = arrSize(i);  // size will have 4 after this statement is executed

Another approach is to use std::array available from C++11. The only downside is that we should know the size while declaring the array
std::array<int, 4> a = { 1, 2, 3, 4 }; // Initialize as { { 1, 2, 3, 4 } } in C++11
int size = a.size(); // size will have 4 after this statement is executed

Another approach is to use std::vector(may be a little heavy if you are just looking for a fixed size array), using the universal initialize available from C++11.
std::vector<int> a = { 1, 2, 3, 4 };
int size = a.size(); // size will have 4 after this statement is executed

Monday 29 August 2016

Taking ownership of the memory from std::shared_ptr

There is no function in shared_ptr using that you take owner ship of the under lying pointer.

This may be because there might be multiple object which is referring to the same pointer.

shared_ptr has a constructor which takes an additional parameter which is used to delete the allocated object.

We will use this deleter to control the ownership.

A simple deleter implementation is shown below,
class Deleter {
private:
    std::shared_ptr<bool> mOwn = std::make_shared<bool>(true);

public:
    void setOwn(bool v) {
        *mOwn = v;
    }

    void operator()(Test *p) {
        if (*mOwn) {
            delete p;
        }
    }
};

Now we can use the above Deleter class to control the ownership of the pointer. An example use is shown below.
Deleter dltr;
std::shared_ptr<Test> obj1 = std::shared_ptr<Test>(new Test(), dltr);
dltr.setOwn(false);

std::shared_ptr<Test> obj2 = obj1;

delete obj2.get(); // safe to delete


We can specify the deleter when we reset the pointer as well.
Test *tobj1 = new Test();
Test *tobj2 = new Test();

Deleter dltr;
dltr.setOwn(false);
std::shared_ptr<Test> obj1 = std::shared_ptr<Test>(tobj1, dltr);
obj1.reset<Test, Deleter>(tobj2, dltr);

delete tobj1; // safe to delete
delete tobj2; // safe to delete

Tuesday 15 March 2016

A splash screen for Unity application(Only useful with personal or free edition) on Android platform

I always wanted to display my own splash screen as the first thing in my applications. And I was looking for a solution for this with
Unity personal edition. And I found one myself, well not a complete one!

With personal edition, unity displays its logo when the application is launched. You cannot suppress it from displaying
it, but what you can do is display a splash screen with your logo first and then let unity display its logo.

To accomplish this what we do is, before starting the UnityPlayerActivity we will start our activity which displays our the splash screen.

Lets go and create this activity.

To make the splash screen configurable, the splash screen activity will accept, splash screen image, splash screen duration and the activity to start once the splash screen is expired.

These configuration values needs to be specified in the AndroidManifest.xml file under the splash screen activity section.

A sample splash screen activity declaration in the manifest file is shown below,
 <activity android:label="@string/app_name"
    android:screenOrientation="portrait"
    android:launchMode="singleTask"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:name="com.example.unitysplash.android.SplashScreen">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
  
  <!--
  Activity com.unity3d.player.UnityPlayerActivity will be launched once the splash screen completes
  -->
      <meta-data android:name="activityToStart" android:value="com.unity3d.player.UnityPlayerActivity" />
  
  <!--
  splash screen displays @drawable/splash_screen image resource
  this image can be kept at, <Unity Project>\Assets\Plugins\Android\res\drawable-nodpi\
  -->
  <meta-data android:name="splashImage" android:resource="@drawable/splash_screen" /> 
  
  <!-- splash screen expires after 1000 milli seconds -->
  <meta-data android:name="duration" android:value="1000" />
  
    </activity>


Path for the AndroidManifest file is <Unity Project>\Assets\Plugins\Android.

If you do not have the AndroidManifest.xml file then you can generate one if you export your project. You can export the project from build settings.
After exporting add the above activity declaration and make sure that default activity's name is changed to "com.unity3d.player.UnityPlayerActivity".

If you are using custom activity for Unity then give its name for activityToStart.

Now lets go and create the activity. We will keep our activity in a jar file, so create and android library project.

Once the project is created add the class SplashScreen which derives from Activity.

In the onCreate of this activity, first retrieve the meta-data as,
        try {
            ActivityInfo ai = getPackageManager().getActivityInfo(this.getComponentName(), PackageManager.GET_META_DATA);
            Bundle bundle = ai.metaData;

            mActivityToStart = bundle.getString("activityToStart", mActivityToStart);
            mSplashImage = bundle.getInt("splashImage", mSplashImage);
            mDuration = bundle.getInt("duration", mDuration);

        } catch (PackageManager.NameNotFoundException e) {
            Log.d(SplashScreen.class.getName(), e.getMessage());
        }

Now create an ImageView and set the specified image resource to this View.
            LinearLayout layout = new LinearLayout(this);
            layout.setOrientation(LinearLayout.HORIZONTAL);

            ImageView splashImage = new ImageView(this);
            splashImage.setImageResource(mSplashImage);
            splashImage.setScaleType(ImageView.ScaleType.FIT_XY);
            layout.addView(splashImage, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

            setContentView(layout, new  ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));


To handle the time-out add a Handler implementation,
    private Handler mSplashTimeoutHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == SplashTimeoutMessage) {
                try {
                    Intent i = new Intent(SplashScreen.this, Class.forName(mActivityToStart));
                    startActivity(i);
                    SplashScreen.this.finish();
                } catch (ClassNotFoundException e) {
                    Log.d(SplashScreen.class.getName(), e.getMessage());
                }
            }
            super.handleMessage(msg);
        }
    };


In the onResume post the handler with delay as the duration mentioned.
        mSplashTimeoutHandler.sendMessageDelayed(mSplashTimeoutHandler.obtainMessage(SplashTimeoutMessage), mDuration);

In case user presses the back key before the splash screen is finished do not launch the final activity. To do this implement onBackPressed as,
        mSplashTimeoutHandler.removeMessages(SplashTimeoutMessage);

Now we are done with SplashScreen activity. Now create a jar out of it and copy it to <Unity Project>\Assets\Plugins\Android

Now if you launch the application splash screen should be the first activity displayed.


Please find a complete example at https://github.com/trsquarelab/unityexamples/tree/master/UnitySplashScreen

Wednesday 9 March 2016

Advanced Android Interview Questions and Answers 4


1. Describe a scenario where an Activity enters pause state but not stop state?

SHOW/HIDE ANSWER
When a semi-transparent activity opens making the previous activity partially visible.
Reference
http://developer.android.com/training/basics/activity-lifecycle/pausing.html

2. What kind of actions are suggested to perform on onPause callback of an Activity implementation?

SHOW/HIDE ANSWER
  • Stop animations or other ongoing actions that could consume CPU
  • Possibly commit unsaved changes
  • Release system resources such as broadcast receivers, handles to camera, sensors, etc.
Reference
http://developer.android.com/training/basics/activity-lifecycle/pausing.html

3. Describe a scenario where onRestart will be called for an Activity implementation?

SHOW/HIDE ANSWER
User launches a new activity B from activity A. And then the user presses back button on activity B.
Here onStop will be called for activity A when user launched activity B. Once user presses back button on activity B, onRestart, onStart and onResume callback are called for activity A.

The onRestart() method, however, is called only when the activity resumes from the stopped state.
Reference
http://developer.android.com/training/basics/activity-lifecycle/stopping.html

4. Describe some of the scenario where an activity could possibly be destroyed?

SHOW/HIDE ANSWER
  • User presses back button
  • finish() method is called for the Activity
  • The Activity is inactive for long time
  • Foreground Activity requires more resources so the system must shut down background processes to recover memory
Reference
http://developer.android.com/training/basics/activity-lifecycle/recreating.html

5. What are some of the advantages of Fragments?

SHOW/HIDE ANSWER
Fragments allows us to modularize the Activity.
Fragments helps us in splitting up views for some devices(phone, tablets) or based on orientations(landscape, portrait).
Fragments helps us to create reusable views.
Reference
http://developer.android.com/training/basics/fragments/index.html

6. What is AIDL?

SHOW/HIDE ANSWER
AIDL stands for Android Interface Definition Language and is used to define the programming interface that the client and server uses to communicate with each other using (IPC).
Following data types are supported by AIDL,
  • primitive types : int, long, char, boolean, etc.
  • String
  • CharSequence
  • List
  • Map
Reference
http://developer.android.com/guide/components/aidl.html

7. What are some of the cases that you would need to handle when using AsyncTask?

SHOW/HIDE ANSWER
Screen rotation : Suppose the device is rotated then the Activity will be recreated making the reference to the Activity invalid. This would even cause memory leaks as the AsyncTask might have a reference to the Activity or worse Views or the AsyncTask is implemented as a nested class of the Activity.
Activity is destroyed: This is very similar to the first one, AsyncTask continues to execute even if the Activity is destroyed.
Need to explicitly implement the cancel logic : If AsyncTask.cancel() is called then AsyncTask.isCancelled() returns true and developer is supposed to handle the AsyncTask.isCancelled() being true case.
By default AsyncTasks has just one worker thread

8. What are the contents of an APK file?

SHOW/HIDE ANSWER
APK(Android application package) is the file format used by Android for distributing and installing apps and software component.
Some of the contents of APK file are,
  • Manifest file in its binary format
  • Certificate of the application
  • Library files for different platform(armeabi, armeabi-v7a, x86, etc)
  • Compiled resource files
  • Asset files
  • classes.dex : Classes compiled in dex file format

9. What are some of the features introduced in Android N?

SHOW/HIDE ANSWER
  • Multi-window support - Users can now open two apps on the screen at once.
  • Notification enhancements - Bundled notifications, Direct reply, Custom views, Template updates
  • Improvement in Doze mode - Doze mode applied in two phases. Any time the screen is off for a period of time and the device is unplugged, Doze applies a subset of the familiar CPU and network restrictions to apps. When the device is stationary again, with screen off and on battery for a period of time, Doze applies the full CPU and network restrictions on PowerManager.WakeLock, AlarmManager alarms, and GPS/Wi-Fi scans.
  • Vulkan API - New graphics API from Khronos Group
  • Quick Settings Tile API
  • Number-blocking - Supports number blocking in the platform itself and provides a framework API to let service providers maintain a blocked-number list.
  • Call screening - CallScreeningService introduced to screen incoming calls.
  • Direct boot - Improved device startup time. Rather than at first boot, apps are compiled Just-in-Time the first time you launch them.
Reference
http://developer.android.com/preview/api-overview.html

10. What are some of the features introduced in Android Marshmallow?

SHOW/HIDE ANSWER
  • Runtime Permissions
  • Doze and App Standby
  • BoringSSL
  • Notifications - Removed method Notification.setLatestEventInfo and introduced Notification.Builder
Reference
http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html

11. What are some of the features introduced in Android Lollipop?

SHOW/HIDE ANSWER
  • Material design
  • Android Runtime (ART) - ART runtime replaces Dalvik as the platform default.
  • Platform support for 64-bit architectures
  • Notifications - Notifications now appear on the user's lock screen, heads-up notification (a small floating window that allows the user to respond or dismiss without leaving the current app)
Reference
http://developer.android.com/about/versions/android-5.0-changes.html

Tuesday 8 March 2016

Advanced Android Interview Questions and Answers 2


1. What is dependency injection?

SHOW/HIDE ANSWER
Is a pattern for resolving dependency. It is an implementation of dependency inversion principle (DIP). Some of the libraries to enable dependency injection for are,
  • AndroidAnnotations
  • Butter Knife
  • Dagger
  • Dagger2
  • RoboGuice

2. How to set permission for content provider?

SHOW/HIDE ANSWER
Read-write permission can be set in the attribute android:permission of provider tag
Read permission can be set in android:readPermission
Write permission can be set in android:writePermission
URI level permission can be set using path-permission tag
Use android:grantUriPermissions to grant temporary permission
Reference
http://developer.android.com/guide/topics/providers/content-provider-creating.html#Permissions

3. What are the different protection levels in permission?

SHOW/HIDE ANSWER
  • normal : The default value, is automatically granted at installation time
  • dangerous : Displays it to the user at installation/run-time for their confirmation
  • signature : Grants if the requesting application is signed with the same certificate as the application that declared the permission
  • signatureOrSystem : Grants if installed in the system image or signature(c)
Reference
http://developer.android.com/guide/topics/manifest/permission-element.html

4. What is a ViewStub?

SHOW/HIDE ANSWER
A ViewStub is an invisible, zero-sized View that can be used to lazily inflate layout resources at runtime.
When a ViewStub is made visible, or when inflate() is invoked, the layout resource is inflated. The ViewStub then replaces itself in its parent with the inflated View or Views.
Therefore, the ViewStub exists in the view hierarchy until setVisibility(int) or inflate() is invoked.
Reference
http://developer.android.com/reference/android/view/ViewStub.html

5. What is the use of merge tag in layout?

SHOW/HIDE ANSWER
merge tag can be used for optimizing the layout. When a layout is included in another one; it is useful in removing unnecessary layout that are just used to wrap views. Reference
http://developer.android.com/training/improving-layouts/reusing-layouts.html#Merge

6. Which is the best place to register and unregister a BroadcastReceiver from an Activity?

SHOW/HIDE ANSWER
onStart and onStop respectively

7. What is the difference between DVM(Dalvik Virtual Machine) and JVM(Java Virtual Machine)?

SHOW/HIDE ANSWER
DVM is register based and is designed to run on low memory devices.
JVM is stack based. The main objective when JVM was designed is to make it run as many platform as possible.
DVM requires less instruction set.
.dex file which DVM can understand is lesser in size compared to .class files.

8. What is a 9 patch image?

SHOW/HIDE ANSWER
Is a stretchable image that helps in solving compatibility issues when used with devices with different screen sizes.
Here an image is divided into 9 parts,
4 corners - Do not scale
2 vertical edges - Scale vertically
2 horizontal edges - Scale horizontally
1 Middle area - Scale vertically and horizontally
Reference
http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

9. Under what license Android is released?

SHOW/HIDE ANSWER
Android is released under Apache Software License, Version 2.0("Apache 2.0"). Linux kernel patches are under the GPLv2 license. Reference
https://source.android.com/source/licenses.html

10. What is a SparseArray?

SHOW/HIDE ANSWER
SparseArrays are used to map integers to Objects. It is called sparse because there can be gaps in the indices.
It is intended to be more memory efficient than using a HashMap to map Integers to Objects, both because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping. Reference
http://developer.android.com/reference/android/util/SparseArray.html

11. What is an ArrayMap?

SHOW/HIDE ANSWER
ArrayMap is a generic key->value mapping data structure that is designed to be more memory efficient than a traditional HashMap.
It keeps its mappings in an integer array of hash codes for each item, and an Object array of the key/value pairs.
ArrayMap uses binary search on the integer array to find a key.
Reference
http://developer.android.com/reference/android/util/ArrayMap.html

12. What is Autoboxing?

SHOW/HIDE ANSWER
Is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes, such as int and Integer Reference
https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html

13. How memory trimming can be done in Android?

SHOW/HIDE ANSWER
Implement ComponentCallbacks2, register it using registerComponentCallbacks on your Activity, Service, ContentProvider, or Application and listen for onTrimMemory callback.
onTrimMemory is called with different memory levels some of them are,
TRIM_MEMORY_RUNNING_MODERATE : The device is beginning to run low on memory
TRIM_MEMORY_RUNNING_LOW : The device is running much lower on memory
TRIM_MEMORY_RUNNING_CRITICAL : The device is running extremely low on memory
Reference
http://developer.android.com/reference/android/content/ComponentCallbacks2.html

14. What is StrictMode?

SHOW/HIDE ANSWER
StrictMode is a developer tool that can be used to detect accidental disk or network access on the application's main thread.
?
1
2
3
4
5
6
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
Reference
http://developer.android.com/reference/android/os/StrictMode.html

15. What are the ways of optimizing layout?

SHOW/HIDE ANSWER
Use Tools(Hierarchy Viewer/Lint) to measure and identifying the bottleneck
Change deeper layouts to flat or wide
Use ViewStub for displaying On Demand
Reference
http://developer.android.com/training/improving-layouts/index.html

16. How to optimize ListView?

SHOW/HIDE ANSWER
  • Use background thread to load ListView data
  • User View Holder pattern
You may also want to try RecyclerView References
http://developer.android.com/training/improving-layouts/smooth-scrolling.html http://blog.trsquarelab.com/2015/12/introduction-to-android-recyclerview.html

17. What is RecyclerView?

SHOW/HIDE ANSWER
RecyclerView can be used to display large data much like ListView.
In RecyclerView we can set custom layout management for its children's, it has animation support built-in, has item decorator support and it uses the View-holder pattern.
Reference
http://blog.trsquarelab.com/2015/12/introduction-to-android-recyclerview.html

18. What is JobScheduler?

SHOW/HIDE ANSWER
An API for scheduling jobs against the framework that will be executed in your application's own process and in main thread. To use job JobScheduler,
  • Create a JobServer implementation: by extending JobService
  • Create JobInfo : Use JobInfo.Builder
  • Get the JobScheduler : Context.getSystemService(Context.JOB_SCHEDULER_SERVICE)
  • schedule the job : JobScheduler.schedule
Reference
http://developer.android.com/reference/android/app/job/JobScheduler.html http://developer.android.com/reference/android/app/job/JobService.html http://developer.android.com/reference/android/app/job/JobInfo.html

19. How to create application that support different languages?

SHOW/HIDE ANSWER
create additional values directories inside res/ that include a hyphen and the ISO language code at the end of the directory name.
Keep the language specific string resources into the corresponding directory.
MyProject/
    res/
       values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml
Reference
http://developer.android.com/training/basics/supporting-devices/languages.html

20. How to create application that support different screen sizes?

SHOW/HIDE ANSWER
Create different layout folder according to the screen sizes.
MyProject/
    res/
        layout/              # default (portrait)
            main.xml
        layout-land/         # landscape
            main.xml
        layout-large/        # large (portrait)
            main.xml
        layout-large-land/   # large landscape
            main.xml
  
Create different bitmaps according to the screen densities.
MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png
Reference
http://developer.android.com/training/basics/supporting-devices/screens.html