Home Blog

Find the smallest positive missing number in array

0

Hi Guys, Welcome to Proto Coders Point. Here is the solution for a problem statement “Find the smallest positive number that does not appear in array”. – JAVA PROGRAM

You car given a Array (Sorted/UnSorted), You need to search the missing small number in the array.

Example

Array { 1, 4, 5, 7, 6 }

Here the missing smallest number starting from 1 to N is checked, so as you can see missing number in above array is 2. After 1 we directly have 4, 5, 7, 6. Therefore 2 is smallest number & is missing .

Example 2

Array { 6, 5, 1, 2, 3, 7 } output: 4.


Source Code JAVA Program – To Find the positive smallest number missing in Array

import java.util.*;
import java.util.Arrays;

class HelloWorld {
    public static void main(String[] args) {
       
        int arr[] = {6,5,1,2,3,7};

        int result = findMissSmall(arr);

       System.out.println(""+result );
    }

    static public int findMissSmall(int[] A) {
        
        int len = A.length;
        int min=1;
        Arrays.sort(A);
   
        if(A[len-1]>0)
        for(int i=0; i<len; i++){
            if(A[i]>0){
                if(A[i]==min) min=min+1;
                if(A[i]>min) break;
            }
        }
        return min;
    }
}

In code, we have manully declared an array & then we are passing the array to findMissSmall() function that iterate through the arrray and return us the smallest missing number in the list.

Let’s understand how findMissSmall() function works

  1. get length of array.
  2. set min = 1.
  3. sort the array.
  4. Perform for-loop to get smallest missing num.

Let’s take the array for tracing with above program

arr = { 6, 2, 1, 5 }

after sorting arr = { 1, 2, 5, 6 }

In for loop

Iteration 1

i = 0, len = 4, min = 1, arr = { 1, 2, 5, 6 }

if( A[i] == min ) // 1 = 1 true, so increment min
min = min + 1; // min = 2


Iteration 2

i = 1, len = 4, min = 2, arr = { 1, 2, 5, 6 }

if( A[i] == min ) // 2 = 2 true, so increment min
min = min + 1; // min = 3


Iteration 3

i = 2, len = 4, min = 3, arr = { 1, 2, 5, 6 }

if( A[i] == min ) // 5 = 3 false, so don’t increment min
min = min + 1;

if( A[i] > min)
break; // 5 > 3 true,

In iteration 3, A[i] is not equal to min i.e 5 != 3, so dont increment min, then check if A[i] > min i.e 5 > 3 so break the for loop and come out.


Finally we have found smallest missing number in Array, return min = 3.

Note: Trace above program by your own Array, it will improve your programming logic & skill & code thinking.

How random number generator works – python random module example

0
python randoan number generator
python randoan number

Welcome to Proto Coders Point, We will lead you to the most readily  understandable solution for your question. Then let’s understand How Random Number Generation (RNG) works in computer.  

It is evident that the game of Tambola involves pure luck, just like when we do things like randomly picking an item, rolling the dice, or considering other activities without the use of computers. 

Would you consider computer generated randomness to be luck? Right, but how does it work? It’s an algorithm,yes , which generates the randomness.

Random number

Let’s explore further. 

  • How RNG works set an example.
  • Need for RNG.
  • It’s Applications in use.
  • Methods: Built-in functions & creating a function for it.
  • Approaches of these Methods.
  • Summarization  

Have you ever thought about why it is impossible to predict what number will be chosen while you play Tambola? Have you ever considered why such randomness is needed? No, probably we think we love to play with our luck right? It seems  exciting, doesn’t it? But what if I told you that there is a shocking truth behind  such randomness. 

Computers were driven by the need to generate random numbers since humans  were not very good at creating them for various security purposes, such as  passwords and cryptography. If I tell you to generate 100 random numbers  between 0-99, you won’t be able to come up with 100100, since you know it will  take a long time, and the probability of the numbers will also be difficult to  understand. The problem will be solved if I give you a set of instructions to do it. However, it will be time-consuming, even after I set an algorithm for you to  generate the numbers.

