Home Blog Page 4

# Check if Array is dominant Array

0

## Most asked interview question – Check if the array is a dominant array or not Problem Statement

You are given an array A of length N . An element X is said to be dominant if the frequency of X in A is strictly greater than the frequency of any other element in the A .
For example, if A=[2,1,4,4,4] then 4 is a dominant element since its frequency is higher than the frequency of any other element in A .
Find if there exists any dominant element in A.

Input Format
The first line of input contains a single integer T — the number of test cases.
Then the test cases follow.
The first line of each test case contains an integer N — the size of the array A .
The second line of each test case contains N space-separated integers denoting the array A.

Output Format
For each test case, output YES if there exists any dominant element in A . Otherwise, output NO.
You may print each character of YES and NO in uppercase or lowercase (for example, yes, yEs, Yes will be considered identical).

Constraints Sample 1:
1 ≤ T ≤ 500
1 ≤ N ≤ 1000
1 ≤ A[i] ≤ N

Sample 1:

Input
4
5
2 2 2 2 2
4
1 2 3 4
4
3 3 2 1
6
1 1 2 2 3 4

Output
YES
NO
YES
N

## Source Code – Below source code is using JavaScript Language

```function isDominantElementPresent(arr) {

var count = {};
arr.forEach(ele=>{
if(count[ele]){
count[ele] +=1;

}else{
count[ele] = 1;
}
});

var maxFrequency = 0;
for (var ele in count) {
maxFrequency = Math.max(maxFrequency, count[ele]);
}
var isDominant = Object.values(count).filter(freq => freq === maxFrequency).length === 1;

return isDominant;
}

function main() {
const t = parseInt(prompt("Enter the number of test cases:"));

for (let i = 0; i < t; i++) {
const n = parseInt(prompt("Enter the size of the array:"));
const arr = prompt("Enter the array elements separated by space:")
.split(" ");

if (isDominantElementPresent(arr)) {
console.log("YES");
} else {
console.log("NO");
}
}
}

main();```

# Flutter FVM – Multiple SDK versions Management

0

Hi Guy’s Welcome to Proto Coders Point. In this Article let’s learn about FVM and how to use multiple flutter sdk on same system/PC/laptop.

## What is FVM?

FVM stands for Flutter Version Management a tools that allows you to work with multiple flutter SDK versions on the particular flutter project. Useful when there is frequent switch between flutter channels, When you use normal flutter sdk channel switches are slow and need time to repeatedly reinstall and set sdk globally but by using FVM it’s easy to install and switch between channels & flutter versions easily and in quick time..

## How to install FVM?

### Installing FVM in Windows

Open command prompt and run below installation cmd to install fvm globally

`dart pub global activate fvm`

### Installing FVM in MacOS

Run below command to install fvm in macOS

```brew tap leoafarias/fvm
brew install fvm```

### Install FVM in Linux/Ubuntu

```brew tap leoafarias/fvm
brew install fvm```

## Set Environment Variable System Path

Open Environment Variable > System Variable > Path > New, Then copy below path.

`C:\Users\Asus\AppData\Local\Pub\Cache\bin`

Once done, Close the running terminal, then restart it and run `fvm` to check if fvm path is successfully set.

Once the fvm installation is completed and environment is set, then we need to install desired version of flutter sdk using FVM cmd. follow below step.

## How to install multiple flutter sdk & use it for flutter project

First we need to get all the released version of flutter sdk available to be installed, then apply it on a particular flutter project and use it.

### Get list of all released version of flutter sdk

`fvm releases`

### Install Multiple Flutter SDK using fvm

Now, once you have the list of flutter sdk version, you can install any number of flutter sdk version using the version number you desired to install.

To Install fvm flutter sdk version use below cmd:

`fvm install <version>`

Example let’s say I want to install latest flutter sdk version 3.19.2, then i need to run cmd `fvm install 3.19.2`.

### Get List of all Install fvm flutter sdk that we can used in switching between flutter version and channel

To get list of all flutter sdk installed using fvm run below cmd:

`fvm list`

### Config/Apply a desired flutter SDK to a project

now Finally after installing fvm flutter sdk to use it or to apply specific version of flutter sdk toa flutter project you can use below code

