Quantcast
Channel: CoderzHeaven
Viewing all 526 articles
Browse latest View live

SQlite Database Operations in Flutter

$
0
0

SQFlite is a Flutter library for doing local Database Operations.

You can download it from here.

To Integrate SQFlite library in your project

In your flutter project add the dependency:

dependencies:
  ...
  sqflite: any

You can download the sample project from here.

Here is a sample DB Utility file.

DBHelper.dart

import 'dart:async';
import 'dart:io' as io;
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'Person.dart';

class DBHelper {
  static Database _db;

  Future<Database> get db async {
    if (_db != null) return _db;
    _db = await initDb();
    return _db;
  }

  //Creating a database with name test.dn in your directory
  initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, "test.db");
    var theDb = await openDatabase(path, version: 1, onCreate: _onCreate);
    return theDb;
  }

  // Creating a table name Employee with fields
  void _onCreate(Database db, int version) async {
    // When creating the db, create the table
    await db.execute(
        "CREATE TABLE Employee(id INTEGER PRIMARY KEY, name TEXT, age TEXT, mobileno TEXT)");
    print("Created tables");
  }

  // Retrieving employees from Employee Tables
  Future<List<Person>> getEmployees() async {
    var dbClient = await db;
    List
<Map> list = await dbClient.rawQuery('SELECT * FROM Employee');
    List<Person> employees = new List();
    for (int i = 0; i < list.length; i++) {
      employees.add(
          new Person(list[i]["name"], list[i]["age"], list[i]["mobileno"]));
    }
    print(employees.length);
    return employees;
  }

  void saveEmployee(Person person) async {
    var dbClient = await db;
    await dbClient.transaction((txn) async {
      var query = 'INSERT INTO Employee (name, age, mobileno) VALUES (' +
          '\'' +
          person.name +
          '\'' +
          ',' +
          '\'' +
          person.age +
          '\'' +
          ',' +
          '\'' +
          person.mobileNo +
          '\'' +
          ")";
      print("Query : " + query);
      return await txn.rawInsert(query);
    });
  }
}

Simple Interview Question and Answer – 1

$
0
0

Question

John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.

For example, there are socks with colors . There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .

Function Description

Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.

sockMerchant has the following parameter(s):

n: the number of socks in the pile
ar: the colors of each sock
Input Format

The first line contains an integer , the number of socks represented in .
The second line contains space-separated integers describing the colors of the socks in the pile.

Constraints

where

Output Format

Print the total number of matching pairs of socks that John can sell.

Sample Input

9
10 20 20 10 10 30 50 10 20

Sample Output

3

Solution


static int sockMerchant(int n, int[] sockArray) {
    int matchCount = 0;
    int currentColor = 0;
    int length = sockArray.length;

    ArrayList<Integer> sockColorsArray = new ArrayList<>();
    for(int i = 0; i < length; i++){
      currentColor = sockArray[i];
      if(sockColorsArray.contains(currentColor)){
         matchCount++;
         sockColorsArray.remove(new Integer(currentColor));
      }else{
         sockColorsArray.add(new Integer(currentColor)); 
      }
    }
    return matchCount;
 }

Interview Question and Solution – 2

$
0
0

Gary is an avid hiker. He tracks his hikes meticulously, paying close attention to small details like topography. During his last hike he took exactly steps. For every step he took, he noted if it was an uphill, , or a downhill, step. Gary’s hikes start and end at sea level and each step up or down represents a unit change in altitude. We define the following terms:

A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
Given Gary’s sequence of up and down steps during his last hike, find and print the number of valleys he walked through.

For example, if Gary’s path is , he first enters a valley units deep. Then he climbs out an up onto a mountain units high. Finally, he returns to sea level and ends his hike.

Function Description

Complete the countingValleys function in the editor below. It must return an integer that denotes the number of valleys Gary traversed.

countingValleys has the following parameter(s):

n: the number of steps Gary takes
s: a string describing his path
Input Format

The first line contains an integer , the number of steps in Gary’s hike.
The second line contains a single string , of characters that describe his path.

Constraints

Output Format

Print a single integer that denotes the number of valleys Gary walked through during his hike.

