Thursday, August 24, 2023

Generating Subsequences

 #include <iostream>

#include <vector>

#include <bits/stdc++.h>


using namespace std;

void print(vector<vector<int>> subsequences)

{   int j = 0;

    for (vector<int> subsequence : subsequences) {

        cout << " subsequence_index " << j++ << endl;

        for (int i : subsequence) {

            cout << i << " ";

        }

        cout << endl;

    }

}


void generate_subsequences(vector<int> sequence, vector<int> b) {

    /*

     * Generates all subsequences of the given sequence.

     *

     * Args:

     *   sequence: The sequence to generate subsequences from.

     *

     * Returns:

     *   A vector of all subsequences of the given sequence.

     */


    int n = sequence.size();

    vector<vector<int>> subsequences;

    subsequences.push_back({});


    for (int i = 0; i < n; i++) {

        int current_size = subsequences.size();

        for (int j = 0; j < current_size; j++) {

            vector<int> new_subsequence = subsequences[j];

            new_subsequence.push_back(sequence[i]);

            subsequences.push_back(new_subsequence);

        }


    }


    //check

    for (vector<int> i : subsequences)

    {

        //compare

        if (i == b)

        {

            cout << "YES" << endl;

            return;

        }

    }


    cout << "NO" << endl;

    return;


    //return subsequences;

}



void solve() {

    int n, m;


    cin >> n >> m;


    vector<int> a(n);

    vector<int> b(m);


    for (int i = 0; i < n; i++)

    {

        cin >> a[i];

    }

    for (int i = 0; i < m; i++)

    {

        cin >> b[i];

    }


    //int size = pow(2, n);

    //vector<vector<int>> c(size);

    //generate_subsequences(a, b);


    int counter = 0;

    int bCounter = 0;

    for (int i = 0; i < n; i++)

    {

        if (counter == m)

        {

            cout << "YES" << endl;

            return;

        }

        if (a[i] == b[bCounter])

        {

            counter++;

            bCounter++;

        }

    }


    if (counter == m)

    {

        cout << "YES" << endl;

        return;

    }

    else {

        cout << "NO" << endl;

        return;

    }



}



int main() {

    //int tc;


    //cin >> tc;


    //while (tc--)

    //{

    solve();

    //}


    return 0;

}


Saturday, June 3, 2023

Vector in C++

 To declare vector in C++, need to include


#include <vector>

using namespace std;

//Declare  an empty vector of integers

vector<int> myVector;

//Declare a vector of strings and initialize it with values

vector<string> myStringVector = {"apple","banana","orange"};

//Declare a vector with specific initialize size

vector<double> myDoubleVector(10);                       

===========================================================

Operations


Adding Elements to a Vector

1) push_back()

This function adds an element to the end of the vector.

eg

    v.push_back("orange");

    v.insert(v.begin() + 2, "peach");

=========



2)Accessing Elements []

#include <iostream>

#include <vector>


using namespace std;


int main() {

  vector<int> v = {1, 2, 3, 4, 5};


  // Use at() to access the element at index 2.

  int element = v.at(2);

  cout << element << endl;


  // Use [] to access the element at index 3.

  element = v[3];

  cout << element << endl;


  // Try to access the element at index 6.

  // This will throw an out_of_range exception.

  try {

    element = v.at(6);

  } catch (out_of_range& e) {

    cout << "Index out of range: " << e.what() << endl;

  }


  return 0;

}


3)  Removing Elements

a) pop_back()

//Removes the last element from the vector


myVector.pop_back();  // Removes the last element from the vector

b) erase()
//Removes an element at a specific position or a range of elements

myVector.erase(myVector.begin() + 1);
myVector.erase(myVector.begin() + 2, myVector.begin() + 4); //Removes index from 2 to 4; (exclusive)


4) Getting information about the vector

a) size()
//Retrieves the number of elements in the vector.
b)empty()
//This function checks if the vector in empty.

===================================================================

Other General Info

1) Iterating over a vector

a) for loop
for(size_t i = 0; i < myVector.size(); ++i)
{
    // Access and process each element using myVector[i];
}