What algorithm does the computer use to generate such an algorithm 

For instance, you like someone and you search for their name on some social site, only to find duplicate profiles with exactly the same name and picture. Oh wait,  how will you find out who the real person is and tell him/her about the fake  accounts? It’s not like you’re going to ask everyone if that’s really her/him. However, you could go and ask the right person personally for their numerical ID for that site. That would work better than falling victim to fraud. 

In simulations, there are thousands of cases in which a little randomness can  make a difference, whether it’s weather patterns, traffic patterns, or shuffling  cards. Then let’s understand how Random Number Generation (RNG) works in  computer. 

In order to simulate randomness, we create deterministic sequences of numbers  that are thought to resemble what random numbers would look like, calling this  pseudo-RNG. They are calculated through a seed value of an algorithm, there are  several pseudo-RNG implementations based on linear congruential generators  based on recurrence relations (Xn + 1 ≡ aXn + c (mod m)

What is python RNG

Additionally, There is something called truly/real-RNG. You can use this security measure to protect transactions such as purchases, tax payments, bank transfers, etc. In order to ensure security and effectively manage fraud & privacy, encryption should be used, since it shouldn’t be vulnerable to hacking.  

Hence a need for entropy, a starting point that cannot be replicated: the first digit you use to create an ID for each transaction must be unique; anything that is replicable is vulnerable. As a solution, truly-RNG uses internal hardware to physically generate randomness, such as number of clock cycles in the processor or mouse movements. It can be used to solve any complicated or sophisticated  application. 

Different Method to generate Random number in Python

It’s time to create a Random number generator python module like that, and what better tool to use than Python 

The Python language works best with less code, use built-in functions, or build any method module you want for it.

Let’s explore the code for pseudo RNG by understanding the basics of random number generation. In simple terms, let’s build for all 8 built-in functions for  generating random numbers in Python. 

NOTE: (*import random python*) Before performing any operations on random generations.

python random module

FUNCTION PURPOSE SAMPLE
Random() Radom floating-point  number [0-1] is  generated, but excludes 0  & 1Randome.random()
Uniform(a,b) Floating-point value  between a & b is  generated. Takes two  parameters to start & to  stop then return float  between them including  the limitsRandom.uniform(3,9)
Randint(a,b) Including a & b generates  random integer from a to  b. Within specified limit like a<= <result> <=brandom.randint(1,5)
Randrange(start,stop,step) Random integer  generated in the  range(start,stop,step) Default value of step is 1Random.randrange(0,1,3)
Shuffle(a) Shuffles list a in place and  return Nonealist = [34,12,94,65,71] print(random.shuffle(alist))
Seed(a) Every time seed(a) is  called same sequence of  random numbers are  generatedRandom.seed(2) Print(random.randint(1,100)) #need same random seed add  Random.seed(2) Print(random.randint(1,100))
Sample(population, n)  Selects n vigilant random  items from a given  population set seq = (23,65,12,90,06) random.sample(seq,3)
Choice(s)  Random item from non empty sequence seq is  chosen. seq = (23,65,12,90,06) random.choice(seq)

Conclusion

Here’s a quick Recap: Our lesson covered what random number generation (RNG)  is, its purposes, its applications, and its uses, as well as the two methodologies  that are used for RNG. As a final step, we learned about Python’s built-in  functions for RNG, with sample code. Make sure you practice this in your python  interpreter. Isn’t RNG been fun? In addition to its value in number generation  methods, it is used widely in many areas, which is driving the development of  technology. It certainly bears in the role of Data Science statistics, irrespective of  whether it is video games, security protection, or encryption. Now it’s time to  build your own module with a purpose. Continue to explore.

How to read contacts list in flutter & display it in listview

0
Flutter Read Contacts List
Flutter Read Contacts List

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial will learn how to access contact list in flutter app.

So here, we will read phone contact list & display it in flutter list & we will also implement making a call when user tap on any contact.

Let’s get started

Strat by creating new flutter project or open existing project in you favorite IDE, I use Android Studio.

Flutter get contact list & make call

Plugin used – Add Dependencies

  1. flutter_contacts: To read contacts from android & iOS devices.
  2. url_launcher: To Make a call when user tap on phone number list.

As i said ,from getting contact list froom phone will user flutter_contacts & to make a phone call will use url_launcher, so add those 2 dependencies in pubspec.yaml file under dependencies sections.

dependencies:
  flutter_contacts:
  url_launcher:

Here i am not defining any version so it will auto take latest version, now hit pub git to download & install above plugin.


Platform specific setup

Android Setup’s

Make sure, flutter android module is enabled to support AndroidX, goto android/gradle.properties

check it or add as below

android.useAndroidX=true
android.enableJetifier=true

Check for compileSdkVersion is 28 or above

android/app/build.gradle file

android {
    compileSdkVersion 31
}

Add permission to access device contact list

Open manifest file, android/add/src/main/AndroidManifest.xml

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

To make a call, we must add DIAL action query in manifest file

<queries>
<!-- If your app makes calls -->
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
</queries>

iOS setup

For iPhone, you need to add NSContactsUsageDescription in info.plist file

ios/Runner/info.plist

<dict>
     ...
     <key>NSContactsUsageDescription</key>
     <string>Reason we need access to the contact list</string>
 </dict>

3. Import flutter_contacts & url_launcher

Now, In main.dart on top import the 2 required dependencies.

import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';

4. Code usage

Flutter plugin to read contacts, by using flutter contacts plugin we can read, create, update, delete contact from devices.

In this tutorial we ill only look into how to read contact in flutter & display in flutter app.

get all contact (lightly fetch)

List<Contact> contacts = await FlutterContacts.getContacts();

get all contacts (fully fetch)

 List<Contact> contacts = await FlutterContacts.getContacts(
      withProperties: true, withPhoto: true);

Get contact first name

contacts.name.first

Get contact last name

contacts.name.last

Get contact full name

contacts.displayname

Get contact email

contacts.emails.first.address

get contact photo

contacts.photo

Source Code – Flutter read contacts list & display it in listview builder

IN below code we are fetchiing all the contacts from contact list & display it in flutter listview builder and when user click or taps on particular phone number from list will make a phone call directly.

main.dart

import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

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

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

class _MyHomePageState extends State<MyHomePage> {
  List<Contact>? contacts;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getContact();
  }

  void getContact() async {
    if (await FlutterContacts.requestPermission()) {
      contacts = await FlutterContacts.getContacts(
          withProperties: true, withPhoto: true);
      print(contacts);
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text(
            "***  App Name  ***",
            style: TextStyle(color: Colors.blue),
          ),
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0,
        ),
        body: (contacts) == null
            ? Center(child: CircularProgressIndicator())
            : ListView.builder(
                itemCount: contacts!.length,
                itemBuilder: (BuildContext context, int index) {
                  Uint8List? image = contacts![index].photo;
                  String num = (contacts![index].phones.isNotEmpty) ? (contacts![index].phones.first.number) : "--";
                  return ListTile(
                      leading: (contacts![index].photo == null)
                          ? const CircleAvatar(child: Icon(Icons.person))
                          : CircleAvatar(backgroundImage: MemoryImage(image!)),
                      title: Text(
                          "${contacts![index].name.first} ${contacts![index].name.last}"),
                      subtitle: Text(num),
                      onTap: () {
                        if (contacts![index].phones.isNotEmpty) {
                          launch('tel: ${num}');
                        }
                      });
                },
              ));
  }
}