Sample Input

8
UDDDUDUU
Sample Output

1
Explanation

If we represent _ as sea level, a step up as /, and a step down as \, Gary’s hike can be drawn as:

_/\ _
\ /
\/\/
He enters and leaves one valley.

Solution ::

// Complete the countingValleys function below.
static int countingValleys(int n, String str) {
    int numValleys = 0, isGoingUp = 0, isGoingDown = 0;
    int length = str.length();
    for(int i = 0; i < length; i++){
        if(str.charAt(i) == 'U'){
            isGoingUp++;
        }
        if(str.charAt(i) == 'D'){
            isGoingUp--;
        }
        if(isGoingUp < 0){
            isGoingDown = 1;
        }
        if(isGoingDown == 1 && isGoingUp == 0){
            numValleys++;
            isGoingDown = 0;
        }
    return numValleys;
}

Interview Question and Answer – 3

$
0
0

Question

Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.

For each game, Emma will get an array of clouds numbered if they are safe or if they must be avoided. For example, indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes and . She could follow the following two paths: or . The first path takes jumps while the second takes .

Function Description

Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.

jumpingOnClouds has the following parameter(s):

c: an array of binary integers

Input Format

The first line contains an integer , the total number of clouds. The second line contains space-separated binary integers describing clouds where .

Constraints

Output Format

Print the minimum number of jumps needed to win the game.

Sample Input 0

7
0 0 1 0 0 1 0

Sample Output 0

4

Explanation:

Emma must avoid and . She can win the game with a minimum of jumps:

jump(2).png

Sample Input 1

6
0 0 0 0 1 0
Sample Output 1

3

Solution

static int jumpingOnClouds(int[] c){
    
        ArrayList<Integer> path = new ArrayList<>();
        path.add(0);

        for (int i = 1; i < c.length; i++) {
            if (c[i] == 0) {
               int last1Index = path.get(path.size() - 1); // 1
                if (path.size() == 1) {
                    path.add(i);
                    continue;
                }
                int last2Index = path.get(path.size() - 2); 
                if(last1Index - last2Index  == 1 && i - last1Index == 1) {
                    path.set(path.size() - 1, i);
                }else {
                    path.add(i);
                }
            }
        }
        return path.size() - 1;

    }

Interview Question & Answer – 4

$
0
0

Question

Lilah has a string, , of lowercase English letters that she repeated infinitely many times.

Given an integer, , find and print the number of letter a’s in the first letters of Lilah’s infinite string.

For example, if the string and , the substring we consider is , the first characters of her infinite string. There are occurrences of a in the substring.

Function Description

Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of a in the prefix of length in the infinitely repeating string.

repeatedString has the following parameter(s):

s: a string to repeat
n: the number of characters to consider

Input Format

The first line contains a single string, .
The second line contains an integer, .

Constraints

For of the test cases, .
Output Format

Print a single integer denoting the number of letter a’s in the first letters of the infinite string created by repeating infinitely many times.

Sample Input

aba
10

Sample Output

7

Explanation

The first letters of the infinite string are abaabaabaa. Because there are a’s, we print on a new line.

Sample Input

a
1000000000000

Sample Output

1000000000000

Solution

static long repeatedString(String s, long n) {
    long aCount = 0;
    long length = s.length();
    long q = n / length;
    long rem = n % length;

    String remString;
    aCount += getCount(s);
    aCount *= q;
    if (rem > 0) {
        remString = s.substring(0, (int) (rem));
        aCount += getCount(remString);
    }
    return aCount;
}

static int getCount(String string) {
    int count = 0;
    if (null == string || string.isEmpty()) {
        return count;
    }
    char[] chars = string.toCharArray();
    for (int i = 0; i < string.length(); i++) {
        if (chars[i] == 'a') {
            count++;
        }
    }
    return count;
}

Interview Question & Answer – 5

$
0
0

Question

Alice and Bob each created one problem for our company. A reviewer rates the two challenges, awarding points on a scale from to for three categories: problem clarity, originality, and difficulty.

We define the rating for Alice’s challenge to be the triplet , and the rating for Bob’s challenge to be the triplet .

Your task is to find their comparison points by comparing with , with , and with .

If , then Alice is awarded point.
If , then Bob is awarded point.
If , then neither person receives a point.
Comparison points is the total points a person earned.

Given and , determine their respective comparison points.

For example, and . For elements , Bob is awarded a point because . For the equal elements and , no points are earned. Finally, for elements , so Alice receives a point. Your return array would be with Alice’s score first and Bob’s second.

Function Description

Complete the function compareTriplets in the editor below. It must return an array of two integers, the first being Alice’s score and the second being Bob’s.

compareTriplets has the following parameter(s):

a: an array of integers representing Alice’s challenge rating
b: an array of integers representing Bob’s challenge rating

Input Format

The first line contains space-separated integers, , , and , describing the respective values in triplet .
The second line contains space-separated integers, , , and , describing the respective values in triplet .

Constraints

Output Format

Return an array of two integers denoting the respective comparison points earned by Alice and Bob.

Sample Input

5 6 7
3 6 10

Sample Output

1 1

Solution

static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) {
    List<Integer> list = new ArrayList<Integer>();
    int aliceCount = 0;
    int bobCount = 0;
    list.add(0, aliceCount);
    list.add(1, bobCount);
    for(int i = 0; i < a.size(); i++){ 
        if(a.get(i) > b.get(i)) {
            list.set(0, ++aliceCount);
        }
        if(a.get(i) < b.get(i)) {
            list.set(1, ++bobCount);
        }
    }
    return list;
}

