Simple Array Sum

You are given an array of integers of size N. Can you find the sum of the elements in the array?

Input
The first line of input consists of an integer N. The next line contains N space-separated integers representing the array elements.
Sample:

6

1 2 3 4 10 11

Output
Output a single value equal to the sum of the elements in the array.
For the sample above you would just print 31 since 1+2+3+4+10+11=31.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
 
public class Solution {
 
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int sum = 0;
        for(int i=0;i<n;i++){
            sum+=in.nextInt();
        }
        System.out.println(sum);    
    }
}

Candies

Alice is a kindergarden teacher. She wants to give some candies to the children in her class. All the children sit in a line ( their positions are fixed), and each of them has a rating score according to his or her performance in the class. Alice wants to give at least 1 candy to each child. If two children sit next to each other, then the one with the higher rating must get more candies. Alice wants to save money, so she needs to minimize the total number of candies given to the children.

Input Format

The first line of the input is an integer N, the number of children in Alice’s class. Each of the following N lines contains an integer that indicates the rating of each child.

Output Format

Output a single line containing the minimum number of candies Alice must buy.

Sample Input

3
1
2
2
Sample Output

4
Explanation

Here 1, 2, 2 is the rating. Note that when two children have equal rating, they are allowed to have different number of candies. Hence optimal distribution will be 1, 2, 1

 
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
 
public class Solution {
 
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n =sc.nextInt();
        int []r = new int[n];
        for(int i=0; i<n; i++){
        r[i] = sc.nextInt();
        }
        System.out.println(distributeCandy(r));
    }
 
    static int distributeCandy(int[] score) {
        int sum =0;
        int n = score.length;
                    int[] c = new int[n];
    for(int i=0; i<n-1; i++){
        if(score[i+1]>score[i]) c[i+1]=c[i]+1;
    }
    for(int i=n-1; i>0; i--){
        if(score[i-1]>score[i]&&!(c[i-1]>c[i])) c[i-1]=c[i]+1;
    }
 
    for(int i:c) sum+=i;
 
        return sum+n;
 
    }
}

Play audio file from Resources – Android

playSample(R.raw.defaultmusic);
 
private void playSample(int resid)
	{
	    AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(resid);
 
	    try
	    {   
	        mp.reset();
	        mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
	        mp.prepare();
	        mp.start();
	        afd.close();
	    }
	    catch (IllegalArgumentException e)
	    {
	        Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
	    }
	    catch (IllegalStateException e)
	    {
	        Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
	    }
	    catch (IOException e)
	    {
	        Log.e(TAG, "Unable to play audio queue do to exception: " + e.getMessage(), e);
	    }
	}

Delete item from ListView on Long press -Cursor Adapter – Android

DBHelper db;
Cursor c;
RecordCursorAdapter recordCursorAdapter;
// RecordCursorAdapter extends CursorAdapter class
 
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
 
            @Override
            public boolean onItemLongClick(AdapterView arg0, View v, int position, long arg3) {
                AlertDialog.Builder ad = new AlertDialog.Builder(ListActivity.this);
                ad.setTitle("Delete");
                ad.setMessage("Sure you want to delete record ?");
                final int pos = position;
                ad.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
 
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //Delete of record from Database and List view.
                        c.moveToPosition(pos);
                        db.delete(c.getInt(c.getColumnIndex(DBHelper.KEY_ID)));
                        c=db.getAll();
                        recordCursorAdapter.swapCursor(c);
                        listView.setAdapter(recordCursorAdapter);
                    }
                });
                ad.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
 
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                ad.show();
                return false;
            }
        });

Delete and getAll() function in DBHelper class

    public void delete(int anInt) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        db.delete(TABLE_RECORD,KEY_ID+"=?",new String[]{String.valueOf(anInt)});
        db.close();
    }
 
public Cursor getAll(){
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery("SELECT  * FROM "+TABLE_RECORD, null);
        return c;
    }

Convert recorded 3gp file to Byte array and store in SQLite database – Android

Use MediaRecorder and store audio in outputFile

outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";;
byte[] soundBytes;
 
try {
    InputStream inputStream = getContentResolver().openInputStream(Uri.fromFile(new File(outputFile)));
    soundBytes = new byte[inputStream.available()];
 
    soundBytes = toByteArray(inputStream);
}catch(Exception e){
    e.printStackTrace();
}
 
public byte[] toByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int read = 0;
        byte[] buffer = new byte[1024];
        while (read != -1) {
            read = in.read(buffer);
            if (read != -1)
                out.write(buffer,0,read);
        }
        out.close();
        return out.toByteArray();
    }

Convert Byte array to 3gp file and play – Android

Get stored byte array from sqlite database

byte[] soundBytes=db.getSound(); 
// db.getSound() returns byte array from database
 
 
String outputFile=Environment.getExternalStorageDirectory().getAbsolutePath() + "/output.3gp";
File path = new File(outputFile);
FileOutputStream fos = null;
try {
     fos = new FileOutputStream(path);
     fos.write(soundBytes);
     fos.close();
} catch (Exception e) {
     e.printStackTrace();
}
MediaPlayer mediaPlayer = new MediaPlayer();
 
try {
     mediaPlayer.setDataSource(outputFile);
     mediaPlayer.prepare();
     mediaPlayer.start();
} catch (IOException e) {
     e.printStackTrace();
}

VideoView fill width and height of container -Android

To fill width and height with video view use the following code in your layout file. Use relative layout to wrap videoview.

<RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_horizontal|center_vertical">
    <VideoView
        android:id="@+id/vidView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center_horizontal|center_vertical" 
        android:layout_alignParentRight="true" 
        android:layout_alignParentLeft="true" 
	android:layout_alignParentTop="true" 
	android:layout_alignParentBottom="true" />
 
</RelativeLayout>

Enable PTP mode in Samsung Galaxy Note 2

  • Dial *#7284# from your phone
  • Change your USB connection settings (modem or PDA) – change it to PDA.
  • Click on the button “Qualcomm USB”
  • In that menu click on MTP + ADB option.
  • Save and reset
  • Wait for your phone to restart
  • Connect your phone via USB
  • There should be a USB symbol on your phone in the status bar-click on it.
  • Select PTP option