`fvm use <version>`

Example: I have install flutter sdk version 3.10.2 and I want to apply this sdk version to one of my flutter project, then simple in root folder of your flutter project run `fvm use 3.10.2`.

once fvm use cmd is done, In your flutter project .`fvm` folder will automatically get created which will have few files defining which version of flutter sdk which it should you use for this flutter project.

# Array Manipulation and Array Methods in TypeScript

0

Hi Guy’s Welcome to Proto Codes Point, In this TypeScript Tutorial let’s check out Array Manipulation & Methods in TypeScript.

## What is Array Manipulation?

In TypeScript Array Manipulation is a technique of performing various operations on arrays to add, remove or update elements of Arrays. This Allows you to change the contents within the array dynamically as required.

## Benefits of Array Manipulation

• Allows for dynamic modification of array contents based on changing requirements.
• Provides flexibility in managing data structures & performing operations efficiently.
• Enables Implementation of various algorithms & solving real-world problems effectively.

## Array Methods in TypeScript

• push()
• pop()
• shift()
• unshift()
• splice()
• concat()
• slice()
• indexOf()
• includes()
• forEach()
• join()
• reverse()
• filter()
• map()
• find()
• findIndex()
• every()
• some()
• sort()

### Method Explanation

push(): Adds one or more elements to the end of an array. Real-life example: Adding items to a shopping cart.

```let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.push("Orange", "Grape");```

pop(): Removes the last element from an array. Real-life example: Removing the last item from a stack.

```let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.pop(); //removes last element i.e.Apple.```

shift(): Removes the first element from an array. Real-Life example: Taking the first book from a bookshelf.

```let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
let firstItem = shoppingCart.shift(); // Watermelon```

unshift(): Adds one or more elements to the beginning of an array. Real-life example: Adding a new books in bookshelf at the starting of the list.

```let shoppingCart: string[] = [ "Watermelon" ,"Apple"];
shoppingCart.unshift("Grape" , "Orange"); // "Grape", "Orange", "Watermelon" ,"Apple" ```

splice(): Adds or removes elements from an array at a specific position. Real-life example: Modifying ingredients in a recipe.

```Real-life exalet shoppingCart: string[] = [ "flour" ,"sugar"];
shoppingCart.splice(1, 1, "Butter"); // Remove "sugar" and add "Butter".```

concat(): Combines two or more arrays and returns a new array.

```let fruitGroup1: string[] = [ "Watermelon" ,"Apple"];
let fruitGroup2: string[] = [ "Grape" ,"Orange"];
let AllFruits: string[] = fruitGroup1.concat(fruitGroup2); // "Grape", "Orange", "Watermelon" ,"Apple" ```

slice(): can be used to selecting a range index from and to from the array and return a new array.

```let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let selectedBooks: string[] = fruits.slice(1,3); ["Orange", "Watermelon"] ```

Select fruits from index 1 to 2 i.e. [“Orange”, “Watermelon”]

indexOf(): This will return the first index at which the given element is found & in case if element is not found the the array we get -1 as responce.

```let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let firstPosition: number = fruits.indexOf("Orange"); 1
let firstPosition: number = fruits.indexOf("banana"); // -1, because the element is not the the array list
```

includes(): check if the element exist in the array or no, return boolean value true or false.

```let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];
let isExist: number = fruits.includes("Orange"); true
let isExist: number = fruits.includes("banana"); false```

forEach(): Iterate to each element in the given array.

```let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];

fruits.forEach(ele=> console.log(ele));```

join(): convert all element into a long string, optionally can add symbols like commas(,) to separate them.

```let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];

let joinedFruits: string[] = fruits.join(","); // "Grape, Orange, Watermelon, Apple"```

reverse(): Reverses the order of the element in an array.

```let fruits: string[] = ["Grape", "Orange", "Watermelon" ,"Apple"];

fruits.reverse(); //[ "Apple",  "Watermelon" , "Orange", "Grape" ]```

filter(): This is used to filter element with a specific condition, if the condition pass the test a new fresh array will be return as per filter login.