Interview Question & Answer – 6

$
0
0

Question

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

For example, the square matrix is shown below:

1 2 3
4 5 6
9 8 9

Ans : | (1+5+9) – (3+5+9) | = 2.

Solution

static int diagonalDifference(int[][] arr) {
    int diagonalSum1 = 0;
    int diagonalSum2 = 0;
    int length = arr.length;
    for (int row = 0; row < length; row++){
        diagonalSum1 += arr[row][row];
        diagonalSum2 += arr[row][length - row - 1];
    }
    return Math.abs(diagonalSum1 - diagonalSum2);
}

Flutter – Saving Data in Local using Shared Preferences

$
0
0

This simple example demonstrates saving an integer value in the local shared preferences.
We will use a flutter plugin called shared_preferences for this.
You can read more about the plugin from here.

Add Dependency

First thing is to add the package to the dependencies.
Go to pubspec.yaml and add the package.

dependencies:
  flutter:
    sdk: flutter
  shared_preferences: "0.4.3"

Example

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class PreferenceDemo extends StatefulWidget {
  PreferenceDemo({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _PreferenceDemo createState() =&amp;gt; _PreferenceDemo();
}

class _PreferenceDemo extends State&amp;lt;PreferenceDemo&amp;gt; {
  int _counter = 0;

  @override
  void initState() {
    super.initState();
    _loadCounter();
  }

  //Loading counter value on start
  _loadCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0);
    });
  }

  //Incrementing counter after click
  _incrementCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      _counter = (prefs.getInt('counter') ?? 0) + 1;
      prefs.setInt('counter', _counter);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: &amp;lt;Widget&amp;gt;[
            Text(
              'Saved counter in Preferences and Reloaded...',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Interview Question & Answer – 7

$
0
0

Question

Write a recursive program to count the number of “a”s in a string.

Solution

package com.test;

public class CountAs {

	static int countA(String str) {
		if (str.length() == 0) {
			return 0;
		}
		int count = 0;
		if (str.substring(0, 1).equals("a")) {
			count = 1;
		}
		return count + countA(str.substring(1));
	}

	public static void main(String[] args) {
		int count = countA("Hello how are you. I am from India.");
		System.out.println("Count A :: " + count);
	}
}

Doing HTTP Calls in Flutter and Parsing Data

$
0
0

Here is a simple example of doing Http calls in Flutter.

In this example we will try to fetch some JSON value from the below url

https://jsonplaceholder.typicode.com/posts/1

You can read more from here.

Add Dependencies

First you need to add the http plugin in dependencies.

dependencies:
  http: <latest_version>

The latest version of http can be found here (https://pub.dartlang.org/packages/http).

Example

Lets look at a simple example where we fetch some data and show it in the UI.

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart' as http;

Future<Post> fetchPost() async {
  final response =
      await http.get('https://jsonplaceholder.typicode.com/posts/1');

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

class Post {
  final int userId;
  final int id;
  final String title;
  final String body;

  Post({this.userId, this.id, this.title, this.body});

  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
      userId: json['userId'],
      id: json['id'],
      title: json['title'],
      body: json['body'],
    );
  }
}

class ServiceCall extends StatefulWidget {
  ServiceCall({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _ServiceCallState createState() => _ServiceCallState();
}

class _ServiceCallState extends State<ServiceCall> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: FutureBuilder<Post>(
          future: fetchPost(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return new Padding(
                  padding: new EdgeInsets.all(10.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text('USER ID : ${snapshot.data.userId}'),
                      Text('TITLE : ${snapshot.data.title}'),
                      Text('BODY : ${snapshot.data.body}'),
                    ],
                  ));
            } else if (snapshot.hasError) {
              return Text("Error : ${snapshot.error}");
            }
            // By default, show a loading spinner
            return CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

Interview Question & Answer – 8

$
0
0

Question

You are in charge of the cake for your niece’s birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out.

For example, if your niece is turning 4 years old, and the cake will have 4 candles of height
4, 4, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are such candles.You are in charge of the cake for your niece’s birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out.

Output Format

Print the number of candles that can be blown out on a new line.

Sample Input

4
3 2 1 3

Sample Output

2

Solution

static int birthdayCakeCandles(int[] ar) {
    int countTallest = 0;
    int tallest = 0, prevTallest = -1;
    int len = ar.length;
    for (int i = 0; i < len; i++) {
        if (tallest <= ar[i]) {
            tallest = ar[i];
            if(prevTallest == tallest) {
                countTallest++;
            }else {
                countTallest = 1;
            }
            prevTallest = tallest;
        }
    }
    return countTallest;
}

Interview Question & Answer – 9

$
0
0

Question

Given a time in -hour AM/PM format, convert it to military (24-hour) time.

Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.

Sample Input

07:05:45PM

Sample Output

19:05:45

Solution

static String timeConversion(String s) {
    String time24 = null;
    int hour24 = 0;

    if (null == s || s.isBlank()) {
        return time24;
    }

    String[] arr = s.split(":");
    String ampm = arr[2].substring(2, 4);
    boolean am = ampm.equalsIgnoreCase("AM");
    if (arr.length > 0) {
        int hour = Integer.parseInt(arr[0]);
        if (hour == 12) {
            if (am) {
                hour24 = 0;
            } else {
                hour24 = hour;
            }
        } else if (hour < 12 && !am) {
            hour24 = hour + 12;
        } else {
            hour24 = hour;
        }
        if (hour24 < 10) {
            arr[0] = "0" + hour24;
        } else {
            arr[0] = String.valueOf(hour24);
        }
    }
    time24 = arr[0] + ":" + arr[1] + ":" + arr[2].substring(0, 2);
    return time24;
}

GridView Demo in Flutter

$
0
0

Hi Friends,

Today we will see how to implement GridView in Flutter.

 

 

We are going to use this service for the data
First we will create a Model for the Grid Cell

class HomeCellVO {
  int id;
  String title;
  String icon;

  HomeCellVO({this.id, this.title, this.icon});

  factory HomeCellVO.fromJson(Map<String, dynamic> json) {
    return HomeCellVO(
      id: json['id'] as int,
      title: json['title'] as String,
      icon: json['icon'] as String,
    );
  }
}

No we will create view for Grid Cell

Create a file named “cell.dart” and copy this into it.

import 'package:flutter/material.dart';
import 'home_cell.dart';

class Cell extends StatelessWidget {
  const Cell(this.homeCellVO);
  @required
  final HomeCellVO homeCellVO;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        child: new Column(
          children: <Widget>[
            Image.network(homeCellVO.icon,
                width: 100.0,
                height: 100.0,
                alignment: Alignment.center,
                fit: BoxFit.cover),
            Text(homeCellVO.title),
          ],
        ),
      ),
    );
  }
}

Service Class

We have the below service class for fetching the data.

service.dart

import 'dart:async';
import 'dart:convert';
import 'home_cell.dart';
import 'constants.dart';
import 'package:http/http.dart' as http;

class Services {
  static Future<List<HomeCellVO>> fetchHomeData() async {
    final response = await http.get(CONSTANTS.HOME_SERVICE_URL);
    if (response.statusCode == 200) {
      List<HomeCellVO> list = parsePostsForHome(response.body);
      return list;
    } else {
      throw Exception(CONSTANTS.INTERNET_ERROR);
    }
  }

  static List<HomeCellVO> parsePostsForHome(String responseBody) {
    final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    return parsed.map<HomeCellVO>((json) => HomeCellVO.fromJson(json)).toList();
  }
}

To read about the http implementation, please read this post.

Also we have a seperate file for constants called constants.dart

class CONSTANTS {
  static const String INTERNET_ERROR = "No Internet Connection";
  static const HOME_SERVICE_URL = 'http://codemansion.co.in/test.json';
}

Implementation

Now the class that implements the GridView

home.dart

import 'package:flutter/material.dart';

import 'cell.dart';
import 'constants.dart';
import 'home_cell.dart';
import 'services.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<HomeCellVO> homeCells = new List();

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(widget.title),
        ),
        body: Container(
          child: FutureBuilder<List<HomeCellVO>>(
            future: Services.fetchHomeData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return new Padding(
                  padding: new EdgeInsets.all(10.0),
                  child: GridView.builder(
                    itemCount: snapshot.data.length,
                    gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 2),
                    itemBuilder: (BuildContext context, int index) {
                      return new GestureDetector(
                        child: Cell(snapshot.data[index]),
                        onTap: () => gridClicked(index),
                      );
                    },
                  ),
                );
              } else if (snapshot.hasError) {
                return Text(CONSTANTS.INTERNET_ERROR);
              }
            },
          ),
        ));
  }
}