How to convert array to collection in javaScript

0
Convert Array to Object Collections
array to object

In JavaScript, Data can we stored in a form of object to store multiple values of complex data structure.

In JS, A Object can be created by {} curly braces, Here data are stored in key-value pair. Keys are always in String & value can be of any datatype.

JavaScript, Array & Object are the most frequently used to manage collection of data, it’s the easiest way to manage data while any event is been performed by users.

Convert array to collection(object) in JS

The best way to convert array to object in JavaScript

['a','b','c']

to

{
'0':'a',
'1':'b',
'2':'c'
}

1. JavaScript Example 1 – Convert array to object

const namesArr = ["Rajat","Proto", "Coders"];

function toObject(arr){
    var ob = {};

    for(var i =0;i<arr.length;i++){
        ob[i] = arr[i];
    }

    return ob;
}
var obj = toObject(namesArr);
console.log(obj);

Output

array to object

2. Array to Object using reduce method & functions

In today’s, JS we have a js method .reduce to iterate to array and remove empty holes from an array, so in below example will use array.reduce to convert array to object collections.

const namesArr = ["Rajat","Proto", "Coders"];

var obj = namesArr.reduce(function(result, item, i) {

    result[i] = item;
    return result;
  }, {});
  
  console.log(obj);

At start of function we pass empty object, then augment the object by increment, and at the end of iteration of function, we get result as { '0': 'Rajat', '1': 'Proto', '2': 'Coders' }.