```// Define an array of numbers
const numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

// Use the filter method to get even numbers
const evenNumbers: number[] = numbers.filter(num => num % 2 === 0);

console.log("Original array:", numbers); [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log("Even numbers:", evenNumbers); [2, 4, 6, 8, 10] ```

map(): The `map` method in TypeScript is used to iterate each element of an given array & create a new array as per required condition or login. Here’s an example: Below I am just iterating array using map and getting uppercase array in return.

```// Define an array of strings
const fruits: string[] = ["apple", "banana", "orange", "grape", "kiwi"];

// Use the map method to create a new array of uppercase fruits
const uppercaseFruits: string[] = fruits.map(fruit => fruit.toUpperCase());

console.log("Uppercase fruits:", uppercaseFruits); ["APPLE", "BANANA", "ORANGE", "GRAPE", "KIWI"]```

find(): This is similar to indexOf but not same, Here in `find` method of TypeScript is used to retrieve the first element in an array that satisfies a given condition. Here’s an example:

```// Define an array of objects representing persons
interface Person {
name: string;
age: number;
}

const people: Person[] = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 },
{ name: "David", age: 35 },
];

// Use the find method to get the first person older than 30
const olderThan30: Person | undefined = people.find(person => person.age > 30);

console.log("People array:", people);
console.log("First person older than 30:", olderThan30);
```

findIndex(): The `findIndex` method in TypeScript is similar to `find`, but instead of returning the element itself, it returns the index of the first element in an array that satisfies a given condition.

```// Define an array of objects representing persons
interface Person {
name: string;
age: number;
}

const people: Person[] = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 },
{ name: "David", age: 35 },
];

// Use the find method to get the first person index value older than 30:
const olderThan30: Person | undefined = people.find(person => person.age > 30);

console.log("People array:", people);
console.log("First person older than 30 it index is :", olderThan30); // 3 ```

every(): The `every` method in TypeScript is used to check if all elements in an array satisfy a given condition. It returns a boolean value. Here’s an example:

```// Define an array of numbers
const numbers: number[] = [2, 4, 6, 8, 10];

// Use the every method to check if all numbers are even
const allEven: boolean = numbers.every(num => num % 2 === 0);

console.log("Numbers array:", numbers);
console.log("Are all numbers even?", allEven);
```

some(): The `some` method in TypeScript is used to check if at least one element in an array satisfies a given condition. It returns a boolean value. Here’s an example:

```// Define an array of numbers
const numbers: number[] = [1, 3, 5, 7, 9, 10];

// Use the some method to check if at least one number is even
const hasEvenNumber: boolean = numbers.some(num => num % 2 === 0);

console.log("Numbers array:", numbers);
console.log("Does the array contain at least one even number?", hasEvenNumber);
```

sort(): The `sort` method in TypeScript is used to sort the elements of an array. By default, it sorts the elements as strings, but you can provide a custom comparison function to define the sorting order. Here’s an example:

```// Define an array of strings
const fruits: string[] = ["banana", "apple", "orange", "kiwi", "grape"];

// Use the sort method to sort the array alphabetically
const sortedFruitsAlphabetical: string[] = fruits.slice().sort();

console.log("Original array:", fruits);
console.log("Sorted array (alphabetical):", sortedFruitsAlphabetical);

// Use the sort method with a custom comparison function to sort by length
const sortedFruitsByLength: string[] = fruits.slice().sort((a, b) => a.length - b.length);

console.log("Sorted array (by length):", sortedFruitsByLength);
```

In the first part of the example, the `sort` method is used without any arguments to sort the `fruits` array alphabetically. Keep in mind that `sort` modifies the original array, so it’s a good practice to create a copy using `slice()` before sorting.

In the second part, a custom comparison function is provided to the `sort` method, sorting the array based on the length of the strings. The comparison function takes two elements, `a` and `b`, and returns a negative value if `a` should come before `b`, a positive value if `a` should come after `b`, or zero if they are equal.

### Conclusion

Array manipulation involves performing operations like adding, removing or modifying elements within the arrays. Understanding array manipulation is very much essential for building applications that involving playing with data or processing the list of datas.

# Solution: Unknown flutter tag | How to Upgrade Flutter SDK

0