gridClicked(int index) {
  print('gridClicked : $index');
}

gridClicked is the function for handling the clicks in the Grid.

Great, we are all done.
Thanks.

Please leave your valuable comments below this post.

All Done

All Done

Doing Simple Navigation in Flutter – Simple Example

$
0
0

Navigation is done is Flutter using the Navigator class.

Lets look at a simple example

The first thing you have to register routes for difference screen is to build a Map of ‘String’ (route) and the page (Widget).

 

Lets say I have a utility class for the Creating Routes named routes.dart. The contents of route.dart contains the below code

import 'package:flutter/material.dart';
import 'exercises_screen.dart';

class Routes {
  static Map<String, WidgetBuilder> buildRoutes() {
    Map<String, WidgetBuilder> routes = new Map<String, WidgetBuilder>();
    routes.putIfAbsent(
        '/exercises', () => (BuildContext context) => new Exercises());
    return routes;
  }
}

My Exercises class will simply look like this

import 'package:flutter/material.dart';

class Exercises extends StatefulWidget {
  const Exercises({Key key}) : super(key: key);

  static const String routeName = '/exercises';
  @override
  State<StatefulWidget> createState() {
    return new _ExercisesState();
  }
}

class _ExercisesState extends State<Exercises> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text("Exercises")),
      body: new Container(child: Text("Exercises")),
    );
  }
}