Object to Array

3. Example 3 – Object to array JavaScript

To convery object to array in js, you can make use on Object.key and map to acheive it.

Let check how

var obj = { '0': 'Rajat','1':'Proto', '2': 'Coders', '3': 'Point' };

var result = Object.keys(obj).map((keys) => obj[keys]);

console.log(result);

Output

object to array javascript

How to change a favicon in flutter web app tab icon

0
flutter web app change favicon logo
flutter web app change favicon logo

Hi Guys, Welcome to Proto Coders Point. In this flutter tutorial article, we will learon the easiest way to change favicon icon in flutter web app.

What is favicon in website

A flutter favicon is a graphic Image or you can say it as a website logo icon that is assoiciated with a webiste. A favicon appears on a address bar i.e. in tabs of a browser when a website loads, it like a identity of a website.

flutter web app favicon

Video Tutorial

How to change favicon in flutter web app

To add favicon icon in flutter web app, follow below steps:-

1. Generate logo – favicon.ico

A logo that you want to show as favicon icon in flutter web app, you need to generate graphic image(icon) of different dimension size (eg: 192 X 192, 512 X 512).

We can make use of online free tools called favicon generator

https://favicon.io/

Drag & Drop your website logo over there, it will automatically generate icons with different dimension sizes. Look as below screenshot.

favicon generator icon

2. Paste generated icon in web folder of flutter project

Now, In flutter project /web folder copy paste the generated icon of size 192 x 192.

Then in /web/icons, paste all the above png images. For better understanding refer my project structure(highlighted)

3. Seting path of favicon in code

Now, in /web/index.html file, set path to new icon you added.

replace

<!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

To

<!-- Favicon -->
<link rel="apple-touch-icon" href="icons/apple-touch-icon.png">
<link rel="icon" type="image/png" href="logo.png"/>

4. Change manifest.json icon filename

Then in manifest.json, set the path to the newly added favicon image, refer screenshot below

Different between Visibility, Opacity & OffStage flutter show/hide widget

0
Difference between Visibility, Opacity,OffStage Widget
Difference between Visibility, Opacity,OffStage Widget

Hi Guys, Welcome to Proto Coders Point. In this article let learn about how to hide widget in flutter, i.e. using Visibility, Opacity, OffStage & difference between them & which is the best widget to hide content in flutter.

Flutter Visibility Widget

Visibility widget is to show/hide widgets, it has a visible property, which helps us in showing or hiding child, when visible is set to false, the actual child is replaced with zero- sized box instead.

Snippet

// manage visibility
              Visibility(
                 
                // showing the child widget
                visible: true, // true to show, false to hide
                child: Text(
                  "Visible/Hide Text Example",
                  
                ),
              ),

Properties