Hi Guy’s Today when I was trying to upgrade my flutter sdk to latest version i.e. 3.19 I was facing an error/warning been showing “Unknown flutter tag. Abandoning upgrade to avoid destroying local changes. it is recommended to use git directly if not working on an official channel.

To fix this all you need to do is you need to run “flutter upgrade” command in the flutter sdk folder itself from the command prompt and also make sure to run the command prompt as administrator.

Video Tutorial

# Alphabets Spinning A – Z & Picking Random Letter with Javascript

0

Hey, everyone! In this Tutorial, we’ll explore HTML with Javascript, demonstrating an alphabet spin from A to Z Similar to Instagram’s video effect/filter where an alphabet spins from A to Z on top of the head, we’ll also pick a random letter from A to Z and display it.

In the World of Web Development JavaScript plays an top important role in giving or adding interactive dynamic features like animation to web apps. On fascinating Example is here to Spin the Alphabets from A-Z and generate a random alphabet from it and display it.

Video Tutorial

Source Code

html

```<!DOCTYPE html>
<html>
<title>Hello World!</title>
<body>
<h1 class="title">Hello World! </h1>
<div id="alpha">A</div>
<script src="script.js"></script>
</body>
</html>```

Here In HTML Code I have added a div container with id as “alpha” so that i can control div tag from javascript code.

Javascript

```var alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

var i = 0;
var loopNo = 0;

function update() {
document.getElementById('alpha').innerHTML = alphabets[i];

i++;
if(i == alphabets.length){
i = 0;
loopNo++;
}
if(loopNo == 1){
var randomIndex = Math.floor(Math.random() * alphabets.length);
var randomAlphabets = alphabets[randomIndex];
console.log(randomIndex);
clearInterval(intervalId);
document.getElementById('alpha').innerHTML = randomAlphabets;
}
}

var intervalId = setInterval(update, 100);
```

Now, let’s check out the javascript code to interact with HTML. The <div> tag/element by using its id ‘alpha’ where the alphabets will be dynamically displayed rapidly A-Z in a loop wise.

Code Walkthrough:

1. Alphabets Array: The script initializes a string `alphabets` containing all uppercase English letters.
2. Variables Initialization: Two variables, `i` and `loopNo`, are initialized to keep track of the current alphabet index and the number of loops.
3. Update Function: The `update()` function is responsible for updating the content of an HTML element with the id ‘alpha’ with the current alphabet.
4. Loop Control: The function increments the index `i` and resets it to 0 when it reaches the length of the alphabet string, simulating a continuous loop.
5. Random Alphabet Generation: After the first loop (`loopNo == 1`), the code selects a random index from the alphabet string and displays the corresponding letter. The `setInterval` is then cleared, stopping the continuous update.

## Conclusion:

In conclusion, This JavaScript code help you in understanding basic of JS like how to make use of setInterval() to call a function repeatedly and perform an event like dynamically changing HTML div tag TextContent and also how to stop the setInterval() using clearInterval(). Such scripts can be used for educational purposes, creating interactive quizzes, or simply for adding a playful touch to a website.

# Tips to Boosting Flutter App Performance

0

Hi Guy’s Welcome to Proto Coders Point. To making your flutter app smooth and better in performance you need to follow some keys points using which you can enhance the performance of your flutter apps.

## 1. State Management

Making use of State Management in flutter is essential for creating a smooth responsive flutter application.

Ya, Flutter provides it’s default state management ie. setState(). but it has a disadvantage that is it reload full app widget tree just to update few things.

Flutter Developer has to make use of better and optimized State Management Solution to make flutter app perform better.

I recommend to make use of `Provider package` which offers streamlined state management in flutter.

Example:

To-Do Note App using Flutter Provider

## 2. Widget Tree Optimization using const

Make use of const constructor on widget where data is not getting updated due to user action.

The const widget make sure that the widget tree & it’s sub child tree will not rebuilt, and prevent unnecessary reload of widget.

By using const keyword in flutter, The widget is instantiated only once during the first build itself.

This will reduce unnecessary load widget or reconstruction and rendering of widget.

```class MyTextWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: const Text(
'Hello, World!',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
),
);
}
}```