Register the Routes

Note the buildRoutes() function used in the “routes” property of the initial MaterialApp.

import 'package:flutter/material.dart';
import 'home.dart';
import 'routes.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Home'),
      routes: Routes.buildRoutes(), // register the routes for the application.
    );
  }
}

Invoke the Push

Its Simple as that…

  Navigator.pushNamed(context, '/exercises');

Note: This will only work if you have registered the screen “Exercises” with route “/exercises”.

Pop Screen

To Pop current screen

  Navigator.of(context).pop();

Interview Question – 9

$
0
0

Question

Maria plays college basketball and wants to go pro. Each season she maintains a record of her play. She tabulates the number of times she breaks her season record for most points and least points in a game. Points scored in the first game establish her record for the season, and she begins counting from there.

For example, assume her scores for the season are represented in the array scores=[12,24,10,24]. Scores are in the same order as the games played. She would tabulate her results as follows:

Game Score Minimum Maximum Min Max
0 12 12 12 0 0
1 24 12 24 0 1
2 10 10 24 1 1
3 24 10 24 1 1

Given Maria’s scores for a season, find and print the number of times she breaks her records for most and least points scored during the season.

You can download the problem statement from here.

Sample Input

10
3,4, 21, 36, 10, 28, 35, 5, 24, 42

