Thursday, January 25, 2024

C++ Template 2

 // #pragma GCC optimize("O3")

// #pragma GCC optimize("Ofast")

// #pragma GCC optimize("unroll-loops")

// #pragma GCC target("avx2,bmi,bmi2,lzcnt,popcnt")

// #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops")

// #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")

 

#include<bits/stdc++.h>

using namespace std;

using namespace chrono;

#define int long long

const int mod=1e9+7;

const int INF = 1e18;


/*/---------------------------------------------------------------------------------------------------------/*/


struct custom_hash {

        static uint64_t splitmix64(uint64_t x) {

                // http://xorshift.di.unimi.it/splitmix64.c

                // https://csacademy.com/app/graph_editor/

                x += 0x9e3779b97f4a7c15;

                x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;

                x = (x ^ (x >> 27)) * 0x94d049bb133111eb;

                return x ^ (x >> 31);

        }

 

        size_t operator()(uint64_t x) const {

                static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();

                return splitmix64(x + FIXED_RANDOM);

        }

};

  

template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> 

istream& operator >> (istream &is, T_container &v) { 

        for(T &x : v) is >> x; return is;

}

#ifdef __SIZEOF_INT128__

ostream& operator << (ostream &os, __int128 const& value){

        static char buffer[64];

        int index = 0;

        __uint128_t T = (value < 0) ? (-(value + 1)) + __uint128_t(1) : value;

        if (value < 0) 

            os << '-';

        else if (T == 0)

            return os << '0';

        for(; T > 0; ++index){

            buffer[index] = static_cast<char>('0' + (T % 10));

            T /= 10;

        }    

        while(index > 0)

            os << buffer[--index];

        return os;

}

istream& operator >> (istream& is, __int128& T){

        static char buffer[64];

        is >> buffer;

        size_t len = strlen(buffer), index = 0;

        T = 0; int mul = 1;

        if (buffer[index] == '-')

            ++index, mul *= -1;

        for(; index < len; ++index)

            T = T * 10 + static_cast<int>(buffer[index] - '0');

        T *= mul;    

        return is;

}

#endif

 

template<typename A, typename B> 

ostream& operator<<(ostream &os, const pair<A, B> &p) { 

        return os << '(' << p.first << ", " << p.second << ')'; 

}

 

template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> 

ostream& operator << (ostream &os, const T_container &v) { 

        os << '{'; string sep; 

        for (const T &x : v) os << sep << x, sep = ", "; 

        return os << '}'; 

}

template<class P, class Q = vector<P>, class R = less<P> > ostream& operator << (ostream& out, priority_queue<P, Q, R> const& M){

        static priority_queue<P, Q, R> U;

        U = M;

        out << "{ ";

        while(!U.empty())

                out << U.top() << " ", U.pop();

        return (out << "}");

 

}

template<class P> ostream& operator << (ostream& out, queue<P> const& M){

        static queue<P> U;

        U = M;

        out << "{"; string sep;

        while(!U.empty()){

                out << sep << U.front(); sep = ", "; U.pop();

        }

        return (out << "}");

}

 

 

#define TRACE

#ifdef TRACE

        #define trace(...) __f(#__VA_ARGS__, __VA_ARGS__)

        template <typename Arg1>

        void __f(const char* name, Arg1&& arg1){

                cerr << name << " : " << arg1 << endl;

        }

        template <typename Arg1, typename... Args>

        void __f(const char* names, Arg1&& arg1, Args&&... args){

                int count_open = 0, len = 1;

                for(int k = 1; ; ++k){

                        char cur = *(names + k);

                        count_open += (cur == '(' ? 1 : (cur == ')' ? -1: 0));

                        if (cur == ',' && count_open == 0){

                               const char* comma = names + k;

                               cerr.write(names, len) << " : " << arg1 << " | ";

                               __f(comma + 1, args...);

                               return;

                        }

                        len = (cur == ' ' ? len : k + 1);

                }

        }

#else

        #define trace(...) 1

#endif

 

/* ----------------------------------------------------- GO DOWN ---------------------------------------------------------------------- */



void solve(){


        int n;

        cin>>n;

        std::vector<int> v(n);


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

                cin>>v[i];

        }

        int mn = *min_element(v.begin(), v.end());

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

                if(v[i]==mn){

                        cout<<i<<endl;

                        return;

                }

        }



}


signed main(){


        

        ios::sync_with_stdio(0);

        cin.tie(0);

        cout.tie(0);

        auto start1 = high_resolution_clock::now();


        int t;

        t=1;

        // cin >> t;

        // Hetu ka laptop

        

        while (t--) {

                solve();   

        }

        


        auto stop1 = high_resolution_clock::now();

        auto duration = duration_cast<microseconds>(stop1 - start1);

        cerr << "Time: " << duration . count() / 1000 << " ms" << endl;

        return 0;


}