b) Using a range based `for` loop

for (const auto& element : myVector) {

    // Access and process each element using 'element'

}

2) Clearing the vector:

          myVector.clear();  // Removes all elements from the vector

3) Sorting 

sort(myVector.begin(), myVector.end());  // Sorts the vector in ascending order

4)Find elements

auto it = std::find(myVector.begin(), myVector.end(), targetValue);  // Searches for 'targetValue'
if (it != myVector.end()) {
    // Element found
}


5)Using vector as function parameters:
  • Pass by reference: When passing a vector to a function, you can pass it by reference to avoid making a copy of the entire vector.

void myFunction(const std::vector<int>& vec) {
    // Access and process the vector elements
}

Initializing vector with a range of values:

  • Using the constructor with iterators: You can initialize a vector with values from another container or a range of elements.
    cpp
    std::vector<int> anotherVector(myVector.begin(), myVector.begin() + 5);  

std::vector<int> myVector(5, 42);  // Resizes the vector to have 5 elements, each initialized to 42

orting a vector with a custom comparison function or lambda expression:

cpp
std::sort(myVector.begin(), myVector.end(), [](const auto& a, const auto& b) { return a > b; // Custom sorting logic (descending order) });
std::reverse(myVector.begin(), myVector.end()); /


Using vector as a multidimensional array:

  • You can create a vector of vectors to represent a 2D array.
    cpp
    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0)); 

Thursday, May 18, 2023

Competive Programming ||

 #include <iostream>

#include "bits/stdc++.h"

using namespace std;


typedef unsigned long long ull;


int main()

{

ull n,k,q;

cin >> n >> k >> q;

vector<ull> temp(200001, 0);

vector<ull> bt(200001, 0);


for (int i = 0; i < n-1; ++i)

{

ull x,y;

cin >> x >> y;

temp[x]++;

temp[y+1]--;

}


ull sum = 0;

for(int i =0; i < 200001; i++)

{

sum += temp[i];

bt[i] = sum;

if(bt[i] >= k){

bt[i] = 1;

}

else

{

bt[i] = 0;

}

}


// final loop

for(int i = 1; i < 200001; i++)

{

bt[i] += bt[i- 1];

}


while(q--)

{

ull x,y;

cin >> x >> y;

ull ans = bt[y];

if(x - 1 >= 0){

ans -= bt[x - 1];

}

cout << ans << endl;

}


    return 0;

}


Tuesday, May 9, 2023

Competitive Programming

  • Build system in Sublime

    { "cmd": ["g++.exe", "-std=c++14", "${file}", "-o", "${file_base_name}.exe", "", "${file_base_name}.exeoutputf.in"], "shell": true, "working_dir": "${file_path}", "selector": "source.cpp", "variants": [ { "name": "Run", "cmd": ["cmd", "/C", "echo '${file_base_name}, it's build success :)'"], "shell": true, "working_dir": "${file_path}" } ] }
  • Multidimensional Array { int R, C;
    cin >> R >> C;
    // Input matrix A int A[100][100];
    for (int i = 0; i < R; i++) {
    for (int j = 0; j < C; j++) {
    cin >> A[i][j];
    } }
    // Input matrix B int B[100][100];
    for (int i = 0; i < R; i++) {
    for (int j = 0; j < C; j++) {
    cin >> B[i][j];
    } } // Call the function to add matrices A and B addMatrices(A, B, R, C, 0, 0);
    // Print the resulting matrix for (int i = 0; i < R; i++) {
    for (int j = 0; j < C; j++) {
    cout << A[i][j] << " ";
    } cout << endl;
    } return 0;


  • 1D Array


    #include
    using namespace std;
    const int MAX_SIZE = 100;
    int main() {
    int n;
    int arr[MAX_SIZE];
    cout << "Enter the size of the array (up to " << MAX_SIZE << "): ";
    cin >> n;
    cout << "Enter " << n << " integers: ";
    for (int i = 0; i < n; i++) {
    cin >> arr[i];
    } cout << "The array contains: ";
    for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
    } cout << endl;
    return 0;
    }