Sample Output

4, 0

Solution

static int[] breakingRecords(int[] scores) {

    int min = scores[0], max = scores[0];
    int minCount = 0, maxCount = 0;

    int len = scores.length;

    for (int i = 0; i < len; i++) {
        if (scores[i] < min) {
            min = scores[i];
            minCount++;
        }
        if (scores[i] > max) {
            max = scores[i];
            maxCount++;
        }
    }
    return new int[]{maxCount, minCount};
}

Interview Question & Answer – 10 – Divisible Sum pairs

$
0
0

Question

Find the count where the number k is divisible by sum of two numbers in the array and first number index should be less than second number index.

Function has the following parameter(s):

n: the integer length of array
ar: an array of integers
k: the integer to divide the pair sum by

You can download the problem statement here.

Solution

 static int divisibleSumPairs(int n, int k, int[] ar) {
    int count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i < j && (ar[i] + ar[j]) % k == 0) {
                ++count;
            }
        }
    }
    return count;
}

Interview Question & Answers – Migratory Birds Count – 11

$
0
0

Question

You have been asked to help study the population of birds migrating across the continent. Each type of bird you are interested in will be identified by an integer value. Each time a particular kind of bird is spotted, its id number will be added to your array of sightings. You would like to be able to find out which type of bird is most common given a list of sightings. Your task is to print the type number of that bird and if two or more types of birds are equally common, choose the type with the smallest ID number.

For example, assume your bird sightings are of types arr=[1, 1, 2, 2, 3]. There are two each of types and , and one sighting of type . Pick the lower of the two types seen twice: type 1.

You can download the problem statement from here.

Solution

We first need a hashmap to save the count of each migratory birds. Then we take the max value of has set. If there are more than one key with same value, get the Min Key from the Hash Set.

 static int migratoryBirds(List<Integer> arr) {
    HashMap<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < arr.size(); i++) {
        int count = 0;
        if (map.containsKey(arr.get(i))) {
            count = map.get(arr.get(i));
        }
        map.put(arr.get(i), ++count);
    }

    int maxValue = Collections.max(map.values());
    int minKey = 0; 
    int curKey = 0;
    for (Map.Entry me : map.entrySet()) {
        if ((int) me.getValue() == maxValue) {
            curKey = (int) me.getKey();
            if ((int) me.getKey() < minKey || minKey == 0) {
                minKey = curKey;
            }
        }
    }
    return minKey;
}

You can checkout the previous Interview Question here.

RNFirebase core module was not found natively on ios – Fix

$
0
0

This issue happens in react-native-firebase for a various reasons.

First thing you have to do is check

  • Firebase/Core is in your pods.
  • Try Cleaning and rebuilding your project.
  • Click on the target you are running in xcode and check the frameworks section in ‘General’ Tab -> Check you have linked libFirebase.a there. If not click the “+” button at the bottom and
    add it. if you are not finding it, then right click the project -> Add Files to Project -> Add and link the project.
  • Comment use_frameworks! in your pods file.
  • If above is not working for you, then try these commands in terminal

    rm -rf ~/Library/Caches/CocoaPods;
    rm -rf Pods;
    rm -rf ~/Library/Developer/Xcode/DerivedData/*;
    pod deintegrate;
    pod setup;
    pod install;

Hide Navigation – Android Tip – 1

Toast at the center of the screen – Android Tip # 2

$
0
0

Here is Tip # 2

Toast at Center of the Screen

LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
              (ViewGroup) findViewById(R.id.custom_toast_layout));
text.setText("Toast at the Center of Screen");

Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Viewing all 526 articles
Browse latest View live