int main2()
{
    std::vector<int> v = { 7, 3, 6, 2, 6 };
    int key = 6;
 
    std::vector<int>::iterator itr = std::find(v.begin(), v.end(), key);
 
    if (itr != v.cend()) {
        std::cout << "Element present at index " << std::distance(v.begin(), itr);
    }
    else {
        std::cout << "Element not found";
    }
 
    return 0;
}

Sunday, January 14, 2024

jQuery

 Wrapper function

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

A function that is executed once the page has been finished loading

$(function () { //all our code will be in here... })

Most jQuery code that we see in the wild resides within some kind of wrapper like this. Using $(function(){}); is a shortcut to jQuery's document.ready function, which is fired once the DOM for the page has loaded

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

https://www.paulirish.com/2009/perf/

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


window object is also known as the Global Namespace. The main concept of namespacing is to provide a way to logically group all the related pieces of a distinct and self-contained part of an application.

Saturday, December 2, 2023

Analogies and Learned

 To make something intelligent is to give it input parameters. Parameters which are nothing but additional valuable information which is needed to ensure that the program works efficiently and flexibly.

Buffering:
The cout stream in C++ is buffered by default, which means that the output is stored in a buffer before being actually written to the console. This buffering introduces some overhead. On the other hand, printf typically flushes the output immediately, reducing the buffering overhead.



Tuesday, November 28, 2023

C++ cp TEMPLATE

 // (╯°□°)╯︵ ┻━┻

2#include<bits/stdc++.h>
3// #include <boost/multiprecision/cpp_int.hpp>
4// using boost::multiprecision::cpp_int;
5using namespace std;
6#define ll                 long long int
7#define lld                long double
8#define vi                 vector<ll>
9#define pb                 push_back
10#define MOD                (ll)(1e9 + 7)
11#define rep(i,a,b)         for(ll i = a; i<b; ++i)
12#define f(a)               for(ll i = 0; i<a; ++i)
13#define all(a)             (a).begin(),(a).end()
14#define present(c,x)       ((c).find(x) != (c).end())
15#define cpresent(c,x)      (find(all(c),x) != (c).end())
16#define p(a)               cout << a << endl;
17#define p2(a,b)            cout << a << " " << b << endl;
18#define fast_io            ios_base::sync_with_stdio(false);cin.tie(NULL);
19//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::://
20// GCD + LCM function
21ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }
22ll lcm(ll a, ll b) { return a * (b / gcd(a, b)); }
23
24int32_t main() {
25    fast_io; cout.tie(NULL);
26    ll tc = 1;
27    cin >> tc;
28    while(tc--) {
29        //
30    }
31}




clude <vector>
*/

using namespace std;


// These will be used later
struct Person {
  string name;
  int age;
} p1, p2, p3;

struct is_older {
  bool operator()(struct Person p1, struct Person p2) {
    	return p1.age > p2.age;
    }
};

bool compare_names(struct Person p1, struct Person p2) {
    	return p1.name < p2.name;
}

bool way_to_sort(int i, int j) { return i > j; }


int main() {

  /*
  ========
   STACK
  ========
  */

  stack <string> distros; //Create a stack of strings.

  distros.push("Ubuntu");  //Pushes elements into the stack.
  distros.push("Mint");

  cout << "Number of distros in the stack are " << distros.size() << endl;
  cout << "Distro on the top is " << distros.top() << endl;

  distros.pop();
  cout << "The top of the stack is now " << distros.top() << endl;

  /*
  ========
   VECTOR
  ========
  */

  vector <int> numbers;

  if (numbers.empty()){ //check if the vector is empty?
    cout << "The vector is empty :(" << endl;
  }

  for(int i=0; i<100; i+=10){ //Add some values to the vector
    numbers.push_back(i);
  }

  cout << "Size of the vector is " << numbers.size() << endl;

  // iterating over the vector, declaring the iterator
  vector <int>::iterator it;

  cout << "The vector contains: ";
  for (it=numbers.begin(); it!=numbers.end(); it++) {
    cout << "  " << *it;
  }

  // getting value at a particular position
  int position = 5;
  cout<<"\nVector at position "<<position<<" contains "<<numbers.at(position)<<endl;

  // deleting an element at a position
  numbers.erase(numbers.begin() + position);
  cout<<"Vector at position "<<position<<" contains "<<numbers.at(position)<<endl;

  // deleting a range of elements, first two elements
  // NOTE: You may expect elements at 0, 1, and 2 to be deleted
  // but index 2 is not inclusive.
  numbers.erase(numbers.begin(), numbers.begin()+2);
  cout << "The vector contains: ";
  for (it=numbers.begin(); it!=numbers.end(); it++) {
    cout << "  " << *it;
  }

  // Clearing the vector
  numbers.clear();
  if (numbers.empty()){
    cout << "\nThe vector is now empty again :(";
  }


  /*
  =========
   HASHMAP
  =========
  */

  // Declaration <key type, value type>
  map <string, string> companies;

  companies["Google"] = "Larry Page";
  companies["Facebook"] = "Mark Zuckerberg";

  // insertion can also be done as
  companies.insert(pair<string, string> ("Xarvis Tech", "xarvis"));
  // or
  companies.insert(map<string,string>::value_type("Quora", "Adam D'Angelo"));
  // or even
  companies.insert(make_pair(string("Uber"), string("Travis Kalanick")));

  // Iterating the map
  map<string, string>::iterator itz;
  cout << "\n\nCompanies and founders" << endl;
  for (itz=companies.begin(); itz!=companies.end(); itz++){
    cout << "Company: " << (*itz).first << "\t Founder: " << itz->second <<endl;
  }

  itz = companies.find("Google");
  cout << itz->second;

  /*
  ==============
   LINKED LISTS
  ==============
  */
  list<int> mylist;
    list<int>::iterator it1,it2,itx;

    // set some values:
    for (int i=1; i<10; ++i) mylist.push_back(10*i);

    // 10 20 30 40 50 60 70 80 90
    it1 = it2 = mylist.begin(); // ^^
    advance (it2,6);            // ^                 ^
    ++it1;                      //    ^              ^

    it1 = mylist.erase (it1);   // 10 30 40 50 60 70 80 90
    //    ^           ^

    it2 = mylist.erase (it2);   // 10 30 40 50 60 80 90
    //    ^           ^

    ++it1;                      //       ^        ^
    --it2;                      //       ^     ^

    mylist.erase (it1,it2);     // 10 30 60 80 90

    cout << "\nmylist contains:";
    for (itx=mylist.begin(); itx!=mylist.end(); ++itx)
        cout << ' ' << *itx;
    cout << '\n';

    // NOTE: it1 still points to 40, and 60 is not deleted
    cout << endl << *it1 << "\t" << *it2 <<endl;

    // This will print an unexpected value
    it1++;
    cout << *it1;

    cout << "\nmylist now contains:";
    for (it1=mylist.begin(); it1!=mylist.end(); ++it1)
        cout << ' ' << *it1;
    cout << '\n';

    /*
  =======
   HEAPS
  =======
  */

  // Creates a max heap
    priority_queue <int> pq;

    // To create a min heap instead, just uncomment the below line
    // priority_queue <int, vector<int>, greater<int> > pq;

    pq.push(5);
    pq.push(1);
    pq.push(10);
    pq.push(30);
    pq.push(20);

    // Extracting items from the heap
    while (!pq.empty())
    {
        cout << pq.top() << " ";
        pq.pop();
    }


    // creating heap from user defined objects
    // Let's initialize the properties of `Person` object first
    p1.name = "Linus Torvalds";
    p1.age = 47;

    p2.name = "Elon Musk";
    p2.age = 46;

    p3.name = "Me!";
    p3.age = 19;

    // Initialize a min heap
    
    // Note: We defined a comparator is_older in the beginning to
    // compare the ages of two people.
    
    priority_queue <struct Person, vector<struct Person>, is_older> mh;
    mh.push(p1);
    mh.push(p2);
    mh.push(p3);

    // Extracting items from the heap
    while (!mh.empty())
    {
    	struct Person p = mh.top();
        cout << p.name << " ";
        mh.pop();
    }

    /*
  =========
   SORTING
  =========
  */

    // The following list type initialization is only supported in versions after C++11
    //vector<int> int_vec = {56, 32, -43, 23, 12, 93, 132, -154};

    // If the above style of initialization doesn't work, use the following one
    static int arr[] = {56, 32, -43, 23, 12, 93, 132, -154};
    int arr_len = sizeof(arr) / sizeof(arr[0]);
    vector <int> int_vec(arr, arr + arr_len);

    cout << endl;
    // Default: sort ascending
    // sort(int_vec.begin(), int_vec.end());
    // To sort in descending order:
    // Do not include the () when you call wayToSort
    // It must be passed as a function pointer or function object
  sort(int_vec.begin(), int_vec.end(), way_to_sort);
    for (vector <int>::iterator i = int_vec.begin(); i!=int_vec.end(); i++)
        cout << *i << " ";
    cout << endl;

    // sorting the array
    sort(arr, arr + arr_len);
    for (int i=0; i < arr_len; i++) {
    	cout << arr[i] << " ";
    }

    // Sorting user-defined objects
    static struct Person persons[] = {p1, p2, p3};
    sort(persons, persons+3, compare_names);

    // This will print out the names in alphabetical order
    for (int i=0; i < 3; i++) {
    	cout << persons[i].name << " ";
    }

  return 0;
}

Hope you found this helpful ðŸ˜ƒ

I've also created a gist for the above cheatsheet. Feel free to fork, suggest changes, or point out bugs!