Thursday, January 19, 2023

Promise and asynchronous Javascript

You can use the Promise object to return a setTimeout and resolve inside it. Here's an example:


Copy code

function waitAndResolve(ms) {

  return new Promise((resolve) => {

    setTimeout(() => {

      resolve();

    }, ms);

  });

}

You can then use the waitAndResolve function like this:


Copy code

waitAndResolve(2000).then(() => {

  console.log("2000 milliseconds have passed!");

});

This will wait for 2000 milliseconds and then resolve the promise, which will cause the message "2000 milliseconds have passed!" to be logged to the console.





Pessimist Kai

Hi

Hello! How can I help you today?





Pessimist Kai

currently my function is like this


"f1(){

f2();

f3();

}"

If you want to make sure that f2() and f3() are called in a specific order, you can make use of JavaScript's async/await feature. Here's an example:


Copy code

async function f1() {

  await f2();




Pessimist Kai

I want to run some logic when f2() and f3() are completed

You can use the .then() method on the returned promise of f2() and f3() or use the await keyword with the function call inside an async function to run some logic after f2() and f3() are completed.


Copy code

async function f1() {

  await f2();

  await f3();

  console.log("Both f2 and f3 are completed");

}

or


Copy code

function f1() {

  f2().then(f3).then(()=>{

    console.log("Both f2 and f3 are completed");

  })

}

In this example, the message "Both f2 and f3 are completed" will be logged to the console after both f2() and f3() have completed their execution.





Pessimist Kai

but I don't want f3() to run after f2(), can't they run parallely?

Yes, you can run f2() and f3() in parallel by using Promise.all() method.


Copy code

function f1() {

  Promise.all([f2(), f3()]).then(()=>{

    console.log("Both f2 and f3 are completed");

  });

}

The Promise.all() method takes an array of promises as an argument and returns a new promise that is fulfilled with an array of the fulfilled values of the original promises, in the same order as the original promises, if all of the original promises are fulfilled.


This way, f2() and f3() will run in parallel and the code inside the .then() callback will be executed after both of them are completed.





Pessimist Kai

but f2() and f3() don't return promise they just do some work and api call

If f2() and f3() are not returning promises, you can wrap them in a new promise, so you can use them with Promise.all() and async/await .


Copy code

function f1() {

  Promise.all([

    new Promise(resolve => f2().then(resolve)),

    new Promise(resolve => f3().then(resolve))

  ]).then(() => {

    console.log("Both f2 and f3 are completed");

  });

}

or


Copy code

async function f1() {

  await Promise.all([

    new Promise(resolve => f2().then(resolve)),

    new Promise(resolve => f3().then(resolve))

  ]);

  console.log("Both f2 and f3 are completed");

}

This way, f2() and f3() will run in parallel and the code inside the .then() callback or the line after await will be executed after both of them are completed.


Alternatively, you can make f2() and f3() return a promise, so you can use them directly with Promise.all() and async/await.





Pessimist Kai

new Promise(resolve => f2().then(resolve)) and

new Promise(resolve => f2(resolve)); same?

How?

new Promise(resolve => f2().then(resolve)) and new Promise(resolve => f2(resolve)) are not the same.


The first one is creating a new promise and passing a resolve function to it, then calling f2() and chaining a .then() method on it, passing the resolve function as a callback. This means that the new promise will be resolved with the value returned by f2().


The second one is creating a new promise and passing the resolve function directly to f2(). This means that f2() is responsible for resolving the promise, and it's unclear when or if it will be resolved.


Here's an example of how to use the second approach to make f2() return a promise:


Copy code

function f2(resolve) {

  // Do some work and api call

  // ...

  // Once the work is done, call resolve

  resolve();

}

and then you can use it like:


Copy code

const f2Promise = new Promise(resolve => f2(resolve));

In summary, the first approach returns a promise that is resolved with the value returned by f2() and the second approach requires f2() to resolve the promise.





Pessimist Kai

remind me how promise works again, please

A promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation, and its resulting value. Promises provide a way to register callbacks to be called when the asynchronous operation completes (or fails) and to handle errors.


Promises have three states:


pending: initial state, neither fulfilled nor rejected.

fulfilled: meaning that the operation completed successfully.

rejected: meaning that the operation failed.

A promise is said to be settled if it is either fulfilled or rejected.


Promises are used for handling asynchronous operations in JavaScript, such as making HTTP requests, reading from a file, waiting for a timer to complete, etc. The main advantage of promises over traditional callback-based code is that they make it easier to handle errors and to compose multiple asynchronous operations.


A promise can be created using the Promise constructor, which takes a single argument: a function called the "executor". The executor function is passed two arguments: a resolve function, which is used to resolve the promise with a value, and a reject function, which is used to reject the promise with a reason (an error).


Once a promise is resolved or rejected, it can't change its state anymore.


Copy code

const promise = new Promise((resolve, reject) => {

  // Do some asynchronous operation

  if (/* the operation was successful */) {

    resolve(/* some value */);

  } else {

    reject(/* some reason */);

  }

});

Promises also have methods, such as .then(), .catch(), .finally() and Promise.all(), Promise.race() etc, which can be used to register callbacks and handle errors.


.then() is used to register a callback that will be called when the promise is fulfilled, with the fulfilled value as an argument.

.catch() is used to register a callback that will be called when the promise is rejected, with the rejection reason as an argument.

.finally() is used to register a callback that will be called when the promise is settled (fulfilled or rejected)

Promise.all() is used to wait for multiple promises to settle and return an array of the fulfilled values in the same order as the original promises, if all of the original promises are fulfilled.

Promise.race() is used to wait for one of multiple promises to settle, and return the value of the first promise that settles.


Promises in JavaScript are a powerful tool to deal with asynchronous operations and they are a standard feature of JavaScript since ECMAScript 6.



result is not undefined — it's a Promise. Even though there's no explicit return of a Promise anywhere, marking the function async automatically wraps whatever it returns in a Promise, silently, every time.




#promise

Wednesday, January 18, 2023

TIL

 https://stackoverflow.com/questions/64567979/how-to-add-custom-css-to-the-single-toast-message-in-angular

F1 - Disable Javascript

URL- Start with hash

single and double quotes JS

Css selectors:- a.t2 //get all anchor with t2 class
-----------------------------------------------

https://stackoverflow.com/questions/48869187/use-cloudblob-existsasync-vs-catch-storageexception-blobnotfound-in-terms-of-pe
-----------------------------------

Friday, January 13, 2023

BITWISE Operators

Setting a bit: To set a specific bit in a number to 1, you can use the bitwise OR operator (|) with a value that has only that bit set. For example, to set the 3rd bit of a number to 1:

num = num | (1 << 3);

Clearing a bit: To clear a specific bit in a number (set it to 0), you can use the bitwise AND operator (&) with a value that has all bits set except for the target bit. For example, to clear the 2nd bit of a number:

num = num & ~(1 << 2);

Toggling a bit: To toggle (flip) a specific bit in a number, you can use the bitwise XOR operator (^) with a value that has only that bit set. For example, to toggle the 4th bit of a number:

num = num ^ (1 << 4);

Checking a bit: To check if a specific bit in a number is set, you can use the bitwise AND operator (&) with a value that has only that bit set. If the result is not zero, then the bit is set. For example, to check if the 5th bit of a number is set:

if ((num & (1 << 5)) != 0) {

    // 5th bit is set

} else {

    // 5th bit is not set

}

Counting set bits: To count the number of bits set to 1 in a number, you can use the trick called "Brian Kernighan's Algorithm" which is an efficient way of counting set bits in a number, It basically flips the last set bit of the number to 0 and count the times you have to do it to reach 0.

int countOnes(uint n) {

    int count = 0;

    while (n > 0) {

        n &= (n-1);

        count++;

    }

    return count;

}

Get the least significant bit: To get the least significant bit (LSB) of a number, you can use the bitwise AND operator (&) with the number 1. For example, to get the LSB of a number:

int lsb = num & 1;