Lazy loading & pagination in flutter improve app performance as it reducing memory usage & can speed up the rendering process.

Example:

ListView.builder widget is particularly useful for implementing lazy loading & pagination in flutter app as it has properties like how much data should be loaded i.e. The itemCount parameter using which we can specify total number of items should be shown in the listview.

Code:

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

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'ListView.builder Example',
home: Scaffold(
appBar: AppBar(
title: Text('ListView.builder Example'),
),
body: ListView.builder(
itemCount: 20, // Number of items in the list
itemBuilder: (BuildContext context, int index) {
// itemBuilder builds each item in the list
return ListTile(
title: Text('Item \$index'),
subtitle: Text('Subtitle \$index'),
child: Text('\$index'),
),
onTap: () {
// Action when an item is tapped
print('Tapped on Item \$index');
},
);
},
),
),
);
}
}
```

## 4. Image Compressing & resizing

If you have flutter app where you display images to the user’s then implementing image compression will rapidly improve performance of the app.

The flutter_image_compress library provides a convenient solution for achieving this task.

```var result = await FlutterImageCompress.compressAndGetFile(
_imageFile!.path,
_imageFile!.path, // Destination path (overwrite the original image)
quality: 50, // Image quality (0 - 100)
);```

Complete Code Example

```import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Image Compression Example',
home: ImageCompressionScreen(),
);
}
}

class ImageCompressionScreen extends StatefulWidget {
@override
_ImageCompressionScreenState createState() => _ImageCompressionScreenState();
}

class _ImageCompressionScreenState extends State<ImageCompressionScreen> {
File? _imageFile;
late File _compressedImageFile;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image Compression Example'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
_imageFile != null
? Image.file(
_imageFile!,
height: 200,
)
: Text('No Image Selected'),
ElevatedButton(
onPressed: () {
_pickImage();
},
child: Text('Select Image'),
),
ElevatedButton(
onPressed: () {
if (_imageFile != null) {
_compressImage();
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Please select an image first.'),
),
);
}
},
child: Text('Compress Image'),
),
],
),
),
);
}

Future<void> _pickImage() async {
// Code to pick an image from the device's gallery
// (You can use any method you prefer to pick an image)
// For example:
// var imagePicker = ImagePicker();
// var pickedFile = await imagePicker.getImage(source: ImageSource.gallery);
// setState(() {
//   _imageFile = File(pickedFile.path);
// });

// For this example, I'm just using a placeholder file path
setState(() {
_imageFile = File('/path/to/your/image.jpg');
});
}

Future<void> _compressImage() async {
// Compress the image
var result = await FlutterImageCompress.compressAndGetFile(
_imageFile!.path,
_imageFile!.path, // Destination path (overwrite the original image)
quality: 50, // Image quality (0 - 100)
);

// Update the UI with the compressed image
setState(() {
_compressedImageFile = result!;
});

// Show a message indicating success
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Image compressed successfully.'),
),
);
}
}
```

## 5. Using flutter devTools for performance profiling

To leverage flutter DevTools more effectively, always run your flutter app in profile mode.

How to run flutter app in profile mode, use below command:

`flutter run --profile`

By running your flutter app in profile mode it gives power to flutter developer that allows app developer to collect detailed app performance data during runTime, Using this data, developer can identify performance bottlenecks, understand resource usage & help developer to optimize their apps accordingly.

## 6. Implementing network caching in flutter

Utilizing caching header will improve performance & reduce unnecessary network traffic. let’s take an example of of using `http` package to handle network request like fetching data.

In the provided code snippet, the `'fetchData' `function demonstrates the usage of the ‘http’ package to perform a GET request to a specified API. The request includes a ‘Cache-Control’ header with a directive of ‘max-age=3600’, indicating a caching duration of 3600 seconds (1 hour).

```Future<void> _fetchData() async {
final url = 'https://api.example.com/data';
final response = await http.get(
Uri.parse(url),
headers: {'Cache-Control': 'max-age=3600'}, // Caching directive
);

if (response.statusCode == 200) {
// If the server returns a successful response, parse the JSON
final responseData = json.decode(response.body);
setState(() {
_data = responseData['data'];
});
} else {
// If the server did not return a successful response, throw an error