visible: bool (true or false)To hide or show the child widget
replacement: WidgetBy default,zero – sizedBox is shown, when visible is set to false, you can use any widget as replacement
maintainSize: boolSuppose you want a empty space when visible is false.
maintainInteractivity: boolUser can interact with widget, even when widget is invisible.

Flutter Opacity Widget

The opacity widget in flutter is used to make it’s child transparent, it can be done by using opacity property and set it 0, (range 0.0 - 1.0). The child is completely invisible when set to opacity 0, but will acquire the space & widget is also interactive.

Snippet

Opacity(
  opacity: _visible ? 1.0 : 0.0,
  child: const Text("Now you see me, now you don't!"),
)

Properties

child: WidgetA widget inside opacity
opacity: 0.0 to 1.0Transparent level to apply to child widget
alwaysIncludeSemantic: boolSemantic info about child is always included.

Flutter OffStage Widget

OffStage in flutter widget lays it child out, as if it in true but don’t draw/render the child widget view on screen, and all don’t take space of screen.

most of the time offstage is used to measure the dimension of widget without showing it on screen.

flutter offstage example

The below example, we have a offstage widget which has child as FlutterLogo widget, when offstage is true, the offstage will be hidden so when offstage is hidden i.e. true, we will display a button to get logo size, which will show size of FlutterLogo widget in snackbar.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: _title,
      home: Scaffold(
        appBar: AppBar(title: const Text(_title)),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );
  }
}

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

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  final GlobalKey _key = GlobalKey();
  bool _offstage = true;

  Size _getFlutterLogoSize() {
    final RenderBox renderLogo =
        _key.currentContext!.findRenderObject()! as RenderBox;
    return renderLogo.size;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Offstage(
          offstage: _offstage,
          child: FlutterLogo(
            key: _key,
            size: 150.0,
          ),
        ),
        Text('Flutter logo is offstage: $_offstage'),
        ElevatedButton(
          child: const Text('Toggle Offstage Value'),
          onPressed: () {
            setState(() {
              _offstage = !_offstage;
            });
          },
        ),
        if (_offstage)
          ElevatedButton(
              child: const Text('Get Flutter Logo size'),
              onPressed: () {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content:
                        Text('Flutter Logo size is ${_getFlutterLogoSize()}'),
                  ),
                );
              }),
      ],
    );
  }
}

Different between Visibility, Opacity, OffStage Widget

Which is the best flutter widget to hide content.

Opacity

Alpha opacity is set to any widget you want, setting it to 0.0 is like invisible then setting to 0.1 is lightly visible and increase the visibility when range set between 0.0 to 1.0, so i hope it easy to understand. Even after setting the opacity to 0.0 and making it invisible the widget will still occupy the space it require, because we have not actually removed the widget instead we just make is transparent, therefore user can touch and click it.

Offstage

The child widget is hidden with this one. It’s as if you put the widget “outside of the screen” so that users don’t notice it. The widget continues to progress through the flutter pipeline until it reaches the final “painting” stage, at which point it accomplishes nothing. This means that all state and animations will be preserved, but nothing will be rendered on the screen. It also won’t take up any space during layout, so there won’t be any gaps, and users won’t be able to click it.

Visibility

Visibility widget in flutter, is very user friendly and convenience, as we have discussed above when visible is set to false, the widget is completely removed and replaced with zero sizedBox, suppose if you want to keep the empty space, then make use of visibility properties like  maintainAnimation maintainSize, maintainStatemaintainInteractivity etc.

when you use maintain state, it will wrap the child with Opacity or Offstage widget. When visible is false (i.e widget is hidden) but you have maintain size, so the empty space visible is wrapped with IgnorePointer so that user can’t click on it, unless you make use of maintainInteractivity : true

Removing Widget

For example, you can use if (condition) to determine whether or not a widget should be included in a list, or you can use condition? child: SizedBox() to directly replace it with a SizedBox. This method avoids unnecessary calculations and is the most efficient.