From de283ede6769eaccd0f5d104e3fc1477e2c118aa Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Tiwari Date: Sat, 12 Oct 2019 11:26:05 +0530 Subject: [PATCH 001/324] Create mergethetools.py --- Hackerearth/mergethetools.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Hackerearth/mergethetools.py diff --git a/Hackerearth/mergethetools.py b/Hackerearth/mergethetools.py new file mode 100644 index 00000000..118393a4 --- /dev/null +++ b/Hackerearth/mergethetools.py @@ -0,0 +1,14 @@ +def merge_the_tools(string, k): + l=len(string)//k + for i in range(l): + t='' + for c in string[i*k:i*k+k]: + if c not in t: t+=c + print(t) + + + # your code goes here + +if __name__ == '__main__': + string, k = input(), int(input()) + merge_the_tools(string, k) From 59be239805c7be7a227797975c55908bec9ef850 Mon Sep 17 00:00:00 2001 From: Sandeep Kumar Tiwari Date: Sat, 12 Oct 2019 11:46:18 +0530 Subject: [PATCH 002/324] Create Time conversion.py 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. Function Description Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format. timeConversion has the following parameter(s): s: a string representing time in hour format Input Format A single string containing a time in -hour clock format (i.e.: or ), where and . Constraints All input times are valid Output Format Convert and print the given time in -hour format, where . --- Hackerearth/Time conversion.py | 37 ++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Hackerearth/Time conversion.py diff --git a/Hackerearth/Time conversion.py b/Hackerearth/Time conversion.py new file mode 100644 index 00000000..2dacaf0b --- /dev/null +++ b/Hackerearth/Time conversion.py @@ -0,0 +1,37 @@ +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + hour = int(s[:2]) + meridian = s[8:] +# Special-case '12AM' -> 0, '12PM' -> 12 (not 24) + if (hour == 12): + hour = 0 + if (meridian == 'PM'): + hour += 12 + return ("%02d" % hour + s[2:8]) + + + + + + + # + # Write your code here. + # + +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() From eb7d4fd5188617b7650e5b125d595e2f77d797ae Mon Sep 17 00:00:00 2001 From: root Date: Mon, 14 Oct 2019 09:55:43 +0530 Subject: [PATCH 003/324] Codechef Solutions --- Codechef/DIFNEIGH.cpp | 133 ++++++++++++++++++++++++++++++++++++++++++ Codechef/EARTSEQ.cpp | 50 ++++++++++++++++ Codechef/XYPIZQ.cpp | 51 ++++++++++++++++ 3 files changed, 234 insertions(+) create mode 100644 Codechef/DIFNEIGH.cpp create mode 100644 Codechef/EARTSEQ.cpp create mode 100644 Codechef/XYPIZQ.cpp diff --git a/Codechef/DIFNEIGH.cpp b/Codechef/DIFNEIGH.cpp new file mode 100644 index 00000000..43c3b12f --- /dev/null +++ b/Codechef/DIFNEIGH.cpp @@ -0,0 +1,133 @@ +#include +using namespace std; + +int main(){ + int t; + int a[50][50]; + int i,j,k; + for(k=0;k<50;k++){ + if(k%2==0){ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=1; + else + a[k][i]=2; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=2; + else + a[i][k]=1; + } + } + else{ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=3; + else + a[k][i]=4; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=4; + else + a[i][k]=3; + } + + } + } + cin>>t; + while(t--){ + int n,m,mod; + cin>>n>>m; + // int a[n][m]; + //int i,j; + if(n>=3&&m>=3){ + cout<<4< +using namespace std; +long long maxi=1000000000; + +int main(){ + int i,j,a[(int)1e6+3]={0}; + vector v; + for(i=2;i*i<=1000001;i++){ + if(a[i]==0){ + //v.push_back(i); + for(j=i*i;j<=1000000;j+=i){ + a[j]=i; + } + + } + } + for(i=2;i<1000001;i++){ + if(a[i]==0) + v.push_back(i); + } + int t; + cin>>t; + while(t--) + { + int n,k,l; + cin>>n; + + long long ans; + //cout<2999) + l=l-2999; + // cout< +using namespace std; +long long maxi=1000000000; +#define l long + +int main(){ + int t; + cin>>t; + while(t--){ + long n,k,x,y,z; + long i,j,gcd; + cin>>n>>k>>x>>y>>z; + long p,q; + q=2*n +1; + if(x==z){ + p=x; + gcd=__gcd(p,q); + cout<

y&&y>x){ + if(k==1) + {p=q-z;} + else if(k==2||k==4){ + p=q-2*y; + } + else{ + p=q-x; + + } + gcd=__gcd(p,q); + cout<

Date: Mon, 14 Oct 2019 10:45:35 +0530 Subject: [PATCH 004/324] Palindrome implement in c++ --- Algorithms/C++/Palindrome.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Algorithms/C++/Palindrome.cpp diff --git a/Algorithms/C++/Palindrome.cpp b/Algorithms/C++/Palindrome.cpp new file mode 100644 index 00000000..555ad216 --- /dev/null +++ b/Algorithms/C++/Palindrome.cpp @@ -0,0 +1,29 @@ +/* C++ Program - Check Palindrome or Not */ + +#include +#include +using namespace std; +int main() +{ + + int num, rem, orig, rev=0; + cout<<"------Enter The number :--------- "; + cin>>num; + orig=num; + while(num!=0) + { + rem=num%10; + rev=rev*10 + rem; + num=num/10; + } + if(rev==orig) // check if original number is equal to its reverse + { + cout<<"A Palindrome"; + } + else + { + cout<<"Not a Palindrome"; + } + getch(); + return 0; +} From 5bc1cc9aaa4ccb32ee26231a7f7947a70225554f Mon Sep 17 00:00:00 2001 From: Sunal Sood Date: Mon, 14 Oct 2019 10:59:27 +0530 Subject: [PATCH 005/324] Program to check Leap Year in C++ --- Algorithms/C++/Leap Year.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Algorithms/C++/Leap Year.cpp diff --git a/Algorithms/C++/Leap Year.cpp b/Algorithms/C++/Leap Year.cpp new file mode 100644 index 00000000..8865c95d --- /dev/null +++ b/Algorithms/C++/Leap Year.cpp @@ -0,0 +1,30 @@ +/* C++ Program - Check Leap Year or Not */ + +#include +#include +using namespace std; +int main() +{ + + int yr; + cout<<"--------Enter year :----------"; + cin>>yr; + if((yr%4==0) && (yr%100!=0)) + { + cout<<"This is a Leap Year"; + } + else if((yr%100==0) && (yr%400==0)) + { + cout<<"This is a Leap Year"; + } + else if(yr%400==0) + { + cout<<"This is a Leap Year"; + } + else + { + cout<<"This is not a Leap Year"; + } + getch(); + return 0; +} From c91fdeaa5eb2b48c6ae2386a254c43db76c8faae Mon Sep 17 00:00:00 2001 From: aman binjola Date: Mon, 14 Oct 2019 12:04:14 +0530 Subject: [PATCH 006/324] added beginners-task problem solution for python --- Hackerearth/Python/Beginners-Task.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hackerearth/Python/Beginners-Task.py diff --git a/Hackerearth/Python/Beginners-Task.py b/Hackerearth/Python/Beginners-Task.py new file mode 100644 index 00000000..4f47e4b1 --- /dev/null +++ b/Hackerearth/Python/Beginners-Task.py @@ -0,0 +1,9 @@ +def beginnersTask(list): + count = 0 + for x in list: + if x % 2 == 0: + count = count + 1 + return count + +a = beginnersTask([0, 2, 3, 4]) +print(a) From 5f52d9b0e8e3088135253064ae86aa0b8caaa970 Mon Sep 17 00:00:00 2001 From: mush60 Date: Mon, 14 Oct 2019 14:53:14 +0700 Subject: [PATCH 007/324] Add The Day Of Programmer Chalengge --- Hackerrank/DayOfProgrammer.php | 49 ++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Hackerrank/DayOfProgrammer.php diff --git a/Hackerrank/DayOfProgrammer.php b/Hackerrank/DayOfProgrammer.php new file mode 100644 index 00000000..79e4e434 --- /dev/null +++ b/Hackerrank/DayOfProgrammer.php @@ -0,0 +1,49 @@ +=1919){ + if($year%4 != 0) { + $mday = 243; + } + else { + if($year%400 != 0 && $year%100 == 0) { + $mday = 243; + } else { + $mday = 244; + } + } + } + elseif ($year == 1918) { + + $mday = 243-13; + } + else { + if($year%4 == 0) { + $mday = 244; + } + else { + $mday = 243; + } + } + + $dp = 256-$mday; + + $str = $dp.".".$mn.".".$year; + + return $str; + +} + +$fptr = fopen(getenv("OUTPUT_PATH"), "w"); + +$year = intval(trim(fgets(STDIN))); + +$result = dayOfProgrammer($year); + +fwrite($fptr, $result . "\n"); + +fclose($fptr); + From b434f8bf80d67ca7595f136732922e50689bbcbe Mon Sep 17 00:00:00 2001 From: namanbiyani Date: Mon, 14 Oct 2019 15:37:08 +0530 Subject: [PATCH 008/324] Added quicksort in haskell --- Algorithms/Haskell/quicksort.hs | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Algorithms/Haskell/quicksort.hs diff --git a/Algorithms/Haskell/quicksort.hs b/Algorithms/Haskell/quicksort.hs new file mode 100644 index 00000000..a0789bb4 --- /dev/null +++ b/Algorithms/Haskell/quicksort.hs @@ -0,0 +1,7 @@ +-- Quicksort program in haskell +quicksort :: (Ord a) => [a] -> [a] +quicksort [] = [] +quicksort (x:xs) = + let smallerSorted = quicksort [a | a <- xs, a <= x] + biggerSorted = quicksort [a | a <- xs, a > x] + in smallerSorted ++ [x] ++ biggerSorted \ No newline at end of file From 86ca086b24c85d98526f3bd3b96563cbfd252f43 Mon Sep 17 00:00:00 2001 From: Megha K C <39724388+Megha-KC@users.noreply.github.com> Date: Mon, 14 Oct 2019 15:37:40 +0530 Subject: [PATCH 009/324] pass 1 of a two pass assembler --- Algorithms/C/pass1.c | 93 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Algorithms/C/pass1.c diff --git a/Algorithms/C/pass1.c b/Algorithms/C/pass1.c new file mode 100644 index 00000000..9ebf346f --- /dev/null +++ b/Algorithms/C/pass1.c @@ -0,0 +1,93 @@ +#include +#include + +main() +{ + char opcode[10],operand[10],label[10],code[10][10],ch,op[10],ml_equ[2]; + int locctr,start,len,i=0,j=0,f; + + FILE *fp1,*fp2,*fp3,*fp4; + fp1=fopen("INPUT.DAT","r");//mnemonic code + fp2=fopen("SYMTAB.DAT","wb+");//SYMTAB + fp3=fopen("INERMEDIATE.DAT","wb+");//intermediate file + fp4=fopen("OPTAB.DAT","r");//OPTAB + + fscanf(fp1,"%s%s%s",label,opcode,operand);//read the first input line + + if(strcmp(opcode,"START")==0) + { + start = atoi(operand);//save starting_address <- #[OPERAND] + locctr = start;//LOCCTR <- starting_address + fprintf(fp3,"%s\t%s\t%s\n",label,opcode,operand);//write line to intermediate file + fscanf(fp1,"%s%s%s",label,opcode,operand);//read next input line + } + else + locctr=0;//LOCCTR <- 0 + + while(strcmp(opcode,"END")!=0) + { + fprintf(fp3,"%d",locctr); + if(strcmp(label,"**")!=0)//label exists + { + //search SYMTAB for LABEL + //if found error = 1 + //else + fprintf(fp2,"%s\t%d\n",label,locctr);//insert{LABEL, LOCCTR} into SYMTAB + } + //search optab for opcode + f = 0; + fseek(fp4,0,SEEK_SET); + while(!feof(fp4)) + { + fscanf(fp4,"%s%s",op,ml_equ); + if(strcmp(opcode,op)==0)//opcode found + { + locctr+=3; + f=1; + break; + } + } + //check if opcode is an assembler directive + if(f==0) + { + if(strcmp(opcode,"WORD")==0) + locctr+=3; + else if(strcmp(opcode,"RESW")==0) + locctr+=(3*(atoi(operand))); + else if(strcmp(opcode,"RESB")==0) + locctr+=(atoi(operand)); + else if(strcmp(opcode,"BYTE")==0) + locctr+=strlen(operand)-3; //since C'' or X'' has to be removed from the string length + //else + // set error + } + + fprintf(fp3,"\t%s\t%s\t%s\n",label,opcode,operand);//write line to intermediate file + fscanf(fp1,"%s%s%s",label,opcode,operand);//read next input line + + } + + fprintf(fp3,"%d\t%s\t%s\t%s\n",locctr,label,opcode,operand);//write last line to intermediate file + +//displaying the output in console + + printf("\n\nThe mnemonic code:\n\n"); + fseek(fp1,0,SEEK_SET); + while((ch=fgetc(fp1))!=EOF) + printf("%c",ch); + + printf("\n\nThe contents of intermediate file :\n\n\t"); + fseek(fp3,0,SEEK_SET); + while((ch = fgetc(fp3))!=EOF) + printf("%c",ch); + + len=locctr-start;//pgm_len = LOCCTR - starting_address + printf("\nThe length of the program is %d.\n\n",len); + + printf("\n\nThe contents of SYMTAB:\n\n"); + fseek(fp2,0,SEEK_SET); + while((ch = fgetc(fp2))!=EOF) + printf("%c",ch); + + fcloseall(); +} From 63dedcec5b50760853c900fa7f6123455c825056 Mon Sep 17 00:00:00 2001 From: namanbiyani Date: Mon, 14 Oct 2019 15:42:55 +0530 Subject: [PATCH 010/324] Added Binary search in haskell --- Algorithms/Haskell/binsearch.hs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Algorithms/Haskell/binsearch.hs diff --git a/Algorithms/Haskell/binsearch.hs b/Algorithms/Haskell/binsearch.hs new file mode 100644 index 00000000..1aca40b3 --- /dev/null +++ b/Algorithms/Haskell/binsearch.hs @@ -0,0 +1,9 @@ +-- Function which will perform binary search in haskell +binsearch :: [Int] -> Int -> Int -> Int -> Int -- list, value, low, high, return int +binsearch xs value low high + | high < low = -1 + | xs!!mid > value = binsearch xs value low (mid-1) + | xs!!mid < value = binsearch xs value (mid+1) high + | otherwise = mid + where + mid = low + ((high - low) `div` 2) \ No newline at end of file From bb4cd6a0442d9d9a7e92cc86e8ec1f68f76838eb Mon Sep 17 00:00:00 2001 From: Megha K C <39724388+Megha-KC@users.noreply.github.com> Date: Mon, 14 Oct 2019 15:48:13 +0530 Subject: [PATCH 011/324] Support files for pass 1 --- Algorithms/C/INPUT.DAT | 10 ++++++++++ Algorithms/C/OPTAB.DAT | 6 ++++++ 2 files changed, 16 insertions(+) create mode 100644 Algorithms/C/INPUT.DAT create mode 100644 Algorithms/C/OPTAB.DAT diff --git a/Algorithms/C/INPUT.DAT b/Algorithms/C/INPUT.DAT new file mode 100644 index 00000000..28d9c457 --- /dev/null +++ b/Algorithms/C/INPUT.DAT @@ -0,0 +1,10 @@ +** START 2000 +** LDA FIVE +** STA ALPHA +** LDCH CHARZ +** STCH C1 +ALPHA RESW 1 +FIVE WORD 5 +CHARZ BYTE C'Z' +C1 RESB 1 +** END ** diff --git a/Algorithms/C/OPTAB.DAT b/Algorithms/C/OPTAB.DAT new file mode 100644 index 00000000..fb77a31a --- /dev/null +++ b/Algorithms/C/OPTAB.DAT @@ -0,0 +1,6 @@ +LDA 00 +STA 0C +ADD 18 +SUB 1C +LDCH 50 +STCH 54 From c6deeedbb7c6cb3010b536b548676641b85fcb59 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 16:38:25 +0530 Subject: [PATCH 012/324] Delete INPUT.DAT --- Algorithms/C/INPUT.DAT | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 Algorithms/C/INPUT.DAT diff --git a/Algorithms/C/INPUT.DAT b/Algorithms/C/INPUT.DAT deleted file mode 100644 index 28d9c457..00000000 --- a/Algorithms/C/INPUT.DAT +++ /dev/null @@ -1,10 +0,0 @@ -** START 2000 -** LDA FIVE -** STA ALPHA -** LDCH CHARZ -** STCH C1 -ALPHA RESW 1 -FIVE WORD 5 -CHARZ BYTE C'Z' -C1 RESB 1 -** END ** From 75904dbbc9d164c9a681b9a3fb97d210ab84c1df Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 16:38:34 +0530 Subject: [PATCH 013/324] Delete OPTAB.DAT --- Algorithms/C/OPTAB.DAT | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 Algorithms/C/OPTAB.DAT diff --git a/Algorithms/C/OPTAB.DAT b/Algorithms/C/OPTAB.DAT deleted file mode 100644 index fb77a31a..00000000 --- a/Algorithms/C/OPTAB.DAT +++ /dev/null @@ -1,6 +0,0 @@ -LDA 00 -STA 0C -ADD 18 -SUB 1C -LDCH 50 -STCH 54 From 1c9d3289adeca5416a17ddfc29073d655b730541 Mon Sep 17 00:00:00 2001 From: Sonal Agrawal <37601228+coolsonu39@users.noreply.github.com> Date: Mon, 14 Oct 2019 17:28:51 +0530 Subject: [PATCH 014/324] Fixes typo --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c91f5e1a..05ef4c49 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,5 +8,5 @@ - For example ```Java/sieve.java```. ## Problem Solutions -- You can directly add the problem solutions to corresponding platform folder. File name should be the ID of the problem on particular plateform. -- If plateform folder doesn't exist then write file name as ```Plateform/file.lang``` where ```Plateform``` is the name of the plateform and ```file.lang``` is the name of file. +- You can directly add the problem solutions to corresponding platform folder. File name should be the ID of the problem on particular platform. +- If platform folder doesn't exist then write file name as ```Platform/file.lang``` where ```Platform``` is the name of the platform and ```file.lang``` is the name of file. From 3a802ba31ad08cf306d59ab84a0b9e05ea077e16 Mon Sep 17 00:00:00 2001 From: Sonal Agrawal <37601228+coolsonu39@users.noreply.github.com> Date: Mon, 14 Oct 2019 17:33:32 +0530 Subject: [PATCH 015/324] Create LUCKFOUR.cpp --- .../LUCKFOUR.cpp" | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 "Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" diff --git "a/Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" "b/Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" new file mode 100644 index 00000000..02010656 --- /dev/null +++ "b/Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" @@ -0,0 +1,18 @@ +#include +using namespace std; + +int main() { + int t, n, c; + cin >> t; + while (t--) { + cin >> n; + c = 0; + while (n) { + c = n%10==4 ? c+1 : c; + n /= 10; + } + + cout << c << endl; + } + return 0; +} From 0b7b474b26be978b3dae315d080b42f159d56c3d Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 18:09:10 +0530 Subject: [PATCH 016/324] Rename Codechef/#include using namespace std; int main() { int t, n, c; cin >> t; while (t--) { cin >> n; c = 0; while (n) { c = n%10==4 ? c+1 : c; n/LUCKFOUR.cpp to Codechef/LUCKFOUR.cpp --- .../LUCKFOUR.cpp" => Codechef/LUCKFOUR.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename "Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" => Codechef/LUCKFOUR.cpp (100%) diff --git "a/Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" b/Codechef/LUCKFOUR.cpp similarity index 100% rename from "Codechef/#include using namespace std; int main() { int t, n, c; \tcin >> t; \twhile (t--) { \t\tcin >> n; \t\tc = 0; \t\twhile (n) { \t\t\tc = n%10==4 ? c+1 : c; \t\t\tn/LUCKFOUR.cpp" rename to Codechef/LUCKFOUR.cpp From 1fe84fb73e8f02a1ea045c64dfbc7fa96bb11dc2 Mon Sep 17 00:00:00 2001 From: Jasani Dhruv Date: Mon, 14 Oct 2019 19:23:39 +0530 Subject: [PATCH 017/324] QueenProblem Alog Added :) --- Algorithms/C++/QueenProblem.cpp | 103 ++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Algorithms/C++/QueenProblem.cpp diff --git a/Algorithms/C++/QueenProblem.cpp b/Algorithms/C++/QueenProblem.cpp new file mode 100644 index 00000000..ac868808 --- /dev/null +++ b/Algorithms/C++/QueenProblem.cpp @@ -0,0 +1,103 @@ +// Much shorter version is added check out :) +// uses C++11 threads to parallelize the computation; also uses backtracking +// Outputs all solutions for any table size +#include +#include +#include +#include +#include +using namespace std; +// Print table. 'pos' is a vector of positions the index in pos is the row, +// and the number at that index is the column where the queen is placed. +static void print(const std::vector &pos) +{ + // print table header + for (int i = 0; i < pos.size(); i++) { + std::cout << std::setw(3) << char('a' + i); + } + + std::cout << '\n'; + + for (int row = 0; row < pos.size(); row++) { + int col = pos[row]; + std::cout << row + 1 << std::setw(3 * col + 3) << " # "; + std::cout << '\n'; + } + + std::cout << "\n\n"; +} + +static bool threatens(int row_a, int col_a, int row_b, int col_b) +{ + return row_a == row_b // same row + or col_a == col_b // same column + or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal +} + +// the i-th queen is in the i-th row +// we only check rows up to end_idx +// so that the same function can be used for backtracking and checking the final solution +static bool good(const std::vector &pos, int end_idx) +{ + for (int row_a = 0; row_a < end_idx; row_a++) { + for (int row_b = row_a + 1; row_b < end_idx; row_b++) { + int col_a = pos[row_a]; + int col_b = pos[row_b]; + if (threatens(row_a, col_a, row_b, col_b)) { + return false; + } + } + } + + return true; +} + +static std::mutex print_count_mutex; // mutex protecting 'n_sols' +static int n_sols = 0; // number of solutions + +// recursive DFS backtracking solver +static void n_queens(std::vector &pos, int index) +{ + // if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return + if (index >= pos.size()) { + if (good(pos, index)) { + std::lock_guard lock(print_count_mutex); + print(pos); + n_sols++; + } + + return; + } + + // backtracking step + if (not good(pos, index)) { + return; + } + + // optimization: the first level of the search tree is parallelized + if (index == 0) { + std::vector> fts; + for (int col = 0; col < pos.size(); col++) { + pos[index] = col; + auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); }); + fts.push_back(std::move(ft)); + } + + for (const auto &ft : fts) { + ft.wait(); + } + } else { // deeper levels are not + for (int col = 0; col < pos.size(); col++) { + pos[index] = col; + n_queens(pos, index + 1); + } + } +} + +int main() +{ + std::vector start(12); // 12: table size + n_queens(start, 0); + std::cout << n_sols << " solutions found.\n"; + return 0; +} \ No newline at end of file From e48129f41f91e488480ed0c5fd9046d2fda1faae Mon Sep 17 00:00:00 2001 From: 13kapilgupta <13kapilgupta@gmail.com> Date: Mon, 14 Oct 2019 19:24:18 +0530 Subject: [PATCH 018/324] Create Huffman_coding.cpp --- Algorithms/C++/Huffman_coding.cpp | 71 +++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 Algorithms/C++/Huffman_coding.cpp diff --git a/Algorithms/C++/Huffman_coding.cpp b/Algorithms/C++/Huffman_coding.cpp new file mode 100644 index 00000000..337e1106 --- /dev/null +++ b/Algorithms/C++/Huffman_coding.cpp @@ -0,0 +1,71 @@ + +using namespace std; +struct Node +{ + int data; + char val; + Node *left,*right; + Node(int a,char b) + { + left=NULL; + right=NULL; + this->val=b; + this->data=a; + } + +}; +struct compare +{ +bool operator()(Node *a,Node *b) +{ + return(a->data>b->data); +}}; +void printme(Node *root,string s) +{ + if(root==NULL)return; + if(root->val!='%') + { + cout<left,s+'0'); + printme(root->right,s+'1'); +} +void func(int arr[],int len,string s) +{ + priority_queue,compare>que; + for(int j=0;j1) + { + left=que.top(); + que.pop(); + right=que.top(); + que.pop(); + top=new Node(left->data+right->data,'%'); + que.push(top); + top->left=left; + top->right=right; + } + printme(top,""); +} +int main() { + //code + int n; + cin>>n; + for(int i=0;i>s; + int arr[s.length()]; + for(int j=0;j>arr[j]; + } + func(arr,s.length(),s); + cout<<'\n'; + } + return 0; +} From a7b2683c2a1936e0c4617fa17817a8ebfbf598aa Mon Sep 17 00:00:00 2001 From: Ayus Das Date: Mon, 14 Oct 2019 19:46:11 +0530 Subject: [PATCH 019/324] Linear search implemented in java --- Algorithms/Java/Linear_search.java | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Algorithms/Java/Linear_search.java diff --git a/Algorithms/Java/Linear_search.java b/Algorithms/Java/Linear_search.java new file mode 100644 index 00000000..ee8abc9d --- /dev/null +++ b/Algorithms/Java/Linear_search.java @@ -0,0 +1,36 @@ +import java.util.Scanner; + + +public class Linear_search { + static int linear_Search(int arr[],int total_elements,int item_required) + { + for(int i=0;i Date: Mon, 14 Oct 2019 20:16:51 +0530 Subject: [PATCH 020/324] added swap-case solution --- Hackerrank/Python/Swap_Case.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Hackerrank/Python/Swap_Case.py diff --git a/Hackerrank/Python/Swap_Case.py b/Hackerrank/Python/Swap_Case.py new file mode 100644 index 00000000..d9b192ba --- /dev/null +++ b/Hackerrank/Python/Swap_Case.py @@ -0,0 +1,8 @@ +def swapCase(s): + a = '' + for x in s: + if x.isupper(): + a = a + x.lower() + else: + a = a + x.upper() + return a From 0d63eff440407af0ed1d9a855ed42a0f6622a6a5 Mon Sep 17 00:00:00 2001 From: Ayus Das Date: Mon, 14 Oct 2019 20:51:21 +0530 Subject: [PATCH 021/324] Quick sort implemented --- Algorithms/C/quick_sort.c | 83 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 Algorithms/C/quick_sort.c diff --git a/Algorithms/C/quick_sort.c b/Algorithms/C/quick_sort.c new file mode 100644 index 00000000..e6e64463 --- /dev/null +++ b/Algorithms/C/quick_sort.c @@ -0,0 +1,83 @@ +//Name : Ayus Das +//Email: ayusdas2000@gmail.com +/* + *This code implementation of Quick sort in C + *language. This program takes the size of the array + *and array elements from the user. +*/ +#include + +// A utility function to swap two elements +void swap(int* a, int* b) +{ + int t = *a; + *a = *b; + *b = t; +} + +/* This function takes last element as pivot, places + the pivot element at its correct position in sorted + array, and places all smaller (smaller than pivot) + to left of pivot and all greater elements to right + of pivot */ +int partition (int arr[], int low, int high) +{ + int pivot = arr[high]; // pivot + int i = (low - 1); // Index of smaller element + + for (int j = low; j <= high- 1; j++) + { + // If current element is smaller than the pivot + if (arr[j] < pivot) + { + i++; // increment index of smaller element + swap(&arr[i], &arr[j]); + } + } + swap(&arr[i + 1], &arr[high]); + return (i + 1); +} + +/* The main function that implements QuickSort + arr[] --> Array to be sorted, + low --> Starting index, + high --> Ending index */ +void quickSort(int arr[], int low, int high) +{ + if (low < high) + { + /* pi is partitioning index, arr[p] is now + at right place */ + int pi = partition(arr, low, high); + + // Separately sort elements before + // partition and after partition + quickSort(arr, low, pi - 1); + quickSort(arr, pi + 1, high); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + printf("Enter the size of the array: "); + int n; + scanf("%d",&n); + int arr[n]; + printf("Enter the elements: \n"); + for(int i=0;i Date: Mon, 14 Oct 2019 21:40:56 +0530 Subject: [PATCH 022/324] Rename Hackerrank/DayOfProgrammer.php to Hackerrank/PHP/DayOfProgrammer.php --- Hackerrank/{ => PHP}/DayOfProgrammer.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerrank/{ => PHP}/DayOfProgrammer.php (100%) diff --git a/Hackerrank/DayOfProgrammer.php b/Hackerrank/PHP/DayOfProgrammer.php similarity index 100% rename from Hackerrank/DayOfProgrammer.php rename to Hackerrank/PHP/DayOfProgrammer.php From 1e09ea9544e9d29fe33cb26e5bb52722c1e988e4 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 21:41:20 +0530 Subject: [PATCH 023/324] Rename Hackerrank/ExtraLongFactorial.php to Hackerrank/PHP/ExtraLongFactorial.php --- Hackerrank/{ => PHP}/ExtraLongFactorial.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerrank/{ => PHP}/ExtraLongFactorial.php (100%) diff --git a/Hackerrank/ExtraLongFactorial.php b/Hackerrank/PHP/ExtraLongFactorial.php similarity index 100% rename from Hackerrank/ExtraLongFactorial.php rename to Hackerrank/PHP/ExtraLongFactorial.php From c79445d0e017313977214c953139328fdf232857 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 21:41:52 +0530 Subject: [PATCH 024/324] Rename Hackerrank/Staircase.py to Hackerrank/Python/Staircase.py --- Hackerrank/{ => Python}/Staircase.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerrank/{ => Python}/Staircase.py (100%) diff --git a/Hackerrank/Staircase.py b/Hackerrank/Python/Staircase.py similarity index 100% rename from Hackerrank/Staircase.py rename to Hackerrank/Python/Staircase.py From 24f4f75343645fd3ee2fa296b7bc4e1850ba07f2 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 21:42:56 +0530 Subject: [PATCH 025/324] Rename Hackerrank/Time_Conversion.py to Hackerrank/Python/Time_Conversion.py --- Hackerrank/{ => Python}/Time_Conversion.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerrank/{ => Python}/Time_Conversion.py (100%) diff --git a/Hackerrank/Time_Conversion.py b/Hackerrank/Python/Time_Conversion.py similarity index 100% rename from Hackerrank/Time_Conversion.py rename to Hackerrank/Python/Time_Conversion.py From 02553f3d9f04b7221b20ced265f2e4368cb9448b Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 14 Oct 2019 21:44:46 +0530 Subject: [PATCH 026/324] Rename Hackerrank/kangaroo.php to Hackerrank/PHP/kangaroo.php --- Hackerrank/{ => PHP}/kangaroo.php | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerrank/{ => PHP}/kangaroo.php (100%) diff --git a/Hackerrank/kangaroo.php b/Hackerrank/PHP/kangaroo.php similarity index 100% rename from Hackerrank/kangaroo.php rename to Hackerrank/PHP/kangaroo.php From 1135530f7303b7ef5375f902756aa4ac52526f25 Mon Sep 17 00:00:00 2001 From: Bharath Date: Mon, 14 Oct 2019 23:24:56 +0530 Subject: [PATCH 027/324] Solution for Leetcode Problem #2: Add Two Numbers in java --- LeetCode/Add_Two_Numbers.java | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 LeetCode/Add_Two_Numbers.java diff --git a/LeetCode/Add_Two_Numbers.java b/LeetCode/Add_Two_Numbers.java new file mode 100644 index 00000000..91b92d86 --- /dev/null +++ b/LeetCode/Add_Two_Numbers.java @@ -0,0 +1,47 @@ +/** + * Definition for singly-linked list. + * public class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { val = x; } + * } + */ +class Solution { + public ListNode addTwoNumbers(ListNode l1, ListNode l2) { + + ListNode curr, dummy; + int l1Digit, l2Digit, sum, carry; + + sum = 0; + carry = 0; + + dummy = new ListNode(0); + curr = dummy; + + while (l1 != null || l2 != null) { + + // get the digit or treat it as 0 + l1Digit = (l1 != null) ? l1.val : 0; + l2Digit = (l2 != null) ? l2.val : 0; + + // calculate sum and carry + sum = carry + l1Digit + l2Digit; + carry = sum / 10; + + // assign the last digit of 'sum' and increment the 'curr' pointer + curr.next = new ListNode(sum % 10); + curr = curr.next; + + // in case l1 and l2 are not of the same length + if (l1 != null) l1 = l1.next; + if (l2 != null) l2 = l2.next; + } + + // there might be a carry still left + if (carry > 0) { + curr.next = new ListNode(carry); + } + + return dummy.next; + } +} \ No newline at end of file From d9ad09286d7df6bf3a0883e380288f69315c0c73 Mon Sep 17 00:00:00 2001 From: jenarddurai Date: Tue, 15 Oct 2019 00:40:41 +0530 Subject: [PATCH 028/324] Add solution for codechef problem MAGICHF --- Codechef/MAGICHF.cpp | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Codechef/MAGICHF.cpp diff --git a/Codechef/MAGICHF.cpp b/Codechef/MAGICHF.cpp new file mode 100644 index 00000000..71f17793 --- /dev/null +++ b/Codechef/MAGICHF.cpp @@ -0,0 +1,32 @@ +#include +#define ll long long +#define ull unsigned long long +#define vi vector +#define pp pair +#define mp make_pair +#define PI acos(-1.0) +#define all(v) v.begin(),v.end() +#define pb push_back +#define INF 1e18 +#define MOD 1000000007 +using namespace std; +int main() +{ + ll t; + cin>>t; + while(t--) + { + ll n,x,s; + cin>>n>>x>>s; + ll b1,b2; + for(ll i=0;i>b1>>b2; + if(b1==x) + x=b2; + else if(b2==x) + x=b1; + } + cout< Date: Tue, 15 Oct 2019 00:54:37 +0530 Subject: [PATCH 029/324] Add solution for codechef problem CHEFADV --- Codechef/CHEFADV.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Codechef/CHEFADV.cpp diff --git a/Codechef/CHEFADV.cpp b/Codechef/CHEFADV.cpp new file mode 100644 index 00000000..0f4205bd --- /dev/null +++ b/Codechef/CHEFADV.cpp @@ -0,0 +1,36 @@ +#include +#define ll long long +#define ull unsigned long long +#define vi vector +#define pp pair +#define mp make_pair +#define PI acos(-1.0) +#define all(v) v.begin(),v.end() +#define pb push_back +#define INF 1e18 +#define MOD 1000000007 +using namespace std; +int main() +{ + ll t; + cin>>t; + while(t--) + { + ll n,m,x,y,p=1,k=1,p1,k1,p2,k2; + cin>>n>>m>>x>>y; + k1=1+((n-1)/x)*x; + p1=1+((m-1)/y)*y; + k2=k1;p2=p1; + if(k1-x>1) + k2=k1-x; + if(p1-y>1) + p2=p1-y; + if(((k==n)&&(p==m))||((k==n)&&(p1==m))||((k==n)&&(p2==m))||((k1==n)&&(p==m))||((k1==n)&&(p1==m))||((k1==n)&&(p2==m))||((k2==n)&&(p==m))||((k2==n)&&(p1==m))||((k2==n)&&(p2==m))) + cout<<"Chefirnemo"; + else if(((k==n-1)&&(p==m-1))||((k==n-1)&&(p1==m-1))||((k==n-1)&&(p2==m-1))||((k1==n-1)&&(p==m-1))||((k1==n-1)&&(p1==m-1))||((k1==n-1)&&(p2==m-1))||((k2==n-1)&&(p==m-1))||((k2==n-1)&&(p1==m-1))||((k2==n-1)&&(p2==m-1))) + cout<<"Chefirnemo"; + else + cout<<"Pofik"; + cout< Date: Tue, 15 Oct 2019 01:02:30 +0530 Subject: [PATCH 030/324] solution for java currency formatter --- Hackerrank/Java/CurrencyFormatter.java | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Hackerrank/Java/CurrencyFormatter.java diff --git a/Hackerrank/Java/CurrencyFormatter.java b/Hackerrank/Java/CurrencyFormatter.java new file mode 100644 index 00000000..7a9db7b6 --- /dev/null +++ b/Hackerrank/Java/CurrencyFormatter.java @@ -0,0 +1,28 @@ +import java.io.*; +import java.util.*; +import java.text.*; +import java.math.*; +import java.util.regex.*; + +public class Solution { + + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + double payment = scanner.nextDouble(); + scanner.close(); + NumberFormat d=NumberFormat.getCurrencyInstance(); + String us=d.format(payment); + NumberFormat e=NumberFormat.getCurrencyInstance(Locale.CHINA); + String china=e.format(payment); + NumberFormat f=NumberFormat.getCurrencyInstance(Locale.FRANCE); + // Write your code here. + String france=f.format(payment); + Locale a=new Locale("en","IN"); + NumberFormat g=NumberFormat.getCurrencyInstance(a); + String india=g.format(payment); + System.out.println("US: " + us); + System.out.println("India: " + india); + System.out.println("China: " + china); + System.out.println("France: " + france); + } +} From 4f2b99abf673020b47a399520eb568835ef99ba2 Mon Sep 17 00:00:00 2001 From: Anderson Tomkelski Date: Mon, 14 Oct 2019 16:46:42 -0300 Subject: [PATCH 031/324] Added AVL Tree in C --- DS/C/avl_tree.c | 239 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 239 insertions(+) create mode 100755 DS/C/avl_tree.c diff --git a/DS/C/avl_tree.c b/DS/C/avl_tree.c new file mode 100755 index 00000000..9fa493de --- /dev/null +++ b/DS/C/avl_tree.c @@ -0,0 +1,239 @@ +# include +# include + +#define clear() printf("\033[H\033[J") + +typedef struct _node{ + int key; + int height, level; + int right_height, left_height; + struct _node *left; + struct _node *right; + struct _node *root_node; +} Node; + +typedef struct _tree{ + Node *root; +} Tree; + +Tree *init_tree(){ + Tree *tree = (Tree*)malloc(sizeof(Tree)); + tree->root=NULL; + return tree; +} + +void show_menu(); +void show_tree(Node *root); +Node * normal_insert(Node *root_node, int value); +Node * search_insert_element(Node *root, int value); +Node * verify_weight(Node *added_node); +Node * right_rotate(Node *root_node); +Node * left_rotate(Node *root_node); +void new_tree_height(Node *sub_tree); +int height_calc(Node *sub_tree); + +int main(){ + Tree *test = init_tree(); + + int value; + int option=-1; + do{ + show_menu(); + scanf("%d", &option); + switch(option){ + case 0: + exit(0); + case 1: + clear(); + printf("\nInsert value: "); + scanf("%d", &value); + if(test->root == NULL) + test->root = normal_insert(test->root,value); + else + test->root = search_insert_element(test->root,value); + break; + case 2: + clear(); + printf ("\nTree elements:\n"); + show_tree(test->root); + getchar(); + getchar(); + break; + default: + clear(); + printf("Invalid\n"); + } + }while(1); +} + +void show_menu(){ + printf("\nAVL Tree\n"); + printf("Choose an option\n"); + printf("0 - Exit\n"); + printf("1 - Insert Element\n"); + printf("2 - List Elements\n"); + printf("\nOption: "); +} + +Node *normal_insert(Node *root_node, int value){ + Node *new_node = (Node*)malloc(sizeof(Node)); + new_node->left = NULL; + new_node->right = NULL; + new_node->root_node = root_node; + new_node->key = value; + new_node->height = 0; + new_node->right_height = 0; + new_node->left_height = 0; + + return new_node; +} + +Node * search_insert_element(Node *root, int value){ + if(root == NULL) + return root; + + if(value > root->key){ + root->right_height++; + root->level = root->left_height - root->right_height; + if(root->right == NULL){ + root->right = normal_insert(root,value); + new_tree_height(root->right); + root = verify_weight(root->right); + }else + root = search_insert_element(root->right,value); + + }else if(value < root->key){ + root->left_height++; + root->level = root->left_height - root->right_height; + if(root->left == NULL){ + root->left = normal_insert(root,value); + new_tree_height(root->left); + root = verify_weight(root->left); + }else + root = search_insert_element(root->left,value); + }else{ + printf("Already inserted"); + } + if(root->left_height>=root->right_height) + root->height = root->left_height; + else + root->height = root->right_height; + +} + + +Node * verify_weight(Node *added_node){ + Node *root_node = added_node->root_node; + Node *root_root_node = root_node->root_node; + + new_tree_height(added_node); + + while(root_root_node != NULL){ + if(root_root_node->level < -1 && root_node->level < 0){ + root_node = left_rotate(root_root_node); + break; + }else if(root_root_node->level > 1 && root_node->level > 0){ + root_node = right_rotate(root_root_node); + break; + }else if(root_root_node->level< -1 && root_node->level > 0){ + root_node = right_rotate(root_node); + root_root_node = left_rotate(root_root_node); + break; + }else if(root_root_node->level > 1 && root_node->level < 0){ + root_node = left_rotate(root_node); + root_root_node = right_rotate(root_root_node); + break; + } + + root_root_node = root_root_node->root_node; + root_node = root_node->root_node; + } + while(root_node->root_node != NULL) + root_node = root_node->root_node; + + return root_node; +} + +void show_tree(Node *root){ + if(root == NULL) + return; + + show_tree(root->left); + if(root->root_node == NULL) + printf("\nKey: %d || Left Height: %d || Right Height: %d || Height: %d || Level: %d || Root: %s", root->key, root->left_height, root->right_height, root->height, root->level, "Raiz"); + else + printf("\nKey: %d || Left Height: %d || Right Height: %d || Height: %d || Level: %d || Root: %d", root->key, root->left_height, root->right_height, root->height, root->level, root->root_node->key); + show_tree(root->right); +} + + +Node * left_rotate(Node *root){ + Node *node_son = root->right; + root->right = node_son->left; + + if ( node_son->left != NULL ) + node_son->left->root_node = root; + node_son->left = root; + node_son->root_node = root->root_node; + if ( root->root_node != NULL ) + if ( root->root_node->left == root ) + root->root_node->left = node_son; + else + root->root_node->right = node_son; + root->root_node = node_son; + + new_tree_height(node_son->right); + new_tree_height(node_son->left); + return node_son; +} + +Node * right_rotate(Node *root){ + Node *node_son = root->left; + + root->left = node_son->right; + if ( node_son->right != NULL ) + node_son->right->root_node = root; + node_son->right = root; + node_son->root_node = root->root_node; + if ( root->root_node != NULL ) + if ( root->root_node->left == root ) + root->root_node->left = node_son; + else + root->root_node->right = node_son; + root->root_node = node_son; + + new_tree_height(node_son->right); + new_tree_height(node_son->left); + return node_son; +} + +void new_tree_height(Node *node_son){ + if(node_son == NULL) + return; + + node_son->right_height = height_calc(node_son->right); + node_son->left_height = height_calc(node_son->left); + if(node_son->left_height >= node_son->right_height) + node_son->height = node_son->left_height; + else + node_son->height = node_son->right_height; + + node_son->level = node_son->left_height - node_son->right_height; + new_tree_height(node_son->root_node); +} + +int height_calc(Node *sub_tree){ + if(sub_tree == NULL) + return 0; + + int t_left_height; + int t_right_height; + + t_left_height = height_calc(sub_tree->left); + t_right_height = height_calc(sub_tree->right); + + if(t_left_height>=t_right_height) + return t_left_height+1; + else + return t_right_height+1; +} From 3d38f3d8a681d8a6c6b8ba4d89638142b254286e Mon Sep 17 00:00:00 2001 From: somya <42448899+somya1209@users.noreply.github.com> Date: Tue, 15 Oct 2019 02:41:41 +0530 Subject: [PATCH 032/324] Create PRDRG.cpp added solution to Chef and Ridges problem --- Codechef/PRDRG.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Codechef/PRDRG.cpp diff --git a/Codechef/PRDRG.cpp b/Codechef/PRDRG.cpp new file mode 100644 index 00000000..c6d8b78d --- /dev/null +++ b/Codechef/PRDRG.cpp @@ -0,0 +1,30 @@ +//author:somya1209 +//problem:prdrg + + +#include +#include +using namespace std; + +int main() { + // your code goes here + int t; + cin>>t; + while(t--) + {long int n,p=0,q,Pn_1=0; + cin>>n; + q=pow(2,n); + for(int i=1;i<=n;++i) + { + if(i%2==0) + p=2*Pn_1-1; + else + p=2*Pn_1+1; + Pn_1=p; + + } + cout< Date: Tue, 15 Oct 2019 08:30:54 +0530 Subject: [PATCH 033/324] Quick sort implemented in Java Quick sort implemented in Java. --- Algorithms/Java/QuickSort.java | 63 ++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Algorithms/Java/QuickSort.java diff --git a/Algorithms/Java/QuickSort.java b/Algorithms/Java/QuickSort.java new file mode 100644 index 00000000..e7eefd0d --- /dev/null +++ b/Algorithms/Java/QuickSort.java @@ -0,0 +1,63 @@ +import java.util.Scanner; + +public class QuickSort +{ + + public static void main(String[] args) + { + Scanner s = new Scanner(System.in); + int i, n, a[]; + System.out.print("Enter value of n: "); + n = s.nextInt(); + a = new int[n]; + System.out.println("Enter " + n + " values"); + for(i=0; ipivot){ + j--; + } + if(i<=j){ + temp=array[i]; + array[i]=array[j]; + array[j]=temp; + i++; + j--; + } + } + if(lowi){ + quickSort(array,i,high); + } + } + +} + +/***************************************************************************************** + +Time Complexity : O(n^2) + +*****************************************************************************************/ From 2a3c7ce22fff0794e3be9903b062b64ffacb970e Mon Sep 17 00:00:00 2001 From: rhinojosa <=> Date: Tue, 15 Oct 2019 00:45:27 -0500 Subject: [PATCH 034/324] Added fibonacci in javascript --- Algorithms/JavaScript/fibonnacci.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Algorithms/JavaScript/fibonnacci.js diff --git a/Algorithms/JavaScript/fibonnacci.js b/Algorithms/JavaScript/fibonnacci.js new file mode 100644 index 00000000..afff9f8a --- /dev/null +++ b/Algorithms/JavaScript/fibonnacci.js @@ -0,0 +1,16 @@ +function fibonacci (num, cache) { + cache = cache || {}; + if (cache[num]) return cache[num]; + if (num <= 1) return 1; + return cache[num] = fibonacci(num - 1, cache) + fibonacci(num - 2, cache); +} + + +console.log(fibonacci(6)) // 13 +console.log(fibonacci(5)) // 8 +console.log(fibonacci(4)) // 5 +console.log(fibonacci(3)) // 3 +console.log(fibonacci(2)) // 2 +console.log(fibonacci(1)) // 1 +console.log(fibonacci(0)) // 1 + From 8c9dde6e1a88e0fc373dbdaa931b3b6a908c9e37 Mon Sep 17 00:00:00 2001 From: Neuron34 Date: Tue, 15 Oct 2019 12:44:01 +0530 Subject: [PATCH 035/324] Adding heapSort in Algorithum --- Algorithms/Java/HeapSort.java | 67 +++++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 Algorithms/Java/HeapSort.java diff --git a/Algorithms/Java/HeapSort.java b/Algorithms/Java/HeapSort.java new file mode 100644 index 00000000..b25ce896 --- /dev/null +++ b/Algorithms/Java/HeapSort.java @@ -0,0 +1,67 @@ +public class HeapSort +{ + + public void sort(int arr[]) + { + int n = arr.length; + + // Build max heap + for (int i = n / 2 - 1; i >= 0; i--) { + heapify(arr, n, i); + } + + + // Heap sort + for (int i=n-1; i>=0; i--) + { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // Heapify root element + heapify(arr, i, 0); + } + } + + void heapify(int arr[], int n, int i) + { + // Find largest among root, left child and right child + int largest = i; + int l = 2*i + 1; + int r = 2*i + 2; + + if (l < n && arr[l] > arr[largest]) + largest = l; + + if (r < n && arr[r] > arr[largest]) + largest = r; + + // Swap and continue heapifying if root is not largest + if (largest != i) + { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + heapify(arr, n, largest); + } + } + + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i < n; ++i) + System.out.print(arr[i]+" "); + System.out.println(); + } + + public static void main(String args[]) + { + int arr[] = {1,12,9,5,6,10}; + HeapSort hs = new HeapSort(); + hs.sort(arr); + + System.out.println("Sorted array is"); + printArray(arr); + } +} \ No newline at end of file From b3bf7ef8a0792c226815291190445d73645c5101 Mon Sep 17 00:00:00 2001 From: NishaSingla1 <56588429+NishaSingla1@users.noreply.github.com> Date: Tue, 15 Oct 2019 17:11:13 +0530 Subject: [PATCH 036/324] Stack Implementation of Stack using Array --- DS/C++/Stack Using Array.txt | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 DS/C++/Stack Using Array.txt diff --git a/DS/C++/Stack Using Array.txt b/DS/C++/Stack Using Array.txt new file mode 100644 index 00000000..12a599e3 --- /dev/null +++ b/DS/C++/Stack Using Array.txt @@ -0,0 +1,63 @@ +#include +using namespace std; +int stack[100], n=100, top=-1; +void push(int val) { + if(top>=n-1) + cout<<"Stack Overflow"<=0) { + cout<<"Stack elements are:"; + for(int i=top; i>=0; i--) + cout<>ch; + switch(ch) { + case 1: { + cout<<"Enter value to be pushed:"<>val; + push(val); + break; + } + case 2: { + pop(); + break; + } + case 3: { + display(); + break; + } + case 4: { + cout<<"Exit"< Date: Tue, 15 Oct 2019 18:47:44 +0530 Subject: [PATCH 037/324] created LGCD.cpp --- Codechef/LGCD.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Codechef/LGCD.cpp diff --git a/Codechef/LGCD.cpp b/Codechef/LGCD.cpp new file mode 100644 index 00000000..7b808751 --- /dev/null +++ b/Codechef/LGCD.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +#define f(i,a,b) for(int i=a;i>Testcase; + while(Testcase--) + { + int N; + cin>>N; + int A[N]; + unordered_mapmap; + f(i,0,N) + { + cin>>A[i]; + map[A[i]]++; + } + int result=0; + f(i,0,N) + { + if(map.find(2*A[i])!=map.end()) + result+=map[2*A[i]]; + } + cout< Date: Tue, 15 Oct 2019 19:22:54 +0530 Subject: [PATCH 038/324] Create leftRotation.py --- Hackerrank/Python/leftRotation.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hackerrank/Python/leftRotation.py diff --git a/Hackerrank/Python/leftRotation.py b/Hackerrank/Python/leftRotation.py new file mode 100644 index 00000000..61d07976 --- /dev/null +++ b/Hackerrank/Python/leftRotation.py @@ -0,0 +1,24 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + + + +if __name__ == '__main__': + nd = input().split() + + n = int(nd[0]) + + d = int(nd[1]) + + a = list(map(int, input().rstrip().split())) + b=a[0:d] + c=a[d:n] + e=c+b + for i in e: + print(i,end=' ') + From 784114f2b7594615a9ffe6d7a7aea6a91be3931b Mon Sep 17 00:00:00 2001 From: Neelam Bugalia Date: Tue, 15 Oct 2019 19:26:25 +0530 Subject: [PATCH 039/324] Create compareTheTriplets.py --- Hackerrank/Python/compareTheTriplets.py | 35 +++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Hackerrank/Python/compareTheTriplets.py diff --git a/Hackerrank/Python/compareTheTriplets.py b/Hackerrank/Python/compareTheTriplets.py new file mode 100644 index 00000000..97fd8f95 --- /dev/null +++ b/Hackerrank/Python/compareTheTriplets.py @@ -0,0 +1,35 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the compareTriplets function below. +def compareTriplets(a, b): + count_a=0 + count_b=0 + for i in range(3): + + if(a[i]>b[i]): + count_a+=1 + elif(a[i] Date: Tue, 15 Oct 2019 19:28:50 +0530 Subject: [PATCH 040/324] Create plusMinus.cpp --- Hackerrank/C++/plusMinus.cpp | 77 ++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Hackerrank/C++/plusMinus.cpp diff --git a/Hackerrank/C++/plusMinus.cpp b/Hackerrank/C++/plusMinus.cpp new file mode 100644 index 00000000..d1f03a8b --- /dev/null +++ b/Hackerrank/C++/plusMinus.cpp @@ -0,0 +1,77 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the plusMinus function below. +void plusMinus(vector arr) { + int a=0,b=0,c=0,n; + n=arr.size(); + for(int i=0;i0) + a=a+1; + else if(arr[i]<0) + b=b+1; + else c=c+1; + + } + float x=a*1.0/n,y=b*1.0/n,z=c*1.0/n; + printf("%.6f\n%.6f\n%.6f", x,y,z); + // cout<> n; + cin.ignore(numeric_limits::max(), '\n'); + + string arr_temp_temp; + getline(cin, arr_temp_temp); + + vector arr_temp = split_string(arr_temp_temp); + + vector arr(n); + + for (int i = 0; i < n; i++) { + int arr_item = stoi(arr_temp[i]); + + arr[i] = arr_item; + } + + plusMinus(arr); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 50bcb70270e2fa1dffd036075cc15f4001029726 Mon Sep 17 00:00:00 2001 From: Neelam Bugalia Date: Tue, 15 Oct 2019 19:31:04 +0530 Subject: [PATCH 041/324] Create timeConversion.py --- Hackerrank/Python/timeConversion.py | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Hackerrank/Python/timeConversion.py diff --git a/Hackerrank/Python/timeConversion.py b/Hackerrank/Python/timeConversion.py new file mode 100644 index 00000000..96c33b34 --- /dev/null +++ b/Hackerrank/Python/timeConversion.py @@ -0,0 +1,35 @@ +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + a=s[0:2] + b=int(a) + if(s[8]=="P"): + if b<12: + b+=12 + if(s[8]=="A"): + if b==12: + b = 0 + c=s[2:8] + d = str(b) + if b <10: + d = '0'+d + out=d+c + return out + + +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() From 61ae0bb34d6af386acf8a7d819cd6a307cca561b Mon Sep 17 00:00:00 2001 From: Neelam Bugalia Date: Tue, 15 Oct 2019 19:32:47 +0530 Subject: [PATCH 042/324] Create diagonalDifference.py --- Hackerrank/Python/diagonalDifference.py | 34 +++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Hackerrank/Python/diagonalDifference.py diff --git a/Hackerrank/Python/diagonalDifference.py b/Hackerrank/Python/diagonalDifference.py new file mode 100644 index 00000000..5997b522 --- /dev/null +++ b/Hackerrank/Python/diagonalDifference.py @@ -0,0 +1,34 @@ +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# +# Complete the 'diagonalDifference' function below. +# +# The function is expected to return an INTEGER. +# The function accepts 2D_INTEGER_ARRAY arr as parameter. +# + +n=int(input()) +a=[] +for _ in range(n): + x=list(map(int,input().split())) + a.append(x) +s1=0 +s2=0 +for i in range(n): + for j in range(n): + + if(i==j): + + s1+=a[i][j] + if(i+j==n-1): + + s2+=a[i][j] +result=abs(s1-s2) +print(result) + From 0aa8fbf9cc71ceb1df82c3d9e3c5b87c512e09e9 Mon Sep 17 00:00:00 2001 From: Eliot Wong Date: Tue, 15 Oct 2019 19:00:59 +0200 Subject: [PATCH 043/324] Add solution for Plus Minus --- Hackerrank/Go/plus-minus.go | 69 +++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 Hackerrank/Go/plus-minus.go diff --git a/Hackerrank/Go/plus-minus.go b/Hackerrank/Go/plus-minus.go new file mode 100644 index 00000000..66da2d5d --- /dev/null +++ b/Hackerrank/Go/plus-minus.go @@ -0,0 +1,69 @@ +// Author: Vatsal Chanana +// URL: https://www.hackerrank.com/challenges/plus-minus/problem + +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +// Complete the plusMinus function below. +func plusMinus(arr []int32) { + pos, neg, zero := 0, 0, 0 + + for _, num := range arr { + if num > 0 { + pos++ + } else if num == 0 { + zero++ + } else { + neg++ + } + } + + size := float32(len(arr)) + fmt.Println(float32(pos) / size) + fmt.Println(float32(neg) / size) + fmt.Println(float32(zero) / size) +} + +func main() { + reader := bufio.NewReaderSize(os.Stdin, 1024 * 1024) + + nTemp, err := strconv.ParseInt(readLine(reader), 10, 64) + checkError(err) + n := int32(nTemp) + + arrTemp := strings.Split(readLine(reader), " ") + + var arr []int32 + + for i := 0; i < int(n); i++ { + arrItemTemp, err := strconv.ParseInt(arrTemp[i], 10, 64) + checkError(err) + arrItem := int32(arrItemTemp) + arr = append(arr, arrItem) + } + + plusMinus(arr) +} + +func readLine(reader *bufio.Reader) string { + str, _, err := reader.ReadLine() + if err == io.EOF { + return "" + } + + return strings.TrimRight(string(str), "\r\n") +} + +func checkError(err error) { + if err != nil { + panic(err) + } +} From fb7a95f295e3d4bd1af2bfe12c77e104e3c6a506 Mon Sep 17 00:00:00 2001 From: Eliot Wong Date: Tue, 15 Oct 2019 19:07:10 +0200 Subject: [PATCH 044/324] Add solution for 'Maximum Element' in Java --- Hackerrank/Java/MaximumElement.java | 58 +++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Hackerrank/Java/MaximumElement.java diff --git a/Hackerrank/Java/MaximumElement.java b/Hackerrank/Java/MaximumElement.java new file mode 100644 index 00000000..c4d3547d --- /dev/null +++ b/Hackerrank/Java/MaximumElement.java @@ -0,0 +1,58 @@ +// Author: Sai Kiran +// URL: https://www.hackerrank.com/challenges/maximum-element/problem +import java.io.*; +import java.util.*; + +public class Solution { + + static class Stack { + static Deque stack = new ArrayDeque(); + static Deque maxValues = new ArrayDeque(); + + public static void push(int x) { + stack.push(x); + + if (maxValues.isEmpty() || maxValues.peek() <= x) { + maxValues.push(x); + } + } + + public static int getMax() { + return maxValues.peek(); + } + + public static void pop() { + if (stack.isEmpty()) return; + + int ret = stack.pop(); + + if (ret == maxValues.peek()) { + maxValues.pop(); + } + } + } + + public static void main(String[] args) { + /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ + + try { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String line = br.readLine(); + int N = Integer.parseInt(line); + + Stack stack = new Stack(); + + for (int i = 0; i < N; i++) { + line = br.readLine(); + if (line.contains(" ")) { + int num = Integer.parseInt(line.split(" ")[1]); + stack.push(num); + } else if (line.equals("2")) { + stack.pop(); + } else { + System.out.println(stack.getMax()); + } + } + } catch (IOException e) {} + } +} From d7117974735c4ce0a92d14c223427c921ff6b520 Mon Sep 17 00:00:00 2001 From: GaganDeepSingla <56605474+GaganDeepSingla@users.noreply.github.com> Date: Wed, 16 Oct 2019 00:03:53 +0530 Subject: [PATCH 045/324] Queue Using Doubly Linked List This Program implements Queue using Doubly Linked List --- DS/C++/Queue with Doubly LL.cpp | 107 ++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 DS/C++/Queue with Doubly LL.cpp diff --git a/DS/C++/Queue with Doubly LL.cpp b/DS/C++/Queue with Doubly LL.cpp new file mode 100644 index 00000000..a5961ff2 --- /dev/null +++ b/DS/C++/Queue with Doubly LL.cpp @@ -0,0 +1,107 @@ +//Queue with Doubly Linked list +#include +using namespace std; +class Node +{ +public: + int data ; + Node *next = NULL; + Node *prev = NULL; + Node(int data) + { + this->data = data ; + } +}; +class Queue +{ + Node* front = NULL; + Node* rear = NULL; + int size = 0 ; + public : + void enqueue(int data) + { + Node *new_node = new Node(data) ; + if(front == NULL) + { + front = new_node; + rear = new_node ; + } + else + { + rear->next = new_node ; + new_node->prev = rear ; + rear = new_node ; + } + size++; + } + void dequeue() + { + if(front == NULL) + { + cout<<"Queue is Already Empty !"<next ; + x->next = NULL ; + x->prev = NULL ; + if(front != NULL) + front->prev = NULL ; + delete x ; + size-- ; + } + } + bool isEmpty() + { + if(size == 0) + return true ; + else + return false ; + } + int Size() + { + return size ; + } + int Front() + { + if(front == NULL || size == 0) + { + cout<<"Queue is Empty"<data ; + } + } + void print() + { + Node *temp = front ; + while(temp != NULL) + { + cout<data<<" "; + temp = temp->next ; + } + cout< Date: Wed, 16 Oct 2019 01:39:21 +0530 Subject: [PATCH 046/324] Rename Queue with Doubly LL.cpp to QueueWithDoublyLL.cpp --- DS/C++/{Queue with Doubly LL.cpp => QueueWithDoublyLL.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DS/C++/{Queue with Doubly LL.cpp => QueueWithDoublyLL.cpp} (100%) diff --git a/DS/C++/Queue with Doubly LL.cpp b/DS/C++/QueueWithDoublyLL.cpp similarity index 100% rename from DS/C++/Queue with Doubly LL.cpp rename to DS/C++/QueueWithDoublyLL.cpp From 4906306c08f22317a53bddbee0b0fb22fc14edaa Mon Sep 17 00:00:00 2001 From: Yenneferr Date: Tue, 15 Oct 2019 20:58:54 -0600 Subject: [PATCH 047/324] added latineSquare code --- Algorithms/C++/Latine Square/LatinSquare.cpp | 118 +++++++++++++++++++ Algorithms/C++/Latine Square/LatinSquare.h | 20 ++++ Algorithms/C++/Latine Square/main.cpp | 8 ++ 3 files changed, 146 insertions(+) create mode 100644 Algorithms/C++/Latine Square/LatinSquare.cpp create mode 100644 Algorithms/C++/Latine Square/LatinSquare.h create mode 100644 Algorithms/C++/Latine Square/main.cpp diff --git a/Algorithms/C++/Latine Square/LatinSquare.cpp b/Algorithms/C++/Latine Square/LatinSquare.cpp new file mode 100644 index 00000000..eba3adbc --- /dev/null +++ b/Algorithms/C++/Latine Square/LatinSquare.cpp @@ -0,0 +1,118 @@ +#include "LatinSquare.h" +#include +#include "Path.h" +using namespace std; + + +LatinSquare::LatinSquare(int n){ + this -> n = n; + m = new int*[n]; + for (int i=0;i i and j and x are: "< +#include "LatinSquare.h" +/* run this program using the console pauser or add your own getch, system("pause") or input loop */ + +int main(int argc, char** argv) { + LatinSquare s(3); + s.calculate(); +} From 6e16dc64877f64244897fc7e09ca61d90ae24ba2 Mon Sep 17 00:00:00 2001 From: Praful932 Date: Wed, 16 Oct 2019 09:58:23 +0530 Subject: [PATCH 048/324] Created Salary.cpp Added solution for codechef problem SALARY. --- Codechef/SALARY.cpp | 47 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Codechef/SALARY.cpp diff --git a/Codechef/SALARY.cpp b/Codechef/SALARY.cpp new file mode 100644 index 00000000..1dcbe9d7 --- /dev/null +++ b/Codechef/SALARY.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; +int main() +{ + // slmax second last maximum + int t,slmax,max,index,it=0,min; + cin>>t; + while(t--) + { + int n,toadd,it=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + sort(a,a+n); + min=a[0]; + while(a[0]!=a[n-1]) + { + // max is last element + max=a[n-1]; + // second last element + index=n-2; + // find second last max + while(a[index]==max) + { + index--; + } + toadd=max-a[index]; + it=it+toadd; + for(int i=0;i Date: Wed, 16 Oct 2019 12:42:27 +0530 Subject: [PATCH 049/324] Added 6 solutions for OCT_LONG_2019 --- Codechef/EVENEDGES.cpp | 234 +++++++++++++++++++++++++++++++ Codechef/MARM.cpp | 38 ++++++ Codechef/MAXLIS(CHALLENGE).cpp | 243 +++++++++++++++++++++++++++++++++ Codechef/MSNG.py | 85 ++++++++++++ Codechef/MSV.cpp | 68 +++++++++ Codechef/SAKTAN.cpp | 41 ++++++ 6 files changed, 709 insertions(+) create mode 100755 Codechef/EVENEDGES.cpp create mode 100755 Codechef/MARM.cpp create mode 100755 Codechef/MAXLIS(CHALLENGE).cpp create mode 100755 Codechef/MSNG.py create mode 100755 Codechef/MSV.cpp create mode 100755 Codechef/SAKTAN.cpp diff --git a/Codechef/EVENEDGES.cpp b/Codechef/EVENEDGES.cpp new file mode 100755 index 00000000..01ac5d59 --- /dev/null +++ b/Codechef/EVENEDGES.cpp @@ -0,0 +1,234 @@ +#include +using namespace std; + +#define ll long long int + +int getPar(int x,int par[]){ + while(x!=par[x]) + x = par[x]; + return x; +} +int find(int x,int y,int par[]) +{ + return ( getPar(x,par) == getPar(y,par) ); +} +int doUnion(int x,int y,int par[],int size[]) +{ + if( find(x,y,par) ) + return -1; + int p1 = getPar(x,par); + int p2 = getPar(y,par); + int s1 = size[p1]; + int s2 = size[p2]; + if( s1 > s2 ) + { + par[p2] = p1; + size[p1] += s2; + } + else + { + par[p1] = p2; + size[p2] += s1; + } + return 1; +} + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n,m; + cin >> n >> m; + + vector< vector > v(n+1); + unordered_map mp; + // init dsu + int par[n+1],size[n+1]; + for(int i=1;i<=n;i++) + { + par[i] = i; + size[i] = 1; + } + + ll B[n+1]={0},A[n+1]={0}, C[n+1]={0}; + set > st; + int first,second; + for(int i=0;i> x >> y; + first = x; + second = y; + // int X = min(x,y); + // int Y = max(x,y); + // if( st.find({X,Y})!=st.end() ) + // continue; + // st.insert({X,Y}); + v[x].push_back(y); + v[y].push_back(x); + // int b = doUnion(x,y,par,size); + A[x]++; + A[y]++; + } + int total = 0; + for(int i=1;i<=n;i++) + { + total += v[i].size(); + } + total /= 2; + // for(int i=0;i<=n;i++) + // A[i] = B[i]+C[i]; + + map > comp; + for(int i=1;i<=n;i++) + { + int p = getPar(i,par); + int size = v[i].size(); + mp[p]+=size; + comp[p].push_back(i); + } + + + int flag=0; + // int count = 0; + // for(auto it=mp.begin();it!=mp.end();it++) + // { + // // cout << it->first << " : " << it->second << endl; + // int edgeInComp = it->second/2; + // if( edgeInComp%2 ) + // count++; + + // } + if( m%2 == 0) + { + // means all the components have even edges. ( so only 1 subraph is required) + cout << 1 << endl; + for(int i=1;i<=n;i++) + cout << 1 << " "; + cout << endl; + } + else + { + + + // need to move 1 node from any one odd component to the other set + // set goToSecond; + // for(auto it=mp.begin();it!=mp.end();it++) + // { + // int edgeInComp = it->second/2; + // if( edgeInComp%2==0 ) + // { + // int p = it->first; + // vector temp = comp[p]; + // for(int i=0;ifirst << " : " << it->second << endl; + // int edgeInComp = it->second/2; + // if( edgeInComp%2 ) + // { + // allSame = 1; + // int p = it->first; + // vector temp = comp[p]; + // for(int i=0;ifirst << " : " << it->second << endl; + // int edgeInComp = it->second/2; + // int flag = 0; + // if( edgeInComp%2 ) + // { + + // int p = it->first; + // vector temp = comp[p]; + // for(int i=0;i +using namespace std; +#define ll long long int + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n,k; + cin >> n >> k; + ll a[n]; + + for(int i=0;i> a[i]; + // k = min(n,k); + + // if( k<=1e6) + // { + for(int i=0;i +using namespace std; + +vector get_K_index(int n,int k) +{ + vector temp; + map mp; + + for(int i=0;i > divide_to_slice(int a[],int n,vector &k_ind) +{ + int size = k_ind.size(); + vector > t(size+1); + for(int i=0;i merge_slices(int a[],int n,vector > &slices) +{ + vector b; + for(int i=0;i &a,int n) +{ + int lis[n]; + lis[0] = 1; + int tail[n]; + tail[0] = a[0]; + int l = 1; + for(int i=1;i A(n); + // cout << "hi"; + for(int i=0;i final_B; + + // if( n>= 5*1e3 ) + // { + // srand(time(0)); + // vector K; + // // k = 3; + // for(int i=0;i final_k; + // vector final_perm; + + // for(int z=0;z<10;z++) + // { + + // // get the k-1 indices to slice the array + // // cout << "choose K-indices: "; + // vector k_ind = get_K_index(n,k); + // // for(int j=0;j > slices = divide_to_slice(a,n,k_ind); + // // cout << "the slices: \n"; + // // for(int i=0;i B = merge_slices(a,n,slices); + // // cout << "The final permutation B: "; + // // for(int i=0;i B; + // for(int i=0;i= La and Lb > M) + // { + // M = Lb; + // final_B = B; + // // final_k = k_ind; + // // final_perm = K; + // } + // loop++; + // if(loop == 10) + // break; + // unsigned seed = 0; + + + // } while (1); + // } + + // cout << "La: " << La << "\nLb: " << M << endl; + // for(int i=0;i V = A; + sort(A.begin()+i,A.begin()+i+k-2); + Lb = LIS(A,n); + if( Lb>=La and Lb>M) + { + M = Lb; + final_B = A; + + } + A = V; + + } + // cout << "La: " << La << "\nLb: " << M << endl; + for(int i=0;i rand_ind; + unordered_map mp; + // cout << "hi"; + for(int i=0;i<100;i++) + { + int r = rand()%(n-k); + while(mp.find(r)!=mp.end() ) + r = rand()%(n-k); + + mp[r] = 1; + rand_ind.push_back(r); + + + } + // for(int i=0;i<100;i++) + // cout << rand_ind[i] << " "; + // cout << endl; + for(int i=0;i<80;i++) + { + vector V = A; + sort(A.begin()+rand_ind[i],A.begin()+rand_ind[i]+k-2); + Lb = LIS(A,n); + if( Lb>=La and Lb>M) + { + M = Lb; + final_B = A; + + } + A = V; + + } + // cout << "La: " << La << "\nLb: " << M << endl; + for(int i=0;i='A' and ch<='Z': + val = ord(ch) - 55 + else: + val = ord(ch) - 48 + + if val>=base: + return -1 + + sum = sum + val * (base**l) + if sum > threshold: + return -1 + l += 1 + return sum + +t = int(input()) +for z in range(t): + n = int(input()) + table = [] + d = {} + for i in range(n): + base, s = input().split() + # print(base , s) + base = int(base) + if base == -1: + j = 2 + temp = [] + local = {} + while j<=36: + num = toDecimal(j,s) + if num!=-1 and num not in local: + local[num] = 1 + # temp.append(num) + if num not in d: + d[num] = 1 + else: + d[num] += 1 + j+=1 + # table.append(temp) + else: + temp = [] + num = toDecimal(base,s) + local = {} + if num!=-1 and num not in local: + local[num] = 1 + # temp.append(num) + if num not in d: + d[num] = 1 + else: + d[num] += 1 + # table.append(temp) + + M = 10**14 + # for i in table: + # for j in i: + # ser = j + # count = 0 + # for k in table: + # for l in k: + # if l == ser: + # count+=1 + + # if count == n: + # if ser < M: + # M = ser + + ans = -1 + for k in sorted(d.keys()): + # print(k,d[k]) + if d[k] == n: + ans = k + break + + # if M <= threshold: + # ans = M + print(ans) \ No newline at end of file diff --git a/Codechef/MSV.cpp b/Codechef/MSV.cpp new file mode 100755 index 00000000..3c469bf1 --- /dev/null +++ b/Codechef/MSV.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; +#define ll long long int + +unordered_map mp; +void factor(int x) +{ + for(int i=1;i<=sqrt(x);i++) + { + if( x%i == 0) + { + if( x/i == i ) + mp[i]++; + else + { + mp[i]++; + mp[x/i]++; + } + } + } +} + +int main() +{ + int t; + cin >> t; + while(t--) + { + int n; + cin >> n ; + int a[n]; + for(int i=0;i> a[i]; + int star[n]; + star[0] = 0; + for(int i=0;i " << endl; + // for(auto it=mp.begin();it!=mp.end();it++) + // cout << it->first << ": " << it->second << endl; + // cout << endl; + } + // cout << "star values:-> "; + // for(int i=0;i M) + { + M = star[i]; + ind = i; + } + } + cout << M << endl; + mp.clear(); + } +} \ No newline at end of file diff --git a/Codechef/SAKTAN.cpp b/Codechef/SAKTAN.cpp new file mode 100755 index 00000000..92e00ba1 --- /dev/null +++ b/Codechef/SAKTAN.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; +#define ll long long int + +int main() +{ + int t; + cin >> t; + while(t--) + { + ll n,m,q; + cin >> n >> m >> q; + ll a[n+1]={0},b[m+1]={0}; + for(int i=0;i> x >> y ; + b[y] += 1; + a[x] += 1; + + } + ll o=0,e=0; + for(int i=1;i<=n;i++) + { + if( a[i]%2) + o++; + else + e++; + } + ll ans = 0; + for(int i=1;i<=m;i++) + { + if( b[i]%2) + ans += e; + else + ans += o; + } + cout << ans << endl; + + } +} \ No newline at end of file From f2666582a2602f0fd82cfb9b7ae2eca023ec0107 Mon Sep 17 00:00:00 2001 From: Sakina Rao <41284051+sakinarao@users.noreply.github.com> Date: Wed, 16 Oct 2019 14:58:23 +0530 Subject: [PATCH 050/324] Added Shortest Job First Scheduling Algorithm --- Algorithms/Java/sjf.java | 243 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 Algorithms/Java/sjf.java diff --git a/Algorithms/Java/sjf.java b/Algorithms/Java/sjf.java new file mode 100644 index 00000000..4b2d8e45 --- /dev/null +++ b/Algorithms/Java/sjf.java @@ -0,0 +1,243 @@ +import java.util.*; +import java.util.Scanner; +import java.io.*; + +class Process /*implements Comparable*/ +{ + int arr_t, bur_t, comp_t, tat, wait_t, flag, bur_t2, st_t; + int pro_id; + + public Process(int pro_id , int arr_t, int bur_t){ + this.pro_id = pro_id; + this.arr_t = arr_t; + this.bur_t = bur_t; + this.flag=0; + this.bur_t2 = this.bur_t; + } + + /*public int compareTo(Process m) + { + return this.arr_t - m.arr_t; + } */ + + public int getArrTime() { return arr_t; } + + public int getStartTime() { return st_t; } +} + +class Order +{ + int pro_id, st_t, end_t; + + public Order(int pro_id , int st_t, int end_t){ + this.pro_id = pro_id; + this.st_t = st_t; + this.end_t = end_t; + } +} + +class ArrTimeCompare implements Comparator +{ + public int compare(Process p1, Process p2) + { + if (p1.getArrTime() < p2.getArrTime()) return -1; + if (p1.getArrTime() > p2.getArrTime()) return 1; + else return 0; + } +} + +class StartTimeCompare implements Comparator +{ + public int compare(Process p1, Process p2) + { + if (p1.getStartTime() < p2.getStartTime()) return -1; + if (p1.getStartTime() > p2.getStartTime()) return 1; + else return 0; + } +} + +public class sjf +{ + static void nonPreEmptive(List p, int n){ + System.out.println("Non-preemptive version"); + //boolean a = true; + int st=0, tot=0; + float avgwt=0, avgta=0; + while(true) + { + int c=n, min=999; + if (tot == n) // total no of process = completed process loop will be terminated + break; + + for (int i=0; i p, int n){ + System.out.println("Preemptive version"); + List o = new ArrayList(); + int i, st=0, tot=0; + float avgwt=0, avgta=0; + int pre_c = n; + int idle = 0; + while(true){ + int min = 999, c = n; + if (tot == n) + break; + + for (i=0; i p = new ArrayList(); + //Process p[] = new Process[n]; + System.out.print("\nEnter the arrival time and burst time of each process::\n"); + for(int i=0;i Date: Wed, 16 Oct 2019 17:31:27 +0530 Subject: [PATCH 051/324] first commit --- HelloWorld/hello.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/HelloWorld/hello.c b/HelloWorld/hello.c index 059c5a0f..50216b96 100644 --- a/HelloWorld/hello.c +++ b/HelloWorld/hello.c @@ -2,6 +2,7 @@ int main() { - printf("Hello World!\n"); + printf("Hello world!\n"); + printf("Happy Hacking!\n"); return 0; } From f04b299c72931903b3b721679ed0594fbafc90f0 Mon Sep 17 00:00:00 2001 From: FILIPI ENZO SIQUEIRA KIKUCHI Date: Wed, 16 Oct 2019 10:41:06 -0300 Subject: [PATCH 052/324] Add Tetrahedron solution --- Codeforces/166E.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Codeforces/166E.cpp diff --git a/Codeforces/166E.cpp b/Codeforces/166E.cpp new file mode 100644 index 00000000..4fa3555e --- /dev/null +++ b/Codeforces/166E.cpp @@ -0,0 +1,26 @@ +#include +#define MAX 10000001 +#define moduloN % 1000000007 +using namespace std; + +unsigned long long n; +unsigned long long toD[MAX]; +unsigned long long toAny[MAX]; + +unsigned long long tetrahedron(unsigned long long x) +{ + toD[0] = 1; + toAny[0] = 0; + for (unsigned long long i = 1; i <= x; i++) + { + toD[i] = (toAny[i - 1] * 3) moduloN; + toAny[i] = ((toAny[i - 1] * 2) + toD[i - 1]) moduloN; + } + return toD[x]; +} + +int main(void) +{ + cin >> n; + cout << tetrahedron(n); +} \ No newline at end of file From fe1129d38ab5f6ed815ed3499a603a2cba0c183c Mon Sep 17 00:00:00 2001 From: Pedro Vieira <46421895+PedrV@users.noreply.github.com> Date: Wed, 16 Oct 2019 17:54:24 +0100 Subject: [PATCH 053/324] Create fibonacci.c --- Algorithms/C/fibonacci.c | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Algorithms/C/fibonacci.c diff --git a/Algorithms/C/fibonacci.c b/Algorithms/C/fibonacci.c new file mode 100644 index 00000000..97f88d94 --- /dev/null +++ b/Algorithms/C/fibonacci.c @@ -0,0 +1,15 @@ +#include + +int main() { + int i, n, t = 0, t1 = 1, nextTerm; + printf("Enter the number of terms: "); + scanf("%d", &n); + printf("Fibonacci Series: "); + for (i = 1; i <= n; ++i) { + printf("%d, ", t); + nextTerm = t + t1; + t = t1; + t1 = nextTerm; + } + return 0; +} From cb3244580b18b86f816821e56055e7275c388381 Mon Sep 17 00:00:00 2001 From: Tayyab-Asghar Date: Wed, 16 Oct 2019 22:40:10 +0500 Subject: [PATCH 054/324] Number to English converter --- Algorithms/C++/Num_to_English.cpp | 341 ++++++++++++++++++++++++++++++ 1 file changed, 341 insertions(+) create mode 100644 Algorithms/C++/Num_to_English.cpp diff --git a/Algorithms/C++/Num_to_English.cpp b/Algorithms/C++/Num_to_English.cpp new file mode 100644 index 00000000..da20b4cd --- /dev/null +++ b/Algorithms/C++/Num_to_English.cpp @@ -0,0 +1,341 @@ +//convert the input number into the letters +#include +#include +using namespace std; + + +//Add a string +string addString(string str, string add) +{ + + string s=""; +/* s+=add; + s+=" "; + s+=str;*/ + for(int i=0;add[i]!='\0';i++) + { + s+=add[i]; + } + s+=" "; + for(int i=0;str[i]!='\0';i++) + { + s+=str[i]; + } + return s; + +} + +//Convert the hundredth terms into the corresponding letters +string hunDigToLetter(string str, int num) +{ + int r; + r=num%10; + if(r!=0) + { + str = addString( str, "Hundred"); + switch (r) + { + case 1: + str= addString(str , "One"); + break; + case 2: + str= addString(str , "Two"); + break; + case 3: + str= addString(str , "Three"); + break; + case 4: + str= addString(str , "Four"); + break; + case 5: + str= addString(str , "Five"); + break; + case 6: + str= addString(str , "Six"); + break; + case 7: + str= addString(str , "Seven"); + break; + case 8: + str= addString(str , "Eight"); + break; + case 9: + str= addString(str , "Nine"); + break; + default: + break; + } + } + return str; +} + +//Convert the ones term into corresponding letters +string onesDigToLetter(string str, int num) +{ + int r; + r=num%10; + if((num/10)%10==1) + { + switch (r) + { + case 0: + str= addString(str , "Ten"); + break; + + case 1: + str= addString(str , "Eleven"); + break; + case 2: + str= addString(str , "Twelve"); + break; + case 3: + str= addString(str , "Thirteen"); + break; + case 4: + str= addString(str , "Fourteen"); + break; + case 5: + str= addString(str , "Fifteen"); + break; + case 6: + str= addString(str , "Sixteen"); + break; + case 7: + str= addString(str , "Seventeen"); + break; + case 8: + str= addString(str , "Eighteen"); + break; + case 9: + str= addString(str , "Nineteen"); + break; + default: + break; + } + } + else + { + + switch (r) + { + case 1: + str= addString(str , "One"); + break; + case 2: + str= addString(str , "Two"); + break; + case 3: + str= addString(str , "Three"); + break; + case 4: + str= addString(str , "Four"); + break; + case 5: + str= addString(str , "Five"); + break; + case 6: + str= addString(str , "Six"); + break; + case 7: + str= addString(str , "Seven"); + break; + case 8: + str= addString(str , "Eight"); + break; + case 9: + str= addString(str , "Nine"); + break; + default: + break; + } + } + return str; + +} + +//Convert the tens term into corresponding letters +string tensDigToLetter(string str, int num) +{ + int r; + r=num%10; + switch (r) + { + case 2: + str= addString(str , "Twenty"); + break; + case 3: + str= addString(str , "Thirty"); + break; + case 4: + str= addString(str , "Forty"); + break; + case 5: + str= addString(str , "Fifty"); + break; + case 6: + str= addString(str , "Sixty"); + break; + case 7: + str= addString(str , "Seventy"); + break; + case 8: + str= addString(str , "Eighty"); + break; + case 9: + str= addString(str , "Ninety"); + break; + default: + break; + } + return str; +} + +int main () +{ + long long num ; + string str=""; + cout<<"Enter the number to convert it into English but the number must be less than 1 billion:\n"; + cin>>num; + if(num<1000000000) //convert numbers less than 1 billion + { + + // cout< Date: Wed, 16 Oct 2019 10:44:49 -0700 Subject: [PATCH 055/324] added GDSUB problem solution of SEPT19B --- Codechef/GDSUB.py | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Codechef/GDSUB.py diff --git a/Codechef/GDSUB.py b/Codechef/GDSUB.py new file mode 100644 index 00000000..3da89c16 --- /dev/null +++ b/Codechef/GDSUB.py @@ -0,0 +1,41 @@ +# author name: namanbansal013 + +def multiply(A, B, m, n): + + prod = [0] * (m + n - 1); + + # Multiply two polynomials term by term + + # Take ever term of first polynomial + for i in range(m): + + # Multiply the current term of first + # polynomial with every term of + # second polynomial. + for j in range(n): + prod[i + j] += A[i] * B[j]; + + return prod; + + +s1=[int(i) for i in input().split()] +n,k=s1[0],s1[1] +s2=[int(j) for j in input().split()] +s3=[] +s3=list(set(s2)) +s4=[] +if(k==0): + print(1) +elif(k==1): + print(n+1) +elif(k>=2): + for c in range(0,len(s3)): + s4.append(s2.count(s3[c])) + p=[s4[0],1] + for d in range(1,len(s4)): + e=[s4[d],1] + p=multiply(p, e, len(p), 2) + if len(s4)>k: + print((sum(p[len(s3)-k:]))%1000000007) + else: + print(sum(p)%1000000007) From 8f535e4d90697cee25ee512e52c005ccdab155cc Mon Sep 17 00:00:00 2001 From: Tayyab-Asghar Date: Wed, 16 Oct 2019 23:00:07 +0500 Subject: [PATCH 056/324] A simple arithmetic calculator --- .vscode/settings.json | 5 ++++ Algorithms/C++/Simple_Calculator.cpp | 41 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 .vscode/settings.json create mode 100644 Algorithms/C++/Simple_Calculator.cpp diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..27f2cfdf --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,5 @@ +{ + "files.associations": { + "ios": "cpp" + } +} \ No newline at end of file diff --git a/Algorithms/C++/Simple_Calculator.cpp b/Algorithms/C++/Simple_Calculator.cpp new file mode 100644 index 00000000..5c9b44e1 --- /dev/null +++ b/Algorithms/C++/Simple_Calculator.cpp @@ -0,0 +1,41 @@ +//This program performs basic arithmetic operations +//Defining simple calculator +#include + +using namespace std; +//Defining function for arithmetic operations +float operation(float num1, float num2, char oper) +{ + while (true) + { + if (oper == '+') return num1 + num2; + if (oper == '-') return num1 - num2; + if (oper == '*') return num1 * num2; + if (oper == '/') return num1 / num2; + cout << "!!wrong operator!!\nSelect one from the following (+,-,*,/) : "; + cin >> oper; + } +} + +int main() +{ + float op1, op2, result; + char oper; + cout << "The program is calculator of basic calculations "; + cout << "Enter '+' for Addition\n"; + cout << "Enter '-' for Subtraction\n"; + cout << "Enter '*' for Multiplication\n"; + cout << "Enter '/' for Division\n"; + + cout << "\nEnter 1st Operand : "; + cin >> op1; + cout << "\nEnter 2nd Operand : "; + cin >> op2; + cout << "\nEnter operator : "; + cin >> oper; + result = operation(op1, op2, oper); + + cout << "This result of integer expression is : " << result << endl; + system("pause"); + return 0; +} \ No newline at end of file From 27ccc499371c5dc71bd93a9eb8935917d011334c Mon Sep 17 00:00:00 2001 From: CrisCrawford Date: Wed, 16 Oct 2019 20:09:27 -0600 Subject: [PATCH 057/324] Added algorithm for frequency analysis! --- Algorithms/C++/Frequency_Analysis.cpp | 29 +++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Algorithms/C++/Frequency_Analysis.cpp diff --git a/Algorithms/C++/Frequency_Analysis.cpp b/Algorithms/C++/Frequency_Analysis.cpp new file mode 100644 index 00000000..ca582f12 --- /dev/null +++ b/Algorithms/C++/Frequency_Analysis.cpp @@ -0,0 +1,29 @@ +/*Decrypting caesar cipher with frecuency analysis the principle of the fecuency analysis is knowing which is the most used letter on a a text given +after 'e' er the most common letter on the english language*/ +#include +#include +using namespace std; + +int main(){ + char sentence[30]; + int count = 1; + + cout << "Write a message: "; + cin.getline(sentence, 30); + + for(int i = 1; i < sentence[i]; i++) + { + for(int j = i + 1; j < sentence[i]; j++) + { + if(sentence[i] == sentence[j]){ + count++; + sentence[j] = 0; + } + } + cout << sentence[i] << " appeared: " << count << " Times" << endl; + count = 1; + } +} + +/*Knowing the most common letter on our message we can now count many spaces there are +between e and the most common letter, this number is possibly the key.*/ \ No newline at end of file From d9313283ea10988194a101728c9b4a09ab4724db Mon Sep 17 00:00:00 2001 From: xoltia <38849891+xoltia@users.noreply.github.com> Date: Wed, 16 Oct 2019 21:37:55 -0500 Subject: [PATCH 058/324] Add C implementation of a queue --- DS/C/queue.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 DS/C/queue.c diff --git a/DS/C/queue.c b/DS/C/queue.c new file mode 100644 index 00000000..341414cf --- /dev/null +++ b/DS/C/queue.c @@ -0,0 +1,57 @@ +#include +#include + +typedef int Value; + +typedef struct Node { + struct Node* previous; + struct Node* next; + Value value; +} Node; + +typedef struct { + Node* head; + Node* tail; +} Queue; + +int is_empty(Queue* queue) +{ + return queue->head == NULL && queue->tail == NULL; +} + +void enqueue(Queue* queue, Value value) { + Node* node = malloc(sizeof(Node)); + Node* head = queue->head; + node->value = value; + node->next = head; + node->previous = NULL; + + if (head != NULL) { + head->previous = node; + } + if (is_empty(queue)) { + queue->tail = node; + } + queue->head = node; +} + +Value dequeue(Queue* queue) { + Value value = queue->tail->value; + Node* tail = queue->tail; + if (queue->tail == queue->head) { + queue->tail = NULL; + queue->head = NULL; + } else { + queue->tail = queue->tail->previous; + } + free(tail); + return value; +} + +Queue* init_queue() +{ + Queue* queue = malloc(sizeof(Queue)); + queue->head = NULL; + queue->tail = NULL; + return queue; +} From 89b86e4388eb8aee2f07405d927a564921721dcd Mon Sep 17 00:00:00 2001 From: Kevva9844 Date: Thu, 17 Oct 2019 12:46:43 +0530 Subject: [PATCH 059/324] first commit --- HelloWorld/helloHack.c | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 HelloWorld/helloHack.c diff --git a/HelloWorld/helloHack.c b/HelloWorld/helloHack.c new file mode 100644 index 00000000..93b31ba6 --- /dev/null +++ b/HelloWorld/helloHack.c @@ -0,0 +1,7 @@ +#include + +int main() +{ + printf("Hello Hactoberfest 2019\n"); + return 0; +} From 8cb1e254c570d88c7c7821334d635bb4ff0418e5 Mon Sep 17 00:00:00 2001 From: Deepam101 <50206813+Deepam101@users.noreply.github.com> Date: Thu, 17 Oct 2019 13:18:08 +0530 Subject: [PATCH 060/324] Create ALTARAY.java --- Codechef/ALTARAY.java | 45 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Codechef/ALTARAY.java diff --git a/Codechef/ALTARAY.java b/Codechef/ALTARAY.java new file mode 100644 index 00000000..1d80c0f1 --- /dev/null +++ b/Codechef/ALTARAY.java @@ -0,0 +1,45 @@ +import java.util.*; +class DP +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int t=sc.nextInt(); + if(t>10 || t<1) + { + return ; + } + for(int i=1;i<=t;i++) + { + int n=sc.nextInt(); + if(n<1 || n>100000) + return; + long a[]=new long[n]; + for(int j=0;j(long)Math.pow(10,9) || a[j]<-(long)Math.pow(10,9)) + return; + } + int length[]=new int[n]; + length[n-1]=1; + count(a,length,a.length-2); + for(int j=0;j0) + length[i]=1; + count(a,length,i-1); + } +} + \ No newline at end of file From 0be93f321b2ddf8fe66e46edb1e8d2acf644cbc5 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Thu, 17 Oct 2019 14:53:38 +0530 Subject: [PATCH 061/324] Delete settings.json --- .vscode/settings.json | 5 ----- 1 file changed, 5 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 27f2cfdf..00000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "files.associations": { - "ios": "cpp" - } -} \ No newline at end of file From a1624be6f8cc79330befe7cf2b766953757f26f9 Mon Sep 17 00:00:00 2001 From: Indrajeet Ratnakar <37216430+IJRatnakar@users.noreply.github.com> Date: Thu, 17 Oct 2019 15:06:12 +0530 Subject: [PATCH 062/324] Create 1195B.cpp --- Codeforces/1195B.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Codeforces/1195B.cpp diff --git a/Codeforces/1195B.cpp b/Codeforces/1195B.cpp new file mode 100644 index 00000000..89efd3df --- /dev/null +++ b/Codeforces/1195B.cpp @@ -0,0 +1,22 @@ +#include +#include +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +using namespace std; + + +int main() +{ + FastRead + ll n,k,t,ans; + cin>>n>>k; + t=sqrt(8*n+8*k+9); + if(2*n+3>=t) + ans=((2*n+3)-t)/2; + else + ans=((2*n+3)+t)/2; + +cout< Date: Thu, 17 Oct 2019 15:07:21 +0530 Subject: [PATCH 063/324] Create 1169A.cpp --- Codeforces/1169A.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Codeforces/1169A.cpp diff --git a/Codeforces/1169A.cpp b/Codeforces/1169A.cpp new file mode 100644 index 00000000..a023968b --- /dev/null +++ b/Codeforces/1169A.cpp @@ -0,0 +1,36 @@ +#include +#include +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +using namespace std; + + +int main() +{ + FastRead + int n,a,x,b,y; + cin>>n>>a>>x>>b>>y; + + while(a!=x && b!=y) + { + + if(a1) + b--; + else + b=n; + //cout< Date: Thu, 17 Oct 2019 15:08:26 +0530 Subject: [PATCH 064/324] Create 1143A.cpp --- Codeforces/1143A.cpp | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Codeforces/1143A.cpp diff --git a/Codeforces/1143A.cpp b/Codeforces/1143A.cpp new file mode 100644 index 00000000..f7a82222 --- /dev/null +++ b/Codeforces/1143A.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +#define MAXN 100001 + + + + int main() + { + FastRead + + ll n,i; + cin>>n; + ll a[n],x=1,y=1; + for(i=0;i>a[i]; + if(a[i]==0) + x=i+1; + else + if(a[i]==1) + y=i+1; + } + cout< Date: Thu, 17 Oct 2019 15:09:21 +0530 Subject: [PATCH 065/324] Create 60A.cpp --- 60A.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 60A.cpp diff --git a/60A.cpp b/60A.cpp new file mode 100644 index 00000000..f4a33d41 --- /dev/null +++ b/60A.cpp @@ -0,0 +1,39 @@ +#include +#include +using namespace std; +#define ll long long int +#define FastRead ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr); +#define MAXN 100001 + + int main() + { + FastRead + + ll n,m,i,j,k; + cin>>n>>m; + string p,s; + int t; + i=1,j=n; + while(m--) + { + cin>>p>>p>>s>>p>>t; + if(s=="left") + { + if(j>t-1) + j=t-1; + } + else + if(s=="right") + { + if(ij) + cout<<-1; + else + cout< Date: Fri, 18 Oct 2019 11:11:55 +0530 Subject: [PATCH 066/324] I added a Backtracking algorithm in python Permutation with backtracking --- Algorithms/Python/Backtracking.py | 35 +++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Algorithms/Python/Backtracking.py diff --git a/Algorithms/Python/Backtracking.py b/Algorithms/Python/Backtracking.py new file mode 100644 index 00000000..3ff477ce --- /dev/null +++ b/Algorithms/Python/Backtracking.py @@ -0,0 +1,35 @@ +def A_n_k(a, n, k, depth, used, curr, ans): + ''' + Implement permutation of k items out of n items + depth: start from 0, and represent the depth of the search + used: track what items are in the partial solution from the set of n + curr: the current partial solution + ans: collect all the valide solutions + ''' + if depth == k: #end condition + ans.append(curr[::]) # use deepcopy because curr is tracking all partial solution, it eventually become [] + return + + for i in range(n): + if not used[i]: + # generate the next solution from curr + curr.append(a[i]) + used[i] = True + print(curr) + # move to the next solution + A_n_k(a, n, k, depth+1, used, curr, ans) + + #backtrack to previous partial state + curr.pop() + print('backtrack: ', curr) + used[i] = False + return + +a = list(map(int, input("Enter the numbers = ").split())) +n = len(a) +ans = [] +used = [False] * len(a) +ans = [] +A_n_k(a, n, n, 0, used, [], ans) +print(ans) + From 1e87005b231f106cd77ba20a45372eabee445b99 Mon Sep 17 00:00:00 2001 From: notayushsonare <47273459+notayushsonare@users.noreply.github.com> Date: Fri, 18 Oct 2019 11:38:31 +0530 Subject: [PATCH 067/324] Python script for getting magnetic links of movies and tvshows Give the movie or tvshow name. If it is available on the website it will give you different Torrent links for you to download. Prerequisite : Bit torrent on your device. --- HelloWorld/movies_tvshows.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 HelloWorld/movies_tvshows.py diff --git a/HelloWorld/movies_tvshows.py b/HelloWorld/movies_tvshows.py new file mode 100644 index 00000000..7519e437 --- /dev/null +++ b/HelloWorld/movies_tvshows.py @@ -0,0 +1,14 @@ +from selenium import webdriver +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.common.by import By +import time +c=2 +driver=webdriver.Chrome(r"C:\Users\Ayush\.spyder-py3/chromedriver") +driver.get("https://www.pirateproxy.space/") +search= driver.find_element_by_xpath("//input[@name='q']") +TVshow=input("Enter a movie or tv show") +search.send_keys(TVshow) +enter=driver.find_element_by_xpath("//input[@type='submit' and @title='Pirate Search']") +enter.click() From 36058af3a166b1cd890b7b11b056f963f65e7f62 Mon Sep 17 00:00:00 2001 From: xarielx Date: Fri, 18 Oct 2019 03:01:06 -0400 Subject: [PATCH 068/324] Added game of like solution in cpp with explanations --- LeetCode/game-of-life.cpp | 59 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 LeetCode/game-of-life.cpp diff --git a/LeetCode/game-of-life.cpp b/LeetCode/game-of-life.cpp new file mode 100644 index 00000000..753b17d8 --- /dev/null +++ b/LeetCode/game-of-life.cpp @@ -0,0 +1,59 @@ +class Solution { +public: + void gameOfLife(vector>& board) { + // Neighbors array to find 8 neighboring cells for a given cell + int neighbors[3] = { 0, 1, -1 }; + + int rows = board.size(); + int cols = board[0].size(); + + // Iterate through board cell by cell. + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + + // For each cell count the number of live neighbors. + int liveNeighbors = 0; + + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + + if (!(neighbors[i] == 0 && neighbors[j] == 0)) { + int r = (row + neighbors[i]); + int c = (col + neighbors[j]); + + // Check the validity of the neighboring cell. + // and whether it was originally a live cell. + if ((r < rows && r >= 0) && (c < cols && c >= 0) && (abs(board[r][c]) == 1)) { + liveNeighbors += 1; + } + } + } + } + + // Rule 1 or Rule 3 + if ((board[row][col] == 1) && (liveNeighbors < 2 || liveNeighbors > 3)) { + // -1 signifies the cell is now dead but originally was live. + board[row][col] = -1; + } + // Rule 4 + if (board[row][col] == 0 && liveNeighbors == 3) { + // 2 signifies the cell is now live but was originally dead. + board[row][col] = 2; + } + } + } + + // Get the final representation for the newly updated board. + for (int row = 0; row < rows; row++) { + for (int col = 0; col < cols; col++) { + if (board[row][col] > 0) { + board[row][col] = 1; + } + else { + board[row][col] = 0; + } + } + } + + } +}; \ No newline at end of file From a7c35e9aa589f8a6b387d645941fa12c67b508f1 Mon Sep 17 00:00:00 2001 From: xarielx Date: Fri, 18 Oct 2019 03:02:09 -0400 Subject: [PATCH 069/324] Added game of like solution in cpp with explanations --- LeetCode/game-of-life.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/game-of-life.cpp b/LeetCode/game-of-life.cpp index 753b17d8..35369dd8 100644 --- a/LeetCode/game-of-life.cpp +++ b/LeetCode/game-of-life.cpp @@ -40,7 +40,7 @@ class Solution { // 2 signifies the cell is now live but was originally dead. board[row][col] = 2; } - } + } } // Get the final representation for the newly updated board. From 92291b9aae4a3dd1cc4f06a0d8abc58ae8053772 Mon Sep 17 00:00:00 2001 From: A-STAR0 <43991558+A-STAR0@users.noreply.github.com> Date: Fri, 18 Oct 2019 13:24:51 +0530 Subject: [PATCH 070/324] Create Jim and the orders.c --- Jim and the orders.c | 59 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Jim and the orders.c diff --git a/Jim and the orders.c b/Jim and the orders.c new file mode 100644 index 00000000..3423c163 --- /dev/null +++ b/Jim and the orders.c @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + int n,min; + scanf("%d",&n); + int order[n],prep[n],sum[n],fal[n],cu[n]; + for(int i=0;isum[k+1]) + { + temp=sum[k]; + sum[k]=sum[k+1]; + sum[k+1]=temp; + } + } + } + int v=0; + cu[v]=sum[0]; + for(int c=0;c<=n-2;c++) + { + if(sum[c]==sum[c+1]) + cu[v]=sum[c+1]; + else + { + v++; + cu[v]=sum[c+1]; + } + } + for(int g=0;g<=v;g++) + { + for(int f=0;f Date: Fri, 18 Oct 2019 14:22:36 +0530 Subject: [PATCH 071/324] Create hello world --- HelloWorld/hello world | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 HelloWorld/hello world diff --git a/HelloWorld/hello world b/HelloWorld/hello world new file mode 100644 index 00000000..50216b96 --- /dev/null +++ b/HelloWorld/hello world @@ -0,0 +1,8 @@ +#include + +int main() +{ + printf("Hello world!\n"); + printf("Happy Hacking!\n"); + return 0; +} From 658cc9f92408108f470be62bdf83fdaf023598db Mon Sep 17 00:00:00 2001 From: Ahsan Farid Date: Fri, 18 Oct 2019 16:16:56 +0500 Subject: [PATCH 072/324] stack in c++ --- Algorithms/C++/stack.cpp | 72 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Algorithms/C++/stack.cpp diff --git a/Algorithms/C++/stack.cpp b/Algorithms/C++/stack.cpp new file mode 100644 index 00000000..7f123603 --- /dev/null +++ b/Algorithms/C++/stack.cpp @@ -0,0 +1,72 @@ +#include +using namespace std; + +class node{ + public: + node *next; + int value; +}; + +class stack{ + node *head; + node *tail; + public: + stack(){ + head=NULL; + tail=NULL; + } + void push(int data){ + node *ptr=new node; + ptr->value=data; + ptr->next=NULL; + if(head==NULL){ + head=ptr; + tail=ptr; + } + else{ + tail->next=ptr; + tail=ptr; + } + } +// pop function started from here + + + void pop(){ + node *prev,*forward; + prev=head; + forward=head->next; + + if(head!=NULL){ + while(forward->next!=NULL){ + prev=prev->next; + forward=forward->next; + } + tail=prev; + prev->next=NULL; + + delete(forward); + } + else{ + cout<<"list is empty"<value<next; + } + } +}; +int main() +{ + stack st; + st.push(23); + st.push(25); + st.push(35); + + st.display(); + return 0; +} + From e6ebf38df051a3b98a963c1e1875610627723408 Mon Sep 17 00:00:00 2001 From: Ahsan Farid Date: Fri, 18 Oct 2019 16:27:05 +0500 Subject: [PATCH 073/324] Queue in c++ --- Algorithms/C++/Queue.cpp | 68 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 Algorithms/C++/Queue.cpp diff --git a/Algorithms/C++/Queue.cpp b/Algorithms/C++/Queue.cpp new file mode 100644 index 00000000..711c4040 --- /dev/null +++ b/Algorithms/C++/Queue.cpp @@ -0,0 +1,68 @@ +#include +using namespace std; + +class node{ + public: + node *next; + int value; +}; + +class que{ + node *head; + node *tail; + public: + que(){ + head=NULL; + tail=NULL; + } + void push(int data){ + node *ptr=new node; + ptr->value=data; + ptr->next=NULL; + if(head==NULL){ + head=ptr; + tail=ptr; + } + else{ + tail->next=ptr; + tail=ptr; + } + } +// pop function started from here + + + void pop(){ + node *prev,*forward; + prev=head; + forward=head->next; + if(head!=NULL){ + head=head->next; + delete(prev); + + } + else{ + cout<<"list is empty"<value<next; + } + cout< Date: Fri, 18 Oct 2019 16:42:19 +0500 Subject: [PATCH 074/324] New file(circular linklist) added --- Algorithms/C++/Circularlinklist.cpp | 123 ++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 Algorithms/C++/Circularlinklist.cpp diff --git a/Algorithms/C++/Circularlinklist.cpp b/Algorithms/C++/Circularlinklist.cpp new file mode 100644 index 00000000..353d5aa5 --- /dev/null +++ b/Algorithms/C++/Circularlinklist.cpp @@ -0,0 +1,123 @@ +#include +using namespace std; +class node{ + public: + int data; + node* next; + node* previous; +}; +class DLL{ + public: + node* head; + node* tail; + DLL() + { + head=NULL; + tail=NULL; + } + void insert(int d) + { + node* ptr; + ptr=head; + node* nptr=new node; + nptr->data=d; + nptr->next=NULL; + nptr->previous=NULL; + if(head==NULL) + { + head=nptr; + tail=head; + } + else + { + tail->next=nptr; + nptr->previous=tail; + nptr->next=head; + tail=nptr; + } + } + void print() + { + node* ptr; + ptr=head; + while(ptr->next!=head) + { + cout<<"THE VALUE INSERTED IS:"<data<next; + + } + cout<<"THE VALUE INSERTED IS:"<data<next!=head) + { + if(ptr->data==s) + { + cout<<"THE VALUE IS FOUND"<next; + } + if(ptr->data==s) + { + cout<<"THE VALUE IS FOUND"<>pos; + s = head; + if(pos == 1) { + count--; + tail->next = s->next; + s->next->previous = tail; + head = s->next; + delete(s); + cout<<"Element Deleted"<next; + ptr = s->previous; + } + ptr->next = s->next; + s->next->previous = ptr; + if (pos == count) { + tail = ptr; + } + count--; + delete(s); + cout<<"Element Deleted"< Date: Fri, 18 Oct 2019 22:02:21 +0530 Subject: [PATCH 075/324] DFS Algorithm added DFS in c++ STL --- Algorithms/C++/DFS.cpp | 60 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Algorithms/C++/DFS.cpp diff --git a/Algorithms/C++/DFS.cpp b/Algorithms/C++/DFS.cpp new file mode 100644 index 00000000..d0268fb8 --- /dev/null +++ b/Algorithms/C++/DFS.cpp @@ -0,0 +1,60 @@ + +// DFS and graph implementaion using stl c++ +#include +#include +using namespace std; + void addEdge(vector arr[],int a,int b); + void addEdge(vector arr[],int a,int b) +{ + arr[a].push_back(b); + arr[b].push_back(a); +} +void DFSuntil(int i,vector arr[],vector &visited) +{ + cout< arr[],int n) +{ + vector visited(n,false); + for(int i=0;i>n; + int edge; + vector arr[n]; + cin>>edge;int a;int b; + for(int i=0;i>a;cin>>b; + addEdge(arr,a,b); + } + vector::iterator itr; + for(int i=0;i"; + for(itr=arr[i].begin();itr Date: Fri, 18 Oct 2019 23:34:03 +0530 Subject: [PATCH 076/324] Create HS08TEST.c --- Codechef/HS08TEST.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Codechef/HS08TEST.c diff --git a/Codechef/HS08TEST.c b/Codechef/HS08TEST.c new file mode 100644 index 00000000..432636a1 --- /dev/null +++ b/Codechef/HS08TEST.c @@ -0,0 +1,33 @@ +//Submitted by Rakshit Naidu + + +#include + +int main(void) { + // your code goes here + int withdraw_amount; + float init_balance; + scanf("%d %f",&withdraw_amount,&init_balance); + + + if(withdraw_amount % 5 == 0) + { + + if(withdraw_amount < (init_balance - 0.5)) + { + init_balance = init_balance - withdraw_amount - 0.5; + printf("%.2f",init_balance); + } + else + { + printf("%.2f",init_balance); + } + + } + else + { + printf("%.2f",init_balance); + } + + return 0; +} From 9281967a61a2de4dc36276ce2998e6c9f15af9b7 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:36:09 +0530 Subject: [PATCH 077/324] Create INTEST.c --- Codechef/INTEST.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Codechef/INTEST.c diff --git a/Codechef/INTEST.c b/Codechef/INTEST.c new file mode 100644 index 00000000..0a521b08 --- /dev/null +++ b/Codechef/INTEST.c @@ -0,0 +1,24 @@ +//Author: Rakshit Naidu + +#include + +int main() { + // Read the input n, k + int n, k; + scanf("%d %d", &n, &k); + + int ans = 0; + + for (int i = 0; i < n; i++) { + int t; + scanf("%d", &t); + + if (t % k == 0) { + ans++; + } + } + + printf("%d\n", ans); + + return 0; +} From 3cac3c113a796cc301a5a0ae99bac54ef6b6cb08 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:37:39 +0530 Subject: [PATCH 078/324] Create FLOW011.c --- Codechef/FLOW011.c | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Codechef/FLOW011.c diff --git a/Codechef/FLOW011.c b/Codechef/FLOW011.c new file mode 100644 index 00000000..cc343991 --- /dev/null +++ b/Codechef/FLOW011.c @@ -0,0 +1,33 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + float hra,da; + float gross_sal; + + if(n<1500) + { + hra = 0.1*n; + da = 0.9*n; + } + else + { + hra = 500; + da = 0.98*n; + } + gross_sal = n + hra + da; + + printf("%.2f\n",gross_sal); + } + return 0; +} + From 9a708c653be07195d1ac7399f6786c40b4fd6b7e Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:38:55 +0530 Subject: [PATCH 079/324] Create GDOG.c --- Codechef/GDOG.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Codechef/GDOG.c diff --git a/Codechef/GDOG.c b/Codechef/GDOG.c new file mode 100644 index 00000000..fb975afa --- /dev/null +++ b/Codechef/GDOG.c @@ -0,0 +1,27 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,k; + scanf("%d %d",&n,&k); + + int x=0; + for(int i=2;i<=k;i++) + { + if(n%i > x) + { + x = n%i; + } + } + + printf("%d\n",x); + } + return 0; +} From dd6197f7d563d5fde5093ab593d1e316f3bdb768 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:41:01 +0530 Subject: [PATCH 080/324] Create CK87MEDI.c --- Codechef/CK87MEDI.c | 55 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Codechef/CK87MEDI.c diff --git a/Codechef/CK87MEDI.c b/Codechef/CK87MEDI.c new file mode 100644 index 00000000..c040750e --- /dev/null +++ b/Codechef/CK87MEDI.c @@ -0,0 +1,55 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,k; + scanf("%d %d",&n,&k); + + int x = n+k; + int a[n]; + + for(int i=0;i a[j+1]) + { + temp = a[j]; + a[j] = a[j+1]; + a[j+1] = temp; + } + } + } + + if(x%2 == 1) + { + int l = (x+1)/2; + printf("%d\n",a[l-1]); + } + else if(x%2==0) + { + int l = x/2; + printf("%d\n",a[l-1]); + } + + //for(int i=0;i Date: Fri, 18 Oct 2019 23:42:17 +0530 Subject: [PATCH 081/324] Create LUCKFOUR.c --- Codechef/LUCKFOUR.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Codechef/LUCKFOUR.c diff --git a/Codechef/LUCKFOUR.c b/Codechef/LUCKFOUR.c new file mode 100644 index 00000000..8577fb87 --- /dev/null +++ b/Codechef/LUCKFOUR.c @@ -0,0 +1,28 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t>0) + { + int n,c=0; + scanf("%d",&n); + + while(n>0) + { + int rem = n % 10; + if(rem==4) + { + c = c+1; + } + n = n / 10; + } + printf("%d\n",c); + t--; + } + return 0; +} From 941ec64c1c004b16560b743773417c903b168e97 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:43:32 +0530 Subject: [PATCH 082/324] Create FLOW004.c --- Codechef/FLOW004.c | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Codechef/FLOW004.c diff --git a/Codechef/FLOW004.c b/Codechef/FLOW004.c new file mode 100644 index 00000000..8577fb87 --- /dev/null +++ b/Codechef/FLOW004.c @@ -0,0 +1,28 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t>0) + { + int n,c=0; + scanf("%d",&n); + + while(n>0) + { + int rem = n % 10; + if(rem==4) + { + c = c+1; + } + n = n / 10; + } + printf("%d\n",c); + t--; + } + return 0; +} From ccf6a07ae3465f1a49380223dd79e41be15fe06b Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:45:17 +0530 Subject: [PATCH 083/324] Create CHEFSQ.c --- Codechef/CHEFSQ.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Codechef/CHEFSQ.c diff --git a/Codechef/CHEFSQ.c b/Codechef/CHEFSQ.c new file mode 100644 index 00000000..37f8e4e8 --- /dev/null +++ b/Codechef/CHEFSQ.c @@ -0,0 +1,55 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n1; + scanf("%d",&n1); + + int a[n1]; + for(int i=0;i Date: Fri, 18 Oct 2019 23:46:32 +0530 Subject: [PATCH 084/324] Create PRB01.c --- Codechef/PRB01.c | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Codechef/PRB01.c diff --git a/Codechef/PRB01.c b/Codechef/PRB01.c new file mode 100644 index 00000000..888d2dec --- /dev/null +++ b/Codechef/PRB01.c @@ -0,0 +1,34 @@ +//Author: Rakshit Naidu + +#include +#include +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,i,flag=0; + scanf("%d",&n); + + for(i=2;i Date: Fri, 18 Oct 2019 23:47:33 +0530 Subject: [PATCH 085/324] Create CHCHCL.c --- Codechef/CHCHCL.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Codechef/CHCHCL.c diff --git a/Codechef/CHCHCL.c b/Codechef/CHCHCL.c new file mode 100644 index 00000000..d9a87d58 --- /dev/null +++ b/Codechef/CHCHCL.c @@ -0,0 +1,26 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int m,n; + scanf("%d %d",&m,&n); + + if(m%2==0||n%2==0) + { + printf("Yes\n"); + } + else + { + printf("No\n"); + } + } + return 0; +} + From c6551cb6ca91af1b66d70ece1e66a714804e5c70 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:48:49 +0530 Subject: [PATCH 086/324] Create MSNSADM1.c --- Codechef/MSNSADM1.c | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Codechef/MSNSADM1.c diff --git a/Codechef/MSNSADM1.c b/Codechef/MSNSADM1.c new file mode 100644 index 00000000..082b8a78 --- /dev/null +++ b/Codechef/MSNSADM1.c @@ -0,0 +1,46 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + int a[n],b[n]; + for(int i=0;i Date: Fri, 18 Oct 2019 23:49:49 +0530 Subject: [PATCH 087/324] Create FRUITS.c --- Codechef/FRUITS.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Codechef/FRUITS.c diff --git a/Codechef/FRUITS.c b/Codechef/FRUITS.c new file mode 100644 index 00000000..bada6a58 --- /dev/null +++ b/Codechef/FRUITS.c @@ -0,0 +1,42 @@ +//Author: Rakshit Naidu + +#include +#include + +int min(int a, int b); + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n,m,k,x=0; + scanf("%d %d %d",&n,&m,&k); + + if(n>=m) + { + x = n - min(m + k,n); + } + else + { + x = m - min(n + k,m); + } + printf("%d\n",x); + } + return 0; +} + +int min(int a, int b) +{ + if(a Date: Fri, 18 Oct 2019 23:50:55 +0530 Subject: [PATCH 088/324] Create TLG.c --- Codechef/TLG.c | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Codechef/TLG.c diff --git a/Codechef/TLG.c b/Codechef/TLG.c new file mode 100644 index 00000000..9f9d1539 --- /dev/null +++ b/Codechef/TLG.c @@ -0,0 +1,42 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t,cumul_1=0,cumul_2=0,lead_1=0,lead_2=0,a,b; + scanf("%d",&t); + + for(int i=0;i cumul_2) + { + if(lead_1 < (cumul_1 - cumul_2)) + { + lead_1 = cumul_1 - cumul_2; + } + } + else + { + if(lead_2 < (cumul_2 - cumul_1)) + { + lead_2 = cumul_2 - cumul_1; + } + } + } + + if(lead_1 > lead_2) + { + printf("1 %d",lead_1); + } + else + { + printf("2 %d",lead_2); + } + + return 0; +} + From ada4d87d2bbea2598dee045696705e953db04531 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:51:50 +0530 Subject: [PATCH 089/324] Create VOWELTB.c --- Codechef/VOWELTB.c | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Codechef/VOWELTB.c diff --git a/Codechef/VOWELTB.c b/Codechef/VOWELTB.c new file mode 100644 index 00000000..c2c1470f --- /dev/null +++ b/Codechef/VOWELTB.c @@ -0,0 +1,22 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + char ch; + scanf("%c",&ch); + if(ch>=65&&ch<=90) + { + if(ch=='A' || ch=='E' || ch=='I' || ch=='O' || ch=='U') + { + printf("Vowel\n"); + } + else + { + printf("Consonant\n"); + } + } + return 0; +} + From a65404e9ff76ed6483cb7b4aaeabcafd0db53725 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:52:37 +0530 Subject: [PATCH 090/324] Create JOHNY.c --- Codechef/JOHNY.c | 51 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Codechef/JOHNY.c diff --git a/Codechef/JOHNY.c b/Codechef/JOHNY.c new file mode 100644 index 00000000..84c3a56a --- /dev/null +++ b/Codechef/JOHNY.c @@ -0,0 +1,51 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + + int a[n]; + for(int i=0;i a[j]) + { + temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + } + int pos=0; + for(int i=0;i Date: Fri, 18 Oct 2019 23:53:56 +0530 Subject: [PATCH 091/324] Create ALPHABET.c --- Codechef/ALPHABET.c | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Codechef/ALPHABET.c diff --git a/Codechef/ALPHABET.c b/Codechef/ALPHABET.c new file mode 100644 index 00000000..eedaaedd --- /dev/null +++ b/Codechef/ALPHABET.c @@ -0,0 +1,40 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + char s[30],str[15]; + scanf("%s",&s); + int x = strlen(s); + int t; + scanf("%d",&t); + + while(t--) + { + scanf("%s",&str); + int i,j; + for(i=0;i=strlen(s)) + { + printf("No\n"); + break; + } + } + if(i>=strlen(str)) + { + printf("Yes\n"); + } + } + + return 0; +} + From 02a33b9791700cc534267ed018596600ba96c834 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:54:59 +0530 Subject: [PATCH 092/324] Create CANDY123.c --- Codechef/CANDY123.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Codechef/CANDY123.c diff --git a/Codechef/CANDY123.c b/Codechef/CANDY123.c new file mode 100644 index 00000000..9d1f0687 --- /dev/null +++ b/Codechef/CANDY123.c @@ -0,0 +1,39 @@ +//Author: Rakshit Naidu + +#include +int func(int x,int y,int r); + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int a,b; + scanf("%d %d",&a,&b); + int rem=2; + func(a,b,rem); + } + return 0; +} +int func(int x,int y,int r) +{ + x = x - (r/2); + r++; + r++; + if(x<0) + { + printf("Bob\n"); + return; + } + y = y - (r/2); + r++; + r++; + if(y<0) + { + printf("Limak\n"); + return; + } + return func(x,y,r); +} From 71ea15ea2316b7e53b791688bd5f861983b8bebe Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:56:32 +0530 Subject: [PATCH 093/324] Create TICKETS5.c --- Codechef/TICKETS5.c | 51 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Codechef/TICKETS5.c diff --git a/Codechef/TICKETS5.c b/Codechef/TICKETS5.c new file mode 100644 index 00000000..069e657e --- /dev/null +++ b/Codechef/TICKETS5.c @@ -0,0 +1,51 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + char str[100]; + scanf("%s",str); + int i,f=1; + char b = str[0]; + char c = str[1]; + if(b!=c) + { + for(i=2;str[i]!='\0';i++) + { + if(i%2==0&&str[i]==b) + { + f=1; + } + else if(i%2==1&&str[i]==c) + { + f=1; + } + else + { + f=0; + break; + } + } + } + else + { + f=0; + } + if(f==1) + { + printf("YES\n"); + } + else + { + printf("NO\n"); + } + } + return 0; +} + From 96464799e6c11530f6b81f62c578fc87bc6ee5f6 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:57:22 +0530 Subject: [PATCH 094/324] Create LOSTMAC.c --- Codechef/LOSTMAX.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Codechef/LOSTMAX.c diff --git a/Codechef/LOSTMAX.c b/Codechef/LOSTMAX.c new file mode 100644 index 00000000..c03c0964 --- /dev/null +++ b/Codechef/LOSTMAX.c @@ -0,0 +1,44 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int i,max,t,a[100],j; + char ch; + scanf("%d",&t); + + while(t--) + { + i=0,max=-1; + + while(1) + { + scanf("%d%c",&a[i],&ch); + i++; + if(ch=='\n') + { + break; + } + } + for(j=0;j max) + { + max = a[j]; + } + } + printf("%d\n",max); + } + return 0; +} + From d01f591f05b015628e9b4e8fc2c8fc09f4a4f5a7 Mon Sep 17 00:00:00 2001 From: RocketRikky <39258575+RocketRikky@users.noreply.github.com> Date: Fri, 18 Oct 2019 23:59:16 +0530 Subject: [PATCH 095/324] Create TWOVSTEN.c --- Codechef/TWOVSTEN.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Codechef/TWOVSTEN.c diff --git a/Codechef/TWOVSTEN.c b/Codechef/TWOVSTEN.c new file mode 100644 index 00000000..040fa942 --- /dev/null +++ b/Codechef/TWOVSTEN.c @@ -0,0 +1,30 @@ +//Author: Rakshit Naidu + +#include + +int main(void) { + // your code goes here + int t; + scanf("%d",&t); + + while(t--) + { + int n; + scanf("%d",&n); + int x = n%10; + if(x==5) + { + printf("1\n"); + } + else if(x==0) + { + printf("0\n"); + } + else + { + printf("-1\n"); + } + } + return 0; +} + From da23280f207ce8165c55d8dca6f95e65abb1e9c0 Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:35:20 +0530 Subject: [PATCH 096/324] Create What's Your Name?.py --- Hackerrank/Python/What's Your Name?.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Hackerrank/Python/What's Your Name?.py diff --git a/Hackerrank/Python/What's Your Name?.py b/Hackerrank/Python/What's Your Name?.py new file mode 100644 index 00000000..9a567bd6 --- /dev/null +++ b/Hackerrank/Python/What's Your Name?.py @@ -0,0 +1,9 @@ +#Submitted by Rakshit Naidu + +def print_full_name(a, b): + print("Hello {} {}! You just delved into python.".format(a,b)) + +if __name__ == '__main__': + first_name = input() + last_name = input() + print_full_name(first_name, last_name) From b2c5a5b98ecb2ad9f5efb6f54a83d6f6d2b37934 Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:36:18 +0530 Subject: [PATCH 097/324] Create Loops.py --- Hackerrank/Python/Loops.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Hackerrank/Python/Loops.py diff --git a/Hackerrank/Python/Loops.py b/Hackerrank/Python/Loops.py new file mode 100644 index 00000000..f2ccb039 --- /dev/null +++ b/Hackerrank/Python/Loops.py @@ -0,0 +1,7 @@ +#Author: Rakshit Naidu + +if __name__ == '__main__': + n = int(input()) + + for i in range(n): + print(i**2) From e77c2e73639ae0a3c84ba89a21164084f8b2c548 Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:37:20 +0530 Subject: [PATCH 098/324] Create Mod Divmod.py --- Hackerrank/Python/Mod Divmod.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Hackerrank/Python/Mod Divmod.py diff --git a/Hackerrank/Python/Mod Divmod.py b/Hackerrank/Python/Mod Divmod.py new file mode 100644 index 00000000..de3b2e69 --- /dev/null +++ b/Hackerrank/Python/Mod Divmod.py @@ -0,0 +1,11 @@ +#Author: Rakshit Naidu + +a = int(input()) +b = int(input()) + +x = a // b +y = a % b + +print(x) +print(y) +print((x,y,)) From f2535615b99ce5750e33082e6362c4066bb0b67c Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:38:04 +0530 Subject: [PATCH 099/324] Create Mutations.py --- Hackerrank/Python/Mutations.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Hackerrank/Python/Mutations.py diff --git a/Hackerrank/Python/Mutations.py b/Hackerrank/Python/Mutations.py new file mode 100644 index 00000000..7eb9d10b --- /dev/null +++ b/Hackerrank/Python/Mutations.py @@ -0,0 +1,11 @@ +#Author: Rakshit Naidu + +def mutate_string(string, position, character): + + return string[0:position]+character+string[position+1:] + +if __name__ == '__main__': + s = input() + i, c = input().split() + s_new = mutate_string(s, int(i), c) + print(s_new) From d7f15b2dd430ddbd95d3abf7a84f404d84e5fadf Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:38:59 +0530 Subject: [PATCH 100/324] Create Python If-Else.py --- Hackerrank/Python/Python If-Else.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Hackerrank/Python/Python If-Else.py diff --git a/Hackerrank/Python/Python If-Else.py b/Hackerrank/Python/Python If-Else.py new file mode 100644 index 00000000..d1e0d30d --- /dev/null +++ b/Hackerrank/Python/Python If-Else.py @@ -0,0 +1,13 @@ +#Author: Rakshit Naidu + +if __name__ == '__main__': + n = int(input().strip()) + + if n % 2 ==0 and n > 20: + print("Not Weird") + elif n % 2 ==0 and n > 5 and n < 21: + print("Weird") + elif n % 2==0 and n > 1 and n < 6: + print("Not Weird") + elif n % 2 == 1: + print("Weird") From 5f0827adfc69a7c43ed3735e7169a66501d344ee Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:39:54 +0530 Subject: [PATCH 101/324] Create Arithmetic Operators.py --- Hackerrank/Python/Arithmetic Operators.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Hackerrank/Python/Arithmetic Operators.py diff --git a/Hackerrank/Python/Arithmetic Operators.py b/Hackerrank/Python/Arithmetic Operators.py new file mode 100644 index 00000000..42744d59 --- /dev/null +++ b/Hackerrank/Python/Arithmetic Operators.py @@ -0,0 +1,10 @@ +#Author: Rakshit Naidu + + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + + print(a+b) + print(a-b) + print(a*b) From ae7adce325e2e275f113dff909415367bed71d62 Mon Sep 17 00:00:00 2001 From: Rakshit Naidu Date: Sat, 19 Oct 2019 00:40:36 +0530 Subject: [PATCH 102/324] Create Python: Division.py --- Hackerrank/Python/Python: Division.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Hackerrank/Python/Python: Division.py diff --git a/Hackerrank/Python/Python: Division.py b/Hackerrank/Python/Python: Division.py new file mode 100644 index 00000000..26004077 --- /dev/null +++ b/Hackerrank/Python/Python: Division.py @@ -0,0 +1,8 @@ +#Author: Rakshit Naidu + +if __name__ == '__main__': + a = int(input()) + b = int(input()) + + print(a//b) + print(a/b) From 4c1ffd3eba568fa9171775b4cd637a2f329d2ced Mon Sep 17 00:00:00 2001 From: Pratama Yoga Santosa Date: Sat, 19 Oct 2019 02:12:54 +0700 Subject: [PATCH 103/324] Add DiagonalDifference solution --- Hackerrank/C++/DiagonalDifference.cpp | 106 ++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 Hackerrank/C++/DiagonalDifference.cpp diff --git a/Hackerrank/C++/DiagonalDifference.cpp b/Hackerrank/C++/DiagonalDifference.cpp new file mode 100644 index 00000000..022b4d37 --- /dev/null +++ b/Hackerrank/C++/DiagonalDifference.cpp @@ -0,0 +1,106 @@ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +/* + * Complete the 'diagonalDifference' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY arr as parameter. + */ + +int diagonalDifference(vector> arr) { + int d1 =0, d2 =0; + + for (int i=0; i> arr(n); + + for (int i = 0; i < n; i++) { + arr[i].resize(n); + + string arr_row_temp_temp; + getline(cin, arr_row_temp_temp); + + vector arr_row_temp = split(rtrim(arr_row_temp_temp)); + + for (int j = 0; j < n; j++) { + int arr_row_item = stoi(arr_row_temp[j]); + + arr[i][j] = arr_row_item; + } + } + + int result = diagonalDifference(arr); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} From aa8f4b0880d94b8e475d1e28b7e976b3382fc180 Mon Sep 17 00:00:00 2001 From: somya <42448899+somya1209@users.noreply.github.com> Date: Sat, 19 Oct 2019 01:05:12 +0530 Subject: [PATCH 104/324] Create INLO33.java --- Codechef/INLO33.java | 90 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 Codechef/INLO33.java diff --git a/Codechef/INLO33.java b/Codechef/INLO33.java new file mode 100644 index 00000000..388d78cb --- /dev/null +++ b/Codechef/INLO33.java @@ -0,0 +1,90 @@ +//author:somya +//problem:INLO33 + +//package algo; +import java.util.*; + +public class Main { +public static int distance[] = new int[300]; +public static int cost[][] = new int[300][300]; +public static int t[] = new int[300]; + + +public static int wait(int distofminpos,int minpos,int k) { + + int next_signal=t[minpos]; + while(distofminpos>next_signal) + {next_signal+=t[minpos]; + + } + + return (next_signal-distofminpos); + + +} + +public static void calc(int n, int s) { +int flag[] = new int[n + 1]; +int i, minpos = 1, k, c, minimum; +for (i = 1; i <= n; i++) { +flag[i] = 0; +distance[i] = cost[s][i]; +} +c = 2; +while (c <= n) { +minimum = 999; +for (k = 1; k <= n; k++) { +if (distance[k] < minimum && flag[k] != 1) { +minimum = distance[k]; + +minpos = k; +} +} +flag[minpos] = 1; +c++; +for (k = 1; k <= n; k++) { + +if ( distance[minpos]+wait(distance[minpos],minpos,k) + cost[minpos][k] < distance[k] && flag[k] != 1) + distance[k] = distance[minpos] +cost[minpos][k]+wait(distance[minpos],minpos,k); +} +} +} + +public static void main(String args[]) { + int n,m, source,dest,x, i,j; + +Scanner in = new Scanner(System.in); + +source = in.nextInt(); +dest = in.nextInt(); +n = in.nextInt(); +m = in.nextInt(); +for( x=1;x<=n;++x) + {t[x]=in.nextInt(); + + + } + + +//enter cost matrix by edges +for( x=0;x Date: Fri, 18 Oct 2019 16:05:55 -0400 Subject: [PATCH 105/324] initial commit --- DS/C++/threadedtree.h | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 DS/C++/threadedtree.h diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h new file mode 100644 index 00000000..5379e09b --- /dev/null +++ b/DS/C++/threadedtree.h @@ -0,0 +1,11 @@ +/*************************************************** + +Notes: +This an implementation of threaded tree in C++ +Threaded tree is a binary search tree that allows for easier in-order traversal +For each node, all right/ left child pointers that would normally be null instead point to the in-order successor node +This implementation supports generic typing and both forward and backward in-order traversal, but does not handle duplicate values + +Iterator implementation also included to facilitate easy traversal via operators + +***************************************************/ \ No newline at end of file From 0d73e98b5c5f91fb716d562e02123ba3a4de123d Mon Sep 17 00:00:00 2001 From: ODAVING Date: Fri, 18 Oct 2019 16:33:06 -0400 Subject: [PATCH 106/324] Added Dictionary Linear Probing to Data Structures --- DS/C++/Dictionary/Table.h | 463 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 463 insertions(+) create mode 100644 DS/C++/Dictionary/Table.h diff --git a/DS/C++/Dictionary/Table.h b/DS/C++/Dictionary/Table.h new file mode 100644 index 00000000..f1255847 --- /dev/null +++ b/DS/C++/Dictionary/Table.h @@ -0,0 +1,463 @@ + +#include +#include +using namespace std; + +template +class Table{ +public: + Table(){} + virtual bool update(const string& key, const TYPE& value)=0; + virtual bool remove(const string& key)=0; + virtual bool find(const string& key, TYPE& value)=0; + virtual int numRecords() const = 0; + virtual bool isEmpty() const = 0; + virtual ~Table(){} +}; + +template +class SimpleTable:public Table{ + + struct Record{ + TYPE data_; + string key_; + Record(const string& key, const TYPE& data){ + key_=key; + data_=data; + } + + }; + + Record** records_; //the table + int max_; //capacity of the array + int size_; //current number of records held + int search(const string& key); + +public: + SimpleTable(int capacity); + SimpleTable(const SimpleTable& other); + SimpleTable(SimpleTable&& other); + virtual bool update(const string& key, const TYPE& value); + virtual bool remove(const string& key); + virtual bool find(const string& key, TYPE& value); + virtual const SimpleTable& operator=(const SimpleTable& other); + virtual const SimpleTable& operator=(SimpleTable&& other); + virtual ~SimpleTable(); + virtual bool isEmpty() const{return size_==0;} + virtual int numRecords() const{return size_;} +}; + + +//returns index of where key is found. +template +int SimpleTable::search(const string& key){ + int rc=-1; + for(int i=0;ikey_==key){ + rc=i; + } + } + return rc; +} + + +template +SimpleTable::SimpleTable(int capacity): Table(){ + records_=new Record*[capacity]; + max_=capacity; + size_=0; +} + +template +SimpleTable::SimpleTable(const SimpleTable& other){ + records_=new Record*[other.max_]; + max_=other.max_; + size_=0; + for(int i=0;ikey_,other.records_[i]->data_); + } +} +template +SimpleTable::SimpleTable(SimpleTable&& other){ + size_=other.size_; + max_=other.max_; + records_=other.records_; + other.records_=nullptr; + other.size_=0; + other.max_=0; +} + +template +bool SimpleTable::update(const string& key, const TYPE& value){ + int idx=search(key); + if(idx==-1){ + if(size_ < max_){ + records_[size_++]=new Record(key,value); + for(int i=0;i records_[j+1]){ + TYPE tmp=records_[j]; + records_[j]=records_[j+1]; + records_[j+1]=tmp; + } + } + } + } + } + else{ + records_[idx]->data_=value; + } + return true; +} + +template +bool SimpleTable::remove(const string& key){ + int idx=search(key); + if(idx!=-1){ + delete records_[idx]; + for(int i=idx;i +bool SimpleTable::find(const string& key, TYPE& value){ + int idx=search(key); + if(idx==-1) + return false; + else{ + value=records_[idx]->data_; + return true; + } +} + +template +const SimpleTable& SimpleTable::operator=(const SimpleTable& other){ + if(this!=&other){ + if(records_){ + int sz=size_; + for(int i=0;ikey_); + } + delete [] records_; + } + records_=new Record*[other.max_]; + max_=other.max_; + size_=0; + for(int i=0;ikey_,other.records_[i]->data_); + } + + } + return *this; +} + +template +const SimpleTable& SimpleTable::operator=(SimpleTable&& other){ + swap(records_,other.records_); + swap(size_,other.size_); + swap(max_,other.max_); + return *this; +} + +template +SimpleTable::~SimpleTable(){ + if(records_){ + int sz=size_; + for(int i=0;ikey_); + } + delete [] records_; + } +} + +template +class LPTable:public Table{ + struct Record { + TYPE data_; + string key_; + //creating a new variable to keep track incase there is a collision + size_t colind_; + + Record(const string& key, const TYPE& data, const size_t colind =0) { + key_ = key; + data_ = data; + colind_ = colind; + } + + }; + + Record** records_; //the table + int maxLP_; //capacity of the array + int sizeLP_; //current number of records held + double loadLP_; //Load Factor for LP table represented as percentage (0.6 = 60%) + + +public: + LPTable(int capacity,double maxLoadFactor); + LPTable(const LPTable& other); + LPTable(LPTable&& other); + virtual bool update(const string& key, const TYPE& value); + virtual bool remove(const string& key); + virtual bool find(const string& key, TYPE& value); + virtual const LPTable& operator=(const LPTable& other); + virtual const LPTable& operator=(LPTable&& other); + virtual ~LPTable(); + virtual bool isEmpty() const { return sizeLP_ == 0; }; + virtual int numRecords() const { return sizeLP_; }; + +}; + +//Constructor that initializes records array and sizeLP_ to safe empty state! While others to their respective values +template +LPTable::LPTable(int capacity,double maxLoadFactor): Table(){ + + records_ = new Record*[capacity]; + + //going through the records array and ensuring that everything is empty + for (int i = 0; i < capacity; i++) + { + records_[i] = nullptr; + } + + maxLP_ = capacity; + sizeLP_ = 0; + loadLP_ = maxLoadFactor; +} + +//Copy Constructor +template +LPTable::LPTable(const LPTable& other){ + + records_ = new Record*[other.maxLP_]; + //shallow coppy the variables + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + for (int i = 0; i < other.maxLP_; i++) + { + //make sure that each record is a nullptr + records_[i] = nullptr; + + //doesn't copy nullptrs, but covers other nullptrs with actual values + if (other.records_[i] != nullptr) + { + records_[i] = new Record(other.records_[i]->key_, other.records_[i]->data_, other.records_[i]->colind_); + } + } +} + +//Move Constructor +template +LPTable::LPTable(LPTable&& other){ + records_ = new Record*[other.maxLP_]; + + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + + for (int i = 0; i < other.maxLP_; i++) + { + records_[i] = other.records_[i]; + other.records_[i] = nullptr; + } + + other.maxLP_ = 0; + other.loadLP_ = 0; + other.sizeLP_ = 0; + delete[] other.records_; //delete the whole table + other.records_ = nullptr; //ensure that destructor doesn't try to delete a nullptr; +} + +template +bool LPTable::update(const string& key, const TYPE& value){ + std::hash hashFunction; //. + + size_t hash = hashFunction(key); // + + int index = hash % maxLP_; //holds the actual place that it needs to store value + + int colind = 0; //keeps track of steps after original index + + for (;records_[index] != nullptr; index= ++index % maxLP_) + { + //you start at the hashed index and check to see if the key's match + if (records_[index]->key_ == key) + { + records_[index]->data_ = value; + return true; //value replaced + } + colind++; + } + + //if a nullptr has been encountered then we place the new value there. + if ((double)sizeLP_ / (double)maxLP_ < loadLP_) + { + records_[index] = new Record(key, value, colind); + sizeLP_++; + return true; + } + + return false; +} + +template +bool LPTable::remove(const string& key){ + std::hash hashFunction; //. + + size_t hash = hashFunction(key); // + + int index = hash % maxLP_; //holds the actual place that it needs to store value + + for (; records_[index] != nullptr; index = ++index % maxLP_) + { + //you start at the hashed index and check to see if the key's match + if (records_[index]->key_ == key) + { + delete records_[index]; + records_[index] = nullptr; + sizeLP_--; + int circular = (index+1) % maxLP_; //ensuring the hash table goes in circle - R-value add + int counter = 1; //because we moved 1 forward from the deletion point + + while (records_[circular] != nullptr) + { + //shifting values to proper place inside the table + if (records_[circular]->colind_ >= counter) + { + records_[circular]->colind_ -= counter; //subtracting a step + records_[index] = records_[circular]; + records_[circular] = nullptr; + index = circular; + counter = 1; //reseting counter + } + else + counter++; //add counter if nothing has to be moved + + circular = ++circular % maxLP_; + } + return true; //value found return true; + } + } + return false; +} + + + +template +bool LPTable::find(const string& key, TYPE& value) { + std::hash hashFunction; //. + + size_t hash = hashFunction(key); // + + int index = hash % maxLP_; //holds the actual place that it needs to store value + + for (; records_[index] != nullptr; index = ++index % maxLP_) + { + //you start at the hashed index and check to see if the key's match + if (records_[index]->key_ == key) + { + value = records_[index]->data_; //changing the reference to value + return true; //value found return true; + } + } + return false; +} + + + +//copy assignment operator that copies the records from other to the current object +//this function also checks for self-assignment and empty tables +template +const LPTable& LPTable::operator=(const LPTable& other){ + if (&other != this) + { + for (int i = 0; i < maxLP_; i++) + { + delete records_[i]; + records_[i] = nullptr; + } + delete[] records_; + records_ = nullptr; + + records_ = new Record*[other.maxLP_]; + //shallow coppy the variables + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + for (int i = 0; i < other.maxLP_; i++) + { + //make sure that each record is a nullptr + records_[i] = nullptr; + + //doesn't copy nullptrs, but covers other nullptrs with actual values + if (other.records_[i] != nullptr) + { + records_[i] = new Record(other.records_[i]->key_, other.records_[i]->data_, other.records_[i]->colind_); + } + } + } + return *this; +} + +//Move assignment operator that moves the records from other to the current object +template +const LPTable& LPTable::operator=(LPTable&& other){ + if (&other != this) + { + //ensuring that records_ is completely empty; + for (int i = 0; i < maxLP_; i++) + { + delete records_[i]; + records_[i] = nullptr; + } + delete[] records_; + records_ = nullptr; + + records_ = new Record*[other.maxLP_]; + + this->maxLP_ = other.maxLP_; + this->loadLP_ = other.loadLP_; + this->sizeLP_ = other.sizeLP_; + + + for (int i = 0; i < other.maxLP_; i++) + { + records_[i] = other.records_[i]; + other.records_[i] = nullptr; + } + + other.maxLP_ = 0; + other.loadLP_ = 0; + other.sizeLP_ = 0; + delete[] other.records_; //delete the whole table + other.records_ = nullptr; //ensures that destructor doesn't try to delete a nullptr; + } + return *this; +} + +//destructor that goes checks for full records and empties it one index at a time. +template +LPTable::~LPTable(){ + if (records_) + { + for (int i = 0; i < maxLP_; i++) + { + delete records_[i]; + records_[i] = nullptr; + } + delete[] records_; + records_ = nullptr; + } +} + + From 44cbf594c893c3b1873446caeea63a15eb2e5776 Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Fri, 18 Oct 2019 16:40:25 -0400 Subject: [PATCH 107/324] basic threadedtree class --- DS/C++/threadedtree.h | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h index 5379e09b..f2317fc6 100644 --- a/DS/C++/threadedtree.h +++ b/DS/C++/threadedtree.h @@ -8,4 +8,27 @@ This implementation supports generic typing and both forward and backward in-ord Iterator implementation also included to facilitate easy traversal via operators -***************************************************/ \ No newline at end of file +***************************************************/ + +#include +using namespace std; + +template +class ThreadedTree { + struct Node{ + T data_; + Node* left_; + Node* right_; + int lFlag_; // Whether the node has a left thread, 0 = no, 1 = yes + int rFlag_; // Whether the node has a right thread, 0 = no, 1 = yes + + Node(const T& data, Node* lt = nullptr, Node* rt = nullptr, int lFlag = 0, int rFlag = 0) { + data_ = data; + left_ = lt; + right_ = rt; + lFlag_ = lFlag; + rFlag_ = rFlag; + } + }; + Node* root_; +}; \ No newline at end of file From 352309f009e8f24bc838b4eae361b975014ddf47 Mon Sep 17 00:00:00 2001 From: Celine <47914387+CelineLind@users.noreply.github.com> Date: Sat, 19 Oct 2019 07:23:02 +1000 Subject: [PATCH 108/324] Created bubbleSort.py --- Algorithms/Python/bubbleSort.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Algorithms/Python/bubbleSort.py diff --git a/Algorithms/Python/bubbleSort.py b/Algorithms/Python/bubbleSort.py new file mode 100644 index 00000000..d5e796e8 --- /dev/null +++ b/Algorithms/Python/bubbleSort.py @@ -0,0 +1,16 @@ +# bubble sort + +# test numbers +toSort = [3, 7, 2, 6, 4] + +# perform bubble sort +for i in range(5): + for j in range(4): + if toSort[j] > toSort[j+1]: + temp = toSort[j] + toSort[j] = toSort[j + 1] + toSort[j + 1] = temp + +# print sorted list +for x in toSort: + print(x) From 6ba433edd4b3fe5891ac48f6606e0c0823b1f260 Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Fri, 18 Oct 2019 17:28:48 -0400 Subject: [PATCH 109/324] const iterator --- DS/C++/threadedtree.h | 170 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 169 insertions(+), 1 deletion(-) diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h index f2317fc6..c812d1fe 100644 --- a/DS/C++/threadedtree.h +++ b/DS/C++/threadedtree.h @@ -6,7 +6,7 @@ Threaded tree is a binary search tree that allows for easier in-order traversal For each node, all right/ left child pointers that would normally be null instead point to the in-order successor node This implementation supports generic typing and both forward and backward in-order traversal, but does not handle duplicate values -Iterator implementation also included to facilitate easy traversal via operators +Const and non-const iterator implementation also included to facilitate easy traversal via operators ***************************************************/ @@ -31,4 +31,172 @@ class ThreadedTree { } }; Node* root_; + +public: + class const_iterator{ + private: + const ThreadedTree* myTree_; + Node* curr_; + + // Private constructor + const_iterator(Node* curr, const ThreadedTree* theTree) { + curr_ = curr; + myTree_ = theTree; + } + + public: + + // Constructor + const_iterator(){ + myTree_ = nullptr; + curr_ = nullptr; + } + + // Postfix ++ increments iterator and returns old value + // @return: iterator containing old value + const_iterator operator++(int){ + const_iterator old = *this; + + // If the current node has a right thread, we use that to move forward + if (curr_->rFlag_ == 1) { + curr_ = curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + curr_ = curr_->right_; + + if (curr_ != nullptr) { + while (curr_->left_ != nullptr && curr_->lFlag_ != 1) { + curr_ = curr_->left_; + } + } + } + + //Return the old node + return old; + } + + // Postfix -- decrements iterator and returns old value + // @return: iterator containing old value + const_iterator operator--(int){ + const_iterator old = *this; + + // If the current node is nullptr, we're at end, move back to actual last value + // Could also implement an end sentinel, which would be more robust, but I don't want to risk breaking the tester + if (curr_ == nullptr) { + if (myTree_->root_ != nullptr) { + curr_ = myTree_->root_; + while (curr_->right_ != nullptr) { + curr_ = curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (curr_->lFlag_ == 1) { + curr_ = curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (curr_->left_ != nullptr) { + curr_ = curr_->left_; + + while (curr_->right_ != nullptr && curr_->rFlag_ != 1) { + curr_ = curr_->right_; + } + } + } + //Return the old node + return old; + } + + // Prefix ++ increments iterator and returns new value + // @return: iterator containing new value + const_iterator operator++(){ + // If the current node has a right thread, we use that to move forward + if (curr_->rFlag_ == 1) { + curr_ = curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + curr_ = curr_->right_; + + if (curr_ != nullptr) { + while (curr_->left_ != nullptr && curr_->lFlag_ != 1) { + curr_ = curr_->left_; + } + } + } + + //Return the new node + return *this; + } + + // Prefix -- decrements iterator and returns new value + // @return: iterator containing new value + const_iterator operator--(){ + // If the current node is nullptr, we're at end, move back to actual last value + if (this->curr_ == nullptr) { + if (myTree_->root_ != nullptr) { + curr_ = myTree_->root_; + while (curr_->right_ != nullptr) { + curr_ = curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (curr_->lFlag_ == 1) { + curr_ = curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (curr_->left_ != nullptr) { + curr_ = curr_->left_; + + while (curr_->right_ != nullptr && curr_->rFlag_ != 1) { + curr_ = curr_->right_; + } + } + } + //Return the new node + return *this; + } + + // Dereference operator returns the data value stored in the current node + // @return: current node's data value + const T& operator*() const{ + return curr_->data_; + } + + // Returns whether or not the current iterator is the same as the rhs iterator + // @return: True/ False if the iterators are the same + bool operator==(const const_iterator& rhs) const{ + bool ret = false; + + //Test if RHS both the same node and in the same ThreadedTree + if (myTree_ == rhs.myTree_ && curr_ == rhs.curr_) { + ret = true; + } + + return ret; + } + + // Returns whether or not the current iterator is NOT the same as the rhs iterator + // @return: True/ False if the iterators are NOT the same + bool operator!=(const const_iterator& rhs) const{ + bool ret = false; + + //Test if either RHS is not in the same tree, or in the same tree but not the same node + if (myTree_ != rhs.myTree_ || curr_ != rhs.curr_) { + ret = true; + } + + return ret; + } + + friend class ThreadedTree; + }; }; \ No newline at end of file From 651c2a52dbca906586df8ed289a0191f9c8cf955 Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Fri, 18 Oct 2019 17:54:26 -0400 Subject: [PATCH 110/324] non-const iterator --- DS/C++/threadedtree.h | 130 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 128 insertions(+), 2 deletions(-) diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h index c812d1fe..4d3c58c6 100644 --- a/DS/C++/threadedtree.h +++ b/DS/C++/threadedtree.h @@ -13,6 +13,7 @@ Const and non-const iterator implementation also included to facilitate easy tra #include using namespace std; +// Generic type threaded tree template class ThreadedTree { struct Node{ @@ -33,6 +34,7 @@ class ThreadedTree { Node* root_; public: + // Const iterator member class const_iterator{ private: const ThreadedTree* myTree_; @@ -45,7 +47,6 @@ class ThreadedTree { } public: - // Constructor const_iterator(){ myTree_ = nullptr; @@ -197,6 +198,131 @@ class ThreadedTree { return ret; } - friend class ThreadedTree; + friend class ThreadedTree; // Make friend to access threaded tree members + }; + + // Non-const iterator member + class iterator:public const_iterator{ + private: + //Private constructor calls the constant iterator's private constructor + iterator(Node* curr, ThreadedTree* theTree) :const_iterator(curr, theTree) {} + + public: + iterator():const_iterator(){} + + const T& operator*() const{ + return this->curr_->data_; + } + + T& operator*(){ + return this->curr_->data_; + } + + iterator operator++(int){ + iterator old = *this; + + // If the current node has a right thread, we use that to move forward + if (this->curr_->rFlag_ == 1) { + this->curr_ = this->curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + this->curr_ = this->curr_->right_; + + if (this->curr_ != nullptr) { + while (this->curr_->left_ != nullptr && this->curr_->lFlag_ != 1) { + this->curr_ = this->curr_->left_; + } + } + } + + //Return the old node + return old; + } + + iterator operator--(int){ + iterator old = *this; + + // If the current node is nullptr, we're at end, move back to actual last value + if (this->curr_ == nullptr) { + if (this->myTree_->root_ != nullptr) { + this->curr_ = this->myTree_->root_; + while (this->curr_->right_ != nullptr) { + this->curr_ = this->curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (this->curr_->lFlag_ == 1) { + this->curr_ = this->curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (this->curr_->left_ != nullptr) { + this->curr_ = this->curr_->left_; + + while (this->curr_->right_ != nullptr && this->curr_->rFlag_ != 1) { + this->curr_ = this->curr_->right_; + } + } + } + //Return the old node + return old; + } + + iterator operator++(){ + // If the current node has a right thread, we use that to move forward + if (this->curr_->rFlag_ == 1) { + this->curr_ = this->curr_->right_; + } + // If it doesn't have a right thread, we need to move to the left-most node in its right subtree + // However we only move forward if the right node isn't nullptr (i.e. we're at max value already) + else { + this->curr_ = this->curr_->right_; + + if (this->curr_ != nullptr) { + while (this->curr_->left_ != nullptr && this->curr_->lFlag_ != 1) { + this->curr_ = this->curr_->left_; + } + } + } + + //Return the new node + return *this; + } + + iterator operator--(){ + // If the current node is nullptr, we're at end, move back to actual last value + if (this->curr_ == nullptr) { + if (this->myTree_->root_ != nullptr) { + this->curr_ = this->myTree_->root_; + while (this->curr_->right_ != nullptr) { + this->curr_ = this->curr_->right_; + } + } + } + else { + // If the current node has a left thread, we use that to move backwards + if (this->curr_->lFlag_ == 1) { + this->curr_ = this->curr_->left_; + } + // If it doesn't have a left thread, we need to move to the right-most node in its left subtree + // However we only move backward if the left node isn't nullptr (i.e. we're at least value already) + else if (this->curr_->left_ != nullptr) { + this->curr_ = this->curr_->left_; + + while (this->curr_->right_ != nullptr && this->curr_->rFlag_ != 1) { + this->curr_ = this->curr_->right_; + } + } + } + + //Return the new node + return *this; + } + + friend class ThreadedTree; // Make friend to access threaded tree members }; }; \ No newline at end of file From 29af89640d315251a3c96736305e9ccb878e80a9 Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Fri, 18 Oct 2019 18:16:32 -0400 Subject: [PATCH 111/324] insertions --- DS/C++/threadedtree.h | 85 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h index 4d3c58c6..2ec600d8 100644 --- a/DS/C++/threadedtree.h +++ b/DS/C++/threadedtree.h @@ -325,4 +325,89 @@ class ThreadedTree { friend class ThreadedTree; // Make friend to access threaded tree members }; + + // Default constructor, sets root node to nullptr + ThreadedTree(){ + root_ = nullptr; + } + + // Inserts a new value into the tree + // @params data: the data value to insert + void insert(const T& data){ + + if (root_ == nullptr) { + root_ = new Node(data); + } + else { + recursiveInsert(root_, data); + } + } + + // Helper function that recursively searches for the correct place to insert a node + // @params node: the current node being inspected while looking for insertion location + // @params parent: the inspected node's immediate parent node + // @params data: the data value to insert + // @return: returns the node modified by the insert (when called recurisely, this chains all the way up to the root) + void recursiveInsert(Node* node, const T& data) { + // If the data is less than the current node's, inspect to the left + if (data < node->data_) { + // If the left node is free, we can add the new node as its left child + if (node->left_ == nullptr || node->lFlag_ == 1) { + Node* ins = new Node(data); + + // Since we are inserting to the left, the new child inherits the current node's left pointer + ins->left_ = node->left_; + // Also need to set the left thread flag of the child if it's not nullptr (i.e. if child is not the least value in the tree) + if (ins->left_ != nullptr) { + ins->lFlag_ = 1; + } + + // The child's right pointer then becomes a thread to the node (iteratively, the parent always comes after left child) + ins->rFlag_ = 1; + ins->right_ = node; + + // Clear the node's left thread flag and point its left to the newly added child + node->lFlag_ = 0; + node->left_ = ins; + + // Null the temporary pointer to avoid errors when going out of scope + ins = nullptr; + } + // If it isn't free, keep inspecting + else { + recursiveInsert(node->left_, data); + } + } + // If the data is greater than the current node's, inspect to the right + else if (data > node->data_) { + // If the right node is free, we can add the new node as its left child + if (node->right_ == nullptr || node->rFlag_ == 1) { + Node* ins = new Node(data); + + // Since we are inserting to the right, the new child inherits the current node's right pointer + ins->right_ = node->right_; + // Also need to set the right thread flag of the child if it's not nullptr (i.e. if child is not the most value in the tree) + if (ins->right_ != nullptr) { + ins->rFlag_ = 1; + } + + // The child's left pointer then becomes a thread to the node (iteratively, the parent always comes after left child) + ins->lFlag_ = 1; + ins->left_ = node; + + // Clear the node's right thread flag and point its right to the newly added child + node->rFlag_ = 0; + node->right_ = ins; + + // Null the temporary pointer to avoid errors when going out of scope + ins = nullptr; + } + // If it isn't free, keep inspecting + else { + recursiveInsert(node->right_, data); + } + } + + // Note: We have to assume that there are no duplicate values as this implementation does not support them + } }; \ No newline at end of file From 3f69d6547c31871f06a36827827e7f1cd965f153 Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Fri, 18 Oct 2019 18:43:16 -0400 Subject: [PATCH 112/324] find functions --- DS/C++/threadedtree.h | 101 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/DS/C++/threadedtree.h b/DS/C++/threadedtree.h index 2ec600d8..d9aed4d8 100644 --- a/DS/C++/threadedtree.h +++ b/DS/C++/threadedtree.h @@ -410,4 +410,105 @@ class ThreadedTree { // Note: We have to assume that there are no duplicate values as this implementation does not support them } + + // Helper function that recursively searches for the node with the given data + // @params node: the current node being inspected while looking for insertion location + // @params data: the data value to insert + // @return: returns the found node with matching data, nullptr (end) if not + Node* recursiveFind(Node* node, const T& data) { + Node* ret = nullptr; + + // Only inspect if the node isn't null + if (node != nullptr) { + // If the value is less than the current node's value, continue search to the left + if (data < node->data_) { + ret = recursiveFind(node->left_, data); + } + // If the data is greater than the current node's value, continue searching to the right + else if (data > node->data_) { + ret = recursiveFind(node->right_, data); + } + // If the data is a match, return the current node + else { + ret = node; + } + } + + return ret; + } + + // Finds the node with the matching data value and returns an iterator to it + // @params node: the data value to find + iterator find(const T& data){ + // The recursiveFind() function will either return a node, if found, or nullptr representing "end" if not found + iterator* ret = new iterator(recursiveFind(root_, data), this); + + return *ret; + } + + // Finds the node with the matching data value and returns a constant iterator to it + // @params node: the data value to find + const_iterator find(const T& data) const{ + // The recursiveFind() function will either return a node, if found, or nullptr representing "end" if not found + const_iterator* ret = new const_iterator(recursiveFind(root_, data), this); + + return *ret; + } + + // Returns an iterator to the left-most (least) node in the tree + // @return: iterator pointing to left-most node + iterator begin(){ + Node* ret = nullptr; + + if (root_ != nullptr) { + ret = root_; + while (ret->left_ != nullptr) { + ret = ret->left_; + } + } + + return iterator(ret, this); + } + + // Returns an iterator containing nullptr, which represents the end of the tree's traversal path + // A nullptr works as a suitable end node, because should not occur anywhere else in the tree's traversal path + // All nullptrs at non-end nodes are replaced by thread pointers in a threaded BST + // The only logical nullptr would be to the right of the maximum value, or "one past" the max node + // @return: iterator pointing to right-most node + iterator end(){ + return iterator(nullptr, this); + } + + // Returns a constant iterator to the left-most (least) node in the tree + // @return: constant iterator pointing to left-most node + const_iterator cbegin()const{ + Node* ret = nullptr; + + if (root_ != nullptr) { + ret = root_; + while (ret->left_ != nullptr) { + ret = ret->left_; + } + } + + return const_iterator(ret, this); + } + + // Returns a constant iterator containing nullptr, which represents the end of the tree's traversal path + // A nullptr works as a suitable end node, because should not occur anywhere else in the tree's traversal path + // All nullptrs at non-end nodes are replaced by thread pointers in a threaded BST + // The only logical nullptr would be to the right of the maximum value, or "one past" the max node + // @return: iterator pointing to right-most node + const_iterator cend() const{ + return const_iterator(nullptr, this); + } + + // Destructor uses postfix operator to delete nodes in tree + ~ThreadedTree(){ + iterator i = begin(); + + while (i != end()) { + delete (i++).curr_; + } + } }; \ No newline at end of file From f4b5b29ae51fe36cf6fefae7037692f3f42fa0f1 Mon Sep 17 00:00:00 2001 From: Anthony Reese Date: Sat, 19 Oct 2019 06:53:20 +0400 Subject: [PATCH 113/324] Create collatz.py --- DS/python/collatz.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 DS/python/collatz.py diff --git a/DS/python/collatz.py b/DS/python/collatz.py new file mode 100644 index 00000000..e28b6cad --- /dev/null +++ b/DS/python/collatz.py @@ -0,0 +1,21 @@ +steps = 1 +seq_length = 1 + +for number in range(1, 10): + start_number = number + list_length = 1 + #print(number) + while(number != 1): + if number % 2 == 0: + number = number / 2 + list_length += 1 + else: + number = 3 * number + 1 + list_length += 1 + + if list_length > steps: + steps = list_length + seq_length = start_number + +print("The initial starting number <= 10000000 is", seq_length) +print("The second-longest sequence of integers <= 10000000 is", steps) From 76354d844875e5362ce1fdea6b44ba6d4693742f Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Sat, 19 Oct 2019 08:24:53 +0530 Subject: [PATCH 114/324] Rename 60A.cpp to Codeforces/60A.cpp --- 60A.cpp => Codeforces/60A.cpp | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 60A.cpp => Codeforces/60A.cpp (100%) diff --git a/60A.cpp b/Codeforces/60A.cpp similarity index 100% rename from 60A.cpp rename to Codeforces/60A.cpp From 5d25dfb23db3e8496edfe2311568348100704867 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Sat, 19 Oct 2019 08:26:24 +0530 Subject: [PATCH 115/324] Delete Jim and the orders.c --- Jim and the orders.c | 59 -------------------------------------------- 1 file changed, 59 deletions(-) delete mode 100644 Jim and the orders.c diff --git a/Jim and the orders.c b/Jim and the orders.c deleted file mode 100644 index 3423c163..00000000 --- a/Jim and the orders.c +++ /dev/null @@ -1,59 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include - -int main() -{ - int n,min; - scanf("%d",&n); - int order[n],prep[n],sum[n],fal[n],cu[n]; - for(int i=0;isum[k+1]) - { - temp=sum[k]; - sum[k]=sum[k+1]; - sum[k+1]=temp; - } - } - } - int v=0; - cu[v]=sum[0]; - for(int c=0;c<=n-2;c++) - { - if(sum[c]==sum[c+1]) - cu[v]=sum[c+1]; - else - { - v++; - cu[v]=sum[c+1]; - } - } - for(int g=0;g<=v;g++) - { - for(int f=0;f Date: Sat, 19 Oct 2019 09:24:55 +0530 Subject: [PATCH 116/324] Hey, i added a resizing algorithm --- Algorithms/C/resize.c | 99 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 Algorithms/C/resize.c diff --git a/Algorithms/C/resize.c b/Algorithms/C/resize.c new file mode 100644 index 00000000..7ccd5697 --- /dev/null +++ b/Algorithms/C/resize.c @@ -0,0 +1,99 @@ +// Copies a BMP file + +#include +#include + +#include "bmp.h" //name of your file for resizing purpose. file should be .h + +int main(int argc, char *argv[]) +{ + // ensure proper usage + if (argc != 3) + { + fprintf(stderr, "Usage: copy infile outfile\n"); + return 1; + } + + // remember filenames + char *infile = argv[1]; + char *outfile = argv[2]; + + // open input file + FILE *inptr = fopen(infile, "r"); + if (inptr == NULL) + { + fprintf(stderr, "Could not open %s.\n", infile); + return 2; + } + + // open output file + FILE *outptr = fopen(outfile, "w"); + if (outptr == NULL) + { + fclose(inptr); + fprintf(stderr, "Could not create %s.\n", outfile); + return 3; + } + + // read infile's BITMAPFILEHEADER + BITMAPFILEHEADER bf; + fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); + + // read infile's BITMAPINFOHEADER + BITMAPINFOHEADER bi; + fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); + + // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 + if (bf.bfType != 0x4d42 || bf.bfOffBits != 54 || bi.biSize != 40 || + bi.biBitCount != 24 || bi.biCompression != 0) + { + fclose(outptr); + fclose(inptr); + fprintf(stderr, "Unsupported file format.\n"); + return 4; + } + + // write outfile's BITMAPFILEHEADER + fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr); + + // write outfile's BITMAPINFOHEADER + fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr); + + // determine padding for scanlines + int padding = (4 - (bi.biWidth * sizeof(RGBTRIPLE)) % 4) % 4; + + // iterate over infile's scanlines + for (int i = 0, biHeight = abs(bi.biHeight); i < biHeight; i++) + { + // iterate over pixels in scanline + for (int j = 0; j < bi.biWidth; j++) + { + // temporary storage + RGBTRIPLE triple; + + // read RGB triple from infile + fread(&triple, sizeof(RGBTRIPLE), 1, inptr); + + // write RGB triple to outfile + fwrite(&triple, sizeof(RGBTRIPLE), 1, outptr); + } + + // skip over padding, if any + fseek(inptr, padding, SEEK_CUR); + + // then add it back (to demonstrate how) + for (int k = 0; k < padding; k++) + { + fputc(0x00, outptr); + } + } + + // close infile + fclose(inptr); + + // close outfile + fclose(outptr); + + // success + return 0; +} From 6ac102e2caa2fb3aae7eda96608d646530981994 Mon Sep 17 00:00:00 2001 From: notayushsonare <47273459+notayushsonare@users.noreply.github.com> Date: Sat, 19 Oct 2019 09:28:17 +0530 Subject: [PATCH 117/324] Creating a local host to share files --- HelloWorld/sharing_of_files.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 HelloWorld/sharing_of_files.py diff --git a/HelloWorld/sharing_of_files.py b/HelloWorld/sharing_of_files.py new file mode 100644 index 00000000..8eae8cda --- /dev/null +++ b/HelloWorld/sharing_of_files.py @@ -0,0 +1,7 @@ +import http.server +import socketserver +PORT = 8080 +Handler = http.server.SimpleHTTPRequestHandler +with socketserver.TCPServer(("", PORT), Handler) as httpd: + print("serving at port", PORT) + httpd.serve_forever() From d60b9ab03a6bfdd63b5f467a4d49dca3b666c7c1 Mon Sep 17 00:00:00 2001 From: Pratama Yoga Santosa Date: Sat, 19 Oct 2019 11:14:37 +0700 Subject: [PATCH 118/324] add birthday cake candles solution --- Hackerrank/C++/BirthdayCakeCandles.cpp | 77 ++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 Hackerrank/C++/BirthdayCakeCandles.cpp diff --git a/Hackerrank/C++/BirthdayCakeCandles.cpp b/Hackerrank/C++/BirthdayCakeCandles.cpp new file mode 100644 index 00000000..b176558d --- /dev/null +++ b/Hackerrank/C++/BirthdayCakeCandles.cpp @@ -0,0 +1,77 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the birthdayCakeCandles function below. +int birthdayCakeCandles(vector ar) { + int max = *max_element(ar.begin(), ar.end()); + int count= 0; + for (int i =0; i> ar_count; + cin.ignore(numeric_limits::max(), '\n'); + + string ar_temp_temp; + getline(cin, ar_temp_temp); + + vector ar_temp = split_string(ar_temp_temp); + + vector ar(ar_count); + + for (int i = 0; i < ar_count; i++) { + int ar_item = stoi(ar_temp[i]); + + ar[i] = ar_item; + } + + int result = birthdayCakeCandles(ar); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 87fb1438e30cd78329f3b7cd9037acd3683c56b1 Mon Sep 17 00:00:00 2001 From: Fernando Date: Sat, 19 Oct 2019 03:39:33 -0500 Subject: [PATCH 119/324] Add Queue class in DS/Java --- DS/Java/Queue.java | 51 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 DS/Java/Queue.java diff --git a/DS/Java/Queue.java b/DS/Java/Queue.java new file mode 100644 index 00000000..8dcdf622 --- /dev/null +++ b/DS/Java/Queue.java @@ -0,0 +1,51 @@ +import java.util.LinkedList; +import java.util.Queue; + +public class Test { + + public static void main(String args[]) { + Queue queue = new LinkedList<>(); + + queue_add(queue); + queue_poll(queue); + queue_add(queue); + queue_peek(queue); + queue_size(queue); + queue_remove(queue); + queue_size(queue); + } + + private static void queue_add(Queue queue) { + for (int i = 0; i < 5; i++) { + queue.add(i); + } + } + + private static void queue_poll(Queue queue) { + System.out.println("Poll :"); + + for (int i = 0; i < 5; i++) { + Integer y = queue.poll(); + System.out.println(y); + } + } + + private static void queue_remove(Queue queue) { + System.out.println("Remove :"); + + for (int i = 0; i < 5; i++) { + Integer y = queue.remove(); + System.out.println(y); + } + } + + private static void queue_peek(Queue queue) { + Integer element = queue.peek(); + System.out.println("Element on queue top : " + element); + } + + private static void queue_size(Queue queue) { + Integer size = queue.size(); + System.out.println("The actual size of the queue is: " + size); + } +} From 029248aecf5260ae1702ce44fec419923df8db80 Mon Sep 17 00:00:00 2001 From: PiotrSkoczylas <44222915+PiotrSkoczylas@users.noreply.github.com> Date: Sat, 19 Oct 2019 10:50:33 +0200 Subject: [PATCH 120/324] Add files via upload --- PHP/fibonacci.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 PHP/fibonacci.php diff --git a/PHP/fibonacci.php b/PHP/fibonacci.php new file mode 100644 index 00000000..6c2b24b0 --- /dev/null +++ b/PHP/fibonacci.php @@ -0,0 +1,12 @@ +"; +} +?> \ No newline at end of file From 17d09b38a55538372f6272961c14b6ec4e58b0e1 Mon Sep 17 00:00:00 2001 From: PiotrSkoczylas <44222915+PiotrSkoczylas@users.noreply.github.com> Date: Sat, 19 Oct 2019 10:55:31 +0200 Subject: [PATCH 121/324] Uploading fibonacci in php to Algorithms folder --- Algorithms/PHP/fibonacci.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Algorithms/PHP/fibonacci.php diff --git a/Algorithms/PHP/fibonacci.php b/Algorithms/PHP/fibonacci.php new file mode 100644 index 00000000..05d7b247 --- /dev/null +++ b/Algorithms/PHP/fibonacci.php @@ -0,0 +1,12 @@ +"; +} +?> From 63b23f43c2beb5fe9bd84f77eba83db679e6fa7e Mon Sep 17 00:00:00 2001 From: PiotrSkoczylas <44222915+PiotrSkoczylas@users.noreply.github.com> Date: Sat, 19 Oct 2019 10:59:16 +0200 Subject: [PATCH 122/324] Uploading Fibonacci in php to Algorithms folder --- Algorithms/PHP/fibonacci.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Algorithms/PHP/fibonacci.php diff --git a/Algorithms/PHP/fibonacci.php b/Algorithms/PHP/fibonacci.php new file mode 100644 index 00000000..05d7b247 --- /dev/null +++ b/Algorithms/PHP/fibonacci.php @@ -0,0 +1,12 @@ +"; +} +?> From 9b96eebea82787071229905749a0607d8247b792 Mon Sep 17 00:00:00 2001 From: PiotrSkoczylas <44222915+PiotrSkoczylas@users.noreply.github.com> Date: Sat, 19 Oct 2019 11:08:03 +0200 Subject: [PATCH 123/324] Uploading prime numbers in php prime numbers up to 1000 in php --- Algorithms/PHP/primeNumbers.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Algorithms/PHP/primeNumbers.php diff --git a/Algorithms/PHP/primeNumbers.php b/Algorithms/PHP/primeNumbers.php new file mode 100644 index 00000000..9f716017 --- /dev/null +++ b/Algorithms/PHP/primeNumbers.php @@ -0,0 +1,15 @@ +1;$x--) + { + if($i%$x==0) + { + $o=false; + break; + } + } + if($o) echo $i."
"; +} +?> From 5a7f7e1d8ebcea0de48fd17e12c38325e66ed2d2 Mon Sep 17 00:00:00 2001 From: PiotrSkoczylas <44222915+PiotrSkoczylas@users.noreply.github.com> Date: Sat, 19 Oct 2019 11:10:25 +0200 Subject: [PATCH 124/324] Uploading prime numbers in php Prime numbers up to 1000 in php From 9261bfddd6ad029dc6db3f1372f64041ca9ec2ed Mon Sep 17 00:00:00 2001 From: paweryk807 <43817473+paweryk807@users.noreply.github.com> Date: Sat, 19 Oct 2019 11:35:27 +0200 Subject: [PATCH 125/324] Dynamic Queue in C++ working on int values :) --- DS/C++/queueCpp.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 DS/C++/queueCpp.cpp diff --git a/DS/C++/queueCpp.cpp b/DS/C++/queueCpp.cpp new file mode 100644 index 00000000..1a75d73c --- /dev/null +++ b/DS/C++/queueCpp.cpp @@ -0,0 +1,77 @@ +#include +using namespace std; + +struct queue +{ + int value; + queue *next; +}; + +void removeFromQueue(queue*& head) // remove first element from queue +{ + if (head) + { + queue* ptr = head->next; + delete head; + head = ptr; + } +} + +void addToQueue(queue*& head, int nValue) // add new value to queue +{ + if (head == nullptr) // first element + { + head = new queue; + head->value = nValue; + head->next = nullptr; + } + else // add element on the end of the queue + { + auto ptr = head; + while (ptr->next) + { + ptr = ptr->next; + } + ptr->next = new queue{ nValue, nullptr }; + } +} + +void deleteQueue(queue *&head) // delete queue +{ + while (head) + { + auto ptr = head->next; + delete head; + head = ptr; + } +} + +void printQueue(queue *head) +{ + while (head) + { + cout << head->value << endl; + head = head->next; + } +} + +int main() +{ + // TEST + queue* pHead = nullptr; + addToQueue(pHead, 231); + addToQueue(pHead, 121); + addToQueue(pHead, 251); + addToQueue(pHead, 12); + addToQueue(pHead, 14); + addToQueue(pHead, 99); + printQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + printQueue(pHead); + deleteQueue(pHead); + + + +} From d709d421fcf3abee9059c0dfbf6afc50c311c304 Mon Sep 17 00:00:00 2001 From: PiotrSkoczylas <44222915+PiotrSkoczylas@users.noreply.github.com> Date: Sat, 19 Oct 2019 11:44:54 +0200 Subject: [PATCH 126/324] Hello world in php --- HelloWorld/helloworld.php | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 HelloWorld/helloworld.php diff --git a/HelloWorld/helloworld.php b/HelloWorld/helloworld.php new file mode 100644 index 00000000..21f83756 --- /dev/null +++ b/HelloWorld/helloworld.php @@ -0,0 +1,3 @@ + \ No newline at end of file From 472ab4f5622083f8c8978dcfc6a787663580f8f3 Mon Sep 17 00:00:00 2001 From: paweryk807 <43817473+paweryk807@users.noreply.github.com> Date: Sat, 19 Oct 2019 11:57:18 +0200 Subject: [PATCH 127/324] Hello World in JavaScript --- HelloWorld/HelloWorld.html | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 HelloWorld/HelloWorld.html diff --git a/HelloWorld/HelloWorld.html b/HelloWorld/HelloWorld.html new file mode 100644 index 00000000..cdb392d4 --- /dev/null +++ b/HelloWorld/HelloWorld.html @@ -0,0 +1,13 @@ + + + + + + + + + + + \ No newline at end of file From 2b15d0cb0179c7288ebdb2b1676c48734e706d5d Mon Sep 17 00:00:00 2001 From: paweryk807 <43817473+paweryk807@users.noreply.github.com> Date: Sat, 19 Oct 2019 13:00:24 +0200 Subject: [PATCH 128/324] BozoSort in CPP --- Algorithms/C++/BozoSort.cpp | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Algorithms/C++/BozoSort.cpp diff --git a/Algorithms/C++/BozoSort.cpp b/Algorithms/C++/BozoSort.cpp new file mode 100644 index 00000000..1d385941 --- /dev/null +++ b/Algorithms/C++/BozoSort.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +bool ifsorted(int* tab, int size) +{ + bool sorted = false; + for (int i = 1; i < size; i++) + { + if (tab[i - 1] <= tab[i]) sorted = true; + else return false; + } + return sorted; +} + +int main() // bozo sort +{ + srand(time(NULL)); + bool sorted = false; + int size = 0; + //long long int counter = 0; + cin >> size; + + int* tab = new int[size]; + + for (int i = 0; i < size; i++) + cin >> tab[i]; + + cout << endl; + while (!sorted) + { + int x = rand() % size; + int y = rand() % size; + int temp = tab[x]; + tab[x] = tab[y]; + tab[y] = temp; + sorted = ifsorted(tab, size); + //counter++; + } + //for (int i = 0; i < size; i++) + // cout << tab[i] << endl; + //cout << endl << endl << counter; +} \ No newline at end of file From 46472e0a5fb791696875c50406ca1a020daeff87 Mon Sep 17 00:00:00 2001 From: Kevva9844 Date: Sat, 19 Oct 2019 20:08:50 +0530 Subject: [PATCH 129/324] first commit --- HelloWorld/hellohack.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 HelloWorld/hellohack.py diff --git a/HelloWorld/hellohack.py b/HelloWorld/hellohack.py new file mode 100644 index 00000000..c3c83042 --- /dev/null +++ b/HelloWorld/hellohack.py @@ -0,0 +1 @@ +print("Hello hacktoberfest") \ No newline at end of file From d31396a5e52c0eb13ba3d2c4b46b16f0ab450ba5 Mon Sep 17 00:00:00 2001 From: Partha Prateem Patra Date: Sat, 19 Oct 2019 21:03:26 +0530 Subject: [PATCH 130/324] added the solution to the apple tree problem a solution to the apple tree problem found on hackerrank.com --- Hackerrank/C++/apple_tree_problem | 159 ++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 Hackerrank/C++/apple_tree_problem diff --git a/Hackerrank/C++/apple_tree_problem b/Hackerrank/C++/apple_tree_problem new file mode 100644 index 00000000..77f7b6c0 --- /dev/null +++ b/Hackerrank/C++/apple_tree_problem @@ -0,0 +1,159 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the countApplesAndOranges function below. +void countApplesAndOranges(int s, int t, int a, int b, int apples_count, int* apples, int oranges_count, int* oranges) { + int x[2] = {0,0}; +for(int i=0;i=s && (a+*(apples+i))<=t) + x[0]+=1; +} +for (int i = 0; i < oranges_count; i++) { + if (b + *(oranges + i) >= s && a + *(oranges + i) <= t) + x[1] += 1; +} +printf("%d \n%d",x[0],x[1]); +} + +int main() +{ + char** st = split_string(readline()); + + char* s_endptr; + char* s_str = st[0]; + int s = strtol(s_str, &s_endptr, 10); + + if (s_endptr == s_str || *s_endptr != '\0') { exit(EXIT_FAILURE); } + + char* t_endptr; + char* t_str = st[1]; + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + char** ab = split_string(readline()); + + char* a_endptr; + char* a_str = ab[0]; + int a = strtol(a_str, &a_endptr, 10); + + if (a_endptr == a_str || *a_endptr != '\0') { exit(EXIT_FAILURE); } + + char* b_endptr; + char* b_str = ab[1]; + int b = strtol(b_str, &b_endptr, 10); + + if (b_endptr == b_str || *b_endptr != '\0') { exit(EXIT_FAILURE); } + + char** mn = split_string(readline()); + + char* m_endptr; + char* m_str = mn[0]; + int m = strtol(m_str, &m_endptr, 10); + + if (m_endptr == m_str || *m_endptr != '\0') { exit(EXIT_FAILURE); } + + char* n_endptr; + char* n_str = mn[1]; + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char** apples_temp = split_string(readline()); + + int* apples = malloc(m * sizeof(int)); + + for (int i = 0; i < m; i++) { + char* apples_item_endptr; + char* apples_item_str = *(apples_temp + i); + int apples_item = strtol(apples_item_str, &apples_item_endptr, 10); + + if (apples_item_endptr == apples_item_str || *apples_item_endptr != '\0') { exit(EXIT_FAILURE); } + + *(apples + i) = apples_item; + } + + int apples_count = m; + + char** oranges_temp = split_string(readline()); + + int* oranges = malloc(n * sizeof(int)); + + for (int i = 0; i < n; i++) { + char* oranges_item_endptr; + char* oranges_item_str = *(oranges_temp + i); + int oranges_item = strtol(oranges_item_str, &oranges_item_endptr, 10); + + if (oranges_item_endptr == oranges_item_str || *oranges_item_endptr != '\0') { exit(EXIT_FAILURE); } + + *(oranges + i) = oranges_item; + } + + int oranges_count = n; + + countApplesAndOranges(s, t, a, b, apples_count, apples, oranges_count, oranges); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} + +char** split_string(char* str) { + char** splits = NULL; + char* token = strtok(str, " "); + + int spaces = 0; + + while (token) { + splits = realloc(splits, sizeof(char*) * ++spaces); + if (!splits) { + return splits; + } + + splits[spaces - 1] = token; + + token = strtok(NULL, " "); + } + + return splits; +} From 4ba6aa46adb1dcf651b2e886dac70cb7179fd692 Mon Sep 17 00:00:00 2001 From: alexsantee Date: Sat, 19 Oct 2019 15:08:05 -0300 Subject: [PATCH 131/324] heap implementation in C --- DS/C/heap.c | 154 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 DS/C/heap.c diff --git a/DS/C/heap.c b/DS/C/heap.c new file mode 100644 index 00000000..9c85bde5 --- /dev/null +++ b/DS/C/heap.c @@ -0,0 +1,154 @@ +#include +#include + +//data type to be stored in the heap +typedef int elem; +//max number of elements in the heap +#define MAX_SIZE 100 + +//easily passing from index zero to index one +#define PARENT (((pos+1)/2)-1) //truncate division +#define LEFT ((pos+1)*2-1) +#define RIGHT (((pos+1)*2+1)-1) +//failed to allocate memory +#define MEM_ERR 1 + +//heap data type definition +struct heap{ + elem *list; + int size; +}; + +//FUNCTIONS +//constructors +int init_heap(int size, struct heap *heap); +struct heap *heapify(elem *list, int size); +//destructor +void destroy_heap(struct heap *heap); +//actions +void insert(elem a, struct heap *heap); +elem extract_min(struct heap *heap); +elem remove_min(struct heap *heap); +//internal functions +int sift_up(int pos, struct heap *heap); +int sift_down(int pos, struct heap *heap); + +//Simple use of heap for sorting +int main(){ + elem list[8] = {45, 42, 26, 48, 86, 39, 46, 30}; + struct heap *heap; + heap = heapify(list, 8); + int i; + for(i=0; i<8; i++){ + printf("%d ", remove_min(heap)); + } + putchar('\n'); + + destroy_heap(heap); + return 0; +} + +//Returns 0 if sucessfull or MEM_ERR if it fails to allocate memory +int init_heap(int size, struct heap *heap){ + heap->size = 0; + heap->list = malloc(sizeof(elem)*size); + if(heap->list == NULL) return MEM_ERR; + return 0; +} + +//Returns heap if sucessfull or NULL if it fails to allocate memory +struct heap *heapify(elem *list, int size){ + + struct heap *heap = malloc(1*sizeof(struct heap)); + //Check for failures when allocating the heap + if(heap==NULL) return NULL; + if (init_heap(MAX_SIZE, heap) == MEM_ERR){ + free(heap); + return NULL; + } + + //Copy list to heap + int i; + for(i=0; ilist[i] = list[i]; + heap->size = size; + + if (size <= 1) {return heap;} //list is already heap + + //Every leaf is a heap, pos is the first non-leaf node + int pos = size-1; + pos = PARENT; + //Put the smallest on top + while(pos >= 0){ + sift_down(pos, heap); + pos--; + } + + return heap; +} + +void destroy_heap(struct heap *heap){ + heap->size=0; + free(heap->list); +} + +void insert(elem a, struct heap *heap){ + int pos = heap->size; //Inserting in the end of the list + heap->list[pos] = a; + heap->size++; + //Pulls the last element up the heap + sift_up(pos, heap); +} + +elem extract_min(struct heap *heap){ + return heap->list[0]; +} + +elem remove_min(struct heap *heap){ + elem min = heap->list[0]; + //Puts last element on top + heap->list[0] = heap->list[--heap->size]; + //Pushes the first element down the heap + sift_down(0, heap); + return min; +} + +int sift_up(int pos, struct heap *heap){ + elem aux; + while(heap->list[pos] < heap->list[PARENT]){ + aux = heap->list[pos]; + heap->list[pos] = heap->list[PARENT]; + heap->list[PARENT] = aux; + pos = PARENT; + } + return pos; +} + +int sift_down(int pos, struct heap *heap){ + elem aux; + while(RIGHT < heap->size){ + if(heap->list[LEFT] <= heap->list[RIGHT] && heap->list[LEFT] < heap->list[pos]){ + aux = heap->list[pos]; + heap->list[pos] = heap->list[LEFT]; + heap->list[LEFT] = aux; + pos = LEFT; + } + else if(heap->list[RIGHT] < heap->list[pos]){ + aux = heap->list[pos]; + heap->list[pos] = heap->list[RIGHT]; + heap->list[RIGHT] = aux; + pos = RIGHT; + } + else{ //current is the smallest + return pos; + } + } + + //Last parent has one child + if(LEFT < heap->size && heap->list[LEFT] < heap->list[pos]){ + aux = heap->list[LEFT]; + heap->list[LEFT] = heap->list[pos]; + heap->list[pos] = aux; + } + + return pos; +} From f0a1c015b16052c6714a9ce14b70775386c11513 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20G=C3=B3mez=20Cota?= <38957780+diegomezcota@users.noreply.github.com> Date: Sat, 19 Oct 2019 13:32:00 -0500 Subject: [PATCH 132/324] Added new problem Insert Node at the tail of a linked list. // Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list --- Hackerrank/C++/insertNodeTailLinkedList.cpp | 70 +++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Hackerrank/C++/insertNodeTailLinkedList.cpp diff --git a/Hackerrank/C++/insertNodeTailLinkedList.cpp b/Hackerrank/C++/insertNodeTailLinkedList.cpp new file mode 100644 index 00000000..897da895 --- /dev/null +++ b/Hackerrank/C++/insertNodeTailLinkedList.cpp @@ -0,0 +1,70 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + + SinglyLinkedList() { + this->head = nullptr; + } + +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtTail function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { + if (!head) head = new SinglyLinkedListNode(data); + else { + SinglyLinkedListNode* curr = head; + while (curr->next) curr = curr->next; + curr->next = new SinglyLinkedListNode(data); + } + return head; +} + +int main() \ No newline at end of file From 54565dc6e99c28650134d3c41376e64304de9e7b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20G=C3=B3mez=20Cota?= <38957780+diegomezcota@users.noreply.github.com> Date: Sat, 19 Oct 2019 13:37:02 -0500 Subject: [PATCH 133/324] New Hackerrank cpp problems Hashmaps, linkedlists, stdin, stdout, helloWorld. --- Hackerrank/C++/inputOutput.cpp | 15 +++++++ Hackerrank/C++/mapsSTL.cpp | 39 +++++++++++++++++ Hackerrank/C++/printLinkedList.cpp | 69 ++++++++++++++++++++++++++++++ Hackerrank/C++/sayHelloWorld.cpp | 10 +++++ 4 files changed, 133 insertions(+) create mode 100644 Hackerrank/C++/inputOutput.cpp create mode 100644 Hackerrank/C++/mapsSTL.cpp create mode 100644 Hackerrank/C++/printLinkedList.cpp create mode 100644 Hackerrank/C++/sayHelloWorld.cpp diff --git a/Hackerrank/C++/inputOutput.cpp b/Hackerrank/C++/inputOutput.cpp new file mode 100644 index 00000000..33fe055c --- /dev/null +++ b/Hackerrank/C++/inputOutput.cpp @@ -0,0 +1,15 @@ +#include +#include +#include +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-input-and-output/problem + +int main() { + int a, b, c; + cin >> a >> b >> c; + cout << a+b+c << endl; + return 0; +} diff --git a/Hackerrank/C++/mapsSTL.cpp b/Hackerrank/C++/mapsSTL.cpp new file mode 100644 index 00000000..609e948e --- /dev/null +++ b/Hackerrank/C++/mapsSTL.cpp @@ -0,0 +1,39 @@ +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/cpp-maps/problem + +int main() { + /* Enter your code here. Read input from STDIN. Print output to STDOUT */ + int iQueries, iType; + long long iData; + string sName; + unordered_map mStudents; + cin >> iQueries; + while (iQueries--){ + cin >> iType; + switch (iType){ + case 1: + cin >> sName >> iData; + mStudents[sName] += iData; + break; + case 2: + cin >> sName; + mStudents[sName] = 0; + break; + case 3: + cin >> sName; + cout << mStudents[sName] << endl; + break; + default: + break; + } + } + return 0; +} \ No newline at end of file diff --git a/Hackerrank/C++/printLinkedList.cpp b/Hackerrank/C++/printLinkedList.cpp new file mode 100644 index 00000000..572c3014 --- /dev/null +++ b/Hackerrank/C++/printLinkedList.cpp @@ -0,0 +1,69 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the printLinkedList function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +void printLinkedList(SinglyLinkedListNode* head) { + SinglyLinkedListNode* curr = head; + while (curr){ + cout << curr->data << endl; + curr = curr->next; + } +} + +int main() \ No newline at end of file diff --git a/Hackerrank/C++/sayHelloWorld.cpp b/Hackerrank/C++/sayHelloWorld.cpp new file mode 100644 index 00000000..c9ca033d --- /dev/null +++ b/Hackerrank/C++/sayHelloWorld.cpp @@ -0,0 +1,10 @@ +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-hello-world/problem + +int main() { + printf("Hello, World!"); + return 0; +} \ No newline at end of file From f6c55d07c4b98261b1ff8191c921a095e29e440f Mon Sep 17 00:00:00 2001 From: Willian Garcia Date: Sat, 19 Oct 2019 15:13:30 -0500 Subject: [PATCH 134/324] 339A,349A,903A,903C --- Codeforces/339A.cpp | 25 +++++++++++++++++++++++++ Codeforces/349A.cpp | 35 +++++++++++++++++++++++++++++++++++ Codeforces/903A.cpp | 24 ++++++++++++++++++++++++ Codeforces/903C.cpp | 36 ++++++++++++++++++++++++++++++++++++ 4 files changed, 120 insertions(+) create mode 100644 Codeforces/339A.cpp create mode 100644 Codeforces/349A.cpp create mode 100644 Codeforces/903A.cpp create mode 100644 Codeforces/903C.cpp diff --git a/Codeforces/339A.cpp b/Codeforces/339A.cpp new file mode 100644 index 00000000..370ef815 --- /dev/null +++ b/Codeforces/339A.cpp @@ -0,0 +1,25 @@ +//339A - Helpful Maths +//Author : wgarcia1309 + +#include +#include +#include +using namespace std; +int main(){ + char s[101]; + int m[100],ind=0; + memset (s,'+',101); + scanf("%s",s); + for(int i=0;i<101;i++){ + if(s[i]!='+' && (int)s[i]!=0){ + m[ind]=(int)s[i]-48; + ind++; + } + } + sort(m,m+ind); + for(int i=0;i +using namespace std; +int main() { + int n,m[100001],change[3]; + change[0]=change[1]=change[2]=0; + cin>>n; + bool x=true; + for(int i=0;i>m[i]; + if((m[i])/25==1 && x){ + change[0]++; + }else if(x){ + if((m[i])/25==2){ + if(change[0]<=0)x=false; + change[0]--; + change[1]++; + }else{ + if(change[0]>0 && change[1]>0){ + change[0]--; + change[1]--; + change[3]++; + }else if (change[0]>2){ + change[0]-=3; + change[3]++; + }else{ + x=false; + } + } + } + } + if(x)cout << "YES\n"; + else cout << "NO\n"; +} \ No newline at end of file diff --git a/Codeforces/903A.cpp b/Codeforces/903A.cpp new file mode 100644 index 00000000..1e244ac8 --- /dev/null +++ b/Codeforces/903A.cpp @@ -0,0 +1,24 @@ +//903A - Hungry Student Problem +//Author : wgarcia1309 +#include +using namespace std; +int main(){ + int n; + bool r[110]; + for(int i=0;i<=109;i++)r[i]=false; + for(int i=3;i<=100;i+=3){ + r[i]=true; + for(int j=7;j<=100;j+=7){ + r[j]=true; + if(i+j<=100)r[i+j]=true; + } + } + cin>>n; + while(n--){ + int t; + cin>>t; + if(r[t])cout<<"YES\n"; + else cout<<"NO\n"; + } + return 0; +} \ No newline at end of file diff --git a/Codeforces/903C.cpp b/Codeforces/903C.cpp new file mode 100644 index 00000000..0d030777 --- /dev/null +++ b/Codeforces/903C.cpp @@ -0,0 +1,36 @@ +//903C - Boxes Packing +//Author : wgarcia1309 +#include +using namespace std; +int main(){ + int n,c[5000],r[5000],ind=0; + cin>>n; + memset(r,0,sizeof(r)); + memset(c,0,sizeof(c)); + for(int i=0;i>r[i]; + sort(r,r+n); + if(n>1){ + c[0]=r[n-1]; + ind++; + bool x=true; + for(int i=n-2;i>=0;i--){ + int m=-1; + for(int j=0;j=c[m]){ + c[ind]=r[i]; + ind++; + }else{ + c[m]=r[i]; + } + } + cout< Date: Sat, 19 Oct 2019 17:33:26 -0500 Subject: [PATCH 135/324] Create HelloWorld.cs --- HelloWorld/HelloWorld.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 HelloWorld/HelloWorld.cs diff --git a/HelloWorld/HelloWorld.cs b/HelloWorld/HelloWorld.cs new file mode 100644 index 00000000..a68542dc --- /dev/null +++ b/HelloWorld/HelloWorld.cs @@ -0,0 +1,12 @@ +using System; + +namespace HelloWorld +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +} From 24a876fb673ad6e32c8531504aa8dfae3c705cfa Mon Sep 17 00:00:00 2001 From: Jared Bardell <54115604+jbardell19@users.noreply.github.com> Date: Sat, 19 Oct 2019 17:45:27 -0500 Subject: [PATCH 136/324] Create SolveMeFirst.cs C# Folder --- Hackerrank/C#/SolveMeFirst.cs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Hackerrank/C#/SolveMeFirst.cs diff --git a/Hackerrank/C#/SolveMeFirst.cs b/Hackerrank/C#/SolveMeFirst.cs new file mode 100644 index 00000000..264d8547 --- /dev/null +++ b/Hackerrank/C#/SolveMeFirst.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; +using System.IO; +class Solution { + + static int solveMeFirst(int a, int b) { + // Hint: Type return a+b; below + + } + + static void Main(String[] args) { + int val1 = Convert.ToInt32(Console.ReadLine()); + int val2 = Convert.ToInt32(Console.ReadLine()); + int sum = solveMeFirst(val1,val2); + Console.WriteLine(sum); + } +} From dd21a852bbe571a6711a7d9b2f29793fb2c32ca1 Mon Sep 17 00:00:00 2001 From: Jared Bardell <54115604+jbardell19@users.noreply.github.com> Date: Sat, 19 Oct 2019 17:51:09 -0500 Subject: [PATCH 137/324] Added line return a+b; --- Hackerrank/C#/SolveMeFirst.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Hackerrank/C#/SolveMeFirst.cs b/Hackerrank/C#/SolveMeFirst.cs index 264d8547..74b98d95 100644 --- a/Hackerrank/C#/SolveMeFirst.cs +++ b/Hackerrank/C#/SolveMeFirst.cs @@ -4,8 +4,8 @@ class Solution { static int solveMeFirst(int a, int b) { - // Hint: Type return a+b; below - + return a+b; + } static void Main(String[] args) { From 155416a43814adfdfc9488db58c5a12d138adaf6 Mon Sep 17 00:00:00 2001 From: deepam101 Date: Sun, 20 Oct 2019 04:45:36 +0530 Subject: [PATCH 138/324] FANCY program of codechef --- Codechef/FANCY.java | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Codechef/FANCY.java diff --git a/Codechef/FANCY.java b/Codechef/FANCY.java new file mode 100644 index 00000000..c78e9dc8 --- /dev/null +++ b/Codechef/FANCY.java @@ -0,0 +1,34 @@ +import java.io.*; +class quotes +{ + public static void main(String args[])throws IOException + { String str=""; + int c=0,f=0; + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); + int n=Integer.parseInt(br.readLine()); + if(n<1 ||n>50) + { + + return; + } + for(int i=1;i<=n;i++) + { + String s=br.readLine(); + str=s+" "; + for(int j=0;j100) + continue; + } + if(s.indexOf(" not ")!=-1 || s.indexOf("not ")==0 || s.lastIndexOf(" not")==s.length()-4 ) + System.out.println("Real Fancy"); + else + System.out.println("regularly fancy"); + + + + } +} +} \ No newline at end of file From d429606461b17de0bf885a7a8fcb3748fc9307fb Mon Sep 17 00:00:00 2001 From: PratikPathak21 <32901042+PratikPathak21@users.noreply.github.com> Date: Sun, 20 Oct 2019 08:21:51 +0530 Subject: [PATCH 139/324] Create 909B.py --- Codeforces/909B.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Codeforces/909B.py diff --git a/Codeforces/909B.py b/Codeforces/909B.py new file mode 100644 index 00000000..9c4d8a49 --- /dev/null +++ b/Codeforces/909B.py @@ -0,0 +1,22 @@ +import math +a=int(input()) +if(a==1): + print(1) +elif(a==2): + print(2) +elif(a==3): + print(4) +elif(a==4): + print(6) +else: + b=a + d=a-2 + e=1 + while(d>0): + if(d>=e): + b+=e + else: + b+=d + d-=1 + e+=1 + print(b) From 3a2aa798ea90e0f59ea3cd239c1592adc725f6f9 Mon Sep 17 00:00:00 2001 From: PratikPathak21 <32901042+PratikPathak21@users.noreply.github.com> Date: Sun, 20 Oct 2019 08:24:16 +0530 Subject: [PATCH 140/324] Create 913B.cpp --- Codeforces/913B.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Codeforces/913B.cpp diff --git a/Codeforces/913B.cpp b/Codeforces/913B.cpp new file mode 100644 index 00000000..c959ca4d --- /dev/null +++ b/Codeforces/913B.cpp @@ -0,0 +1,42 @@ +#include +using namespace std; +int main() +{ + int t,z=0,d=0,e=0; + cin>>t; + int a[t-1]; + int b[t]={0}; + for(int i=0;i>a[i]; + b[a[i]-1]+=1; + } + for(int i=0;i0) + {d+=1; + int c=0; + for(int j=0;j=3) + {e+=1; + } + else + { + cout<<"No"< Date: Sun, 20 Oct 2019 08:28:32 +0530 Subject: [PATCH 141/324] Create C++BIT2B.cpp --- Codechef/C++BIT2B.cpp | 151 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 151 insertions(+) create mode 100644 Codechef/C++BIT2B.cpp diff --git a/Codechef/C++BIT2B.cpp b/Codechef/C++BIT2B.cpp new file mode 100644 index 00000000..241e7229 --- /dev/null +++ b/Codechef/C++BIT2B.cpp @@ -0,0 +1,151 @@ +#include + +using namespace std; + +#define fast_cin() ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); +#define MAX 1000000 +#define ll long long +#define db double +#define str string +#define pb push_back +#define For(i,s,e) for (ll i=(s); i<(e); i++) +#define Forrev(i,s,e) for (ll i=(s); i>=(e); i--) +#define all(v) v.begin(),v.end() + +#define vll vector +#define vs vector +#define mapll map +#define pll pair +#define initialise(a, x) memset(a, x, sizeof(a)) +#define maxheap priority_queue +#define minheap priority_queue ,greater> + +#define ff first +#define ss second +#define endl "\n" +#define mp make_pair +const ll mod=1e9 + 7; + +ll takemod(ll a) { + return ((a%mod)+mod)%mod; +} + +ll gcd(ll a, ll b) { + if (b == 0) + return a; + return gcd(b, a % b); +} + +ll fast_exp(ll base, ll expo) { + ll res=1; + while(expo>0) { + if(expo&1) res=(res*base)%mod; + base=(base*base)%mod; + expo>>=1;} + return res; +} + +ll modinv(ll a) { + return takemod(fast_exp(takemod(a), mod-2)); +} + + +signed main() +{ + fast_cin(); + #ifndef ONLINE_JUDGE + freopen("C:/IO/in.txt", "r", stdin); + freopen("C:/IO/out.txt", "w", stdout); + #endif + ll t,n; + cin>>t; + For(l,0,t) + { + cin>>n; + ll arr[n]; + For(i,0,n) + { + cin>>arr[i]; + } + + ll x; + cin>>x; + + ll i=0,j=n-1,sum1=0,sum2=0; + ll sumarr[n]; + memset(sumarr,0,sizeof(sumarr)); + + ll markarr[n]; + memset(markarr,-1,sizeof(markarr)); + + while(i<=j) + { + if(i==j) + { + if(markarr[i]!=-1) + break; + ll ans1=0,ans2=0; + For(k,0,n) + { + //cout<=ans2) + { + markarr[i]=1; + i++; + } + else + { + markarr[i]=2; + j--; + } + } + else + { + sum1=0,sum2=0; + sum2=arr[j]; + markarr[j]=2; + while(ix*sum2) + { + sumarr[i]+=x*sum2-sum1; + sum1=sum2; + markarr[i]=1; + if(sumarr[i]==arr[i]) + i++; + break; + } + else + { + sum1+=arr[i]-sumarr[i]; + markarr[i]=1; + i++; + } + } + j--; + //cout< Date: Sun, 20 Oct 2019 09:47:42 +0530 Subject: [PATCH 142/324] Added Solution for Journey to the Moon Hackerrank --- Hackerrank/Python/JourneytotheMoon.py | 54 +++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Hackerrank/Python/JourneytotheMoon.py diff --git a/Hackerrank/Python/JourneytotheMoon.py b/Hackerrank/Python/JourneytotheMoon.py new file mode 100644 index 00000000..e8e32d8d --- /dev/null +++ b/Hackerrank/Python/JourneytotheMoon.py @@ -0,0 +1,54 @@ +MAXN = 100000+5 +MAXI = 1000000+5 + +n,i = input().split(' ') + +n = int(n) +I = int(i) + +a = [-1 for i in range(0,n)] +co = [1 for i in range(0,n)] + +def F(x): + t = x + while ( a[t] != -1 ): + t = a[t] + if ( ( a[x] != -1 ) & ( a[x] != t ) ): + a[x] = t + #co[t] += co[x] + return t + +def U(x,y): + fx = F(x) + fy = F(y) + #print("!! %d %d"%(fx,fy)) + if ( fx != fy ): + a[fx] = fy + co[fy] += co[fx] + + +for i in range(0,I): + x,y = input().split(' ') + x = int(x) + y = int(y) + U(x,y) + + +l = [] +c = 0 +A = 0 + +for i in range(0,n): + if ( a[i] == -1 ): + l.insert(c,co[i]) + A += co[i] + c = c+1 + +#print(l) +ans = 0 +for i in range(0,c): + ans += l[i]*(A-l[i]) + +ans = ans//2 + +print(ans) From 29f08961292e272eaa7a690d4b20e27386775a84 Mon Sep 17 00:00:00 2001 From: Bhanuka Rathnayaka Date: Sun, 20 Oct 2019 09:51:09 +0530 Subject: [PATCH 143/324] Solution for Hackerrank Dijkstra Shortest Reach 2 #26 Solution for Hackerrank Dijkstra Shortest Reach 2 Hackerrank --- Hackerrank/Python/DijkstraShortestReach2.py | 49 +++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Hackerrank/Python/DijkstraShortestReach2.py diff --git a/Hackerrank/Python/DijkstraShortestReach2.py b/Hackerrank/Python/DijkstraShortestReach2.py new file mode 100644 index 00000000..8a16a1cc --- /dev/null +++ b/Hackerrank/Python/DijkstraShortestReach2.py @@ -0,0 +1,49 @@ + +from collections import defaultdict + +import heapq + + +def dijkstra(S, N, G): + D = {} + H = [(0, S)] + + for n in range(1, N + 1): + D[n] = float('inf') + + D[S] = 0 + + while H: + t = heapq.heappop(H) + for h in G[t[1]]: + if D[h[0]] > D[t[1]] + h[1]: + D[h[0]] = D[t[1]] + h[1] + if (h[1], h[0]) in H: + H.remove((h[1], h[0])) + heapq.heapify(H) + heapq.heappush(H, (D[h[0]], h[0])) + + return D + + +def main(): + T = int(input()) + + for _ in range(T): + N, M = [int(i) for i in input().split()] + + G = defaultdict(set) + + for _ in range(M): + e = [int(i) for i in input().split()] + G[e[0]].add((e[1], e[2])) + G[e[1]].add((e[0], e[2])) + + S = int(input()) + + D = dijkstra(S, N, G) + print(' '.join(str(D[n]) if D[n] != float('inf') else '-1' for n in range(1, N + 1) if n != S)) + + +if __name__ == "__main__": + main() From f7ad3ccbb012bee631ccb40308a3f8635244d15f Mon Sep 17 00:00:00 2001 From: Janitha133 <33251135+Janitha133@users.noreply.github.com> Date: Sun, 20 Oct 2019 10:06:03 +0530 Subject: [PATCH 144/324] Palindrome Index Given a string of lowercase letters in the range ascii[a-z], determine a character that can be removed to make the string a palindrome. There may be more than one solution, but any will do. For example, if your string is "bcbc", you can either remove 'b' at index 0 or 'c' at index 3. If the word is already a palindrome or there is no solution, return -1. Otherwise, return the index of a character to remove. --- Hackerrank/Java/PalindromeIndex.java | 38 ++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Hackerrank/Java/PalindromeIndex.java diff --git a/Hackerrank/Java/PalindromeIndex.java b/Hackerrank/Java/PalindromeIndex.java new file mode 100644 index 00000000..3d805bcb --- /dev/null +++ b/Hackerrank/Java/PalindromeIndex.java @@ -0,0 +1,38 @@ +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the palindromeIndex function below. + static int palindromeIndex(String s) { + + + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int q = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int qItr = 0; qItr < q; qItr++) { + String s = scanner.nextLine(); + + int result = palindromeIndex(s); + + bufferedWriter.write(String.valueOf(result)); + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} From 5111b01e4cd7ff9da5ef1da1bee228eb250af7df Mon Sep 17 00:00:00 2001 From: Janitha133 <33251135+Janitha133@users.noreply.github.com> Date: Sun, 20 Oct 2019 10:15:55 +0530 Subject: [PATCH 145/324] String Construction Amanda has a string of lowercase letters that she wants to copy to a new string. She can perform the following operations with the given costs. She can perform them any number of times to construct a new string : Append a character to the end of string p at a cost of 1 dollar. Choose any substring of p and append it to the end of p at no charge. Given n strings s[i], find and print the minimum cost of copying each s[i] to p[i] on a new line. For example, given a string s =abcabc, it can be copied for 3 dollars. Start by copying a,b and c individually at a cost of 1 dollar per character. String p=abc at this time. Copy p[0:2] to the end of p at no cost to complete the copy. --- Hackerrank/Java/StringConstruction.java | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Hackerrank/Java/StringConstruction.java diff --git a/Hackerrank/Java/StringConstruction.java b/Hackerrank/Java/StringConstruction.java new file mode 100644 index 00000000..db672e56 --- /dev/null +++ b/Hackerrank/Java/StringConstruction.java @@ -0,0 +1,38 @@ +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the stringConstruction function below. + static int stringConstruction(String s) { + + + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int q = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int qItr = 0; qItr < q; qItr++) { + String s = scanner.nextLine(); + + int result = stringConstruction(s); + + bufferedWriter.write(String.valueOf(result)); + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} From 860760a2e2888a18077d2955b226eca44e996336 Mon Sep 17 00:00:00 2001 From: Janitha133 <33251135+Janitha133@users.noreply.github.com> Date: Sun, 20 Oct 2019 10:25:03 +0530 Subject: [PATCH 146/324] Plus Minus Given an array of integers, calculate the fractions of its elements that are positive, negative, and are zeros. Print the decimal value of each fraction on a new line. --- Hackerrank/c/PlusMinus.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Hackerrank/c/PlusMinus.c diff --git a/Hackerrank/c/PlusMinus.c b/Hackerrank/c/PlusMinus.c new file mode 100644 index 00000000..e90488a9 --- /dev/null +++ b/Hackerrank/c/PlusMinus.c @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include +#include + +int main() +{ + int n; + + scanf("%d",&n); + int arr[n]; + int arr_i; + + for(arr_i = 0; arr_i < n; arr_i++) + { + scanf("%d",&arr[arr_i]); + } + float a=0 ,b=0 ,c=0 ; + for(arr_i = 0; arr_i < n; arr_i++) + { if(arr[arr_i]> 0) + {a += 1;} + + else if(arr[arr_i]<0) + {b += 1;} + + else + {c += 1;} + } + printf("%f\n%f\n%f\n", a/n, b/n, c/n); + + return 0; +} From 23e1a601e84db13405f8e64b0dc9349fbad76ebf Mon Sep 17 00:00:00 2001 From: Janitha133 <33251135+Janitha133@users.noreply.github.com> Date: Sun, 20 Oct 2019 10:34:01 +0530 Subject: [PATCH 147/324] update Palindrome Index --- Hackerrank/Java/PalindromeIndex.java | 56 +++++++++++++++------------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/Hackerrank/Java/PalindromeIndex.java b/Hackerrank/Java/PalindromeIndex.java index 3d805bcb..c12b9d5b 100644 --- a/Hackerrank/Java/PalindromeIndex.java +++ b/Hackerrank/Java/PalindromeIndex.java @@ -8,31 +8,37 @@ public class Solution { - // Complete the palindromeIndex function below. - static int palindromeIndex(String s) { - - - } - - private static final Scanner scanner = new Scanner(System.in); - - public static void main(String[] args) throws IOException { - BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); - - int q = scanner.nextInt(); - scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); - - for (int qItr = 0; qItr < q; qItr++) { - String s = scanner.nextLine(); - - int result = palindromeIndex(s); - - bufferedWriter.write(String.valueOf(result)); - bufferedWriter.newLine(); +public static boolean palindrome(String s){ + StringBuffer sb = new StringBuffer(); + sb = sb.append(s); + sb = sb.reverse(); + String n = sb.toString(); + if(n.equals(s)){ + return true; + } + else return false; +} +public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + for(int a=0; a Date: Sun, 20 Oct 2019 10:39:21 +0530 Subject: [PATCH 148/324] Non-Divisible Subset --- Hackerrank/C++/NonDivisibleSubset.cpp | 31 +++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Hackerrank/C++/NonDivisibleSubset.cpp diff --git a/Hackerrank/C++/NonDivisibleSubset.cpp b/Hackerrank/C++/NonDivisibleSubset.cpp new file mode 100644 index 00000000..9d7ebce1 --- /dev/null +++ b/Hackerrank/C++/NonDivisibleSubset.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include +#include +using namespace std; + +int main() { + int n,k; + cin>>n>>k; + int rem[k]={0}; + for(int i=0;i>x; + rem[x%k]++; + }int count = 0; + count += min(rem[0],1); + if(k%2 != 0){ + for(int i=1;i<(k/2)+1;i++){ + count += max(rem[i],rem[k-i]); + } + } + else{ + for(int i=1;i Date: Sun, 20 Oct 2019 02:10:35 -0400 Subject: [PATCH 149/324] Create helloworld.html helloworld.html --- HelloWorld/helloworld.html | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 HelloWorld/helloworld.html diff --git a/HelloWorld/helloworld.html b/HelloWorld/helloworld.html new file mode 100644 index 00000000..321fd2a7 --- /dev/null +++ b/HelloWorld/helloworld.html @@ -0,0 +1,9 @@ + + + + Hello World + + +

Hello World!
This is an example of a simple HTML page with Hello World at the Title.

+ + From bb1f54cbbcf9db121a4d3c331110876adb7600f6 Mon Sep 17 00:00:00 2001 From: Jessica Wong <39626651+wongjessica@users.noreply.github.com> Date: Sun, 20 Oct 2019 02:12:54 -0400 Subject: [PATCH 150/324] Create HelloWorld.java HelloWorld.java, helloworld program in Java --- HelloWorld/HelloWorld.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 HelloWorld/HelloWorld.java diff --git a/HelloWorld/HelloWorld.java b/HelloWorld/HelloWorld.java new file mode 100644 index 00000000..6c31ff73 --- /dev/null +++ b/HelloWorld/HelloWorld.java @@ -0,0 +1,9 @@ +/* HelloWorld.java + */ + +public class HelloWorld +{ + public static void main(String[] args) { + System.out.println("Hello World!"); + } +} From 9c029e40050542a02e202ca62a085798ce6ecd45 Mon Sep 17 00:00:00 2001 From: Jessica Wong <39626651+wongjessica@users.noreply.github.com> Date: Sun, 20 Oct 2019 02:14:46 -0400 Subject: [PATCH 151/324] Create helloworld.cpp helloworld.cpp, C++ program for Hello World --- HelloWorld/helloworld.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 HelloWorld/helloworld.cpp diff --git a/HelloWorld/helloworld.cpp b/HelloWorld/helloworld.cpp new file mode 100644 index 00000000..9fcd9252 --- /dev/null +++ b/HelloWorld/helloworld.cpp @@ -0,0 +1,10 @@ +#include + +using namespace std; + +int main() +{ + cout<<"Hello World"; + + return 0; +} From 3b7097310a7663696820814118102befb011473a Mon Sep 17 00:00:00 2001 From: Jessica Wong <39626651+wongjessica@users.noreply.github.com> Date: Sun, 20 Oct 2019 02:23:53 -0400 Subject: [PATCH 152/324] Create twoSum.cpp twoSum.cpp from https://leetcode.com/problems/two-sum/ --- LeetCode/twoSum.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/twoSum.cpp diff --git a/LeetCode/twoSum.cpp b/LeetCode/twoSum.cpp new file mode 100644 index 00000000..adac5e35 --- /dev/null +++ b/LeetCode/twoSum.cpp @@ -0,0 +1,21 @@ +vector twoSum(vector &numbers, int target) +{ + //Key is the number and value is its index in the vector. + unordered_map hash; + vector result; + for (int i = 0; i < numbers.size(); i++) { + int numberToFind = target - numbers[i]; + + //if numberToFind is found in map, return them + if (hash.find(numberToFind) != hash.end()) { + //+1 because indices are NOT zero based + result.push_back(hash[numberToFind] + 1); + result.push_back(i + 1); + return result; + } + + //number was not found. Put it in the map. + hash[numbers[i]] = i; + } + return result; +} From 7b83ead9d388a8e7e79c2585858af35c77a9c785 Mon Sep 17 00:00:00 2001 From: aounmalhi Date: Sun, 20 Oct 2019 04:08:36 -0700 Subject: [PATCH 153/324] Add files via upload --- Algorithms/C++/cNode.cpp | 37 ++++++++++++++++ Algorithms/C++/cNode.h | 17 ++++++++ Algorithms/C++/cQue.cpp | 92 ++++++++++++++++++++++++++++++++++++++++ Algorithms/C++/cQue.h | 18 ++++++++ 4 files changed, 164 insertions(+) create mode 100644 Algorithms/C++/cNode.cpp create mode 100644 Algorithms/C++/cNode.h create mode 100644 Algorithms/C++/cQue.cpp create mode 100644 Algorithms/C++/cQue.h diff --git a/Algorithms/C++/cNode.cpp b/Algorithms/C++/cNode.cpp new file mode 100644 index 00000000..42cf283b --- /dev/null +++ b/Algorithms/C++/cNode.cpp @@ -0,0 +1,37 @@ +#include +#include "cNode.h" + +using namespace std; + +cNode::cNode() :data(0),priority(0) +{ +} + +cNode::cNode(int d):data(d), priority(0){ +} + +cNode::cNode(int d, int p):data(d), priority(p) +{} + +int cNode::getData(){ + return data; + } + +cNode* cNode::setData(int data){ + this->data=data; + } + +void cNode::print()const{ + cout<priority=Prior; +} + +cNode::~cNode() +{ +} diff --git a/Algorithms/C++/cNode.h b/Algorithms/C++/cNode.h new file mode 100644 index 00000000..c6841970 --- /dev/null +++ b/Algorithms/C++/cNode.h @@ -0,0 +1,17 @@ +class cNode +{ + int data; + int priority; +public: + cNode *next; + cNode(); + cNode(int d); + cNode(int d, int p); + int getData(); + cNode* setData(int data); + void print()const; + int getPriority() const; + void setPriority(int prior); + ~cNode(); +}; + diff --git a/Algorithms/C++/cQue.cpp b/Algorithms/C++/cQue.cpp new file mode 100644 index 00000000..ee22428e --- /dev/null +++ b/Algorithms/C++/cQue.cpp @@ -0,0 +1,92 @@ +#include +#include "cQue.h" + +using namespace std; + +cQue::cQue():tail(NULL) +{ +} + +cQue::cQue(cNode* &ptr):cStack(ptr),tail(top){ + } + +bool cQue::isNotEmpty()const{ + return cStack::isNotEmpty(); + } + +bool cQue::isEmpty()const{ + return cStack::isEmpty(); + } + +cNode* cQue::remove(){ + if(!top->next) + tail=NULL; + return cStack::pop(); + } + +cQue& cQue::add(cNode* &ptr){ + if(tail){ + tail->next=ptr; + tail=tail->next; + } + else + { + tail=ptr; + top=ptr; + } + tail->next=NULL; + ptr=NULL; + return *this; + } + +void cQue::print()const{ // + cStack::print(); + } + +cQue::cQue(const cQue &src){ /// + this->top=src.top; + this->tail=src.tail; + if(src.top){ + cNode *sptr,*dptr; + dptr=top=new cNode(*src.top); + sptr=top->next; + while(sptr){ + dptr->next=new cNode(*sptr); + dptr=dptr->next; + sptr=sptr->next; + } + tail=dptr; + } + } + +cQue& cQue::operator=(const cQue& obj){ + if(this==&obj) + return *this; + if(true){ + cQue temp; + temp.top=top; + temp.tail=tail; + } + if(true){ + cQue temp=obj; + top=temp.top; + tail=temp.tail; + temp.top=NULL; + temp.tail=NULL; + } + return *this; + } + +cQue::~cQue() +{ + cNode *ptr = top; + + tail = NULL; + + while (ptr) + { + ptr = ptr -> next; + delete top; + top = ptr; + } +} diff --git a/Algorithms/C++/cQue.h b/Algorithms/C++/cQue.h new file mode 100644 index 00000000..5b536ca9 --- /dev/null +++ b/Algorithms/C++/cQue.h @@ -0,0 +1,18 @@ +#pragma once +#include"cStack.h" +class cQue:protected cStack{ +protected: + cNode *tail; +public: + cQue(); + cQue(cNode* &ptr); + bool isNotEmpty()const; + bool isEmpty()const; + cNode* remove(); + cQue& add(cNode* &ptr); + void print()const; + cQue(const cQue &src); + cQue& operator=(const cQue& obj); + ~cQue(); +}; + From c0a468d46fc7daaf833845830945f26906fd972e Mon Sep 17 00:00:00 2001 From: VIPUL SHARMA <35504451+vipulSharma18@users.noreply.github.com> Date: Sun, 20 Oct 2019 20:16:38 +0530 Subject: [PATCH 154/324] Added Codeforces global round 5's question 1 solution --- Codeforces/1237A.cpp | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Codeforces/1237A.cpp diff --git a/Codeforces/1237A.cpp b/Codeforces/1237A.cpp new file mode 100644 index 00000000..8ea9e6e7 --- /dev/null +++ b/Codeforces/1237A.cpp @@ -0,0 +1,57 @@ +//vipul sharma, code forces global round question 1 +#include +using namespace std; + +int main(){ + int n; cin>>n; + int a[n]; + int orig[n]; + float temp; + int sum = 0; + for(int i =0; i>temp; + orig[n] = temp; + if((int)temp%2==0){ + a[i] = temp/2; + } + else{ + temp = temp/2.0; + temp += 0.5; + a[i] = (int)temp; + } + sum+=a[i]; + } + int change=1; + if(sum>0){ + for(int i =0; i0){ + a[i] -=1; + sum -=1; + } + cout<0 + for(int i =0; i0){ + // a[i] +=1; //adding 1 to ceil is wrong + // sum +=1; + //} + cout< Date: Mon, 21 Oct 2019 00:08:34 +0530 Subject: [PATCH 155/324] Added Convertion of infix to postfix expression in C --- Algorithms/C/infixtopostfixconvertion.c | 110 ++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 Algorithms/C/infixtopostfixconvertion.c diff --git a/Algorithms/C/infixtopostfixconvertion.c b/Algorithms/C/infixtopostfixconvertion.c new file mode 100644 index 00000000..3fa9528d --- /dev/null +++ b/Algorithms/C/infixtopostfixconvertion.c @@ -0,0 +1,110 @@ +/* This Program converts infix expression to postfix expression */ +#include +#include + +#define MAX_SIZE 100 +// Top of the stack +int top = -1; +// Array representing stack +char stack[MAX_SIZE]; +// Checks whether stack is empty or not +int isStackEmpty(void){ + return (top < 0) ? 1 : 0; +} +// Checks whether stack is full or not +int isStackFull(void){ + return (top == MAX_SIZE) ? 1 : 0; +} +// Push elements in the stack +void pushStack(char item){ + if(isStackFull()){ + printf("Stack Overflow!\n"); + return; + } + top++; + stack[top] = item; +} +// Pop elements in the stack +char popStack(void){ + if(isStackEmpty()){ + printf("Stack Underflow!\n"); + return -1; + } + char item = stack[top]; + top--; + return item; +} +// Function to input the infix expression +void scanExp(char *str){ + char ch,i; + for(i=0; (ch=getchar()) != '\n'; i++){ + str[i] = ch; + } + str[i] = '\0'; +} + +// Function to check whether the character is an operator +int isOperator(char ch){ + switch(ch){ + case '^': + case '/': + case '*': + case '+': + case '-': + return 1; + default: + return 0; + } +} + +// Function converts the infix expression to postfix expression +void infix2postfix(char *infix, char *postfix){ + // Operator Predecence + int operators[256]; + operators['^'] = 0; + operators['*'] = 1; + operators['/'] = 1; + operators['+'] = 2; + operators['-'] = 2; + + infix[strlen(infix)] = ')'; + + int i, j; + pushStack('('); + for(i=0,j=0;!isStackEmpty();){ + if(!isOperator(infix[i]) && infix[i] != '(' && infix[i] != ')'){ + postfix[j]=infix[i]; + i++; + j++; + }else if(infix[i] == '('){ + pushStack(infix[i]); + i++; + }else if(isOperator(infix[i])){ + while(isOperator(stack[top]) && operators[stack[top]] <= operators[infix[i]]){ + char operator = popStack(); + postfix[j]=operator; + j++; + } + pushStack(infix[i]); + i++; + }else if(infix[i] == ')'){ + char item; + while((item=popStack()) != '('){ + postfix[j] = item; + j++; + } + i++; + } + } + postfix[j] = '\0'; +} + +int main(void){ + char infix[100], postfix[100]; + printf("Enter the infix expression : "); + scanExp(infix); + printf("Infix Expression : %s\n", infix); + infix2postfix(infix, postfix); + printf("Postfix Expression : %s\n", postfix); + return 0; +} From a5d10a7379c14609143539f58bbb9aff873ae774 Mon Sep 17 00:00:00 2001 From: Archiita Date: Mon, 21 Oct 2019 00:15:54 +0530 Subject: [PATCH 156/324] Added Sorting a linked list in cpp --- Algorithms/C++/linkdlistsort.cpp | 74 ++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Algorithms/C++/linkdlistsort.cpp diff --git a/Algorithms/C++/linkdlistsort.cpp b/Algorithms/C++/linkdlistsort.cpp new file mode 100644 index 00000000..ce54052a --- /dev/null +++ b/Algorithms/C++/linkdlistsort.cpp @@ -0,0 +1,74 @@ + +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} + }; +ListNode* merge(ListNode* A, ListNode* B){ + if(A == NULL){ + return B; + } + if(B == NULL){ + return A; + } + + ListNode* head = NULL; + + if(A->val < B->val){ + head = A; + A = A->next; + } + else{ + head = B; + B = B->next; + } + + ListNode* temp = head; + + while(A != NULL && B != NULL){ + if(A->val < B->val){ + temp->next = A; + A = A->next; + } + else{ + temp->next = B; + B = B->next; + } + temp = temp->next; + } + + if(A != NULL){ + temp->next = A; + } + else{ + temp->next = B; + } + + return head; +} + +ListNode* Solution::sortList(ListNode* A) { + // Do not write main() function. + // Do not read input, instead use the arguments to the function. + // Do not print the output, instead return values as specified + // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details + + ListNode* head = A; + + if(head == NULL || head->next == NULL){ + return head; + } + + ListNode* start = A; + ListNode* end = A->next; + + while(end != NULL && end->next != NULL){ + start = start->next; + end = (end->next)->next; + } + + end = start->next; + start->next = NULL; + + return merge(sortList(head), sortList(end)); +} From 0da4ee0549f3306104d51ea0e3b5f7660710cd1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20G=C3=B3mez=20Cota?= <38957780+diegomezcota@users.noreply.github.com> Date: Sun, 20 Oct 2019 20:51:17 -0500 Subject: [PATCH 157/324] Add node at specific position of linked list --- Hackerrank/C++/insertNodeSpecificPosition.cpp | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 Hackerrank/C++/insertNodeSpecificPosition.cpp diff --git a/Hackerrank/C++/insertNodeSpecificPosition.cpp b/Hackerrank/C++/insertNodeSpecificPosition.cpp new file mode 100644 index 00000000..e4c9a33b --- /dev/null +++ b/Hackerrank/C++/insertNodeSpecificPosition.cpp @@ -0,0 +1,92 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtPosition function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { + + SinglyLinkedListNode *curr = head, *temp; + + if (position == 0){ + temp = head; + head = new SinglyLinkedListNode(data); + head->next = temp; + } + + while (--position) curr = curr->next; + + temp = curr->next; + curr->next = new SinglyLinkedListNode(data); + curr->next->next = temp; + + return head; +} + +int main() \ No newline at end of file From 4bdacddd24d3372ee21ada923aeb067ab9464443 Mon Sep 17 00:00:00 2001 From: Carbon24 <47106927+Carbon24@users.noreply.github.com> Date: Mon, 21 Oct 2019 11:57:20 +0530 Subject: [PATCH 158/324] Create 1206B.cpp Added 1206B --- Codeforces/1206B.cpp | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Codeforces/1206B.cpp diff --git a/Codeforces/1206B.cpp b/Codeforces/1206B.cpp new file mode 100644 index 00000000..8897c624 --- /dev/null +++ b/Codeforces/1206B.cpp @@ -0,0 +1,33 @@ +#include +#include +using namespace std; +using LL =long long; + +int main(){ + LL n,ele,noof0=0; + cin>>n; + vector pos,neg; + LL nsum=0,psum=0; + for(int i=0;i>ele; + if(ele<0)neg.push_back(ele); + else if(ele>0)pos.push_back(ele); + else nsum++,noof0++; + } + for(auto a:neg)nsum+=-a-1; + for(auto a:pos)psum+=a-1; + + if(neg.size()%2==0) + cout<< nsum+psum; + else + { + if(noof0) + cout< Date: Mon, 21 Oct 2019 12:00:40 +0530 Subject: [PATCH 159/324] Create 1206A.cpp 1206A --- Codeforces/1206A.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Codeforces/1206A.cpp diff --git a/Codeforces/1206A.cpp b/Codeforces/1206A.cpp new file mode 100644 index 00000000..adb92db8 --- /dev/null +++ b/Codeforces/1206A.cpp @@ -0,0 +1,21 @@ +#include +#include +using namespace std; +using LL =long long; + +int main() + { + LL n,m; + cin>>n; + vector A(n); + for(auto &a:A)cin>>a; + cin>>m; + vector B(m); + for(auto &b:B)cin>>b; + sort(A.begin(),A.end()); + sort(B.begin(),B.end()); + + cout< Date: Mon, 21 Oct 2019 12:02:46 +0530 Subject: [PATCH 160/324] Create 1220A.cpp 1220A --- Codeforces/1220A.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Codeforces/1220A.cpp diff --git a/Codeforces/1220A.cpp b/Codeforces/1220A.cpp new file mode 100644 index 00000000..b63bdbed --- /dev/null +++ b/Codeforces/1220A.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL n,a,b; + cin>>n; + string str; + cin>>str; + unordered_map um; + for(int i=0;i Date: Mon, 21 Oct 2019 12:04:03 +0530 Subject: [PATCH 161/324] Create 1221A.cpp some recent codeforce contest solutions --- Codeforces/1221A.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Codeforces/1221A.cpp diff --git a/Codeforces/1221A.cpp b/Codeforces/1221A.cpp new file mode 100644 index 00000000..2416cc14 --- /dev/null +++ b/Codeforces/1221A.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL t,n,a,b; + cin>>t; + while(t--){ + b=0; + cin>>n; + unordered_map um; + for(int i=0;i>a; + if(a<=2048) + um[a]++; + } + for(int i=0;i<12;i++) + { + if(um[1<=2)um[1<<(i+1)]+=um[1< Date: Mon, 21 Oct 2019 12:05:05 +0530 Subject: [PATCH 162/324] Create 1221B.cpp some recent codeforce contest solutions --- Codeforces/1221B.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Codeforces/1221B.cpp diff --git a/Codeforces/1221B.cpp b/Codeforces/1221B.cpp new file mode 100644 index 00000000..a889c48d --- /dev/null +++ b/Codeforces/1221B.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL t,i=0; + cin>>t; + char a[t][t]; + while(i Date: Mon, 21 Oct 2019 12:05:44 +0530 Subject: [PATCH 163/324] Create 1221C.cpp some recent codeforce contest solutions --- Codeforces/1221C.cpp | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Codeforces/1221C.cpp diff --git a/Codeforces/1221C.cpp b/Codeforces/1221C.cpp new file mode 100644 index 00000000..09decef0 --- /dev/null +++ b/Codeforces/1221C.cpp @@ -0,0 +1,15 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL t,c,m,x; + cin>>t; + while(t--){ + cin>>c>>m>>x; + LL min1=__min(c,m); + LL max1=(c+m+x)/3; + min1=min(max1,min1); + cout< Date: Mon, 21 Oct 2019 12:06:28 +0530 Subject: [PATCH 164/324] Create 1230A.cpp some recent codeforce contest solutions --- Codeforces/1230A.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Codeforces/1230A.cpp diff --git a/Codeforces/1230A.cpp b/Codeforces/1230A.cpp new file mode 100644 index 00000000..50b1008d --- /dev/null +++ b/Codeforces/1230A.cpp @@ -0,0 +1,12 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL n,a,b,c,d; + cin>>a>>b>>c>>d; + if(a+b==c+d || a+c==b+d || a+d==b+c || a==b+c+d || b==a+c+d || c==a+b+d || d==a+b+c)cout<<"YES"; + else + cout<<"NO"; + +} From cea0916ea294e8ba13474f8f9dcd30570eacd035 Mon Sep 17 00:00:00 2001 From: Carbon24 <47106927+Carbon24@users.noreply.github.com> Date: Mon, 21 Oct 2019 12:07:16 +0530 Subject: [PATCH 165/324] Create 1230B.cpp some recent codeforce contest solutions --- Codeforces/1230B.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Codeforces/1230B.cpp diff --git a/Codeforces/1230B.cpp b/Codeforces/1230B.cpp new file mode 100644 index 00000000..3854deb6 --- /dev/null +++ b/Codeforces/1230B.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; +using LL =long long; + +int main() { + LL n,k; + cin>>n>>k; + int a[n],i=1,j=0; + string str; + cin>>str; + if(k==0) + cout< Date: Mon, 21 Oct 2019 12:08:40 +0530 Subject: [PATCH 166/324] Create 1236A.cpp some recent codeforce contest solutions --- Codeforces/1236A.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Codeforces/1236A.cpp diff --git a/Codeforces/1236A.cpp b/Codeforces/1236A.cpp new file mode 100644 index 00000000..29747893 --- /dev/null +++ b/Codeforces/1236A.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; +using LL =long long;#include +#include +using namespace std; +using LL= long long; + +int main() +{ + int t,p=0; + cin>>t; + for(int j=0;j>a>>b>>c; + while(b>0 && c>1) + { + c-=2; + b--; + p+=3; + } + while(a>0 && b>1) + { + b-=2; + a--; + p+=3; + } + cout< Date: Mon, 21 Oct 2019 12:11:28 +0530 Subject: [PATCH 167/324] Create 1236C.cpp solution for recent codeforce contest question --- Codeforces/1236C.cpp | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Codeforces/1236C.cpp diff --git a/Codeforces/1236C.cpp b/Codeforces/1236C.cpp new file mode 100644 index 00000000..52982b6c --- /dev/null +++ b/Codeforces/1236C.cpp @@ -0,0 +1,31 @@ +#include +using namespace std; +using LL =long long; +LL x,y,z; + +int main() { + LL n,k=1,m=0; + cin>>n; + int a[n][n]={0}; + for(int i=0;i Date: Mon, 21 Oct 2019 12:12:31 +0530 Subject: [PATCH 168/324] Create 1238A.cpp solution for recent codeforce contest question --- Codeforces/1238A.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Codeforces/1238A.cpp diff --git a/Codeforces/1238A.cpp b/Codeforces/1238A.cpp new file mode 100644 index 00000000..6c6e86ea --- /dev/null +++ b/Codeforces/1238A.cpp @@ -0,0 +1,18 @@ +#include +using namespace std; + + +int main() +{ + int t; + cin>>t; + long long x,y,i; + while(t--) + { + cin>>x>>y; + i=x-y; + + if(i==1)cout<<"NO"< Date: Mon, 21 Oct 2019 12:13:22 +0530 Subject: [PATCH 169/324] Create 1244B.cpp solution for recent codeforce contest question --- Codeforces/1244B.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Codeforces/1244B.cpp diff --git a/Codeforces/1244B.cpp b/Codeforces/1244B.cpp new file mode 100644 index 00000000..fa62a776 --- /dev/null +++ b/Codeforces/1244B.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; +using LL =long long; +int a[1004],ones,zeros; + +int main() { + LL t,k,count=0; + cin>>t; + string str; + while(t--) + { + cin>>k; + cin>>str; + int y=0,z1=0,z2=0; + while(!(str[y++]-'0'))z1++; + y=k-1; + while(!(str[y--]-'0'))z2++; + + if(str[0]=='1'|| str[k-1]=='1') + cout<<2*k< Date: Mon, 21 Oct 2019 12:14:03 +0530 Subject: [PATCH 170/324] Create 1248B.cpp solution for recent codeforce contest question --- Codeforces/1248B.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Codeforces/1248B.cpp diff --git a/Codeforces/1248B.cpp b/Codeforces/1248B.cpp new file mode 100644 index 00000000..10749bd9 --- /dev/null +++ b/Codeforces/1248B.cpp @@ -0,0 +1,20 @@ +#include +using namespace std; +using LL =long long; +LL x,y,z; + +int main() { + LL n,sum1=0,sum2=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + sort(a,a+n); + + for(int i=0;i Date: Mon, 21 Oct 2019 15:16:57 +0530 Subject: [PATCH 171/324] Rename Hackerrank/c/PlusMinus.c to Hackerrank/C/PlusMinus.c --- Hackerrank/{c => C}/PlusMinus.c | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerrank/{c => C}/PlusMinus.c (100%) diff --git a/Hackerrank/c/PlusMinus.c b/Hackerrank/C/PlusMinus.c similarity index 100% rename from Hackerrank/c/PlusMinus.c rename to Hackerrank/C/PlusMinus.c From 7c31046a9a56f5a2aa5d1bcde154c08c4ffaad1a Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 21 Oct 2019 15:19:19 +0530 Subject: [PATCH 172/324] Rename C++BIT2B.cpp to BIT2B.cpp --- Codechef/{C++BIT2B.cpp => BIT2B.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Codechef/{C++BIT2B.cpp => BIT2B.cpp} (100%) diff --git a/Codechef/C++BIT2B.cpp b/Codechef/BIT2B.cpp similarity index 100% rename from Codechef/C++BIT2B.cpp rename to Codechef/BIT2B.cpp From 21eb24849648cb69d0192292627e68ce539b3087 Mon Sep 17 00:00:00 2001 From: deepam101 Date: Mon, 21 Oct 2019 19:50:12 +0530 Subject: [PATCH 173/324] hidden.cpp --- Codechef/CHNUM.java | 89 +++++++++++++++++++++++++++++++++++++++++++++ Codechef/HDDN.cpp | 80 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+) create mode 100644 Codechef/CHNUM.java create mode 100644 Codechef/HDDN.cpp diff --git a/Codechef/CHNUM.java b/Codechef/CHNUM.java new file mode 100644 index 00000000..91cd09d1 --- /dev/null +++ b/Codechef/CHNUM.java @@ -0,0 +1,89 @@ +import java.util.*; +import java.lang.Math; +class Byteland +{ + public static void main(String args[]) + { + Scanner sc=new Scanner(System.in); + int t=sc.nextInt(),j=0; + if(t<1 || t>20) + return; + int c[][]=new int[t][2]; + int count1=0,count2=0,count3=0,max=0,min=0,sum=0; + for(int i=1;i<=t;i++) + { + max=0;min=0;count1=0;count2=0;count3=0; + int n=sc.nextInt(); + + if(n<1 || n>100000) + continue; + sum+=n; + int a[]=new int[n]; + + for( j=0;jMath.pow(10,9)) + continue; + } + + + for(j=0;j0) + count1++; + + else if(a[j]<0) + count2++; + + else count3++; + + if(count1!=0 && count2!=0) + { + if(count3!=0) + { + if(count1>count2) + {max=count1+count3; + min=count2;} + else + {max=count2+count3; + min=count1; + } + } + else + { + if(count1>count2) + { + max=count1; + min=count2; + } + else + { + max=count2; + min=count1; + } + } + } + else + { + if(count1!=0) + { + max=count1;min=count1; + } + if(count2!=0) + { + max=count2;min=count2; + } + + } + + c[i-1][0]=max; + c[i-1][1]=min; + + } + if(sum<=500000) + for(int i=0;i + +using namespace std; + +struct Node { + int x, y, z; +}; + +const int N = (int)5e5 + 5; + +int n, k, m, a[N], fa[N], lim[N], used[N], cnt[N], pre[N]; +vector v; + +int find(int x) { + return x == fa[x] ? x : fa[x] = find(fa[x]); +} + +void init() { + cin >> n >> k >> m; + v.clear(); + fa[0] = 1; + fa[n + 1] = n + 1; + for(int i = 1 ; i <= n ; ++i) { + pre[i] = 0; + cnt[i] = 0; + used[i] = 0; + lim[i] = 0; + a[i] = -1; + fa[i] = i; + } + for(int i = 0 ; i < m ; ++i) { + int x, y, z; cin >> x >> y >> z; + v.push_back({x, y, z}); + } + sort(v.begin(), v.end(), [&](Node x, Node y) { return x.z < y.z; }); +} +bool solve() { + for(auto i : v) { + if(a[i.z] != -1 || i.y > i.z) return false; + a[i.z] = i.x; fa[i.z] = fa[i.z + 1]; + i.y -= cnt[i.x]; + if(i.y < 1) return false; + cnt[i.x] += i.y; lim[i.z] = i.x; + int tt = i.z; + i.z = pre[i.x]; + while(i.y > 1) { + i.z = find(i.z); +// cerr << pre[i.x] << ' ' << i.z << '\n'; + if(i.z >= tt) break; + a[i.z] = i.x; fa[i.z] = fa[i.z + 1]; i.y--; + } + pre[i.x] = tt; + if(i.y > 1) return false; + } + int now = 1; + for(int i = n ; i >= 1 ; --i) { + if(a[i] == -1) { + while(used[now] && now <= k) now++; + if(now > k) return false; + a[i] = now; + } + else if(lim[i] > 0) { + used[lim[i]] = 1; + } + } + cout << "Yes\n"; + for(int i = 1 ; i <= n ; ++i) cout << a[i] << " \n"[i == n]; + return true; +} + +int main() { + ios_base::sync_with_stdio(0), cin.tie(0); + int t; cin >> t; + while(t--) { + init(); + if(!solve()) cout << "No\n"; + } +} From dfa40b4d9e234d58ab5f00c2ff47d3159bc0e4d7 Mon Sep 17 00:00:00 2001 From: deepam101 Date: Mon, 21 Oct 2019 19:54:11 +0530 Subject: [PATCH 174/324] order n chaos problem --- Codechef/ORDNCHS.cpp | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Codechef/ORDNCHS.cpp diff --git a/Codechef/ORDNCHS.cpp b/Codechef/ORDNCHS.cpp new file mode 100644 index 00000000..50603619 --- /dev/null +++ b/Codechef/ORDNCHS.cpp @@ -0,0 +1,47 @@ +#include +#include +using namespace std; +typedef pair pr; +#define fr first +#define se second +pr p[10][10]; +char r(char c){ + return"XO"[c=='X']; +} +void work(){ + int i,x,y; + char s[5]; + pr t; + printf("CHAOS\n"); + fflush(stdout); + for(i=0;i<18;i++){ + scanf("%d%d%s",&x,&y,s); + t=p[x][y]; + printf("%d %d %c\n",t.fr,t.se,(x==1||x==6)&&(y==1||y==6)?s[0]:r(s[0])); + fflush(stdout); + } +} +int main(){ + #define gao(a,b,c,d) p[a][b]={c,d};p[c][d]={a,b}; + gao(1,1,6,6) + gao(1,6,6,1) + gao(1,3,1,4) + gao(6,3,6,4) + gao(3,1,4,1) + gao(3,6,4,6) + gao(2,2,2,3) + gao(3,2,3,3) + gao(4,4,4,5) + gao(5,4,5,5) + gao(4,2,5,2) + gao(4,3,5,3) + gao(2,4,3,4) + gao(2,5,3,5) + gao(1,2,5,6) + gao(2,1,6,5) + gao(5,1,1,5) + gao(6,2,2,6) + int T; + scanf("%d",&T); + while(T--)work(); +} From 38b5bffd2eb454cf6dfac670ab685e9f9c39b701 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 21 Oct 2019 15:38:54 +0530 Subject: [PATCH 175/324] Rename PHP/fibonacci.php to fibonacci.php --- PHP/fibonacci.php => fibonacci.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename PHP/fibonacci.php => fibonacci.php (91%) diff --git a/PHP/fibonacci.php b/fibonacci.php similarity index 91% rename from PHP/fibonacci.php rename to fibonacci.php index 6c2b24b0..05d7b247 100644 --- a/PHP/fibonacci.php +++ b/fibonacci.php @@ -9,4 +9,4 @@ function Fibo($n) { echo Fibo($i)."
"; } -?> \ No newline at end of file +?> From 110aac017656128fe69b8eaa4d5291ec6bd9eeba Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 21 Oct 2019 15:39:11 +0530 Subject: [PATCH 176/324] Delete fibonacci.php --- fibonacci.php | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 fibonacci.php diff --git a/fibonacci.php b/fibonacci.php deleted file mode 100644 index 05d7b247..00000000 --- a/fibonacci.php +++ /dev/null @@ -1,12 +0,0 @@ -"; -} -?> From 2c71b66a59def19722c2634321779086efa6d02d Mon Sep 17 00:00:00 2001 From: yctseng1227 Date: Mon, 21 Oct 2019 19:20:57 +0800 Subject: [PATCH 177/324] created 1216D.cpp --- Codeforces/1216D.cpp | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Codeforces/1216D.cpp diff --git a/Codeforces/1216D.cpp b/Codeforces/1216D.cpp new file mode 100644 index 00000000..7d96aace --- /dev/null +++ b/Codeforces/1216D.cpp @@ -0,0 +1,40 @@ +// code by yctseng1227 +#include +#define _ ios_base::sync_with_stdio(0);cin.tie(0); +#define PB push_back +typedef long long ll; +using namespace std; + +#define MAXN 200005 + +int gcd(int a, int b) { return b ? gcd(b, a%b) : a; } + +int main() +{_ + ll n, g, MAX=0; cin >> n; + vector vv(n), v; + for(int i=0; i> vv[i]; + MAX = max(MAX, vv[i]); + } + for(int i=0; i Date: Mon, 21 Oct 2019 20:09:50 +0800 Subject: [PATCH 178/324] Created 1166C.cpp --- Codeforces/1166C.cpp | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Codeforces/1166C.cpp diff --git a/Codeforces/1166C.cpp b/Codeforces/1166C.cpp new file mode 100644 index 00000000..255d3330 --- /dev/null +++ b/Codeforces/1166C.cpp @@ -0,0 +1,29 @@ +// code by yctseng1227 +#include +#define _ ios_base::sync_with_stdio(0);cin.tie(0); +#define ALL(x) x.begin(),x.end() +typedef long long ll; +using namespace std; + +#define MAXN 200005 + +int main() +{_ + int n; cin >> n; + vector v(n); + for(int i=0; i> v[i]; + if(v[i]<0) v[i]*=-1; + } + sort(ALL(v)); + + ll ans = 0, k=1; + for(int i=0; i Date: Mon, 21 Oct 2019 20:18:07 +0530 Subject: [PATCH 179/324] Update DFS.cpp --- Algorithms/C++/DFS.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Algorithms/C++/DFS.cpp b/Algorithms/C++/DFS.cpp index d0268fb8..993c3f3f 100644 --- a/Algorithms/C++/DFS.cpp +++ b/Algorithms/C++/DFS.cpp @@ -38,7 +38,8 @@ int main() cin>>edge;int a;int b; for(int i=0;i>a;cin>>b; + cin>>a; + cin>>b; addEdge(arr,a,b); } vector::iterator itr; From d1386f784c1ba3a56cdbd232016d42bb01275f58 Mon Sep 17 00:00:00 2001 From: Shashank <32913634+skumrao@users.noreply.github.com> Date: Mon, 21 Oct 2019 20:19:46 +0530 Subject: [PATCH 180/324] Update Fibonacci.cpp --- Algorithms/C++/Fibonacci.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/Algorithms/C++/Fibonacci.cpp b/Algorithms/C++/Fibonacci.cpp index fce13b43..0ecfadee 100644 --- a/Algorithms/C++/Fibonacci.cpp +++ b/Algorithms/C++/Fibonacci.cpp @@ -1,3 +1,4 @@ +// Cpp program to print fibonacci numbers #include using namespace std; From 32c4a533234fcd181f672af954123c96d4161de5 Mon Sep 17 00:00:00 2001 From: Shashank <32913634+skumrao@users.noreply.github.com> Date: Mon, 21 Oct 2019 20:21:07 +0530 Subject: [PATCH 181/324] Update ALPHABET.c --- Codechef/ALPHABET.c | 1 + 1 file changed, 1 insertion(+) diff --git a/Codechef/ALPHABET.c b/Codechef/ALPHABET.c index eedaaedd..5b23234b 100644 --- a/Codechef/ALPHABET.c +++ b/Codechef/ALPHABET.c @@ -14,6 +14,7 @@ int main(void) { { scanf("%s",&str); int i,j; + int l=strlen(str); for(i=0;i Date: Mon, 21 Oct 2019 20:21:56 +0530 Subject: [PATCH 182/324] Update hello.cpp --- HelloWorld/hello.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/HelloWorld/hello.cpp b/HelloWorld/hello.cpp index 5bc3b38b..e8864b2b 100644 --- a/HelloWorld/hello.cpp +++ b/HelloWorld/hello.cpp @@ -3,6 +3,7 @@ using namespace std; int main() { - cout << "Hello World!" << endl; + cout << "Hello World!" ; + cout<< endl; return 0; } From 78e1115e301cdf5ae1f7996dd15afdddfecbfc73 Mon Sep 17 00:00:00 2001 From: Shashank <32913634+skumrao@users.noreply.github.com> Date: Mon, 21 Oct 2019 20:23:06 +0530 Subject: [PATCH 183/324] Update 303.py --- LeetCode/303.py | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/LeetCode/303.py b/LeetCode/303.py index 8e607a0a..4874aa34 100644 --- a/LeetCode/303.py +++ b/LeetCode/303.py @@ -1,9 +1,7 @@ -''' -Problem: 303. Range Sum Query - Immutable -https://leetcode.com/problems/range-sum-query-immutable/ -Author: Luis Herrera -Summary: We use a prefix array to make the queries in constant time O(1). -''' +#Problem: 303. Range Sum Query - Immutable +#https://leetcode.com/problems/range-sum-query-immutable/ +#Author: Luis Herrera +#Summary: We use a prefix array to make the queries in constant time O(1). class NumArray(object): From 535b1f35a8cb1aa3fcfc636abfb4d794ab322d99 Mon Sep 17 00:00:00 2001 From: Pratama Yoga Santosa Date: Mon, 21 Oct 2019 22:34:04 +0700 Subject: [PATCH 184/324] Add "Compare The Triplets" solution --- Hackerrank/C++/CompareTheTriplets.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Hackerrank/C++/CompareTheTriplets.cpp diff --git a/Hackerrank/C++/CompareTheTriplets.cpp b/Hackerrank/C++/CompareTheTriplets.cpp new file mode 100644 index 00000000..2ff70b2a --- /dev/null +++ b/Hackerrank/C++/CompareTheTriplets.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +int main() { + // your code goes here + unsigned int a[3],A=0; + unsigned int b[3],B=0; + for (int i = 0; i<3;i++) cin>>a[i]; + for(int j =0;j<3;j++) + { + cin>>b[j]; + + if (a[j]>b[j]) A++; + else if (a[j] Date: Mon, 21 Oct 2019 23:19:10 +0530 Subject: [PATCH 185/324] Create mergeSort.js Javascript implementation of mergeSort Algorithm - properly documented - contains multistep explainations --- Algorithms/JavaScript/mergeSort.js | 44 ++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Algorithms/JavaScript/mergeSort.js diff --git a/Algorithms/JavaScript/mergeSort.js b/Algorithms/JavaScript/mergeSort.js new file mode 100644 index 00000000..99afae46 --- /dev/null +++ b/Algorithms/JavaScript/mergeSort.js @@ -0,0 +1,44 @@ + +// Merge the two arrays: left and right +function merge (left, right) { + let resultArray = [], leftIndex = 0, rightIndex = 0; + + // We will concatenate values into the resultArray in order + while (leftIndex < left.length && rightIndex < right.length) { + if (left[leftIndex] < right[rightIndex]) { + resultArray.push(left[leftIndex]); + leftIndex++; // move left array cursor + } else { + resultArray.push(right[rightIndex]); + rightIndex++; // move right array cursor + } + } + + // We need to concat here because there will be one element remaining + // from either left OR the right + return resultArray + .concat(left.slice(leftIndex)) + .concat(right.slice(rightIndex)); +} + +// Merge Sort Implentation (Recursion) +function mergeSort (unsortedArray) { + // No need to sort the array if the array only has one element or empty + if (unsortedArray.length <= 1) { + return unsortedArray; + } + // In order to divide the array in half, we need to figure out the middle + const middle = Math.floor(unsortedArray.length / 2); + + // This is where we will be dividing the array into left and right + const left = unsortedArray.slice(0, middle); + const right = unsortedArray.slice(middle); + + // Using recursion to combine the left and right + return merge( + mergeSort(left), mergeSort(right) + ); +} + +let a = [10,233,14,1675,85,653,809,85] +console.log(mergeSort(a)); From 604e87703651148119a63f287046f9556b47be76 Mon Sep 17 00:00:00 2001 From: Anshul Garg <45210080+garganshul108@users.noreply.github.com> Date: Mon, 21 Oct 2019 23:26:15 +0530 Subject: [PATCH 186/324] Create SURCHESS.cpp Solution for a medium level Codechef problem SURCHESS (appeared in OCT 18 Long Challange) --- Codechef/SURCHESS.cpp | 103 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 Codechef/SURCHESS.cpp diff --git a/Codechef/SURCHESS.cpp b/Codechef/SURCHESS.cpp new file mode 100644 index 00000000..65b76642 --- /dev/null +++ b/Codechef/SURCHESS.cpp @@ -0,0 +1,103 @@ +// problem link: https://www.codechef.com/OCT18B/problems/SURCHESS/ + +#include +#define ll long long +#define fr(v,s,n) for(int v=s;((sn);((s0 && j>0) ? dp[k][i-1][j-1] : 0; + int v3 = (i>0) ? dp[k][i-1][yy] : 0; + int v4 = (j>0) ? dp[k][xx][j-1] : 0; + int val = v1 + v2 - v3 - v4; + int nl = min(xx-i+1,yy-j+1); + + len[val] = max(len[val],nl); +} + +int main() +{ + cin>>n>>m; + + fr(i,0,n) cin>>board[i]; + + char idealboard[2][n][m]; + idealboard[0][0][0] = '0'; + fr(i,1,m) + { + idealboard[0][0][i] = flip(idealboard[0][0][i-1]); + } + fr(i,1,n) + { + idealboard[0][i][0] = flip(idealboard[0][i-1][0]); + fr(j,1,m) + { + idealboard[0][i][j] = flip(idealboard[0][i][j-1]); + } + } + + fr(i,0,n) fr(j,0,m) idealboard[1][i][j] = flip(idealboard[0][i][j]); + + + + fr(k,0,2) fr(i,0,n) fr(j,0,m) dp[k][i][j] = 0; + + + fr(k,0,2) fr(i,0,n) fr(j,0,m) if(board[i][j] != idealboard[k][i][j]) dp[k][i][j] = 1; + + fr(k,0,2) fr(i,1,m) dp[k][0][i] = dp[k][0][i-1] + dp[k][0][i]; + fr(k,0,2) fr(i,1,n) dp[k][i][0] = dp[k][i-1][0] + dp[k][i][0]; + + fr(k,0,2) fr(i,1,n) fr(j,1,m) dp[k][i][j] = dp[k][i-1][j] + dp[k][i][j-1] - dp[k][i-1][j-1] + dp[k][i][j]; + + int minc = min(dp[0][n-1][m-1],dp[1][n-1][m-1]); + + + fr(k,0,2) fr(i,0,n) fr(j,0,m) + { + int xx = i; + int yy = j; + while(xx < n && yy < m) + { + evaluate(i,j,xx,yy,k); + xx++; + yy++; + } + } + + + + fr(i,1,max(dp[0][n-1][m-1],dp[1][n-1][m-1])) + { + len[i] = max(len[i],len[i-1]); + } + int q; + cin>>q; + while(q--) + { + int k; + cin>>k; + if(k > minc) cout< Date: Mon, 21 Oct 2019 14:46:39 -0500 Subject: [PATCH 187/324] Added solve me first problem --- Hackerrank/C++/solveMeFirst.cpp | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Hackerrank/C++/solveMeFirst.cpp diff --git a/Hackerrank/C++/solveMeFirst.cpp b/Hackerrank/C++/solveMeFirst.cpp new file mode 100644 index 00000000..ab33007a --- /dev/null +++ b/Hackerrank/C++/solveMeFirst.cpp @@ -0,0 +1,22 @@ +#include +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/solve-me-first/problem + +int solveMeFirst(int a, int b) { + // Hint: Type return a+b; below + return a + b; +} + +int main() { + int num1, num2; + int sum; + cin>>num1>>num2; + sum = solveMeFirst(num1,num2); + cout< Date: Mon, 21 Oct 2019 17:26:38 -0500 Subject: [PATCH 188/324] Create Numper pair or odd --- Algorithms/C/Numper pair or odd | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Algorithms/C/Numper pair or odd diff --git a/Algorithms/C/Numper pair or odd b/Algorithms/C/Numper pair or odd new file mode 100644 index 00000000..53b4d722 --- /dev/null +++ b/Algorithms/C/Numper pair or odd @@ -0,0 +1,13 @@ +#include +#include + +int main(){ + int num; + print("Write a number\n"); + scanf("%d",&num); + if(num%2){ + printf("Is pair"); + }else{ + printf("Is odd"); + } +} From 12683676af7f50d758ad55333991d8cf064c2517 Mon Sep 17 00:00:00 2001 From: danvcoss <44591736+danvcoss@users.noreply.github.com> Date: Mon, 21 Oct 2019 17:29:27 -0500 Subject: [PATCH 189/324] Create HelloWordC --- HelloWorld/HelloWordC | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 HelloWorld/HelloWordC diff --git a/HelloWorld/HelloWordC b/HelloWorld/HelloWordC new file mode 100644 index 00000000..ebb92cef --- /dev/null +++ b/HelloWorld/HelloWordC @@ -0,0 +1,7 @@ +#include +#include + +int main(){ + printf("Hello World\n"); + return(0); +} From 9be39c7260486dabfb9d7710c538fd0bc12cc0d7 Mon Sep 17 00:00:00 2001 From: danvcoss <44591736+danvcoss@users.noreply.github.com> Date: Mon, 21 Oct 2019 17:33:02 -0500 Subject: [PATCH 190/324] Create addnumbers --- Algorithms/C++/addnumbers | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Algorithms/C++/addnumbers diff --git a/Algorithms/C++/addnumbers b/Algorithms/C++/addnumbers new file mode 100644 index 00000000..385559fc --- /dev/null +++ b/Algorithms/C++/addnumbers @@ -0,0 +1,11 @@ +#include + +using namespace spr + +int main(){ + int a,b; + cout<<"Write two numbers to add"<>a>>b; + int r=a+b; + cout<<"The add is "< Date: Mon, 21 Oct 2019 22:59:58 -0300 Subject: [PATCH 191/324] selection sort --- Algorithms/Python/selection_sort.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Algorithms/Python/selection_sort.py diff --git a/Algorithms/Python/selection_sort.py b/Algorithms/Python/selection_sort.py new file mode 100644 index 00000000..b4b9eb11 --- /dev/null +++ b/Algorithms/Python/selection_sort.py @@ -0,0 +1,14 @@ +import sys +A = [64, 25, 12, 22, 11] + +for i in range(len(A)): + min_idx = i + for j in range(i+1, len(A)): + if A[min_idx] > A[j]: + min_idx = j + + A[i], A[min_idx] = A[min_idx], A[i] + +print ("Sorted array") +for i in range(len(A)): + print("%d" %A[i]), From 144e268f42f4df1d2f7c347ce913faccb7a7bcec Mon Sep 17 00:00:00 2001 From: Abhishek Tiwari <39875465+becomeahacker@users.noreply.github.com> Date: Tue, 22 Oct 2019 14:47:59 +0530 Subject: [PATCH 192/324] Add Hackerearth Solutions Solutions by: Abhishek Tiwari (@become) --- Hackerearth/Acronym.cpp | 44 ++++++++++++++ Hackerearth/Arania Exumai Blast.cpp | 37 ++++++++++++ Hackerearth/Battle of Words.cpp | 61 +++++++++++++++++++ Hackerearth/Max Profit.cpp | 35 +++++++++++ Hackerearth/Old and Cold Numbers.cpp | 33 ++++++++++ Hackerearth/Palindromic Grid.cpp | 90 ++++++++++++++++++++++++++++ 6 files changed, 300 insertions(+) create mode 100644 Hackerearth/Acronym.cpp create mode 100644 Hackerearth/Arania Exumai Blast.cpp create mode 100644 Hackerearth/Battle of Words.cpp create mode 100644 Hackerearth/Max Profit.cpp create mode 100644 Hackerearth/Old and Cold Numbers.cpp create mode 100644 Hackerearth/Palindromic Grid.cpp diff --git a/Hackerearth/Acronym.cpp b/Hackerearth/Acronym.cpp new file mode 100644 index 00000000..18fe7b5b --- /dev/null +++ b/Hackerearth/Acronym.cpp @@ -0,0 +1,44 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int k; cin>>k; string s; +map m; +while(k--) +{ + cin>>s; + m[s]=1; +} +cin>>k; +while(--k) +{ + cin>>s; + if(m[s]==0) + cout<>s; +if(m[s]==0) + cout< +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) + +using namespace std; +int main() +{ +string s; +int i,count=0; +getline(cin,s); +for(i=0;i +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +tc{ +string s; +getline(cin,s); +int a[26]={0}; +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']++; +} +getline(cin,s); +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']--; +} +bool fir=false,sec=false; +fi(26) +{ + if(a[i]>0) + fir=true; + if(a[i]<0) + sec=true; +} +if(fir && sec) + cout<<"You draw some."<<"\n"; +else { + if(fir) + cout<<"You win some.\n"; + else + cout<<"You lose some.\n"; +} +} + + +return 0; +} diff --git a/Hackerearth/Max Profit.cpp b/Hackerearth/Max Profit.cpp new file mode 100644 index 00000000..c023f3de --- /dev/null +++ b/Hackerearth/Max Profit.cpp @@ -0,0 +1,35 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +using namespace std; + +int main() +{ +int n, ans=0; +scanf("%d", &n); +int a[n]; +for (int i=0; ians) +ans=a[i]-a[j]; +} +printf("%d\n", ans); +return 0; +} diff --git a/Hackerearth/Old and Cold Numbers.cpp b/Hackerearth/Old and Cold Numbers.cpp new file mode 100644 index 00000000..a3fb51c6 --- /dev/null +++ b/Hackerearth/Old and Cold Numbers.cpp @@ -0,0 +1,33 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--) +{ + +} + + + +return 0; +} diff --git a/Hackerearth/Palindromic Grid.cpp b/Hackerearth/Palindromic Grid.cpp new file mode 100644 index 00000000..ab5ff2e1 --- /dev/null +++ b/Hackerearth/Palindromic Grid.cpp @@ -0,0 +1,90 @@ +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--){ + +int m,n; +cin>>n>>m; +int count[26]={0}; +int single = 0,pairs=0; string ent; +fi(n){cin>>ent; fj(m) ++count[ent[j]-'a'];} +fi(26) +{ + if(count[i]%2) + { + ++single; + + } + count[i]=count[i]>>1; + if(count[i]%2) + { + ++pairs; + } +} +//cout<<"P : "< Date: Tue, 22 Oct 2019 15:30:00 +0530 Subject: [PATCH 193/324] Create CoinChange.cpp --- Hackerrank/C++/CoinChange.cpp | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Hackerrank/C++/CoinChange.cpp diff --git a/Hackerrank/C++/CoinChange.cpp b/Hackerrank/C++/CoinChange.cpp new file mode 100644 index 00000000..f7261ec4 --- /dev/null +++ b/Hackerrank/C++/CoinChange.cpp @@ -0,0 +1,36 @@ +#include + +using namespace std; + +long getWays(long n, vector < long > c, long m){ + long table[n+1][m]; + + for(int j=0; j=0) ? table[i-c[j]][j]:0; + long y = (j>=1) ? table[i][j-1]:0; + + table[i][j]= x+y; + } + } + return table[n][m-1]; +} + +int main() { + int n; + int m; + cin >> n >> m; + vector c(m); + for(int c_i = 0; c_i < m; c_i++){ + cin >> c[c_i]; + } + // Print the number of ways of making change for 'n' units using coins having the values given by 'c' + long ways = getWays(n, c, m); + cout< Date: Tue, 22 Oct 2019 15:32:12 +0530 Subject: [PATCH 194/324] Create SamAndSubstrings.cpp --- Hackerrank/C++/SamAndSubstrings.cpp | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Hackerrank/C++/SamAndSubstrings.cpp diff --git a/Hackerrank/C++/SamAndSubstrings.cpp b/Hackerrank/C++/SamAndSubstrings.cpp new file mode 100644 index 00000000..08525454 --- /dev/null +++ b/Hackerrank/C++/SamAndSubstrings.cpp @@ -0,0 +1,38 @@ +#include + +using namespace std; + +// Complete the substrings function below. +// Utility method to covert character digit to +// integer digit +int toDigit(char ch) +{ + return (ch - '0'); +} +int substrings(string s) { + int MOD=1000000007; + int l=s.length(); + long long int res = 0; + long long int f = 1; + for(int i = l-1; i >= 0; i--) { + res = (res + (s[i]-'0')*f*(i+1)) % MOD; + f = (f*10+1) % MOD; + } + return res; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string n; + getline(cin, n); + + int result = substrings(n); + + fout << result << "\n"; + + fout.close(); + + return 0; +} From 4668ea0a571ca57d6938d5ceef7cb1df081f1a60 Mon Sep 17 00:00:00 2001 From: Chhatrapal Nayak Date: Tue, 22 Oct 2019 15:32:41 +0530 Subject: [PATCH 195/324] Create SherlockAndCost.cpp --- Hackerrank/C++/SherlockAndCost.cpp | 95 ++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 Hackerrank/C++/SherlockAndCost.cpp diff --git a/Hackerrank/C++/SherlockAndCost.cpp b/Hackerrank/C++/SherlockAndCost.cpp new file mode 100644 index 00000000..85381f03 --- /dev/null +++ b/Hackerrank/C++/SherlockAndCost.cpp @@ -0,0 +1,95 @@ +#include + +using namespace std; + +vector split_string(string); + +int maxi(int a,int b) +{ + if(a>b) + return a; + else + return b; +} +// Complete the cost function below. +int cost(vector B) { + int hi=0,lo=0; + int N=B.size(); + for(int i=1;i> t; + cin.ignore(numeric_limits::max(), '\n'); + + for (int t_itr = 0; t_itr < t; t_itr++) { + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + string B_temp_temp; + getline(cin, B_temp_temp); + + vector B_temp = split_string(B_temp_temp); + + vector B(n); + + for (int i = 0; i < n; i++) { + int B_item = stoi(B_temp[i]); + + B[i] = B_item; + } + + int result = cost(B); + + fout << result << "\n"; + } + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From b314179546ab1730840ff429aa280678a235fa3d Mon Sep 17 00:00:00 2001 From: Chhatrapal Nayak Date: Tue, 22 Oct 2019 15:33:13 +0530 Subject: [PATCH 196/324] Create Equal.cpp --- Hackerrank/C++/Equal.cpp | 104 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 Hackerrank/C++/Equal.cpp diff --git a/Hackerrank/C++/Equal.cpp b/Hackerrank/C++/Equal.cpp new file mode 100644 index 00000000..96d65b32 --- /dev/null +++ b/Hackerrank/C++/Equal.cpp @@ -0,0 +1,104 @@ +#include + +using namespace std; + +vector split_string(string); + +int ops(int n) +{ + int res=n/5; + n%=5; + res+=n/2; + n%=2; + res+=n; + return res; +} + +// Complete the equal function below. +int equal(vector arr) { + + int min=INT_MAX; + for(int i=0;i> t; + cin.ignore(numeric_limits::max(), '\n'); + + for (int t_itr = 0; t_itr < t; t_itr++) { + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + string arr_temp_temp; + getline(cin, arr_temp_temp); + + vector arr_temp = split_string(arr_temp_temp); + + vector arr(n); + + for (int i = 0; i < n; i++) { + int arr_item = stoi(arr_temp[i]); + + arr[i] = arr_item; + } + + int result = equal(arr); + + fout << result << "\n"; + } + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 28d72249ca89437a8e1b90208422e81156f11e0b Mon Sep 17 00:00:00 2001 From: Chhatrapal Nayak Date: Tue, 22 Oct 2019 15:37:45 +0530 Subject: [PATCH 197/324] Update Equal.cpp --- Hackerrank/C++/Equal.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Hackerrank/C++/Equal.cpp b/Hackerrank/C++/Equal.cpp index 96d65b32..87c279e3 100644 --- a/Hackerrank/C++/Equal.cpp +++ b/Hackerrank/C++/Equal.cpp @@ -1,5 +1,5 @@ #include - +#DEFINE PI 3.14 using namespace std; vector split_string(string); From 12d3cb20e5e1e811a773c794501a180827cd7be6 Mon Sep 17 00:00:00 2001 From: Chhatrapal Nayak Date: Tue, 22 Oct 2019 15:40:15 +0530 Subject: [PATCH 198/324] Create LonelyInteger.cpp --- Hackerrank/C++/LonelyInteger.cpp | 81 ++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 Hackerrank/C++/LonelyInteger.cpp diff --git a/Hackerrank/C++/LonelyInteger.cpp b/Hackerrank/C++/LonelyInteger.cpp new file mode 100644 index 00000000..dfb4adb3 --- /dev/null +++ b/Hackerrank/C++/LonelyInteger.cpp @@ -0,0 +1,81 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the lonelyinteger function below. +int lonelyinteger(vector a) { + int res[100]={0}; + int lone=0; + for(int i=0;i> n; + cin.ignore(numeric_limits::max(), '\n'); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split_string(a_temp_temp); + + vector a(n); + + for (int i = 0; i < n; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + int result = lonelyinteger(a); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 17c2101a62e67c2905ed39f0ec2615866e38ce0e Mon Sep 17 00:00:00 2001 From: Chhatrapal Nayak Date: Tue, 22 Oct 2019 15:43:19 +0530 Subject: [PATCH 199/324] Create tree.cpp --- DS/tree.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 DS/tree.cpp diff --git a/DS/tree.cpp b/DS/tree.cpp new file mode 100644 index 00000000..269c9035 --- /dev/null +++ b/DS/tree.cpp @@ -0,0 +1,21 @@ +/* you only have to complete the function given below. +Node is defined as + +struct node +{ + int data; + node* left; + node* right; +}; + +*/ + +void preOrder(node *root) { + if(root) + { + cout<data<<" "; + preOrder(root->left); + preOrder(root->right); + } + +} From 9c5688880cf4e970dca3d7f74e51b3a3ed46d5b6 Mon Sep 17 00:00:00 2001 From: Chhatrapal Nayak Date: Tue, 22 Oct 2019 15:44:51 +0530 Subject: [PATCH 200/324] Create Jesse&Cookies.cpp --- DS/C++/Jesse&Cookies.cpp | 109 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 DS/C++/Jesse&Cookies.cpp diff --git a/DS/C++/Jesse&Cookies.cpp b/DS/C++/Jesse&Cookies.cpp new file mode 100644 index 00000000..3c46b2cc --- /dev/null +++ b/DS/C++/Jesse&Cookies.cpp @@ -0,0 +1,109 @@ +#include + +using namespace std; + +vector split_string(string); + +/* + * Complete the cookies function below. + */ +int cookies(int k, vector A) { + + int count=0; + priority_queue, greater> pq; + sort(A.begin(),A.end()); + + if(A.size()==1 && A[0]=k) + break; + } + return count; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string nk_temp; + getline(cin, nk_temp); + + vector nk = split_string(nk_temp); + + int n = stoi(nk[0]); + + int k = stoi(nk[1]); + + string A_temp_temp; + getline(cin, A_temp_temp); + + vector A_temp = split_string(A_temp_temp); + + vector A(n); + + for (int A_itr = 0; A_itr < n; A_itr++) { + int A_item = stoi(A_temp[A_itr]); + + A[A_itr] = A_item; + } + + int result = cookies(k, A); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 9bdb341308c2ab42a5247b85ee1ef8f8a152226c Mon Sep 17 00:00:00 2001 From: muznahaftab Date: Tue, 22 Oct 2019 19:34:21 +0530 Subject: [PATCH 201/324] Added Selection Sort in C++ --- Algorithms/C++/SelectionSort.cpp | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Algorithms/C++/SelectionSort.cpp diff --git a/Algorithms/C++/SelectionSort.cpp b/Algorithms/C++/SelectionSort.cpp new file mode 100644 index 00000000..79aabff4 --- /dev/null +++ b/Algorithms/C++/SelectionSort.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; +void selection_sort(int a[], int n) +{ + int i, j, min, temp ; + for(i = 0; i < n-1 ; i++) + { + min = i; + for (j = i+1; j < n; j++) + { + if (a[j] < a[min]) + { + min = j; + } + } + temp = a[i]; + a[i] = a[min]; + a[min] = temp; + } +} +int main () +{ + int n , i, ch; + cout<<"\nEnter the number of elements: "; + cin>>n; + int a[n]; + cout<<"\nEnter "<> a[i]; + selection_sort( a, n ); + cout<<"Sorted Array:\n"; + for(int i = 0 ; i < n; i++ ) + cout< Date: Tue, 22 Oct 2019 21:38:16 +0530 Subject: [PATCH 202/324] Create helloworld.go --- HelloWorld/helloworld.go | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 HelloWorld/helloworld.go diff --git a/HelloWorld/helloworld.go b/HelloWorld/helloworld.go new file mode 100644 index 00000000..cf22b5e5 --- /dev/null +++ b/HelloWorld/helloworld.go @@ -0,0 +1,8 @@ +package main + +import "fmt" + +func main() { + + fmt.Println("Hello, World!") +} From db26c113bc9d24b0242fd817e4eeef61255fef0c Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Tue, 22 Oct 2019 21:47:11 +0530 Subject: [PATCH 203/324] Create helloworld.kt --- HelloWorld/helloworld.kt | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 HelloWorld/helloworld.kt diff --git a/HelloWorld/helloworld.kt b/HelloWorld/helloworld.kt new file mode 100644 index 00000000..277db964 --- /dev/null +++ b/HelloWorld/helloworld.kt @@ -0,0 +1,3 @@ +fun main() { + println("Hello, World!") +} From bdfa6a65c4c7396925b565248169206969fc08a1 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Tue, 22 Oct 2019 22:06:26 +0530 Subject: [PATCH 204/324] Create helloworld.rs --- HelloWorld/helloworld.rs | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 HelloWorld/helloworld.rs diff --git a/HelloWorld/helloworld.rs b/HelloWorld/helloworld.rs new file mode 100644 index 00000000..e7a11a96 --- /dev/null +++ b/HelloWorld/helloworld.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} From a715abc0e61b0e5f2045cffd1fed38588580454a Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Tue, 22 Oct 2019 22:06:54 +0530 Subject: [PATCH 205/324] Create helloworld.jl --- HelloWorld/helloworld.jl | 1 + 1 file changed, 1 insertion(+) create mode 100644 HelloWorld/helloworld.jl diff --git a/HelloWorld/helloworld.jl b/HelloWorld/helloworld.jl new file mode 100644 index 00000000..3a4e995f --- /dev/null +++ b/HelloWorld/helloworld.jl @@ -0,0 +1 @@ +println("hello world") From 5025cb5cc190f0e6158a5024821d862a4e6c2d1d Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Tue, 22 Oct 2019 22:07:39 +0530 Subject: [PATCH 206/324] Update helloworld.jl --- HelloWorld/helloworld.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HelloWorld/helloworld.jl b/HelloWorld/helloworld.jl index 3a4e995f..e55bd904 100644 --- a/HelloWorld/helloworld.jl +++ b/HelloWorld/helloworld.jl @@ -1 +1 @@ -println("hello world") +println("Hello, World!") From 3774d2f4269567597321da396941b6416bf36d9e Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Tue, 22 Oct 2019 22:08:02 +0530 Subject: [PATCH 207/324] Update helloworld.jl From 7d9fd788d021cb0b3d92d5ae9afec7bc8915dce8 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Tue, 22 Oct 2019 22:08:22 +0530 Subject: [PATCH 208/324] Update helloworld.rs --- HelloWorld/helloworld.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HelloWorld/helloworld.rs b/HelloWorld/helloworld.rs index e7a11a96..0672e510 100644 --- a/HelloWorld/helloworld.rs +++ b/HelloWorld/helloworld.rs @@ -1,3 +1,3 @@ fn main() { - println!("Hello, world!"); + println!("Hello, World!"); } From 596a934e79903c4cfdff1a6038cf61a5e0e943d8 Mon Sep 17 00:00:00 2001 From: Harshit Richariya <35799384+HarshitRichariya@users.noreply.github.com> Date: Tue, 22 Oct 2019 23:56:12 +0530 Subject: [PATCH 209/324] Create fizzBuzz.js Added FizzBuzz --- Algorithms/JavaScript/fizzBuzz.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Algorithms/JavaScript/fizzBuzz.js diff --git a/Algorithms/JavaScript/fizzBuzz.js b/Algorithms/JavaScript/fizzBuzz.js new file mode 100644 index 00000000..8f28f513 --- /dev/null +++ b/Algorithms/JavaScript/fizzBuzz.js @@ -0,0 +1,18 @@ +function fizzbuzz(num) { + for(let i=1; i<=num; i++) { + if(i%3 === 0 && i%5 === 0) { + console.log("FizzBuzz"); + } else if(i%3 === 0) { + console.log("Fizz"); + } else if(i%5 === 0) { + console.log("Buzz"); + } else { + console.log(i); + } + } +} + +fizzbuzz(20); +fizzbuzz(30); +fizzbuzz(40); +fizzbuzz(50); From 24d5e768ca09fe4453829d167657a4aaeacd3ad7 Mon Sep 17 00:00:00 2001 From: Rajarshi24 <40721635+Rajarshi24@users.noreply.github.com> Date: Wed, 23 Oct 2019 01:10:19 +0530 Subject: [PATCH 210/324] Add files via upload --- Hackerrank/C/Counting Sort 2.cpp | 147 +++++++++++++++++++++++++++++ Hackerrank/C/Grid Challenge.cpp | 125 ++++++++++++++++++++++++ Hackerrank/C/Priyanka And Toys.cpp | 96 +++++++++++++++++++ 3 files changed, 368 insertions(+) create mode 100644 Hackerrank/C/Counting Sort 2.cpp create mode 100644 Hackerrank/C/Grid Challenge.cpp create mode 100644 Hackerrank/C/Priyanka And Toys.cpp diff --git a/Hackerrank/C/Counting Sort 2.cpp b/Hackerrank/C/Counting Sort 2.cpp new file mode 100644 index 00000000..7eeceeb0 --- /dev/null +++ b/Hackerrank/C/Counting Sort 2.cpp @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the countingSort function below. + +// Please store the size of the integer array to be returned in result_count pointer. For example, +// int a[3] = {1, 2, 3}; +// +// *result_count = 3; +// +// return a; +// +int* countingSort(int arr_count, int* arr, int* result_count) { + int flag,k=0; + int temp[100]; + * result_count=arr_count; + int *result=malloc(arr_count*sizeof(int)); + for(int i=0;i<100;i++) + temp[i]=0; + for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the gridChallenge function below. + +// Please either make the string static or allocate on the heap. For example, +// static char str[] = "hello world"; +// return str; +// +// OR +// +// char* str = "hello world"; +// return str; +// +char* gridChallenge(int grid_count, char** grid) { + + char* ans1="YES"; + char* ans2="NO"; + + char key; + int k; + for(int i=0;i=0&&grid[i][k]>key) + { + grid[i][k+1]=grid[i][k]; + k=k-1; + } + grid[i][k+1]=key; + } + } + + for(int i=0;igrid[j+1][i]) + return ans2; + } + } + return ans1; + +} + +int main() +{ + FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); + + char* t_endptr; + char* t_str = readline(); + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + for (int t_itr = 0; t_itr < t; t_itr++) { + char* n_endptr; + char* n_str = readline(); + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char** grid = malloc(n * sizeof(char*)); + + for (int i = 0; i < n; i++) { + char* grid_item = readline(); + + *(grid + i) = grid_item; + } + + int grid_count = n; + + char* result = gridChallenge(grid_count, grid); + + fprintf(fptr, "%s\n", result); + } + + fclose(fptr); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} diff --git a/Hackerrank/C/Priyanka And Toys.cpp b/Hackerrank/C/Priyanka And Toys.cpp new file mode 100644 index 00000000..bbb6296b --- /dev/null +++ b/Hackerrank/C/Priyanka And Toys.cpp @@ -0,0 +1,96 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the toys function below. +int toys(vector w) { + sort(w.begin(),w.end()); + long int flag=0,z,count; + long int size; + while(!w.empty()) + { + count=0; + flag++; + size=w.size(); + z=w.front(); + + /*for(int i=0;i=z&&w[i]<=z+4) + count++; + + } + for(int i=0;i> n; + cin.ignore(numeric_limits::max(), '\n'); + + string w_temp_temp; + getline(cin, w_temp_temp); + + vector w_temp = split_string(w_temp_temp); + + vector w(n); + + for (int i = 0; i < n; i++) { + int w_item = stoi(w_temp[i]); + + w[i] = w_item; + } + + int result = toys(w); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 65e5490873d202451b52224685da3e55811aec33 Mon Sep 17 00:00:00 2001 From: Ayush Jain Date: Wed, 23 Oct 2019 11:40:17 +0530 Subject: [PATCH 211/324] added solution to compare The triplets https://www.hackerrank.com/challenges/compare-the-triplets/problem --- Hackerrank/C++/compareTheTriplets.cpp | 108 ++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Hackerrank/C++/compareTheTriplets.cpp diff --git a/Hackerrank/C++/compareTheTriplets.cpp b/Hackerrank/C++/compareTheTriplets.cpp new file mode 100644 index 00000000..5cab4b1c --- /dev/null +++ b/Hackerrank/C++/compareTheTriplets.cpp @@ -0,0 +1,108 @@ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the compareTriplets function below. +vector compareTriplets(vector a, vector b) { +vector arr(2); +for(int i=0;i<3;i++) +{ + if(a[i]>b[i]) + arr[0]++; + else if(b[i]>a[i]) + arr[1]++; + +} +return arr; + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split(rtrim(a_temp_temp)); + + vector a(3); + + for (int i = 0; i < 3; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + string b_temp_temp; + getline(cin, b_temp_temp); + + vector b_temp = split(rtrim(b_temp_temp)); + + vector b(3); + + for (int i = 0; i < 3; i++) { + int b_item = stoi(b_temp[i]); + + b[i] = b_item; + } + + vector result = compareTriplets(a, b); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} From 814277e6f568d924b2962e205d995f56d64e3b96 Mon Sep 17 00:00:00 2001 From: TejusWadbudhe Date: Wed, 23 Oct 2019 22:09:15 +0530 Subject: [PATCH 212/324] More algorithms on C#, Elixir, Javascript, Kotlin --- Algorithms/C#/BinaryInsertionSort.cs | 38 +++++++++++++ Algorithms/C#/BubbleSort.cs | 34 ++++++++++++ Algorithms/C#/HeapSort.cs | 61 ++++++++++++++++++++ Algorithms/C#/InsertionSort.cs | 48 ++++++++++++++++ Algorithms/C#/MergeSort.cs | 68 +++++++++++++++++++++++ Algorithms/C#/QuickSort.cs | 77 ++++++++++++++++++++++++++ Algorithms/C#/SelectionSort.cs | 42 ++++++++++++++ Algorithms/C#/ShellSort.cs | 32 +++++++++++ Algorithms/Elixir/selectionSort.exs | 30 ++++++++++ Algorithms/JavaScript/HeapSort.js | 50 +++++++++++++++++ Algorithms/JavaScript/Insertionsort.js | 13 +++++ Algorithms/JavaScript/MergeSort.js | 18 ++++++ Algorithms/JavaScript/Quicksort.js | 37 +++++++++++++ Algorithms/JavaScript/RadixSort.js | 63 +++++++++++++++++++++ Algorithms/JavaScript/bogoSort.js | 28 ++++++++++ Algorithms/JavaScript/bubbleSort.js | 15 +++++ Algorithms/JavaScript/countingSort.js | 24 ++++++++ Algorithms/JavaScript/selectionSort.js | 20 +++++++ Algorithms/Kotlin/BubbleSort.kt | 53 ++++++++++++++++++ Algorithms/Kotlin/HeapSort.kt | 71 ++++++++++++++++++++++++ Algorithms/Kotlin/MergeSort.kt | 51 +++++++++++++++++ Algorithms/Kotlin/QuickSort.kt | 39 +++++++++++++ Algorithms/Kotlin/insertionSort.kt | 24 ++++++++ Algorithms/Kotlin/selectionSort.kt | 16 ++++++ 24 files changed, 952 insertions(+) create mode 100644 Algorithms/C#/BinaryInsertionSort.cs create mode 100644 Algorithms/C#/BubbleSort.cs create mode 100644 Algorithms/C#/HeapSort.cs create mode 100644 Algorithms/C#/InsertionSort.cs create mode 100644 Algorithms/C#/MergeSort.cs create mode 100644 Algorithms/C#/QuickSort.cs create mode 100644 Algorithms/C#/SelectionSort.cs create mode 100644 Algorithms/C#/ShellSort.cs create mode 100644 Algorithms/Elixir/selectionSort.exs create mode 100644 Algorithms/JavaScript/HeapSort.js create mode 100644 Algorithms/JavaScript/Insertionsort.js create mode 100644 Algorithms/JavaScript/MergeSort.js create mode 100644 Algorithms/JavaScript/Quicksort.js create mode 100644 Algorithms/JavaScript/RadixSort.js create mode 100644 Algorithms/JavaScript/bogoSort.js create mode 100644 Algorithms/JavaScript/bubbleSort.js create mode 100644 Algorithms/JavaScript/countingSort.js create mode 100644 Algorithms/JavaScript/selectionSort.js create mode 100644 Algorithms/Kotlin/BubbleSort.kt create mode 100644 Algorithms/Kotlin/HeapSort.kt create mode 100644 Algorithms/Kotlin/MergeSort.kt create mode 100644 Algorithms/Kotlin/QuickSort.kt create mode 100644 Algorithms/Kotlin/insertionSort.kt create mode 100644 Algorithms/Kotlin/selectionSort.kt diff --git a/Algorithms/C#/BinaryInsertionSort.cs b/Algorithms/C#/BinaryInsertionSort.cs new file mode 100644 index 00000000..6cf9d382 --- /dev/null +++ b/Algorithms/C#/BinaryInsertionSort.cs @@ -0,0 +1,38 @@ +// C# Program implementing +// binary insertion sort +using System; + +class GFG { + + public static void Main() + { + int []arr = {37, 23, 0, 17, 12, 72, 31, + 46, 100, 88, 54 }; + + sort(arr); + + for(int i = 0; i < arr.Length; i++) + Console.Write(arr[i] + " "); + } + + public static void sort(int []array) + { + for (int i = 1; i < array.Length; i++) + { + int x = array[i]; + + // Find location to insert using + // binary search + int j = Math.Abs(Array.BinarySearch( + array, 0, i, x) + 1); + + // Shifting array to one location right + System.Array.Copy(array, j, array, + j+1, i-j); + + // Placing element at its correct + // location + array[j] = x; + } + } +} diff --git a/Algorithms/C#/BubbleSort.cs b/Algorithms/C#/BubbleSort.cs new file mode 100644 index 00000000..75c1a653 --- /dev/null +++ b/Algorithms/C#/BubbleSort.cs @@ -0,0 +1,34 @@ +// Bubble Sort with C# +using System; + +namespace BubbleSort +{ + class MainClass + { + public static void Main() + { + // test numbers to sort + int[] toSort = { 5, 2, 6, 8, 3}; + + // perform bubble sort + for (int i = 0; i < 5; i++) + { + for (int j = 0; j < 4; j++) + { + if (toSort[j] > toSort[j + 1]) + { + int temp = toSort[j]; + toSort[j] = toSort[j + 1]; + toSort[j + 1] = temp; + } + } + } + + // print to console results + for (int i = 0; i < 5; i++) + { + Console.WriteLine(toSort[i]); + } + } + } +} diff --git a/Algorithms/C#/HeapSort.cs b/Algorithms/C#/HeapSort.cs new file mode 100644 index 00000000..abf394bd --- /dev/null +++ b/Algorithms/C#/HeapSort.cs @@ -0,0 +1,61 @@ +using System; +class heapsort +{ + int[] r = { 2,5,1,10,6,9,3,7,4,8}; + public void hsort() + { + int i, t; + for (i = 5; i >= 0; i--) + { + adjust(i, 9); + } + for (i = 8; i >= 0; i--) + { + t = r[i + 1]; + r[i + 1] = r[0]; + r[0] = t; + adjust(0, i); + } + } + private void adjust(int i, int n) + { + int t, j; + try + { + t = r[i]; + j = 2 * i; + while (j <= n) + { + if (j < n && r[j] < r[j + 1]) + j++; + if (t >=r[j]) + break; + r[j / 2] = r[j]; + j *= 2; + } + r[j / 2] = t; + } + catch (IndexOutOfRangeException e) + { + Console.WriteLine("Array Out of Bounds ", e); + } + } + public void print() + { + for (int i = 0; i < 10; i++) + { + Console.WriteLine("{0}", r[i]); + } + + } + public static void Main() + { + heap obj = new heap(); + Console.WriteLine("Elements Before sorting : "); + obj.print(); + obj.hsort(); + Console.WriteLine("Elements After sorting : "); + obj.print(); + Console.Read(); + } +} \ No newline at end of file diff --git a/Algorithms/C#/InsertionSort.cs b/Algorithms/C#/InsertionSort.cs new file mode 100644 index 00000000..113940c3 --- /dev/null +++ b/Algorithms/C#/InsertionSort.cs @@ -0,0 +1,48 @@ +/* + * C# Program to Perform Insertion Sort + */ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.IO; +namespace ConsoleApplication1 +{ + class Program + { + static void Main(string[] args) + { + int[] arr = new int[5] { 83, 12, 3, 34, 60 }; + int i; + Console.WriteLine("The Array is :"); + for (i = 0; i < 5; i++) + { + Console.WriteLine(arr[i]); + } + insertsort(arr, 5); + Console.WriteLine("The Sorted Array is :"); + for (i = 0; i < 5; i++) + Console.WriteLine(arr[i]); + Console.ReadLine(); + } + static void insertsort(int[] data, int n) + { + int i, j; + for (i = 1; i < n; i++) + { + int item = data[i]; + int ins = 0; + for (j = i - 1; j >= 0 && ins != 1; ) + { + if (item < data[j]) + { + data[j + 1] = data[j]; + j--; + data[j + 1] = item; + } + else ins = 1; + } + } + } + } +} \ No newline at end of file diff --git a/Algorithms/C#/MergeSort.cs b/Algorithms/C#/MergeSort.cs new file mode 100644 index 00000000..af157100 --- /dev/null +++ b/Algorithms/C#/MergeSort.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace CSharpMergeSort +{ + class Mergesort + { + + static public void DoMerge(int [] numbers, int left, int mid, int right) + { + int [] temp = new int[25]; + int i, left_end, num_elements, tmp_pos; + + left_end = (mid - 1); + tmp_pos = left; + num_elements = (right - left + 1); + + while ((left <= left_end) && (mid <= right)) + { + if (numbers[left] <= numbers[mid]) + temp[tmp_pos++] = numbers[left++]; + else + temp[tmp_pos++] = numbers[mid++]; + } + + while (left <= left_end) + temp[tmp_pos++] = numbers[left++]; + + while (mid <= right) + temp[tmp_pos++] = numbers[mid++]; + + for (i = 0; i < num_elements; i++) + { + numbers[right] = temp[right]; + right--; + } + } + + static public void MergeSort_Recursive(int [] numbers, int left, int right) + { + int mid; + + if (right > left) + { + mid = (right + left) / 2; + MergeSort_Recursive(numbers, left, mid); + MergeSort_Recursive(numbers, (mid + 1), right); + + DoMerge(numbers, left, (mid+1), right); + } + } + + static void Main(string[] args) + { + int[] numbers = { 3, 8, 7, 5, 2, 1, 9, 6, 4 }; + int len = 9; + + Console.WriteLine("MergeSort By Recursive Method"); + MergeSort_Recursive(numbers, 0, len - 1); + for (int i = 0; i < 9; i++) + Console.WriteLine(numbers[i]); + + Console.WriteLine(numbers[i]); + + } + } +} \ No newline at end of file diff --git a/Algorithms/C#/QuickSort.cs b/Algorithms/C#/QuickSort.cs new file mode 100644 index 00000000..12f13f29 --- /dev/null +++ b/Algorithms/C#/QuickSort.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace sortQuickAlgorithm +{ + class quickSortAlgorithm + { + + private int[] array = new int[20]; + private int len; + + public void QuickSortAlgorithm() + { + sort(0, len - 1); + } + + public void sort(int left, int right) + { + int pivot, leftend, rightend; + + leftend = left; + rightend = right; + pivot = array[left]; + + while (left < right) { while ((array[right] >= pivot) && (left < right)) + { + right--; + } + + if (left != right) + { + array[left] = array[right]; + left++; + } + + while ((array[left] >= pivot) && (left < right)) + { + left++; + } + + if (left != right) + { + array[right] = array[left]; + right--; + } + } + + array[left] = pivot; + pivot = left; + left = leftend; + right = rightend; + + if (left < pivot) { sort(left, pivot - 1); } if (right > pivot) + { + sort(pivot + 1, right); + } + } + + public static void Main() + { + quickSortAlgorithm q_Sort = new quickSortAlgorithm(); + + int[] array = { 41, 32, 15, 45, 63, 72, 57, 43, 32, 52, 183}; + q_Sort.array = array; + q_Sort.len = q_Sort.array.Length; + q_Sort.QuickSortAlgorithm(); + + for (int j = 0; j < q_Sort.len; j++) + { + Console.WriteLine(q_Sort.array[j]); + } + Console.ReadKey(); + } + } +} \ No newline at end of file diff --git a/Algorithms/C#/SelectionSort.cs b/Algorithms/C#/SelectionSort.cs new file mode 100644 index 00000000..9c71b5cd --- /dev/null +++ b/Algorithms/C#/SelectionSort.cs @@ -0,0 +1,42 @@ +/* + * C# Program to Perform a Selection Sort + */ +using System; +class Program +{ + static void Main(string[] args) + { + int array_size = 10; + int[] array = new int[10] { 100, 50, 20, 40, 10, 60, 80, 70, 90, 30 }; + Console.WriteLine("The Array Before Selection Sort is: "); + for (int i = 0; i < array_size; i++) + { + Console.WriteLine(array[i]); + } + int tmp, min_key; + + for (int j = 0; j < array_size - 1; j++) + { + min_key = j; + + for (int k = j + 1; k < array_size; k++) + { + if (array[k] < array[min_key]) + { + min_key = k; + } + } + + tmp = array[min_key]; + array[min_key] = array[j]; + array[j] = tmp; + } + + Console.WriteLine("The Array After Selection Sort is: "); + for (int i = 0; i < 10; i++) + { + Console.WriteLine(array[i]); + } + Console.ReadLine(); + } +} \ No newline at end of file diff --git a/Algorithms/C#/ShellSort.cs b/Algorithms/C#/ShellSort.cs new file mode 100644 index 00000000..d785fa51 --- /dev/null +++ b/Algorithms/C#/ShellSort.cs @@ -0,0 +1,32 @@ +private void SortArrayWithShellSort() + { + int[] array = { 297,183, 464 }; + ShellSort(array); + } + + + private void ShellSort(int[] array) + { + int n = array.Length; + int gap = n / 2; + int temp; + + while (gap > 0) + { + for (int i = 0; i + gap < n; i++) + { + int j = i + gap; + temp = array[j]; + + while (j - gap >= 0 && temp < array[j - gap]) + { + array[j] = array[j - gap]; + j = j - gap; + } + + array[j] = temp; + } + + gap = gap / 2; + } + } \ No newline at end of file diff --git a/Algorithms/Elixir/selectionSort.exs b/Algorithms/Elixir/selectionSort.exs new file mode 100644 index 00000000..e9fc96d0 --- /dev/null +++ b/Algorithms/Elixir/selectionSort.exs @@ -0,0 +1,30 @@ +defmodule Selection do + def sort(list) when is_list(list) do + do_selection(list, []) + end + + def do_selection([head|[]], acc) do + acc ++ [head] + end + + def do_selection(list, acc) do + min = min(list) + do_selection(:list.delete(min, list), acc ++ [min]) + end + + defp min([first|[second|[]]]) do + smaller(first, second) + end + + defp min([first|[second|tail]]) do + min([smaller(first, second)|tail]) + end + + defp smaller(e1, e2) do + if e1 <= e2 do + e1 + else + e2 + end + end +end \ No newline at end of file diff --git a/Algorithms/JavaScript/HeapSort.js b/Algorithms/JavaScript/HeapSort.js new file mode 100644 index 00000000..e38ba112 --- /dev/null +++ b/Algorithms/JavaScript/HeapSort.js @@ -0,0 +1,50 @@ +function heapSort(arr){ + var len = arr.length, + end = len-1; + + heapify(arr, len); + + while(end > 0){ + swap(arr, end--, 0); + DownHeapify(arr, 0, end); + } + return arr; +} + +function heapify(arr, len){ + // breaking the array into root + two sides, to create tree (heap) + var mid = Math.floor((len-2)/2); + while(mid >= 0){ + DownHeapify(arr, mid--, len-1); + } +} + +function DownHeapify(arr, start, end){ + var root = start, + child = root*2 + 1, + toSwap = root; + while(child <= end){ + if(arr[toSwap] < arr[child]){ + swap(arr, toSwap, child); + } + if(child+1 <= end && arr[toSwap] < arr[child+1]){ + swap(arr, toSwap, child+1) + } + if(toSwap != root){ + swap(arr, root, toSwap); + root = toSwap; + } + else{ + return; + } + toSwap = root; + child = root*2+1 + } +} + + +function swap(arr, i, j){ + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} \ No newline at end of file diff --git a/Algorithms/JavaScript/Insertionsort.js b/Algorithms/JavaScript/Insertionsort.js new file mode 100644 index 00000000..cba0266c --- /dev/null +++ b/Algorithms/JavaScript/Insertionsort.js @@ -0,0 +1,13 @@ +const insertionSort = arr => { + const len = arr.length; + for (let i = 0; i < len; i++) { + let el = arr[i]; + let j; + + for (j = i - 1; j >= 0 && arr[j] > el; j--) { + arr[j + 1] = arr[j]; + } + arr[j + 1] = el; + } + return arr; + }; \ No newline at end of file diff --git a/Algorithms/JavaScript/MergeSort.js b/Algorithms/JavaScript/MergeSort.js new file mode 100644 index 00000000..f2feaa21 --- /dev/null +++ b/Algorithms/JavaScript/MergeSort.js @@ -0,0 +1,18 @@ +function mergeSort (arr) { + if (arr.length < 2) { + return arr; + } + + var mid = Math.floor(arr.length / 2); + var subLeft = mergeSort(arr.slice(0, mid)); + var subRight = mergeSort(arr.slice(mid)); + + return merge(subLeft, subRight); +} + +function merge (node1, node2) { + var result = []; + while (node1.length > 0 && node2.length > 0) + result.push(node1[0] < node2[0] ? node1.shift() : node2.shift()); + return result.concat(node1.length ? node1 : node2); +} \ No newline at end of file diff --git a/Algorithms/JavaScript/Quicksort.js b/Algorithms/JavaScript/Quicksort.js new file mode 100644 index 00000000..4a63031c --- /dev/null +++ b/Algorithms/JavaScript/Quicksort.js @@ -0,0 +1,37 @@ +function quickSort(arr, left, right){ + var len = arr.length, + pivot, + partitionIndex; + + + if(left < right){ + pivot = right; + partitionIndex = partition(arr, pivot, left, right); + + //sort left and right + quickSort(arr, left, partitionIndex - 1); + quickSort(arr, partitionIndex + 1, right); + } + return arr; +} + +function partition(arr, pivot, left, right){ + var pivotValue = arr[pivot], + partitionIndex = left; + + for(var i = left; i < right; i++){ + if(arr[i] < pivotValue){ + swap(arr, i, partitionIndex); + partitionIndex++; + } + } + swap(arr, right, partitionIndex); + return partitionIndex; +} + +function swap(arr, i, j){ + var temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; +} + \ No newline at end of file diff --git a/Algorithms/JavaScript/RadixSort.js b/Algorithms/JavaScript/RadixSort.js new file mode 100644 index 00000000..7706595d --- /dev/null +++ b/Algorithms/JavaScript/RadixSort.js @@ -0,0 +1,63 @@ +var testArray = [ 31, 654, 222, 74, 689, 45, 89, 223, 345, 145, 8 ]; + + function radixBucketSort (arr) { + var idx1, idx2, idx3, len1, len2, radix, radixKey; + var radices = {}, buckets = {}, num, curr; + var currLen, radixStr, currBucket; + + len1 = arr.length; + len2 = 10; // radix sort uses ten buckets + + // find the relevant radices to process for efficiency + for (idx1 = 0;idx1 < len1;idx1++) { + radices[arr[idx1].toString().length] = 0; + } + + // loop for each radix. For each radix we put all the items + // in buckets, and then pull them out of the buckets. + for (radix in radices) { + // put each array item in a bucket based on its radix value + len1 = arr.length; + for (idx1 = 0;idx1 < len1;idx1++) { + curr = arr[idx1]; + // item length is used to find its current radix value + currLen = curr.toString().length; + // only put the item in a radix bucket if the item + // key is as long as the radix + if (currLen >= radix) { + // radix starts from beginning of key, so need to + // adjust to get redix values from start of stringified key + radixKey = curr.toString()[currLen - radix]; + // create the bucket if it does not already exist + if (!buckets.hasOwnProperty(radixKey)) { + buckets[radixKey] = []; + } + // put the array value in the bucket + buckets[radixKey].push(curr); + } else { + if (!buckets.hasOwnProperty('0')) { + buckets['0'] = []; + } + buckets['0'].push(curr); + } + } + // for current radix, items are in buckets, now put them + // back in the array based on their buckets + // this index moves us through the array as we insert items + idx1 = 0; + // go through all the buckets + for (idx2 = 0;idx2 < len2;idx2++) { + // only process buckets with items + if (buckets[idx2] != null) { + currBucket = buckets[idx2]; + // insert all bucket items into array + len1 = currBucket.length; + for (idx3 = 0;idx3 < len1;idx3++) { + arr[idx1++] = currBucket[idx3]; + } + } + } + buckets = {}; + } + } + radixBucketSort(testArray); \ No newline at end of file diff --git a/Algorithms/JavaScript/bogoSort.js b/Algorithms/JavaScript/bogoSort.js new file mode 100644 index 00000000..84270705 --- /dev/null +++ b/Algorithms/JavaScript/bogoSort.js @@ -0,0 +1,28 @@ +function isSorted(arr) { + if (arr.length == 0 || arr.length == 1) { + return true; + } + + for (let i=0;i arr[i+1]) { + return false; + } + } + + return true; +} + +function shuffleArray(array) { + for (let i = array.length - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + [array[i], array[j]] = [array[j], array[i]]; + } + return array; +} + +function bogoSort(data) { + while (!isSorted(data)) { + data = shuffleArray(data); + }; + return data; +} \ No newline at end of file diff --git a/Algorithms/JavaScript/bubbleSort.js b/Algorithms/JavaScript/bubbleSort.js new file mode 100644 index 00000000..09588d27 --- /dev/null +++ b/Algorithms/JavaScript/bubbleSort.js @@ -0,0 +1,15 @@ +const bubbleSort = (numArray) => { + let rotated; + do { + rotated = false; + for (let i = 0; i < numArray.length-1; i++) { + if (numArray[i] > numArray[i+1]) { + store = numArray[i]; + numArray[i] = numArray[i+1]; + numArray[i+1] = store; + rotated = true; + } + } + } while (rotated === true) + return numArray + } diff --git a/Algorithms/JavaScript/countingSort.js b/Algorithms/JavaScript/countingSort.js new file mode 100644 index 00000000..f254168e --- /dev/null +++ b/Algorithms/JavaScript/countingSort.js @@ -0,0 +1,24 @@ +function counntingSort(arr, min, max) { + let i = min, + j = 0, + len = arr.length, + count = []; + + for (i; i <= max; i++) { + count[i] = 0; + } + + for (i = 0; i < len; i++) { + count[arr[i]] += 1; + } + + for (i = min; i <= max; i++) { + while (count[i] > 0) { + arr[j] = i; + j++; + count[i]--; + } + } + + return arr; +} \ No newline at end of file diff --git a/Algorithms/JavaScript/selectionSort.js b/Algorithms/JavaScript/selectionSort.js new file mode 100644 index 00000000..4397c43e --- /dev/null +++ b/Algorithms/JavaScript/selectionSort.js @@ -0,0 +1,20 @@ +function selectionSort(A) { + var len = array_length(A); + for (var i = 0; i < len - 1; i = i + 1) { + var j_min = i; + for (var j = i + 1; j < len; j = j + 1) { + if (A[j] < A[j_min]) { + j_min = j; + } else {} + } + if (j_min !== i) { + swap(A, i, j_min); + } else {} + } +} + +function swap(A, x, y) { + var temp = A[x]; + A[x] = A[y]; + A[y] = temp; +} \ No newline at end of file diff --git a/Algorithms/Kotlin/BubbleSort.kt b/Algorithms/Kotlin/BubbleSort.kt new file mode 100644 index 00000000..1527ee3d --- /dev/null +++ b/Algorithms/Kotlin/BubbleSort.kt @@ -0,0 +1,53 @@ +import java.util.* + +fun input(): Array{ + //instance of Scanner class + val reader: Scanner = Scanner(System.`in`) + + //creating the array + println("enter size of array : ") + var size:Int=reader.nextInt() + var myArray=Array(size){0} + + //initializing the array + for (i in 0..(size-1)){ + print("\nEnter element : ") + myArray.set(i,reader.nextInt()) + } + + return myArray +} + +fun display(myArray: Array){ + for (element in myArray) + print(" "+ element) +} + +fun main(args: Array){ + var array=input() + println("array before sorting : ") + display(array) + array=bubbleSort(array) + println("\narray after sorting : ") + display(array) + +} + +fun bubbleSort(array: Array): Array { + + for(i in 0..(array.size-2)) + for (j in 0..(array.size-2-i)){ + if(array.get(j+1) arr[largest]) + largest = l + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r + + // If largest is not root + if (largest != i) { + val swap = arr[i] + arr[i] = arr[largest] + arr[largest] = swap + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest) + } + } + + companion object { + + /* A utility function to print array of size n */ + internal fun printArray(arr: IntArray) { + val n = arr.size + for (i in 0 until n) + print(arr[i].toString() + " ") + println() + } + + // Driver program + @JvmStatic + fun main(args: Array) { + val arr = intArrayOf(12, 11, 13, 5, 6, 7) + val n = arr.size + + val ob = HeapSort() + ob.sort(arr) + + println("Sorted array is") + printArray(arr) + } + } +} \ No newline at end of file diff --git a/Algorithms/Kotlin/MergeSort.kt b/Algorithms/Kotlin/MergeSort.kt new file mode 100644 index 00000000..cbc488fb --- /dev/null +++ b/Algorithms/Kotlin/MergeSort.kt @@ -0,0 +1,51 @@ +/** + * Created by jens on 3/8/17. + */ + +fun mergeSort(list: List): List { + if (list.size <= 1) { + return list + } + + val middle = list.size / 2 + var left = list.subList(0,middle); + var right = list.subList(middle,list.size); + + return merge(mergeSort(left), mergeSort(right)) +} + + +fun merge(left: List, right: List): List { + var indexLeft = 0 + var indexRight = 0 + var newList : MutableList = mutableListOf() + + while (indexLeft < left.count() && indexRight < right.count()) { + if (left[indexLeft] <= right[indexRight]) { + newList.add(left[indexLeft]) + indexLeft++ + } else { + newList.add(right[indexRight]) + indexRight++ + } + } + + while (indexLeft < left.size) { + newList.add(left[indexLeft]) + indexLeft++ + } + + while (indexRight < right.size) { + newList.add(right[indexRight]) + indexRight++ + } + + return newList; +} + +fun main(args: Array) { + val numbers = mutableListOf(38,27,43,3,9,82,10) + val sortedList = mergeSort(numbers) + println("Unsorted: $numbers") + println("Sorted: $sortedList") +} \ No newline at end of file diff --git a/Algorithms/Kotlin/QuickSort.kt b/Algorithms/Kotlin/QuickSort.kt new file mode 100644 index 00000000..a2522d1b --- /dev/null +++ b/Algorithms/Kotlin/QuickSort.kt @@ -0,0 +1,39 @@ +fun main(args: Array) { + val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() + quickSort(array, 0, array.size-1) + for(i in array) println(i) +} + +fun quickSort(array: IntArray, left: Int, right: Int) { + val index = partition (array, left, right) + if(left < index-1) { + quickSort(array, left, index-1) + } + if(index < right) { + quickSort(array,index, right) + } +} + +fun partition(array: IntArray, l: Int, r: Int): Int { + var left = l + var right = r + val pivot = array[(left + right)/2] + while (left <= right) { + while (array[left] < pivot) left++ + + while (array[right] > pivot) right-- + + if (left <= right) { + swapArray(array, left,right) + left++ + right-- + } + } + return left +} + +fun swapArray(a: IntArray, b: Int, c: Int) { + val temp = a[b] + a[b] = a[c] + a[c] = temp +} diff --git a/Algorithms/Kotlin/insertionSort.kt b/Algorithms/Kotlin/insertionSort.kt new file mode 100644 index 00000000..31e3c62f --- /dev/null +++ b/Algorithms/Kotlin/insertionSort.kt @@ -0,0 +1,24 @@ +import java.util.* + +fun insertionsort(items:MutableList):List{ + if (items.isEmpty() || items.size<2){ + return items + } + for (count in 1..items.count() - 1){ + // println(items) + val item = items[count] + var i = count + while (i>0 && item < items[i - 1]){ + items[i] = items[i - 1] + i -= 1 + } + items[i] = item + } + return items +} +fun main(args: Array) { + val names = mutableListOf(8, 3, 2, 7, 4) + println(names) + var ordered = insertionsort(names) + println(ordered) +} diff --git a/Algorithms/Kotlin/selectionSort.kt b/Algorithms/Kotlin/selectionSort.kt new file mode 100644 index 00000000..b80366c7 --- /dev/null +++ b/Algorithms/Kotlin/selectionSort.kt @@ -0,0 +1,16 @@ +fun selectionSort(A:Array){ + var n = A.size + var temp: Int + for(i in n-1 downTo 0){ + var max = i + for(j in 0 until i){ + if(A[j] > A[max]) + max = j + } + if(i != max){ + temp = A[i] + A[i]= A[max] + A[max] = temp + } + } +} From 3bb269befd377bcca72bdf39900fb798643a4348 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Diego=20G=C3=B3mez=20Cota?= <38957780+diegomezcota@users.noreply.github.com> Date: Wed, 23 Oct 2019 15:03:27 -0500 Subject: [PATCH 213/324] Solved compare the triplets problem --- Hackerrank/compareTheTriplets.cpp | 108 ++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 Hackerrank/compareTheTriplets.cpp diff --git a/Hackerrank/compareTheTriplets.cpp b/Hackerrank/compareTheTriplets.cpp new file mode 100644 index 00000000..33c63aa8 --- /dev/null +++ b/Hackerrank/compareTheTriplets.cpp @@ -0,0 +1,108 @@ +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/compare-the-triplets/problem + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the compareTriplets function below. +vector compareTriplets(vector a, vector b) { + + int iAliceScore = 0, iBobScore = 0; + + for (int i = 0; i < 3; ++i){ + if (a[i] > b[i]) ++iAliceScore; + else if (a[i] < b[i]) ++iBobScore; + } + + return {iAliceScore, iBobScore}; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split(rtrim(a_temp_temp)); + + vector a(3); + + for (int i = 0; i < 3; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + string b_temp_temp; + getline(cin, b_temp_temp); + + vector b_temp = split(rtrim(b_temp_temp)); + + vector b(3); + + for (int i = 0; i < 3; i++) { + int b_item = stoi(b_temp[i]); + + b[i] = b_item; + } + + vector result = compareTriplets(a, b); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} From 8b1031cc0986a04334a2890fdb68f93739fb4aaa Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:43:52 +0530 Subject: [PATCH 214/324] Create CountOfIntegers.c --- Hackerearth/CountOfIntegers.c | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Hackerearth/CountOfIntegers.c diff --git a/Hackerearth/CountOfIntegers.c b/Hackerearth/CountOfIntegers.c new file mode 100644 index 00000000..0d640d5b --- /dev/null +++ b/Hackerearth/CountOfIntegers.c @@ -0,0 +1,40 @@ + #include + #include + #define SIZE 1000001 + typedef long int ll; + ll Find(ll Prime[],ll N){ + ll temp=N,curr=Prime[N]; + while(N>1){ + N/=Prime[N]; + if(Prime[N]!=curr){ + temp=(temp/curr)*(curr-1); + curr=Prime[N]; + } + } + return(temp); + } + int main(){ + ll i,j,N,Q; + ll *Prime=(ll *)malloc(SIZE*sizeof(ll)); + ll *count=(ll *)malloc(SIZE*sizeof(ll)); + ll *Sum=(ll *)malloc(SIZE*sizeof(ll)); + for(i=0;i Date: Thu, 24 Oct 2019 02:45:44 +0530 Subject: [PATCH 215/324] Create palindrome.js Logic to check if a word is spelled same as forward and backward --- Algorithms/JavaScript/palindrome.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Algorithms/JavaScript/palindrome.js diff --git a/Algorithms/JavaScript/palindrome.js b/Algorithms/JavaScript/palindrome.js new file mode 100644 index 00000000..f0f21aae --- /dev/null +++ b/Algorithms/JavaScript/palindrome.js @@ -0,0 +1,15 @@ +function isPalindrome(str) { + str = str.toLowerCase(); + let strArr = str.split(/\W/); + let newStr = strArr.join(''); + + if(newStr === newStr.split('').reverse().join('')) { + console.log(true); + } else { + console.log(false); + } +} + +isPalindrome("Madam, I'm Adam"); // true +isPalindrome("racecar"); // true +isPalindrome("hacktoberfest"); // false From 29173fbc6e132b62b5b7afa13ade6f2294a2089f Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:46:00 +0530 Subject: [PATCH 216/324] Create SpecialPointsOfAPolygon.c --- Hackerearth/SpecialPointsOfAPolygon.c | 44 +++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Hackerearth/SpecialPointsOfAPolygon.c diff --git a/Hackerearth/SpecialPointsOfAPolygon.c b/Hackerearth/SpecialPointsOfAPolygon.c new file mode 100644 index 00000000..e34aec54 --- /dev/null +++ b/Hackerearth/SpecialPointsOfAPolygon.c @@ -0,0 +1,44 @@ +#include + +#include +int main() + +{ + int n; + scanf("%d ",&n); + + + int a, b, i = 0, count = 0, dount = 0; + int*c = NULL; + c = (int*)calloc(n, sizeof(int)); + int*d = NULL; + d = (int*)calloc(n, sizeof(int)); + scanf("%d %d", &a, &b); + for (int k = 0; k < n; k++) + { + int x, y; + scanf("%d %d",&x,&y); + *(c + k) = x; + *(d + k) = y; + } + + while (i < n) + { + if (a > *(c + i) && b > *(d + i)) + { + count++; + } + else if (a < *(c + i) && b < *(d + i)) + { + dount++; + } + i++; + } + if (count == dount) + { + printf("%d %d", a, b); + } + + + return 0; +} From 0a7a9e844bae0061c9da85a303ea1e058dfd98f0 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:47:25 +0530 Subject: [PATCH 217/324] Rename SpecialPointsOfAPolygon.c to Special Points Of A Polygon.c --- .../{SpecialPointsOfAPolygon.c => Special Points Of A Polygon.c} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerearth/{SpecialPointsOfAPolygon.c => Special Points Of A Polygon.c} (100%) diff --git a/Hackerearth/SpecialPointsOfAPolygon.c b/Hackerearth/Special Points Of A Polygon.c similarity index 100% rename from Hackerearth/SpecialPointsOfAPolygon.c rename to Hackerearth/Special Points Of A Polygon.c From 1c931cb13fa2de4adcea97442a4aad633cd62348 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:47:48 +0530 Subject: [PATCH 218/324] Rename CountOfIntegers.c to Count Of Integers.c --- Hackerearth/{CountOfIntegers.c => Count Of Integers.c} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Hackerearth/{CountOfIntegers.c => Count Of Integers.c} (100%) diff --git a/Hackerearth/CountOfIntegers.c b/Hackerearth/Count Of Integers.c similarity index 100% rename from Hackerearth/CountOfIntegers.c rename to Hackerearth/Count Of Integers.c From ca508318ab8542ddb37fbcfe24d294a4ff5c12b1 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:50:14 +0530 Subject: [PATCH 219/324] Create 9A.py --- Codeforces/9A.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Codeforces/9A.py diff --git a/Codeforces/9A.py b/Codeforces/9A.py new file mode 100644 index 00000000..43d22b0a --- /dev/null +++ b/Codeforces/9A.py @@ -0,0 +1,19 @@ +s = input() +y = s[0] +w = s[2] +if int(y) > int(w): + p = 7 - int(y) +else: + p = 7 - int(w) +if p == 1: + print('1/6') +if p == 2: + print('1/3') +if p == 3: + print('1/2') +if p == 4: + print('2/3') +if p == 5: + print('5/6') +if p == 6: + print('1/1') From 2da44dd0347b2b1e6ef3573478cbdb7843976d6c Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:51:32 +0530 Subject: [PATCH 220/324] Create 281A.cpp --- Codeforces/281A.cpp | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Codeforces/281A.cpp diff --git a/Codeforces/281A.cpp b/Codeforces/281A.cpp new file mode 100644 index 00000000..45fb2262 --- /dev/null +++ b/Codeforces/281A.cpp @@ -0,0 +1,13 @@ +#include +#include + +using namespace std; + +int main() +{ + string s; + cin >> s; + s[0] = towupper(s[0]); + cout << s < Date: Thu, 24 Oct 2019 02:52:40 +0530 Subject: [PATCH 221/324] Create 1030A.py --- Codeforces/1030A.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Codeforces/1030A.py diff --git a/Codeforces/1030A.py b/Codeforces/1030A.py new file mode 100644 index 00000000..028d4d95 --- /dev/null +++ b/Codeforces/1030A.py @@ -0,0 +1,10 @@ +p_in = input() +s_in = input() +p = 0 +for x in range(int(p_in)*2 - 1): + if s_in[x] == '1': + p = 1 +if p == 1: + print("Hard") +else: + print("Easy") From 48a111b2dcf797ae504e2fecc78a347d5863eb79 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 24 Oct 2019 02:54:55 +0530 Subject: [PATCH 222/324] Create 935A.py --- Codeforces/935A.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Codeforces/935A.py diff --git a/Codeforces/935A.py b/Codeforces/935A.py new file mode 100644 index 00000000..1a162cd5 --- /dev/null +++ b/Codeforces/935A.py @@ -0,0 +1,7 @@ +inp = int(input()) +output = 0 +for x in range(1, int(inp/2) + 1): + s = str((inp-x)/x) + if s[-1] == '0' and s[-2] == '.': + output += 1 +print(output) From 174c4a5d4a840e773ba772d65406a27e7f266709 Mon Sep 17 00:00:00 2001 From: Harshit Richariya <35799384+HarshitRichariya@users.noreply.github.com> Date: Thu, 24 Oct 2019 03:19:39 +0530 Subject: [PATCH 223/324] Create fibonacci-position.js Code for getting the number at a given position in fibonacci series --- Algorithms/JavaScript/fibonacci-position.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Algorithms/JavaScript/fibonacci-position.js diff --git a/Algorithms/JavaScript/fibonacci-position.js b/Algorithms/JavaScript/fibonacci-position.js new file mode 100644 index 00000000..c3f41fdf --- /dev/null +++ b/Algorithms/JavaScript/fibonacci-position.js @@ -0,0 +1,14 @@ +function fibonacci(position) { + if(position < 3) return 1; + else { + return fibonacci(position - 1) + fibonacci(position - 2); + } +} + +console.log(fibonacci(1)); // 1 +console.log(fibonacci(2)); // 1 +console.log(fibonacci(3)); // 2 +console.log(fibonacci(4)); // 3 +console.log(fibonacci(5)); // 5 +console.log(fibonacci(6)); // 8 +console.log(fibonacci(7)); // 13 From df4cfa5ac4ae72f6b4285027218754e6ad4f81f9 Mon Sep 17 00:00:00 2001 From: Viktor Guilherme Date: Wed, 23 Oct 2019 19:02:57 -0300 Subject: [PATCH 224/324] fibonacci.c --- Algorithms/C/fibonacci.c | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Algorithms/C/fibonacci.c b/Algorithms/C/fibonacci.c index 97f88d94..f2af0a6e 100644 --- a/Algorithms/C/fibonacci.c +++ b/Algorithms/C/fibonacci.c @@ -1,4 +1,30 @@ #include +#include //openmp library + +long fib(long n) +{ + long i, j; + + if (n < 2) + return n; + else if (n < z) + { + return fib(n-1) + fib (n-2); + } + else + { + #pragma omp parallel sections + { + #pragma omp section + i = fib(n-1); + #pragma omp section + j = fib(n-2); + } + return i + j; + } +} + + int main() { int i, n, t = 0, t1 = 1, nextTerm; From 9a2b10da7921eb4ee3a7c5a7bb222a97fd24b5f0 Mon Sep 17 00:00:00 2001 From: G-M-C Date: Thu, 24 Oct 2019 18:40:47 +0530 Subject: [PATCH 225/324] Modified Kaprekar Numbers Solution --- .DS_Store | Bin 0 -> 6148 bytes Hackerrank/.DS_Store | Bin 0 -> 6148 bytes Hackerrank/C/ModifiedKaprekarNumbers.c | 118 +++++++++++++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 .DS_Store create mode 100644 Hackerrank/.DS_Store create mode 100644 Hackerrank/C/ModifiedKaprekarNumbers.c diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..69e7e802ab1dc5c8dcae9064230ef061daf1cfd3 GIT binary patch literal 6148 zcmeHK-EPw`6h7_>b2GszgtT4e28oM;I(0B4gjBj#P>Da0!7c!8X_KzevSdn9Dkw$0 z;T?cC;8A!29)t&g&yJarv=eu1LOzoH9oy%#ldmUsO+>6UayE#nM8r`9mJL)3OpJ>% zXC>8h8OY=u5qXr*kd7#xi`E@l0jX-@ocRSZ=A#rz>Bbs zOL2koslZtU=P5m*9ePe(YS9aLU9=x8dP4TIz%Egnto#a6iO(4&R_Gzwc$PyvO@v~j z#vWK;iFePkj2tThE1<(XN521GIlXawtbV8Oy<^{tlY0FJD=n2TTwLbd;Kn86jWrC% zR$?ckxMfGLMC+NI413Do2}A$Hw|g%=cf41IN`Vzjsho^ z^H}Ks=M`SrtFBKbjmE8-+1R`@t(lXpt$NMeY}}qsD}3$R#=Y+T(YyDP57UodAO?)# z(2%yO@DF^2vrwS7RuuSQaDZ{a6)`SS*GD?+%9QYnNykJ&WJTok2pktbkxIUT=pqHO z@ym$sBDRC1v8a=e7RkVPCK)P7vkpF|Ha!NO@)6`1SnjM$$H+k+S^=%Vxm7^y z4U@x~0Jve-{MDRM=EFOA#Y5mQsN!m8mNROX=u0Ra{fyEX9;g zOkF;hTA8UE3X`j2ep7}MYo@4ct$5S~rWx`~MSA+$daL=YMzCDj&0xF#uDK?t7c50&=L3+CW@Tarsd8zc9} zcd&f}AH^r|L41IAW_Og_RsV@d*n!<|cITVD%y-;w763$N5^Vr906=0Rbn4js#wbqh zidA@q@&v7+LiA{Ic~{WdEg7$uB<$U&Vvze&cpmrCAWC zgON^-qXAOhzK+vKO*?9mMq|B>Zvs-*WNp8(Hk-BE51MX!b9>%&XIopXrn}jGIG@+# z>fMdUdk2Rnr?ZdqPiIDXft!=ITZ}*9933p}*dL{dNa7Di zeFZ>ta9SJsbOE3om(gR)4PpdMm{dfQD)@>aOghfH%<~v?gC-pWUp@psS?~=-=%?fQ zuBL +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the kaprekarNumbers function below. +void kaprekarNumbers(int p, int q) { + long i;int check=0; + int cnt=0; long sum1=0,sum2=0; + + + for(i=p;i<=q;i++) + {long sq=pow(i,2); + + long a=sq,b=sq; + cnt=0;sum1=sum2=0; + int flag=1;int mult1=0,mult2=0; + + while(a>0) + {a=a/10; + cnt=cnt+1;} + + + while(b>0) + {int rem=b%10; + b=b/10; + + if(flag<=floor((cnt+1)/2)) + {sum1=sum1+(rem*pow(10,mult1)); + flag+=1;mult1++;continue;} + + if(flag>floor((cnt+1)/2)&&flag<=cnt) + {sum2+=rem*pow(10,mult2); + flag+=1;mult2++;}} + int tot=sum1+sum2; + + if((tot==i)&&(tot%100!=0)&&(tot!=10)) + {printf("%d ",i); + check++;}} + + + + if(check==0) + printf("INVALID RANGE"); + + + + + + +} + +int main() +{ + char* p_endptr; + char* p_str = readline(); + int p = strtol(p_str, &p_endptr, 10); + + if (p_endptr == p_str || *p_endptr != '\0') { exit(EXIT_FAILURE); } + + char* q_endptr; + char* q_str = readline(); + int q = strtol(q_str, &q_endptr, 10); + + if (q_endptr == q_str || *q_endptr != '\0') { exit(EXIT_FAILURE); } + + kaprekarNumbers(p, q); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { + break; + } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { + break; + } + + alloc_length <<= 1; + + data = realloc(data, alloc_length); + + if (!line) { + break; + } + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + + data = realloc(data, data_length); + } else { + data = realloc(data, data_length + 1); + + data[data_length] = '\0'; + } + + return data; +} From f05f5152eed3206c66a4e5e192c10a17eb1ccb58 Mon Sep 17 00:00:00 2001 From: G-M-C Date: Thu, 24 Oct 2019 19:31:17 +0530 Subject: [PATCH 226/324] Save The Prisoner --- Hackerrank/C/SaveThePrisoner.c | 128 +++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 Hackerrank/C/SaveThePrisoner.c diff --git a/Hackerrank/C/SaveThePrisoner.c b/Hackerrank/C/SaveThePrisoner.c new file mode 100644 index 00000000..38643b09 --- /dev/null +++ b/Hackerrank/C/SaveThePrisoner.c @@ -0,0 +1,128 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the saveThePrisoner function below. +int saveThePrisoner(int n, int m, int s) { + + + if((s+m-1)<=n) + {return s+m-1;} + else + {int rem= abs(m-n-1+s); + + if(rem%n==0) + { + return n;} + else + + return rem%n;} + + + + + + +} + +int main() +{ + FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); + + char* t_endptr; + char* t_str = readline(); + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + for (int t_itr = 0; t_itr < t; t_itr++) { + char** nms = split_string(readline()); + + char* n_endptr; + char* n_str = nms[0]; + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char* m_endptr; + char* m_str = nms[1]; + int m = strtol(m_str, &m_endptr, 10); + + if (m_endptr == m_str || *m_endptr != '\0') { exit(EXIT_FAILURE); } + + char* s_endptr; + char* s_str = nms[2]; + int s = strtol(s_str, &s_endptr, 10); + + if (s_endptr == s_str || *s_endptr != '\0') { exit(EXIT_FAILURE); } + + int result = saveThePrisoner(n, m, s); + + fprintf(fptr, "%d\n", result); + } + + fclose(fptr); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} + +char** split_string(char* str) { + char** splits = NULL; + char* token = strtok(str, " "); + + int spaces = 0; + + while (token) { + splits = realloc(splits, sizeof(char*) * ++spaces); + if (!splits) { + return splits; + } + + splits[spaces - 1] = token; + + token = strtok(NULL, " "); + } + + return splits; +} From f2fdfb2d52d4c1f0cd509a3ab91ece20fde259de Mon Sep 17 00:00:00 2001 From: G-M-C Date: Thu, 24 Oct 2019 19:41:53 +0530 Subject: [PATCH 227/324] Modified Kaprekar Numbers --- Hackerrank/C/.DS_Store | Bin 0 -> 6148 bytes Hackerrank/C/SaveThePrisoner.c | 128 --------------------------------- 2 files changed, 128 deletions(-) create mode 100644 Hackerrank/C/.DS_Store delete mode 100644 Hackerrank/C/SaveThePrisoner.c diff --git a/Hackerrank/C/.DS_Store b/Hackerrank/C/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..7e4cd73743f528315affabd08acff13ee5ba0023 GIT binary patch literal 6148 zcmeHK!A=4(5PgG~V7L&CQExqZGSRD-6)?saj0t{#0;>{{B`61Od+}rZK0iR;w2hHn zxhgR;o9UZ&JJacFv)uxa=4@~XGyv47ij@r(KZw3pElDM|tP{n@c)<{3+{2+;>TM0H z$bhch7Fx(K9gc8-J|>u)kFtJml=bML+vS+L|KWueu!%Ez3^AZj3lF%( zh)?SGL%Jl!TOr0CI?QCiD0kG9)&=8C7&pZuttl><=M#FYPw}i#7qgO`Lc}_*n8l2J zJAQAfRrY!MNI- zC1ea31AoncejglFF^QN5^q&qE{t7^>ve^r5{W(-07cq&L2jm-y1Xp5km3YOF;Ldgz z`y~xkjI_eEoMf>Fezg%eeqnLg5DBh)dVY^d -#include -#include -#include -#include -#include -#include -#include -#include - -char* readline(); -char** split_string(char*); - -// Complete the saveThePrisoner function below. -int saveThePrisoner(int n, int m, int s) { - - - if((s+m-1)<=n) - {return s+m-1;} - else - {int rem= abs(m-n-1+s); - - if(rem%n==0) - { - return n;} - else - - return rem%n;} - - - - - - -} - -int main() -{ - FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); - - char* t_endptr; - char* t_str = readline(); - int t = strtol(t_str, &t_endptr, 10); - - if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } - - for (int t_itr = 0; t_itr < t; t_itr++) { - char** nms = split_string(readline()); - - char* n_endptr; - char* n_str = nms[0]; - int n = strtol(n_str, &n_endptr, 10); - - if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } - - char* m_endptr; - char* m_str = nms[1]; - int m = strtol(m_str, &m_endptr, 10); - - if (m_endptr == m_str || *m_endptr != '\0') { exit(EXIT_FAILURE); } - - char* s_endptr; - char* s_str = nms[2]; - int s = strtol(s_str, &s_endptr, 10); - - if (s_endptr == s_str || *s_endptr != '\0') { exit(EXIT_FAILURE); } - - int result = saveThePrisoner(n, m, s); - - fprintf(fptr, "%d\n", result); - } - - fclose(fptr); - - return 0; -} - -char* readline() { - size_t alloc_length = 1024; - size_t data_length = 0; - char* data = malloc(alloc_length); - - while (true) { - char* cursor = data + data_length; - char* line = fgets(cursor, alloc_length - data_length, stdin); - - if (!line) { break; } - - data_length += strlen(cursor); - - if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } - - size_t new_length = alloc_length << 1; - data = realloc(data, new_length); - - if (!data) { break; } - - alloc_length = new_length; - } - - if (data[data_length - 1] == '\n') { - data[data_length - 1] = '\0'; - } - - data = realloc(data, data_length); - - return data; -} - -char** split_string(char* str) { - char** splits = NULL; - char* token = strtok(str, " "); - - int spaces = 0; - - while (token) { - splits = realloc(splits, sizeof(char*) * ++spaces); - if (!splits) { - return splits; - } - - splits[spaces - 1] = token; - - token = strtok(NULL, " "); - } - - return splits; -} From 7eb4ea0b3b5685d425cd13bd6ee83fccdaa8e89f Mon Sep 17 00:00:00 2001 From: Mathana Kumar S Date: Fri, 25 Oct 2019 10:55:42 +0530 Subject: [PATCH 228/324] Added Kadane's Algorithm in PHP --- Algorithms/PHP/kadanealgo.php | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Algorithms/PHP/kadanealgo.php diff --git a/Algorithms/PHP/kadanealgo.php b/Algorithms/PHP/kadanealgo.php new file mode 100644 index 00000000..1c7f1f35 --- /dev/null +++ b/Algorithms/PHP/kadanealgo.php @@ -0,0 +1,22 @@ + \ No newline at end of file From d05564ae98087b8d9ce90a8516cbf2ec6737c2e4 Mon Sep 17 00:00:00 2001 From: Soumya Raj Darbari Date: Fri, 25 Oct 2019 13:17:00 +0530 Subject: [PATCH 229/324] Create TIMEASR.cpp --- Codechef/TIMEASR.cpp | 61 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Codechef/TIMEASR.cpp diff --git a/Codechef/TIMEASR.cpp b/Codechef/TIMEASR.cpp new file mode 100644 index 00000000..7a58f3a7 --- /dev/null +++ b/Codechef/TIMEASR.cpp @@ -0,0 +1,61 @@ +/* + Just For You 97116:) +*/ + +#include +using namespace std; + +//important constants +#define pi M_PI +#define mod 1000000007 +#define maX(a,b) ((a)>(b)?(a):(b)) +#define miN(a,b) ((a)<(b)?(a):(b) +#define abS(x) ((x)<0?-(x):(x)) + +#ifdef ONLINE_JUDGE +#define MAX 200005 +#else +#define MAX 1000 +#endif + +int a[MAX],b[MAX]; +char s[100],r[100],t[100]; + +const double EPS = 1e-9; +double ang[MAX],angle; +int hh[MAX],mm[MAX]; + +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + // freopen("output.txt","w",stdout); + #endif + + int t,n,m,k,l,x,y,z,flag,count,sum,d,mx,mn,prod; + double hour_angle = 0.0; + double minute_angle = 0.0; + + for(int i=0;i<60*12;i++){ + if(i%60==0) + minute_angle=0; + else + minute_angle+=6.0; + hh[i] = i/60; + mm[i] = i%60; + ang[i] = abS(minute_angle-hour_angle); + if(ang[i]-EPS>180.0) + ang[i] = 360.0 - ang[i]; + hour_angle += 0.5; + } + + double error = 1.0/120.0; + scanf("%d",&t); + while(t--){ + scanf("%lf",&angle); + for(int i=0;i<12*60;i++){ + if(abS(ang[i]-angle) Date: Fri, 25 Oct 2019 13:18:21 +0530 Subject: [PATCH 230/324] Create BRLADDER.cpp --- Codechef/BRLADDER.cpp | 54 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Codechef/BRLADDER.cpp diff --git a/Codechef/BRLADDER.cpp b/Codechef/BRLADDER.cpp new file mode 100644 index 00000000..3997d797 --- /dev/null +++ b/Codechef/BRLADDER.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +//important constants +#define pi M_PI +#define mod 1000000007 +#define maX(a,b) ((a)>(b)?(a):(b)) +#define miN(a,b) ((a)<(b)?(a):(b)) + +#ifdef ONLINE_JUDGE +#define MAX 200005 +#else +#define MAX 100000 +#endif + +int a[MAX],b[MAX]; +char s[MAX],r[MAX]; +int test; + +int main(){ + #ifndef ONLINE_JUDGE + freopen("input.txt","r",stdin); + // freopen("output.txt","w",stdout); + #endif + + int t,n,m,k,l,x,y,z,flag,count,d,mx,mn; + long long int sum,prod; + + scanf("%d",&test); + + while(test--){ + flag=0; + // scanf("%d",&n); + scanf("%d%d",&n,&m); + + if(n%2 && m%2){ + if(abs(n-m)==2) + flag=1; + }else if(n%2){ + if(m-n==1) + flag=1; + }else if(m%2){ + if(n-m==1) + flag=1; + }else{ + if(abs(n-m)==2) + flag=1; + } + if(flag) printf("YES\n"); + else printf("NO\n"); + + } + return 0; +} From 062455b35bcded8172a81bf6da85e35cb45afb7c Mon Sep 17 00:00:00 2001 From: Soumya Raj Darbari Date: Fri, 25 Oct 2019 13:19:16 +0530 Subject: [PATCH 231/324] Create COINS.cpp --- Codechef/COINS.cpp | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Codechef/COINS.cpp diff --git a/Codechef/COINS.cpp b/Codechef/COINS.cpp new file mode 100644 index 00000000..0cefc3ca --- /dev/null +++ b/Codechef/COINS.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +map m; + +long long int change(long long int n){ + if(n<12) return n; + if(m[n]) return m[n]; + m[n]=change(n/2)+change(n/3)+change(n/4); + return m[n]; +} + +int main(){ + long long int n,count=0; + while(scanf("%lld",&n)>0){ + m[n]=1; + count=max(n,change(n/2)+change(n/3)+change(n/4)); + printf("%lld\n",count); + count=0; + m.clear(); + } + return 0; +} From 67b12f52d06924cf480fa91cd1112d1062b025cd Mon Sep 17 00:00:00 2001 From: pdolata Date: Fri, 25 Oct 2019 10:44:52 +0200 Subject: [PATCH 232/324] Add least common multiple algorithm --- Algorithms/JavaScript/leastCommonMultiple.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Algorithms/JavaScript/leastCommonMultiple.js diff --git a/Algorithms/JavaScript/leastCommonMultiple.js b/Algorithms/JavaScript/leastCommonMultiple.js new file mode 100644 index 00000000..27386e5f --- /dev/null +++ b/Algorithms/JavaScript/leastCommonMultiple.js @@ -0,0 +1,17 @@ +const leastCommonMultiple = (a,b) => { + let x = a; + let y = b + while(x !== y) { + if(x>y){ + x = x - y; + } + else { + y = y - x; + } + } + return (a * b) / x; +} + +//examples +// leastCommonMultiple(2,3); +// leastCommonMultiple(192,348); \ No newline at end of file From 22b46d911882e697ed494c8b6291405043682502 Mon Sep 17 00:00:00 2001 From: Dawood-Asghar <56993489+Dawood-Asghar@users.noreply.github.com> Date: Fri, 25 Oct 2019 14:11:03 +0500 Subject: [PATCH 233/324] Create Node.h --- DS/C++/Node.h | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 DS/C++/Node.h diff --git a/DS/C++/Node.h b/DS/C++/Node.h new file mode 100644 index 00000000..f8e02d47 --- /dev/null +++ b/DS/C++/Node.h @@ -0,0 +1,34 @@ +#include + +using namespace std; + +class Node +{ + private: + int Data; + public: + Node() + { + Data = 0; + } + + Node(int data) + { + Data = data; + } + + void Set_Data(int data) + { + Data = data; + } + + int Get_Data() + { + return Data; + } + + void Print() + { + cout << Data; + } +}; From b0d7a816c3e1dd8ee858db404bbca1358f0ce60a Mon Sep 17 00:00:00 2001 From: Raman1309 <40718728+Raman1309@users.noreply.github.com> Date: Fri, 25 Oct 2019 22:00:43 +0530 Subject: [PATCH 234/324] MATCHES.cpp Solution for codechef MATCHES. Link for the problem: https://www.codechef.com/problems/MATCHES --- Codechef/MATCHES.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Codechef/MATCHES.cpp diff --git a/Codechef/MATCHES.cpp b/Codechef/MATCHES.cpp new file mode 100644 index 00000000..abd38b20 --- /dev/null +++ b/Codechef/MATCHES.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +int main() +{ + int t; + cin>>t; + while(t--) + { + int a,b,rem; + long long int res,k; + int ar[]={6,2,5,5,4,5,6,3,7,6}; + cin>>a>>b; + res=a+b; + k=0; + while(res>0) + { + rem=res%10; + k=k+ar[rem]; + res/=10; + } + cout< Date: Fri, 25 Oct 2019 22:05:49 +0530 Subject: [PATCH 235/324] S10E.cpp Solution for codechef S10E from October Challenge 2019 Divison 2. Link for problem: https://www.codechef.com/OCT19B/problems/S10E --- Codechef/S10E.cpp | 96 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Codechef/S10E.cpp diff --git a/Codechef/S10E.cpp b/Codechef/S10E.cpp new file mode 100644 index 00000000..4ff99ed2 --- /dev/null +++ b/Codechef/S10E.cpp @@ -0,0 +1,96 @@ +/*Chef wants to buy a new phone, but he is not willing to spend a lot of money. +Instead, he checks the price of his chosen model everyday and waits for the price +to drop to an acceptable value. So far, he has observed the price for N days +(numbere 1 through N); for each valid i, the price on the i-th day was Pi dollars. + +On each day, Chef considers the price of the phone to be good if it is strictly +smaller than all the prices he has observed during the previous five days. If +there is no record of the price on some of the previous five days (because Chef +has not started checking the price on that day yet), then Chef simply ignores +that previous day ― we could say that he considers the price on that day to be +infinite. + +Now, Chef is wondering ― on how many days has he considered the price to be good? +Find the number of these days. + +Input +The first line of the input contains a single integer T denoting the number of +test cases. The description of T test cases follows. +The first line of each test case contains a single integer N. +The second line contains N space-separated integers P1,P2,…,PN. + + +Output +For each test case, print a single line containing one integer ― the number of +days with a good price. + +Constraints +1≤T≤100 +7≤N≤100 +350≤Pi≤750 for each valid i +Subtasks +Subtask #1 (30 points): N=7 +Subtask #2 (70 points): original constraints + +Example Input +1 +7 +375 750 723 662 647 656 619 + +Example Output +2 + +Explanation +Example case 1: Chef considers the price to be good on day 1, because he has not +observed any prices on the previous days. The prices on days 2,3,4,5,6 are not +considered good because they are greater than the price on day 1. Finally, the +price on day 7 is considered good because it is smaller than all of the prices +on days 2,3,4,5,6.*/ + + +#include +using namespace std; + +int main() +{ + int t; + cin>>t; + while(t--) + { + int n; + cin>>n; + int a[n],i,j,k,temp; + + for(i=0;i>a[i]; + + k=0; + for(i=0;ia[i]) + k++; + } + else + { + temp=a[i-5]; + for(j=i-5;ja[i]) + k++; + } + } + cout< Date: Fri, 25 Oct 2019 23:12:13 -0500 Subject: [PATCH 236/324] Added DynamicArray data structure --- DS/C++/DynamicArray.cpp | 118 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 118 insertions(+) create mode 100644 DS/C++/DynamicArray.cpp diff --git a/DS/C++/DynamicArray.cpp b/DS/C++/DynamicArray.cpp new file mode 100644 index 00000000..925af26d --- /dev/null +++ b/DS/C++/DynamicArray.cpp @@ -0,0 +1,118 @@ +#include + +using namespace std; + +class DynamicArray { + + private: + int capacity, used; + int* data; + void resize(int new_capacity); + public: + static const int DEFAULT_CAPACITY = 1; + DynamicArray(int initial_capacity = DEFAULT_CAPACITY); + DynamicArray(const DynamicArray& src); + ~DynamicArray(); + DynamicArray& operator=(const DynamicArray& rhs); + int size() const; + bool empty() const; + void add(int anInt); + void remove(int anInt); + void print(ostream& out) const; +}; + +void DynamicArray::resize(int new_capacity) +{ + if (new_capacity < used) + new_capacity = used; + if (new_capacity < 1) + new_capacity = 1; + int* temp = new int[new_capacity]; + for(int x = 0; x < used; ++x) + { + temp[x] = data[x]; + } + delete[] data; + data = temp; + capacity = new_capacity; +} + +DynamicArray::DynamicArray(int initial_capacity) : capacity(initial_capacity), used(0) +{ + if (initial_capacity < 1) + initial_capacity = DEFAULT_CAPACITY; + data = new int[initial_capacity]; +} + +DynamicArray::~DynamicArray() { delete[] data; } + +DynamicArray& DynamicArray::operator=(const DynamicArray& rhs) +{ + if (this != &rhs) + { + int* newData = new int[rhs.capacity]; + for (int x = 0; x < rhs.used; ++x) + newData[x] = rhs.data[x]; + delete [] data; + data = newData; + capacity = rhs.capacity; + used = rhs.used; + } + return *this; +} + +int DynamicArray::size() const { return used; } + +bool DynamicArray::empty() const { return used == 0; } + +void DynamicArray::add(int anInt) +{ + if (used+1 > capacity) + resize(1.5 * capacity + 1); + data[used] = anInt; + ++used; +} + +void DynamicArray::remove(int anInt) +{ + int x = 0; + while(data[x] != anInt) + ++x; + for(int y = x; y < used-1; ++y) + data[y] = data[y + 1]; + --used; +} + +void DynamicArray::print(ostream& out) const +{ + if (used > 0) + { + out << data[0]; + for (int x = 1; x < used; ++x) + out << " " << data[x]; + } +} + +int main() +{ + DynamicArray test; + test.add(10); + test.add(20); + test.add(30); + + cout << "\ntest.size() : " << test.size(); + cout << "\ntest.empty() : " << (test.empty() ? "true" : "false"); + + cout << "\nThe dynamic array test is : "; + test.print(cout); + test.remove(10); + cout << "\nThe dynamic array test is : "; + test.print(cout); + test.remove(30); + cout << "\nThe dynamic array test is : "; + test.print(cout); + test.remove(20); + cout << "\ntest.size() : " << test.size(); + cout << "\ntest.empty() : " << (test.empty() ? "true" : "false"); + return 0; +} \ No newline at end of file From 8f72bf285abffd9c5d4ce0bd751745af092c6323 Mon Sep 17 00:00:00 2001 From: DanielCarpenter Date: Fri, 25 Oct 2019 23:13:26 -0500 Subject: [PATCH 237/324] Update README.md added my data structure to list --- DS/README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/DS/README.md b/DS/README.md index 642e3a71..3b5701f8 100644 --- a/DS/README.md +++ b/DS/README.md @@ -8,3 +8,4 @@ - Heap - Deque - Graph +- Dynamic Array From d8004fb07812637050304ea171db6c3eff7c3745 Mon Sep 17 00:00:00 2001 From: SATYAM MISHRA <53936345+SATYAM86400@users.noreply.github.com> Date: Sat, 26 Oct 2019 14:58:30 +0530 Subject: [PATCH 238/324] Create Algo.py --- Algo.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Algo.py diff --git a/Algo.py b/Algo.py new file mode 100644 index 00000000..ef67deb1 --- /dev/null +++ b/Algo.py @@ -0,0 +1,32 @@ +# Python 3.x code to demonstrate star pattern + +# Function to demonstrate printing pattern triangle +def triangle(n): + + # number of spaces + k = 2*n - 2 + + # outer loop to handle number of rows + for i in range(0, n): + + # inner loop to handle number spaces + # values changing acc. to requirement + for j in range(0, k): + print(end=" ") + + # decrementing k after each loop + k = k - 1 + + # inner loop to handle number of columns + # values changing acc. to outer loop + for j in range(0, i+1): + + # printing stars + print("* ", end="") + + # ending line after each row + print("\r") + +# Driver Code +n = 5 +triangle(n) From 7534241bdc7a24b3508a80f8e3ec6232c71fa5fc Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Sat, 26 Oct 2019 16:31:57 +0530 Subject: [PATCH 239/324] Rename Algo.py to HelloWorld/Algo.py --- Algo.py => HelloWorld/Algo.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Algo.py => HelloWorld/Algo.py (100%) diff --git a/Algo.py b/HelloWorld/Algo.py similarity index 100% rename from Algo.py rename to HelloWorld/Algo.py From 4b30f6de01e55a2ccd048310cb3948c851c00505 Mon Sep 17 00:00:00 2001 From: Ayush Jain Date: Sat, 26 Oct 2019 23:02:24 +0530 Subject: [PATCH 240/324] Create viralAdvertising.cpp --- Hackerrank/C++/viralAdvertising.cpp | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Hackerrank/C++/viralAdvertising.cpp diff --git a/Hackerrank/C++/viralAdvertising.cpp b/Hackerrank/C++/viralAdvertising.cpp new file mode 100644 index 00000000..78ace890 --- /dev/null +++ b/Hackerrank/C++/viralAdvertising.cpp @@ -0,0 +1,34 @@ +#include + +using namespace std; + +// Complete the viralAdvertising function below. +int viralAdvertising(int n) { + int likes = 0; + int current = 5; + while(n){ + likes += current/2; + current/=2; + current = 3*current; + n--; + } + return likes; + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + int n; + cin >> n; + cin.ignore(numeric_limits::max(), '\n'); + + int result = viralAdvertising(n); + + fout << result << "\n"; + + fout.close(); + + return 0; +} From 74a96f1599033bc31ce46d634a1a23c24a5c4f68 Mon Sep 17 00:00:00 2001 From: Ayush Jain Date: Sat, 26 Oct 2019 23:15:51 +0530 Subject: [PATCH 241/324] Create kangaroo.cpp --- Hackerrank/C++/kangaroo.cpp | 73 +++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 Hackerrank/C++/kangaroo.cpp diff --git a/Hackerrank/C++/kangaroo.cpp b/Hackerrank/C++/kangaroo.cpp new file mode 100644 index 00000000..11bec119 --- /dev/null +++ b/Hackerrank/C++/kangaroo.cpp @@ -0,0 +1,73 @@ +#include + +using namespace std; + +vector split_string(string); + +// Complete the kangaroo function below. +string kangaroo(int x1, int v1, int x2, int v2) { + int del_x = x1-x2; + int del_v = v2-v1; + + float k = (float)del_x/del_v; + + if(k<0){return "NO";} + if(floor(k)==k){return "YES";} + return "NO"; + +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string x1V1X2V2_temp; + getline(cin, x1V1X2V2_temp); + + vector x1V1X2V2 = split_string(x1V1X2V2_temp); + + int x1 = stoi(x1V1X2V2[0]); + + int v1 = stoi(x1V1X2V2[1]); + + int x2 = stoi(x1V1X2V2[2]); + + int v2 = stoi(x1V1X2V2[3]); + + string result = kangaroo(x1, v1, x2, v2); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} From 40f0deda58caf5c18aabc31352fdad94c8a0dcd9 Mon Sep 17 00:00:00 2001 From: Ayush Jain Date: Sat, 26 Oct 2019 23:20:15 +0530 Subject: [PATCH 242/324] Create bon-appetit.cpp --- Hackerrank/C++/bon-appetit.cpp | 96 ++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Hackerrank/C++/bon-appetit.cpp diff --git a/Hackerrank/C++/bon-appetit.cpp b/Hackerrank/C++/bon-appetit.cpp new file mode 100644 index 00000000..6f65e916 --- /dev/null +++ b/Hackerrank/C++/bon-appetit.cpp @@ -0,0 +1,96 @@ +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the bonAppetit function below. +void bonAppetit(vector bill, int k, int b) { +int total = 0; +for(int i=0;i nk = split(rtrim(nk_temp)); + + int n = stoi(nk[0]); + + int k = stoi(nk[1]); + + string bill_temp_temp; + getline(cin, bill_temp_temp); + + vector bill_temp = split(rtrim(bill_temp_temp)); + + vector bill(n); + + for (int i = 0; i < n; i++) { + int bill_item = stoi(bill_temp[i]); + + bill[i] = bill_item; + } + + string b_temp; + getline(cin, b_temp); + + int b = stoi(ltrim(rtrim(b_temp))); + + bonAppetit(bill, k, b); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} From 5a6869b6531fc523804ac33d14fcf26340bf3d99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Ku=C5=9Bpit?= Date: Sun, 27 Oct 2019 00:31:43 +0200 Subject: [PATCH 243/324] Create helloworld.d hello world i d lang --- HelloWorld/helloworld.d | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 HelloWorld/helloworld.d diff --git a/HelloWorld/helloworld.d b/HelloWorld/helloworld.d new file mode 100644 index 00000000..c353d70a --- /dev/null +++ b/HelloWorld/helloworld.d @@ -0,0 +1,5 @@ +import std.stdio; +void main() +{ + writeln("Hello, world!"); +} From fa7554510b2338ff637ba9fbd870f01dcbfe6838 Mon Sep 17 00:00:00 2001 From: Julie Lollis Date: Sat, 26 Oct 2019 16:29:50 -0700 Subject: [PATCH 244/324] add CodeWars Ruby rot13 --- CodeWars/Ruby/rot13 | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 CodeWars/Ruby/rot13 diff --git a/CodeWars/Ruby/rot13 b/CodeWars/Ruby/rot13 new file mode 100644 index 00000000..b3d869d4 --- /dev/null +++ b/CodeWars/Ruby/rot13 @@ -0,0 +1,15 @@ +# rot13 - Chance Cantrell + +def rot13(string) + decrypted = "" + shift = 13 + encrypt = ([*('a'..'z')].zip([*('a'..'z')].rotate(shift)) + [*('A'..'Z')].zip([*('A'..'Z')].rotate(shift))).to_h + string.chars.map do |char| + if char.match?(/[a-zA-Z]/) + decrypted << encrypt.fetch(char, " ") + else + decrypted << char + end + end + decrypted +end From bc0e57f64a985ea3e1ff7a16362c6d8271820986 Mon Sep 17 00:00:00 2001 From: c_m906 Date: Sat, 26 Oct 2019 18:32:37 -0500 Subject: [PATCH 245/324] Java solution for Leetcode problem 34 --- LeetCode/First_and_last_sorted_array.java | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 LeetCode/First_and_last_sorted_array.java diff --git a/LeetCode/First_and_last_sorted_array.java b/LeetCode/First_and_last_sorted_array.java new file mode 100644 index 00000000..3fea98c5 --- /dev/null +++ b/LeetCode/First_and_last_sorted_array.java @@ -0,0 +1,34 @@ +/* Problem 34. Find First and Last Position of Element in Sorted Array + * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. + * + * Your algorithm's runtime complexity must be in the order of O(log n). + * + * If the target is not found in the array, return [-1, -1]. + */ + +public class First_and_last_sorted_array { + public int[] searchRange(int[] nums, int target) { + int[] targetRange = {-1, -1}; + + for(int i = 0; i=0; i--){ + if(nums[i] == target){ + targetRange[1] = i; + break; + } + } + + return targetRange; + + } +} From d3b7dd332e43ad2c2fe384afb999af8c2e959160 Mon Sep 17 00:00:00 2001 From: Julie Lollis Date: Sat, 26 Oct 2019 16:35:50 -0700 Subject: [PATCH 246/324] add CodeWars Ruby gematria-for-all --- CodeWars/Ruby/gematria-for-all | 42 ++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 CodeWars/Ruby/gematria-for-all diff --git a/CodeWars/Ruby/gematria-for-all b/CodeWars/Ruby/gematria-for-all new file mode 100644 index 00000000..258d4317 --- /dev/null +++ b/CodeWars/Ruby/gematria-for-all @@ -0,0 +1,42 @@ +# gematria-for-all - Chance Cantrell + +def gematria(string) + hash = { + :a => 1, + :b => 2, + :c => 3, + :d => 4, + :e => 5, + :f => 6, + :g => 7, + :h => 8, + :i => 9, + :k => 10, + :l => 20, + :m => 30, + :n => 40, + :o => 50, + :p => 60, + :q => 70, + :r => 80, + :s => 90, + :t => 100, + :u => 200, + :x => 300, + :y => 400, + :z => 500, + :j => 600, + :v => 700, + :w => 900 + } + + str = string.delete(' ').split('') + value = [] + + str.each do |x| + if x.match(/[a-zA-Z]/) + value << hash[:"#{x.downcase}"] + end + end + value.sum +end From 538f8394246a54ae1f3f0c42a46769d7aa039207 Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Sat, 26 Oct 2019 19:41:25 -0400 Subject: [PATCH 247/324] Initial commit --- Algorithms/Python/SlidingWindowMinMax.py | 76 ++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Algorithms/Python/SlidingWindowMinMax.py diff --git a/Algorithms/Python/SlidingWindowMinMax.py b/Algorithms/Python/SlidingWindowMinMax.py new file mode 100644 index 00000000..c670e6df --- /dev/null +++ b/Algorithms/Python/SlidingWindowMinMax.py @@ -0,0 +1,76 @@ +# Sliding window technique for finding max/ min window sum +# Done in a Pythonic way + +import random +import math + +def slidingWindowFind(minmax, data, winSize): + # Check for invalid window size + if (len(data) < winSize): + print("Cannot perform sliding window - window size must be less than array length") + return None + + ret = None + + # Sum up the first window + if (minmax = 0): + print("Finding the minimum window") + print("/t Array: " + str(data)) + print("/t Window size: " + str(winSize)) + + # Starting min value is infinity + ret = float("inf") + + # Sliding window + for i in range(winSize, len(data)): + # Slide window forward by 1 element each time + currentSum = sum(data[i-winSize:i]) + print("Current window: " + str(data[:winSize])) + print("Window sum: " + str(currentSum)) + print("Current min: " + str(ret)) + + ret = min(ret, currentSum) + + elif(minmax = 1): + print("Finding the maximum window") + print("/t Array: " + str(data)) + print("/t Window size: " + str(winSize)) + + # Starting min value is negative infinity + ret = float("-inf") + + # Sliding window + for i in range(winSize, len(data)): + # Slide window forward by 1 element each time + currentSum = sum(data[i-winSize:i]) + print("Current window: " + str(data[:winSize])) + print("Window sum: " + str(currentSum)) + print("Current min: " + str(ret)) + + ret = max(ret, currentSum) + + else: + print("Invalid sliding window option - use 0 for min, and 1 for max") + return None + + return ret + + +if __name__== "__main__": + array = [] + + # Generate random array with random length between 10 and 20 elements + for i in range(random.randint(9,20)): + array.append(random.randint(1, 11)) # Append random number between 1 and 10 + + winSize = random.randint(2, 6) # Generate random window size between 2 and 5 + + print("Run sliding window to find max and min...") + minVal = slidingWindowFind(0, array, winSize) + maxVal = slidingWindowFind(1, array, winSize) + + print("Minimum sum:" + str(minVal)) + print("Maximum sum:" + str(maxVal)) + + + \ No newline at end of file From 4b430ecbe1048efc5bb0a860fb518a86d73c23fd Mon Sep 17 00:00:00 2001 From: Jerry Shueh Date: Sat, 26 Oct 2019 19:46:20 -0400 Subject: [PATCH 248/324] Fixed some silly mistakes --- Algorithms/Python/SlidingWindowMinMax.py | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Algorithms/Python/SlidingWindowMinMax.py b/Algorithms/Python/SlidingWindowMinMax.py index c670e6df..2c143f6e 100644 --- a/Algorithms/Python/SlidingWindowMinMax.py +++ b/Algorithms/Python/SlidingWindowMinMax.py @@ -1,4 +1,5 @@ # Sliding window technique for finding max/ min window sum +# Integer array and window size are randomly generated # Done in a Pythonic way import random @@ -13,10 +14,10 @@ def slidingWindowFind(minmax, data, winSize): ret = None # Sum up the first window - if (minmax = 0): + if (minmax == 0): print("Finding the minimum window") - print("/t Array: " + str(data)) - print("/t Window size: " + str(winSize)) + print("\t Array: " + str(data)) + print("\t Window size: " + str(winSize)) # Starting min value is infinity ret = float("inf") @@ -25,16 +26,16 @@ def slidingWindowFind(minmax, data, winSize): for i in range(winSize, len(data)): # Slide window forward by 1 element each time currentSum = sum(data[i-winSize:i]) - print("Current window: " + str(data[:winSize])) + print("Current window: " + str(data[i-winSize:i])) print("Window sum: " + str(currentSum)) print("Current min: " + str(ret)) ret = min(ret, currentSum) - elif(minmax = 1): + elif(minmax == 1): print("Finding the maximum window") - print("/t Array: " + str(data)) - print("/t Window size: " + str(winSize)) + print("\t Array: " + str(data)) + print("\t Window size: " + str(winSize)) # Starting min value is negative infinity ret = float("-inf") @@ -43,9 +44,9 @@ def slidingWindowFind(minmax, data, winSize): for i in range(winSize, len(data)): # Slide window forward by 1 element each time currentSum = sum(data[i-winSize:i]) - print("Current window: " + str(data[:winSize])) + print("Current window: " + str(data[i-winSize:i])) print("Window sum: " + str(currentSum)) - print("Current min: " + str(ret)) + print("Current max: " + str(ret)) ret = max(ret, currentSum) @@ -67,9 +68,10 @@ def slidingWindowFind(minmax, data, winSize): print("Run sliding window to find max and min...") minVal = slidingWindowFind(0, array, winSize) + print("\n") maxVal = slidingWindowFind(1, array, winSize) - print("Minimum sum:" + str(minVal)) + print("\nMinimum sum:" + str(minVal)) print("Maximum sum:" + str(maxVal)) From 937ea7ecbd46288e49d5bfdecd36b69f95f8267b Mon Sep 17 00:00:00 2001 From: jlollis Date: Sat, 26 Oct 2019 17:39:56 -0700 Subject: [PATCH 249/324] add CodeWars add-unique-number.rb --- CodeWars/Ruby/find-unique-number.rb | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 CodeWars/Ruby/find-unique-number.rb diff --git a/CodeWars/Ruby/find-unique-number.rb b/CodeWars/Ruby/find-unique-number.rb new file mode 100644 index 00000000..5179c18a --- /dev/null +++ b/CodeWars/Ruby/find-unique-number.rb @@ -0,0 +1,16 @@ +def find_uniq(arr) + new_arr = arr.dup + match = new_arr.uniq[1] + alt = new_arr.uniq[0] + count = 0 + arr.each do |x| + unless x == match + count += 1 + end + end + if count > 1 + match + else + alt + end +end From 604b58bbf570f709aa3edc9ed25024167d4f06f0 Mon Sep 17 00:00:00 2001 From: jlollis Date: Sat, 26 Oct 2019 17:44:40 -0700 Subject: [PATCH 250/324] add CodeWars find-the-parity-outlier.rb --- CodeWars/Ruby/find-the-parity-outlier | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 CodeWars/Ruby/find-the-parity-outlier diff --git a/CodeWars/Ruby/find-the-parity-outlier b/CodeWars/Ruby/find-the-parity-outlier new file mode 100644 index 00000000..f2ee7725 --- /dev/null +++ b/CodeWars/Ruby/find-the-parity-outlier @@ -0,0 +1,11 @@ +def find_outlier(integers) + even = integers.each.select {|el| el.even?} + odd = integers.each.select {|el| el.odd?} + + if even.length < odd.length + outlier = even.join.to_i + else + outlier = odd.join.to_i + end + return outlier +end From e94e254d895a4b3d55ae198909626f238d360f00 Mon Sep 17 00:00:00 2001 From: jlollis Date: Sat, 26 Oct 2019 17:49:49 -0700 Subject: [PATCH 251/324] add fibonacci-sequence.bf --- CodeWars/Ruby/Bf/fibonacci-sequence.bf | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 CodeWars/Ruby/Bf/fibonacci-sequence.bf diff --git a/CodeWars/Ruby/Bf/fibonacci-sequence.bf b/CodeWars/Ruby/Bf/fibonacci-sequence.bf new file mode 100644 index 00000000..ac49cab5 --- /dev/null +++ b/CodeWars/Ruby/Bf/fibonacci-sequence.bf @@ -0,0 +1,15 @@ +[ Compute (and print) the first + 11 elements of the Fibonacci Sequence + 1, 1, 2, 3, 5, ... ] + ++++++++++++ +>+>>>>++++++++++++++++++++++++++++++++++++++++++++ +>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+> ++<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[- +<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<< +-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]] +>[<<+>>[-]]<<<<<<<]>>>>>[+++++++++++++++++++++++++ ++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++ +++++++++++++++++++++++++++++++++++++++++++++.[-]<< +<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<< +[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-] From e1467bec19f1b35d610898a65b35807da2bb1fd8 Mon Sep 17 00:00:00 2001 From: BlairTodd97 Date: Sun, 27 Oct 2019 00:16:21 -0500 Subject: [PATCH 252/324] Enqueue and Dequeue Algorithms in .h file --- Algorithms/C++/queue.h | 116 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 Algorithms/C++/queue.h diff --git a/Algorithms/C++/queue.h b/Algorithms/C++/queue.h new file mode 100644 index 00000000..a35af4a4 --- /dev/null +++ b/Algorithms/C++/queue.h @@ -0,0 +1,116 @@ + #include + #include + #include + using namespace std; + + class Queue { + private: + + struct Node + { + string name; //stores name of group + int people; //stores position of each group memebers + Node *next; + }; + + Node *front; + Node *rear; + int count; + + public: + Queue(); + void enqueue(string, int); + string dequeue(); //removes queue item + bool isEmpty(); //tests if queue is empty + void clear(); //clears entire queue + int size(); //returns the counter + }; + + Queue::Queue() + { //Constructor + front = NULL; + rear = NULL; + count = 0; + } + + + void Queue::enqueue(string x, int y) + { // inserts value + Node *temp = new Node; //at the rear + temp->name = x; + temp->people = y; + temp->next = NULL; + + if(isEmpty()) + { + front = temp; + rear = temp; + } + + else + { + rear->next = temp; + rear = temp; + } + + count++; + } + + string Queue::dequeue() + { // removes value at the front teturns it + + assert(!isEmpty()); + + string groupName; + int members; + + Node *temp = new Node; + temp->name = front->name; + temp->people = front->people; + front = front->next; + + groupName = temp->name; + + members = temp->people; + delete temp; + + count--; + + string convert = to_string(members); + string total = groupName + " " + convert; + return total; + } + + bool Queue::isEmpty() + { // tests if queue is empty using bool + + bool flag; + + if(count > 0) + flag = false; + + else + flag = true; + + return flag; + } + + + int Queue::size() + { // returns counter + + return count; + } + + void Queue::clear() + { // clears the queue + + string x; + + while(!isEmpty()) + { + x = dequeue(); + cout << x << endl; + } + } + From fe0765497aef7f19278d80c39de6ad1b6aa8f024 Mon Sep 17 00:00:00 2001 From: David Date: Sun, 27 Oct 2019 22:10:01 -0400 Subject: [PATCH 253/324] Dfs inorder, preorder and postorder of binary tree --- Algorithms/Haskell/dfs.hs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Algorithms/Haskell/dfs.hs diff --git a/Algorithms/Haskell/dfs.hs b/Algorithms/Haskell/dfs.hs new file mode 100644 index 00000000..256150e3 --- /dev/null +++ b/Algorithms/Haskell/dfs.hs @@ -0,0 +1,19 @@ +data Tree a = Node a (Tree a) (Tree a) | Leaf a | Empty deriving(Show, Read, Eq) + +-- Travel In Order +dfs :: Tree a -> [a] +dfs Empty = [] +dfs (Leaf a) = [a] +dfs (Node a l r) = dfs l ++ [a] ++ dfs r + +-- Travel Pre Order +dfsPreOrder :: Tree a -> [a] +dfsPreOrder Empty = [] +dfsPreOrder (Leaf a) = [a] +dfsPreOrder (Node a l r) = [a] ++ dfsPreOrder l ++ dfsPreOrder r + +-- Travel Post Order +dfsPostOrder :: Tree a -> [a] +dfsPostOrder Empty = [] +dfsPostOrder (Leaf a) = [a] +dfsPostOrder (Node a l r) = dfsPostOrder l ++ dfsPostOrder r ++ [a] \ No newline at end of file From 4a34ff8a93d3a1ccbe76017404f31ce6a8e5c87b Mon Sep 17 00:00:00 2001 From: Prateek-Thakare <47851059+Prateek-Thakare@users.noreply.github.com> Date: Mon, 28 Oct 2019 09:41:34 +0530 Subject: [PATCH 254/324] Adding Chefing Solution --- Codechef/CHEFING.cpp | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Codechef/CHEFING.cpp diff --git a/Codechef/CHEFING.cpp b/Codechef/CHEFING.cpp new file mode 100644 index 00000000..1f8645c6 --- /dev/null +++ b/Codechef/CHEFING.cpp @@ -0,0 +1,38 @@ +//link:https://www.codechef.com/FEB19B/problems/CHEFING/ +#include +using namespace std; +int main() +{ + int t,n; + cin>>t; + while(t) + { int cnt=0; + cin>>n; + int a[26]={0}; + bool f[26]; + memset(f,false,sizeof(f)); + for(int i=0;i>s; + int l=s.length(); + for(int j=0;j Date: Mon, 28 Oct 2019 18:37:52 +0530 Subject: [PATCH 255/324] Added Perl prog --- HelloWorld/HelloWorld.pl | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 HelloWorld/HelloWorld.pl diff --git a/HelloWorld/HelloWorld.pl b/HelloWorld/HelloWorld.pl new file mode 100644 index 00000000..07cb7698 --- /dev/null +++ b/HelloWorld/HelloWorld.pl @@ -0,0 +1,10 @@ +#!/usr/bin/perl +# usage perl HelloWorld.pl + +# Modules used +use strict; +use warnings; + +# Print function +print("Hello World!\n"); + From 65343e64762bff43da44ab1a7857f6114a0a17f5 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Mon, 28 Oct 2019 18:39:04 +0530 Subject: [PATCH 256/324] Delete .DS_Store --- Hackerrank/C/.DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Hackerrank/C/.DS_Store diff --git a/Hackerrank/C/.DS_Store b/Hackerrank/C/.DS_Store deleted file mode 100644 index 7e4cd73743f528315affabd08acff13ee5ba0023..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK!A=4(5PgG~V7L&CQExqZGSRD-6)?saj0t{#0;>{{B`61Od+}rZK0iR;w2hHn zxhgR;o9UZ&JJacFv)uxa=4@~XGyv47ij@r(KZw3pElDM|tP{n@c)<{3+{2+;>TM0H z$bhch7Fx(K9gc8-J|>u)kFtJml=bML+vS+L|KWueu!%Ez3^AZj3lF%( zh)?SGL%Jl!TOr0CI?QCiD0kG9)&=8C7&pZuttl><=M#FYPw}i#7qgO`Lc}_*n8l2J zJAQAfRrY!MNI- zC1ea31AoncejglFF^QN5^q&qE{t7^>ve^r5{W(-07cq&L2jm-y1Xp5km3YOF;Ldgz z`y~xkjI_eEoMf>Fezg%eeqnLg5DBh)dVY^d Date: Mon, 28 Oct 2019 18:39:50 +0530 Subject: [PATCH 257/324] Delete .DS_Store --- Hackerrank/.DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Hackerrank/.DS_Store diff --git a/Hackerrank/.DS_Store b/Hackerrank/.DS_Store deleted file mode 100644 index 2e703acf21aa15d300a445bb9e1011a7eb1cdd3c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK;c62>5S~rWx`~MSA+$daL=YMzCDj&0xF#uDK?t7c50&=L3+CW@Tarsd8zc9} zcd&f}AH^r|L41IAW_Og_RsV@d*n!<|cITVD%y-;w763$N5^Vr906=0Rbn4js#wbqh zidA@q@&v7+LiA{Ic~{WdEg7$uB<$U&Vvze&cpmrCAWC zgON^-qXAOhzK+vKO*?9mMq|B>Zvs-*WNp8(Hk-BE51MX!b9>%&XIopXrn}jGIG@+# z>fMdUdk2Rnr?ZdqPiIDXft!=ITZ}*9933p}*dL{dNa7Di zeFZ>ta9SJsbOE3om(gR)4PpdMm{dfQD)@>aOghfH%<~v?gC-pWUp@psS?~=-=%?fQ zuBL Date: Mon, 28 Oct 2019 18:40:04 +0530 Subject: [PATCH 258/324] Delete .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 69e7e802ab1dc5c8dcae9064230ef061daf1cfd3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHK-EPw`6h7_>b2GszgtT4e28oM;I(0B4gjBj#P>Da0!7c!8X_KzevSdn9Dkw$0 z;T?cC;8A!29)t&g&yJarv=eu1LOzoH9oy%#ldmUsO+>6UayE#nM8r`9mJL)3OpJ>% zXC>8h8OY=u5qXr*kd7#xi`E@l0jX-@ocRSZ=A#rz>Bbs zOL2koslZtU=P5m*9ePe(YS9aLU9=x8dP4TIz%Egnto#a6iO(4&R_Gzwc$PyvO@v~j z#vWK;iFePkj2tThE1<(XN521GIlXawtbV8Oy<^{tlY0FJD=n2TTwLbd;Kn86jWrC% zR$?ckxMfGLMC+NI413Do2}A$Hw|g%=cf41IN`Vzjsho^ z^H}Ks=M`SrtFBKbjmE8-+1R`@t(lXpt$NMeY}}qsD}3$R#=Y+T(YyDP57UodAO?)# z(2%yO@DF^2vrwS7RuuSQaDZ{a6)`SS*GD?+%9QYnNykJ&WJTok2pktbkxIUT=pqHO z@ym$sBDRC1v8a=e7RkVPCK)P7vkpF|Ha!NO@)6`1SnjM$$H+k+S^=%Vxm7^y z4U@x~0Jve-{MDRM=EFOA#Y5mQsN!m8mNROX=u0Ra{fyEX9;g zOkF;hTA8UE3X`j2ep7}MYo@4ct$ Date: Mon, 28 Oct 2019 22:05:31 +0530 Subject: [PATCH 259/324] 786A --- Codeforces/786A.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Codeforces/786A.py diff --git a/Codeforces/786A.py b/Codeforces/786A.py new file mode 100644 index 00000000..a824fcdb --- /dev/null +++ b/Codeforces/786A.py @@ -0,0 +1,24 @@ + class T: + h = ('Lose', 'Loop', 'Win') + def __init__(t): + t.s = list(map(int, input().split()))[1:] + t.p = [len(t.s)] * n + t.p[0] = 0 + def f(t, i): + for d in t.s: + j = (i - d) % n + if t.p[j] > 0: yield j + def g(t): + print(*[t.h[min(q, 1)] for q in t.p[1:]]) + n = int(input()) + r, m = T(), T() + q = [(r, m, 0), (m, r, 0)] + while q: + x, y, i = q.pop() + for j in y.f(i): + y.p[j] = -1 + for k in x.f(j): + x.p[k] -= 1 + if not x.p[k]: q.append((x, y, k)) + r.g() + m.g() \ No newline at end of file From 3e47dceb725013c0956fb44a0ae4f0cad67d50e8 Mon Sep 17 00:00:00 2001 From: spriha27 Date: Tue, 29 Oct 2019 00:03:13 +0530 Subject: [PATCH 260/324] Added Codechef solutions --- Codechef/CHEFAPAR.cpp | 24 ++++++++++++++++++++ Codechef/FLOW007.cpp | 19 ++++++++++++++++ Codechef/HOLES.cpp | 52 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 Codechef/CHEFAPAR.cpp create mode 100644 Codechef/FLOW007.cpp create mode 100644 Codechef/HOLES.cpp diff --git a/Codechef/CHEFAPAR.cpp b/Codechef/CHEFAPAR.cpp new file mode 100644 index 00000000..065ffae2 --- /dev/null +++ b/Codechef/CHEFAPAR.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +int main() { + int t,n,flag; + cin>>t; + for(int i=0;i>n; + int sum=0,a[n]; + flag = 0; + for(int j=0;j>a[j]; + if(a[j]==0){ + sum=sum+1000; + flag=1; + } + if(flag==1){ + sum=sum+100; + } + } + cout< +using namespace std; + +int main() { + int t,n; + cin>>t; + for(int i=0;i>n; + while(n>0){ + sum=sum*10; + rem=n%10; + sum=sum+rem; + n=n/10; + } + cout< + +using namespace std; + + + +int main() { + + int t,count; + + cin>>t; + +string s; + + for(int i=0;i>s; + + //cout< Date: Mon, 28 Oct 2019 18:24:30 -0400 Subject: [PATCH 261/324] Created mergeSort in Java --- Algorithms/Java/MergeSort.java | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Algorithms/Java/MergeSort.java diff --git a/Algorithms/Java/MergeSort.java b/Algorithms/Java/MergeSort.java new file mode 100644 index 00000000..5e13dbcd --- /dev/null +++ b/Algorithms/Java/MergeSort.java @@ -0,0 +1,51 @@ +void merge(int array_[], int left, int middle, int right) + { + int n1 = middle - left + 1; + int n2 = right - middle; + int lhs[] = new int [n1]; + int rhs[] = new int [n2]; + + for (int i=0; i Date: Mon, 28 Oct 2019 19:44:28 -0300 Subject: [PATCH 262/324] Problem 1097B Solution for problem 1097B in C++ language --- Codeforces/1097B.cpp | 50 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Codeforces/1097B.cpp diff --git a/Codeforces/1097B.cpp b/Codeforces/1097B.cpp new file mode 100644 index 00000000..7c7e292a --- /dev/null +++ b/Codeforces/1097B.cpp @@ -0,0 +1,50 @@ +// Codeforces 2019 +// Vinicius Rodrigues 15.10.2019 +// Petr and a Combination Lock : Problem 1097B + +#include +#include + +using namespace std; + +void input(vector *vec) +{ + int rots, num; + scanf("%d", &rots); + for(int i = 0; i < rots; i++) + { + scanf("%d", &num); + vec -> push_back(num); + } +} + +int sumWithBitmask(vector nums, int bitmask) +{ + int summation = 0; + for(int i = 0; i < nums.size(); i++) + { + if(bitmask bitand 1 << i) + summation += nums[i]; + else + summation -= nums[i]; + } + return summation; +} + +bool checkIfValid(vector nums) +{ + for(int i = 0; i < 1 << nums.size(); i++) + if(sumWithBitmask(nums, i) % 360 == 0) + return true; + return false; +} + +int main() +{ + vector nums(0); + input(&nums); + if(checkIfValid(nums)) + printf("YES\n"); + else + printf("NO\n"); +} From fa7a3e7de8b59b0f92dc98978a065608165e8f80 Mon Sep 17 00:00:00 2001 From: viniciusrplima <54158629+viniciusrplima@users.noreply.github.com> Date: Mon, 28 Oct 2019 19:45:16 -0300 Subject: [PATCH 263/324] Problem 476B Solution for Problem 476B in C++ language --- 476B.cpp | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 476B.cpp diff --git a/476B.cpp b/476B.cpp new file mode 100644 index 00000000..7c72394b --- /dev/null +++ b/476B.cpp @@ -0,0 +1,63 @@ +// Codeforces 2019 +// Vinicius Rodrigues 15.10.2019 +// Dreamoon and WiFi : Problem 476B + +#include +#include +#include +#include +#include + +using namespace std; + +double pfat(int n, int k) +{ + if(n == 0 or n == k) return 1; + + double factor = 1.0f; + for(int i = k+1; i <= n; i++) + factor *= i; + + return factor; +} + +double comb(int n, int r) +{ + if(n < r) return 0; + return pfat(n, max(r, n - r)) / pfat(min(r, n - r), 0); +} + +double calcScore(string str) +{ + return count(str.begin(), str.end(), '+') - count(str.begin(), str.end(), '-'); +} + +double calcSpace(string str) +{ + return count(str.begin(), str.end(), '?'); +} + +double calcPositives(float score, int spaces) +{ + return (score + spaces) / 2; +} + +int main() +{ + string send, reach; + cin >> send >> reach; + + double deltaScore = calcScore(send) - calcScore(reach); + double spaces = calcSpace(reach); + double positives = calcPositives(deltaScore, spaces); + double prob; + + if(spaces > 0 and abs(deltaScore) <= spaces and round(positives) == positives) + prob = comb(spaces, positives) * pow(0.5, positives) * pow(0.5, spaces - positives); + else + prob = !deltaScore ? 1.0f : 0.0f; + + + printf("%.12f\n", prob); + return 0; +} From e4da64570c3b67804db64a064c5ce8b6afabf0a8 Mon Sep 17 00:00:00 2001 From: viniciusrplima <54158629+viniciusrplima@users.noreply.github.com> Date: Mon, 28 Oct 2019 19:47:48 -0300 Subject: [PATCH 264/324] Delete 476B.cpp file Upload em local inapropriado --- 476B.cpp | 63 -------------------------------------------------------- 1 file changed, 63 deletions(-) delete mode 100644 476B.cpp diff --git a/476B.cpp b/476B.cpp deleted file mode 100644 index 7c72394b..00000000 --- a/476B.cpp +++ /dev/null @@ -1,63 +0,0 @@ -// Codeforces 2019 -// Vinicius Rodrigues 15.10.2019 -// Dreamoon and WiFi : Problem 476B - -#include -#include -#include -#include -#include - -using namespace std; - -double pfat(int n, int k) -{ - if(n == 0 or n == k) return 1; - - double factor = 1.0f; - for(int i = k+1; i <= n; i++) - factor *= i; - - return factor; -} - -double comb(int n, int r) -{ - if(n < r) return 0; - return pfat(n, max(r, n - r)) / pfat(min(r, n - r), 0); -} - -double calcScore(string str) -{ - return count(str.begin(), str.end(), '+') - count(str.begin(), str.end(), '-'); -} - -double calcSpace(string str) -{ - return count(str.begin(), str.end(), '?'); -} - -double calcPositives(float score, int spaces) -{ - return (score + spaces) / 2; -} - -int main() -{ - string send, reach; - cin >> send >> reach; - - double deltaScore = calcScore(send) - calcScore(reach); - double spaces = calcSpace(reach); - double positives = calcPositives(deltaScore, spaces); - double prob; - - if(spaces > 0 and abs(deltaScore) <= spaces and round(positives) == positives) - prob = comb(spaces, positives) * pow(0.5, positives) * pow(0.5, spaces - positives); - else - prob = !deltaScore ? 1.0f : 0.0f; - - - printf("%.12f\n", prob); - return 0; -} From 6b493a62646c836b1db0724e3c868a8a638bfb44 Mon Sep 17 00:00:00 2001 From: viniciusrplima <54158629+viniciusrplima@users.noreply.github.com> Date: Mon, 28 Oct 2019 19:48:38 -0300 Subject: [PATCH 265/324] Problem 476B Solution for problem 476B in C++ language --- Codeforces/476B.cpp | 63 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Codeforces/476B.cpp diff --git a/Codeforces/476B.cpp b/Codeforces/476B.cpp new file mode 100644 index 00000000..7c72394b --- /dev/null +++ b/Codeforces/476B.cpp @@ -0,0 +1,63 @@ +// Codeforces 2019 +// Vinicius Rodrigues 15.10.2019 +// Dreamoon and WiFi : Problem 476B + +#include +#include +#include +#include +#include + +using namespace std; + +double pfat(int n, int k) +{ + if(n == 0 or n == k) return 1; + + double factor = 1.0f; + for(int i = k+1; i <= n; i++) + factor *= i; + + return factor; +} + +double comb(int n, int r) +{ + if(n < r) return 0; + return pfat(n, max(r, n - r)) / pfat(min(r, n - r), 0); +} + +double calcScore(string str) +{ + return count(str.begin(), str.end(), '+') - count(str.begin(), str.end(), '-'); +} + +double calcSpace(string str) +{ + return count(str.begin(), str.end(), '?'); +} + +double calcPositives(float score, int spaces) +{ + return (score + spaces) / 2; +} + +int main() +{ + string send, reach; + cin >> send >> reach; + + double deltaScore = calcScore(send) - calcScore(reach); + double spaces = calcSpace(reach); + double positives = calcPositives(deltaScore, spaces); + double prob; + + if(spaces > 0 and abs(deltaScore) <= spaces and round(positives) == positives) + prob = comb(spaces, positives) * pow(0.5, positives) * pow(0.5, spaces - positives); + else + prob = !deltaScore ? 1.0f : 0.0f; + + + printf("%.12f\n", prob); + return 0; +} From 4fd7003a257f3137b5a6612adaedba0391cbdea2 Mon Sep 17 00:00:00 2001 From: David Date: Mon, 28 Oct 2019 21:34:30 -0400 Subject: [PATCH 266/324] BubbleSort in Haskell --- Algorithms/Haskell/BubbleSort.hs | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 Algorithms/Haskell/BubbleSort.hs diff --git a/Algorithms/Haskell/BubbleSort.hs b/Algorithms/Haskell/BubbleSort.hs new file mode 100644 index 00000000..35a2c6d8 --- /dev/null +++ b/Algorithms/Haskell/BubbleSort.hs @@ -0,0 +1,9 @@ +bubblesort' :: (Ord a) => [a] -> [a] +bubblesort' [] = [] +bubblesort' [x] = [x] +bubblesort' (x:xs) + | x <= head xs = x : bubblesort' xs + | x > head xs = head xs : bubblesort' (x: tail xs) + +bubblesort :: (Ord a) => [a] -> [a] +bubblesort xs = foldl (\acc _ -> bubblesort' acc) xs xs \ No newline at end of file From 9a44cc0a4d37e0244cd590bac130432210cde909 Mon Sep 17 00:00:00 2001 From: Abhishek Keshri Date: Tue, 29 Oct 2019 18:11:28 +0530 Subject: [PATCH 267/324] Create README.md --- Hackerrank/JavaScript/10-Days-Of-JS/README.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/README.md diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/README.md b/Hackerrank/JavaScript/10-Days-Of-JS/README.md new file mode 100644 index 00000000..e0a99f71 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/README.md @@ -0,0 +1,3 @@ +# 10 Days Of JavaScript + +Solutions to 10 Days Of JS problems @ HackerRank. From fe66945b3716235100390ed6a2298c86e8b7feaa Mon Sep 17 00:00:00 2001 From: Abhishek Keshri Date: Tue, 29 Oct 2019 18:12:35 +0530 Subject: [PATCH 268/324] Add files via upload --- .../10-Days-Of-JS/day0-data-types.js | 64 +++++++++++ .../10-Days-Of-JS/day0-hello-world.js | 45 ++++++++ .../day1-arithmetic-operators.js | 56 ++++++++++ .../JavaScript/10-Days-Of-JS/day1-function.js | 35 ++++++ .../10-Days-Of-JS/day1-let-const.js | 41 +++++++ .../JavaScript/10-Days-Of-JS/day2-if-else.js | 48 ++++++++ .../JavaScript/10-Days-Of-JS/day2-loops.js | 53 +++++++++ .../JavaScript/10-Days-Of-JS/day2-switch.js | 62 +++++++++++ .../JavaScript/10-Days-Of-JS/day3-arrays.js | 51 +++++++++ .../JavaScript/10-Days-Of-JS/day3-throw.js | 54 +++++++++ .../10-Days-Of-JS/day3-try-catch.js | 42 +++++++ .../JavaScript/10-Days-Of-JS/day4-class.js | 22 ++++ .../10-Days-Of-JS/day4-count-objects.js | 55 +++++++++ .../JavaScript/10-Days-Of-JS/day4-objects.js | 48 ++++++++ .../JavaScript/10-Days-Of-JS/day5-arrows.js | 41 +++++++ .../10-Days-Of-JS/day5-inheritance.js | 33 ++++++ .../10-Days-Of-JS/day5-template-literals.js | 54 +++++++++ .../JavaScript/10-Days-Of-JS/day6-bitwise.js | 39 +++++++ .../JavaScript/10-Days-Of-JS/day6-date.js | 43 +++++++ .../JavaScript/10-Days-Of-JS/day7-regex1.js | 40 +++++++ .../JavaScript/10-Days-Of-JS/day7-regex2.js | 41 +++++++ .../JavaScript/10-Days-Of-JS/day7-regex3.js | 44 ++++++++ .../10-Days-Of-JS/day8-button-container.html | 44 ++++++++ .../JavaScript/10-Days-Of-JS/day8-button.html | 25 +++++ .../10-Days-Of-JS/day9-binary-calculator.html | 105 ++++++++++++++++++ 25 files changed, 1185 insertions(+) create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day0-data-types.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html create mode 100644 Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day0-data-types.js b/Hackerrank/JavaScript/10-Days-Of-JS/day0-data-types.js new file mode 100644 index 00000000..b13a54ef --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day0-data-types.js @@ -0,0 +1,64 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* The variables 'firstInteger', 'firstDecimal', and 'firstString' are declared for you -- do not modify them. +* Print three lines: +* 1. The sum of 'firstInteger' and the Number representation of 'secondInteger'. +* 2. The sum of 'firstDecimal' and the Number representation of 'secondDecimal'. +* 3. The concatenation of 'firstString' and 'secondString' ('firstString' must be first). +* +* Parameter(s): +* secondInteger - The string representation of an integer. +* secondDecimal - The string representation of a floating-point number. +* secondString - A string consisting of one or more space-separated words. +**/ +function performOperation(secondInteger, secondDecimal, secondString) { + // Declare a variable named 'firstInteger' and initialize with integer value 4. + const firstInteger = 4; + + // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0. + const firstDecimal = 4.0; + + // Declare a variable named 'firstString' and initialize with the string "HackerRank". + const firstString = 'HackerRank '; + + // Write code that uses console.log to print the sum of the 'firstInteger' and 'secondInteger' (converted to a Number type) on a new line. + console.log(firstInteger + Number(secondInteger)); + + // Write code that uses console.log to print the sum of 'firstDecimal' and 'secondDecimal' (converted to a Number type) on a new line. + console.log(firstDecimal + Number(secondDecimal)); + + // Write code that uses console.log to print the concatenation of 'firstString' and 'secondString' on a new line. The variable 'firstString' must be printed first. + console.log(firstString + secondString); +} + + +function main() { + const secondInteger = readLine(); + const secondDecimal = readLine(); + const secondString = readLine(); + + performOperation(secondInteger, secondDecimal, secondString); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js b/Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js new file mode 100644 index 00000000..7826dc44 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day0-hello-world.js @@ -0,0 +1,45 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* A line of code that prints "Hello, World!" on a new line is provided in the editor. +* Write a second line of code that prints the contents of 'parameterVariable' on a new line. +* +* Parameter: +* parameterVariable - A string of text. +**/ +function greeting(parameterVariable) { + // This line prints 'Hello, World!' to the console: + console.log('Hello, World!'); + console.log(parameterVariable); + // Write a line of code that prints parameterVariable to stdout using console.log: + +} + + +function main() { + const parameterVariable = readLine(); + + greeting(parameterVariable); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js b/Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js new file mode 100644 index 00000000..083ce7bc --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day1-arithmetic-operators.js @@ -0,0 +1,56 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* Calculate the area of a rectangle. +* +* length: The length of the rectangle. +* width: The width of the rectangle. +* +* Return a number denoting the rectangle's area. +**/ +function getArea(length, width) { + let area; + // Write your code here + area = length * width; + + return area; +} + +/** +* Calculate the perimeter of a rectangle. +* +* length: The length of the rectangle. +* width: The width of the rectangle. +* +* Return a number denoting the perimeter of a rectangle. +**/ +function getPerimeter(length, width) { + let perimeter; + // Write your code here + perimeter = 2 * (length + width); + return perimeter; +} + + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js b/Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js new file mode 100644 index 00000000..19eef5b0 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day1-function.js @@ -0,0 +1,35 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} +/* + * Create the function factorial here + */ +function factorial(n) { + var result = 1; + while (n > 0) { + result *=n; + n--; + } + return result; +} + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js b/Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js new file mode 100644 index 00000000..230b4f88 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day1-let-const.js @@ -0,0 +1,41 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function main() { + // Write your code here. Read input using 'readLine()' and print output using 'console.log()'. + const PI = Math.PI; + let r = Number(readLine()); + // Print the area of the circle: + console.log((PI * (r * r))); + // Print the perimeter of the circle: + console.log(2 * (PI * r)); + try { + // Attempt to redefine the value of constant variable PI + PI = 0; + // Attempt to print the value of PI + console.log(PI); + } catch(error) { + console.error("You correctly declared 'PI' as a constant."); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js b/Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js new file mode 100644 index 00000000..59ce0fd8 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day2-if-else.js @@ -0,0 +1,48 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function getGrade(score) { + let grade; + // Write your code here + if (score > 25 && score <= 30) + grade = 'A'; + else if (score > 20 && score <= 25) + grade = 'B'; + if (score > 15 && score <= 20) + grade = 'C'; + else if (score > 10 && score <= 15) + grade = 'D'; + if (score > 5 && score <= 10) + grade = 'E'; + else if (score >= 0 && score <= 5) + grade = 'F'; + return grade; +} + + +function main() { + const score = +(readLine()); + + console.log(getGrade(score)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js b/Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js new file mode 100644 index 00000000..1a20dee3 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day2-loops.js @@ -0,0 +1,53 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the vowelsAndConsonants function. + * Print your output using 'console.log()'. + */ +function vowelsAndConsonants(s) { + var i = 0; + while (s[i]!=null) + { + if ((s[i] == 'a') || (s[i] == 'e') || (s[i] == 'i') || (s[i] == 'o') || (s[i] == 'u')) { + console.log(s[i]); + } + i++; + } + i = 0; + while (s[i] != null) { + if (!((s[i] == 'a') || (s[i] == 'e') || (s[i] == 'i') || (s[i] == 'o') || (s[i] == 'u'))) { + console.log(s[i]); + } + i++; + } + +} + + +function main() { + const s = readLine(); + + vowelsAndConsonants(s); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js b/Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js new file mode 100644 index 00000000..3097aa68 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day2-switch.js @@ -0,0 +1,62 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function getLetter(s) { + let letter; + // Write your code here + switch (s[0]){ + case 'a': + case 'e': + case 'i': + case 'o': + case 'u': + letter = 'A'; + break; + case 'b': + case 'c': + case 'd': + case 'f': + case 'g': + letter = 'B'; + break; + case 'h': + case 'j': + case 'k': + case 'l': + case 'm': + letter = 'C'; + break; + default: + letter = 'D'; + break; + } + return letter; +} + + +function main() { + const s = readLine(); + + console.log(getLetter(s)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js b/Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js new file mode 100644 index 00000000..c5b30604 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day3-arrays.js @@ -0,0 +1,51 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/** +* Return the second largest number in the array. +* @param {Number[]} nums - An array of numbers. +* @return {Number} The second largest number in the array. +**/ +function getSecondLargest(nums) { + // Complete the function + nums.sort(function (a, b) { return a - b });; + let res = 0; + let largest = nums.pop(); + + for (let i = nums.length; i != null; i--) { + if (nums[i] < largest) { + res = nums[i]; + break; + } + } + return res; +} + + +function main() { + const n = +(readLine()); + const nums = readLine().split(' ').map(Number); + + console.log(getSecondLargest(nums)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js b/Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js new file mode 100644 index 00000000..bcc8a1e3 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day3-throw.js @@ -0,0 +1,54 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the isPositive function. + * If 'a' is positive, return "YES". + * If 'a' is 0, throw an Error with the message "Zero Error" + * If 'a' is negative, throw an Error with the message "Negative Error" + */ +function isPositive(a) { + if (a > 0) { + return 'YES'; + } else if (a == 0) { + throw new Error('Zero Error'); + } else if (a < 0) { + throw new Error('Negative Error'); + } +} + + +function main() { + const n = +(readLine()); + + for (let i = 0; i < n; i++) { + const a = +(readLine()); + + try { + console.log(isPositive(a)); + } catch (e) { + console.log(e.message); + } + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js b/Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js new file mode 100644 index 00000000..63dc1c1a --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day3-try-catch.js @@ -0,0 +1,42 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function reverseString(s) { + try { + s = s.split("").reverse().join(""); + } + catch (e) { + console.log(e.message); + } + finally { + console.log(s); + } +} + + +function main() { + const s = eval(readLine()); + + reverseString(s); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js b/Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js new file mode 100644 index 00000000..f4df9b4a --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day4-class.js @@ -0,0 +1,22 @@ +/* + * Implement a Polygon class with the following properties: + * 1. A constructor that takes an array of integer side lengths. + * 2. A 'perimeter' method that returns the sum of the Polygon's side lengths. + */ +class Polygon{ + constructor(sides) { + this.sides = sides; + } + perimeter() { + return this.sides.reduce((total, side) => total + side); + } + +} + +const rectangle = new Polygon([10, 20, 10, 20]); +const square = new Polygon([10, 10, 10, 10]); +const pentagon = new Polygon([10, 20, 30, 40, 43]); + +console.log(rectangle.perimeter()); +console.log(square.perimeter()); +console.log(pentagon.perimeter()); diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js b/Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js new file mode 100644 index 00000000..8c744ad3 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day4-count-objects.js @@ -0,0 +1,55 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Return a count of the total number of objects 'o' satisfying o.x == o.y. + * + * Parameter(s): + * objects: an array of objects with integer properties 'x' and 'y' + */ +function getCount(objects) { + let count = 0 + + for (let item of objects) { + if (item.x == item.y) { + count++ + } + + } + return count +} + + +function main() { + const n = +(readLine()); + let objects = []; + + for (let i = 0; i < n; i++) { + const [a, b] = readLine().split(' '); + + objects.push({x: +(a), y: +(b)}); + } + + console.log(getCount(objects)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js b/Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js new file mode 100644 index 00000000..f8e8093f --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day4-objects.js @@ -0,0 +1,48 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Complete the Rectangle function + */ +function Rectangle(a, b) { + let rec = { + length: a, + width: b, + perimeter: 2 * (a + b), + area : a * b + }; + return rec; + } + +function main() { + const a = +(readLine()); + const b = +(readLine()); + + const rec = new Rectangle(a, b); + + console.log(rec.length); + console.log(rec.width); + console.log(rec.perimeter); + console.log(rec.area); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js b/Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js new file mode 100644 index 00000000..299575dd --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day5-arrows.js @@ -0,0 +1,41 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Modify and return the array so that all even elements are doubled and all odd elements are tripled. + * + * Parameter(s): + * nums: An array of numbers. + */ +function modifyArray(nums) { + return nums.map(elem => elem % 2 == 0 ? elem * 2 : elem * 3); +} + + +function main() { + const n = +(readLine()); + const a = readLine().split(' ').map(Number); + + console.log(modifyArray(a).toString().split(',').join(' ')); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js b/Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js new file mode 100644 index 00000000..20255bfa --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day5-inheritance.js @@ -0,0 +1,33 @@ +class Rectangle { + constructor(w, h) { + this.w = w; + this.h = h; + } +} + +/* + * Write code that adds an 'area' method to the Rectangle class' prototype + */ +Rectangle.prototype.area = function () { + return (this.w * this.h); +} +/* + * Create a Square class that inherits from Rectangle and implement its class constructor + */ +class Square extends Rectangle{ + constructor(s) { + super(s,s); + } +} + + +if (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify([ 'constructor' ])) { + const rec = new Rectangle(3, 4); + const sqr = new Square(3); + + console.log(rec.area()); + console.log(sqr.area()); +} else { + console.log(-1); + console.log(-1); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js b/Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js new file mode 100644 index 00000000..448ccebe --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day5-template-literals.js @@ -0,0 +1,54 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +/* + * Determine the original side lengths and return an array: + * - The first element is the length of the shorter side + * - The second element is the length of the longer side + * + * Parameter(s): + * literals: The tagged template literal's array of strings. + * expressions: The tagged template literal's array of expression values (i.e., [area, perimeter]). + */ +function sides(literals, ...expressions) { + let arr = []; + let area = Number(expressions[0]); + let perimeter = Number(expressions[1]); + arr[0] = Number((perimeter + Math.sqrt((perimeter * perimeter) - (16 * area)))/4) + arr[1] = Number((perimeter - Math.sqrt((perimeter * perimeter) - (16 * area)))/4) + return arr.sort(); +} + + +function main() { + let s1 = +(readLine()); + let s2 = +(readLine()); + + [s1, s2] = [s1, s2].sort(); + + const [x, y] = sides`The area is: ${s1 * s2}.\nThe perimeter is: ${2 * (s1 + s2)}.`; + + console.log((s1 === x) ? s1 : -1); + console.log((s2 === y) ? s2 : -1); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js b/Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js new file mode 100644 index 00000000..f6e945ce --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day6-bitwise.js @@ -0,0 +1,39 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} +function getMaxLessThanK(n, k) { + // (╯°□°)╯︵ ┻━┻ + return ((k | (k - 1)) > n) ? (k - 2) : (k - 1); +} + + + +function main() { + const q = +(readLine()); + + for (let i = 0; i < q; i++) { + const [n, k] = readLine().split(' ').map(Number); + + console.log(getMaxLessThanK(n, k)); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js b/Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js new file mode 100644 index 00000000..50b9a4b2 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day6-date.js @@ -0,0 +1,43 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +// The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" +function getDayName(dateString) { + let date = new Date(dateString); + let dayNum = date.getDay(); + + let dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] + return dayNames[dayNum]; +} + + +function main() { + const d = +(readLine()); + + for (let i = 0; i < d; i++) { + const date = readLine(); + + console.log(getDayName(date)); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js new file mode 100644 index 00000000..d9e34332 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex1.js @@ -0,0 +1,40 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function regexVar() { + /* + * Declare a RegExp object variable named 're' + * It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u}) + */ + const re = new RegExp("^([aeiou]).*\\1$") + return re; +} + + +function main() { + const re = regexVar(); + const s = readLine(); + + console.log(re.test(s)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js new file mode 100644 index 00000000..98c8d31c --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex2.js @@ -0,0 +1,41 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function regexVar() { + /* + * Declare a RegExp object variable named 're' + * It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.', + * followed by one or more letters. + */ + const re = /^(Mr|Mrs|Ms|Dr|Er)\.[A-Za-z]*$/ + return re; +} + + +function main() { + const re = regexVar(); + const s = readLine(); + + console.log(!!s.match(re)); +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js new file mode 100644 index 00000000..00fdae03 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day7-regex3.js @@ -0,0 +1,44 @@ +'use strict'; + +process.stdin.resume(); +process.stdin.setEncoding('utf-8'); + +let inputString = ''; +let currentLine = 0; + +process.stdin.on('data', inputStdin => { + inputString += inputStdin; +}); + +process.stdin.on('end', _ => { + inputString = inputString.trim().split('\n').map(string => { + return string.trim(); + }); + + main(); +}); + +function readLine() { + return inputString[currentLine++]; +} + +function regexVar() { + /* + * Declare a RegExp object variable named 're' + * It must match ALL occurrences of numbers in a string. + */ + const re = /\d+/g + return re; +} + + +function main() { + const re = regexVar(); + const s = readLine(); + + const r = s.match(re); + + for (const e of r) { + console.log(e); + } +} diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html new file mode 100644 index 00000000..779a8039 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button-container.html @@ -0,0 +1,44 @@ + + + + + Buttons Grid + + + +
+ + + + + + + + + +
+ + + + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html new file mode 100644 index 00000000..be377481 --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day8-button.html @@ -0,0 +1,25 @@ + + + + + Button + + + + + + + + diff --git a/Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html b/Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html new file mode 100644 index 00000000..e5d236ad --- /dev/null +++ b/Hackerrank/JavaScript/10-Days-Of-JS/day9-binary-calculator.html @@ -0,0 +1,105 @@ + + + + + + Binary Calculator + + + + +
+
+
+ + + + + + + + +
+
+ + + + From f296604ac3420e03d3e1c0e7c703d3f79463b748 Mon Sep 17 00:00:00 2001 From: Abhishek Keshri Date: Tue, 29 Oct 2019 18:19:53 +0530 Subject: [PATCH 269/324] Add LeetCode Solutions. --- LeetCode/1137-nth-tribonacci-number.c | 24 +++++++++++++++++++++ LeetCode/5079-intersection-of-arrays.py | 7 +++++++ LeetCode/5080-two-sum-bsts.py | 28 +++++++++++++++++++++++++ LeetCode/5205-uniq-no-occurence.py | 21 +++++++++++++++++++ 4 files changed, 80 insertions(+) create mode 100644 LeetCode/1137-nth-tribonacci-number.c create mode 100644 LeetCode/5079-intersection-of-arrays.py create mode 100644 LeetCode/5080-two-sum-bsts.py create mode 100644 LeetCode/5205-uniq-no-occurence.py diff --git a/LeetCode/1137-nth-tribonacci-number.c b/LeetCode/1137-nth-tribonacci-number.c new file mode 100644 index 00000000..7c72d4ad --- /dev/null +++ b/LeetCode/1137-nth-tribonacci-number.c @@ -0,0 +1,24 @@ +//#1137 + int tribonacci(int n){ + + int first = 0; + int second = 1; + int third = 1; + int result = 0; + + if (n == 0) result = first; + if (n == 1) result = second; + if (n == 2) result = third; + + while(n > 2) + { + result = first + second + third; + first = second; + second = third; + third = result; + n--; + } + + return result; + +} diff --git a/LeetCode/5079-intersection-of-arrays.py b/LeetCode/5079-intersection-of-arrays.py new file mode 100644 index 00000000..8d0d0178 --- /dev/null +++ b/LeetCode/5079-intersection-of-arrays.py @@ -0,0 +1,7 @@ +class Solution: + def arraysIntersection(self, arr1: List[int], arr2: List[int], arr3: List[int]) -> List[int]: + outList = [] + for item in arr1: + if item in arr2 and item in arr3: + outList.append(item) + return(outList) diff --git a/LeetCode/5080-two-sum-bsts.py b/LeetCode/5080-two-sum-bsts.py new file mode 100644 index 00000000..0d0ae533 --- /dev/null +++ b/LeetCode/5080-two-sum-bsts.py @@ -0,0 +1,28 @@ +class Solution: + def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool: + flag = 0 + listTemp = [] + def inOrderList(root) -> List[int]: + if not root: + return + inOrderList(root.left) + listTemp.append(root.val) + inOrderList(root.right) + return(listTemp) + + listTree1 = inOrderList(root1) + listTemp = [] + listTree2 = inOrderList(root2) + + for item1 in listTree1: + for item2 in listTree2: + result = item1 + item2 + if result == target: + flag = 1 + break + + if flag == 0: + return False + else: + return True + diff --git a/LeetCode/5205-uniq-no-occurence.py b/LeetCode/5205-uniq-no-occurence.py new file mode 100644 index 00000000..13dc8925 --- /dev/null +++ b/LeetCode/5205-uniq-no-occurence.py @@ -0,0 +1,21 @@ +class Solution(object): + def uniqueOccurrences(self, arr): + """ + :type arr: List[int] + :rtype: bool + """ + + uniqList = list(set(arr)) + countList = [] + + for x in uniqList: + count = arr.count(x) + if count not in countList: + countList.append(count) + + uniqCount = list(set(countList)) + + if (len(uniqList) == len(uniqCount)): + return True + else: + return False From 12fdd9be206d7e8702a94f837ab2795ff74c232e Mon Sep 17 00:00:00 2001 From: Permadi Wibisono Date: Tue, 29 Oct 2019 23:23:45 +0700 Subject: [PATCH 270/324] Add stack data structure algo in go --- DS/Go/stack.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 DS/Go/stack.go diff --git a/DS/Go/stack.go b/DS/Go/stack.go new file mode 100644 index 00000000..1a3b6fc0 --- /dev/null +++ b/DS/Go/stack.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" +) + +func main() { + size := 20 + stack := make([]int, 0) + printPeek(stack) + fmt.Println("Push operations:") + for i := 0; i < size; i++ { + stack = push(stack, i+1) + printPeek(stack) + } + fmt.Println("Pop operations:") + for i := 0; i < size; i++ { + stack = pop(stack) + } +} + +func push(stack []int, value int) []int { + newStack := make([]int, len(stack)+1) + for i := 0; i < len(stack); i++ { + newStack[i] = stack[i] + } + newStack[len(stack)] = value + fmt.Println("Pushed: ", value) + fmt.Println("After pushed: ", newStack) + return newStack +} + +func pop(stack []int) []int { + printPeek(stack) + if len(stack) > 0 { + p := peek(stack) + fmt.Println("Popped: ", p) + newStack := stack[:len(stack)-1] + fmt.Println("After popped: ", newStack) + return newStack + } + return stack +} + +func printPeek(stack []int) { + if len(stack) == 0 { + fmt.Println("Stack is empty now.") + } else { + fmt.Println("Peek:", peek(stack)) + } +} + +func peek(stack []int) int { + return stack[len(stack)-1] +} From 79a0973866b32560ff6b61da8561bbb79a94ef1e Mon Sep 17 00:00:00 2001 From: Permadi Wibisono Date: Tue, 29 Oct 2019 23:31:50 +0700 Subject: [PATCH 271/324] Add queue data structure algo in go --- DS/Go/queue.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 DS/Go/queue.go diff --git a/DS/Go/queue.go b/DS/Go/queue.go new file mode 100644 index 00000000..5e2281b4 --- /dev/null +++ b/DS/Go/queue.go @@ -0,0 +1,55 @@ +package main + +import ( + "fmt" +) + +func main() { + size := 20 + queue := make([]int, 0) + printPeek(queue) + fmt.Println("Push operations:") + for i := 0; i < size; i++ { + queue = enQueue(queue, i+1) + printPeek(queue) + } + fmt.Println("Pop operations:") + for i := 0; i < size; i++ { + queue = deQueue(queue) + } +} + +func enQueue(queue []int, value int) []int { + newQueue := make([]int, len(queue)+1) + for i := 0; i < len(queue); i++ { + newQueue[i] = queue[i] + } + newQueue[len(queue)] = value + fmt.Println("Enqueue: ", value) + fmt.Println("After enqueue: ", newQueue) + return newQueue +} + +func deQueue(queue []int) []int { + printPeek(queue) + if len(queue) > 0 { + p := peek(queue) + fmt.Println("Dequeue: ", p) + newQueue := queue[1:len(queue)] + fmt.Println("After dequeue: ", newQueue) + return newQueue + } + return queue +} + +func printPeek(queue []int) { + if len(queue) == 0 { + fmt.Println("Queue is empty now.") + } else { + fmt.Println("Peek:", peek(queue)) + } +} + +func peek(queue []int) int { + return queue[0] +} From 5b1258be6716edd2d22e2af1a37a8d77d7a2a560 Mon Sep 17 00:00:00 2001 From: nairitya03 Date: Tue, 29 Oct 2019 22:53:29 +0530 Subject: [PATCH 272/324] Adding Simple Array Sum.py --- Algorithms/C++/BozoSort.cpp | 84 +-- Algorithms/C++/cNode.cpp | 74 +- Algorithms/C++/cNode.h | 34 +- Algorithms/C++/cQue.cpp | 184 ++--- Algorithms/C++/cQue.h | 36 +- Algorithms/JavaScript/MergeSort.js | 18 - Algorithms/JavaScript/leastCommonMultiple.js | 32 +- Algorithms/PHP/fibonacci.php | 24 +- Algorithms/PHP/kadanealgo.php | 42 +- Algorithms/PHP/primeNumbers.php | 30 +- Algorithms/Python/mergesort.py | 70 +- Codechef/DIFNEIGH.cpp | 264 +++---- Codechef/EARTSEQ.cpp | 98 +-- Codechef/EVENEDGES.cpp | 0 Codechef/MARM.cpp | 0 Codechef/MAXLIS(CHALLENGE).cpp | 0 Codechef/MSNG.py | 0 Codechef/MSV.cpp | 0 Codechef/SAKTAN.cpp | 0 Codechef/SALARY.cpp | 94 +-- Codechef/XYPIZQ.cpp | 100 +-- Codeforces/1237A.cpp | 112 +-- DS/C++/QueueWithDoublyLL.cpp | 214 +++--- DS/C++/Stack Using Array.txt | 124 ++-- DS/C++/queueCpp.cpp | 154 ++-- DS/C/avl_tree.c | 0 DS/Linked_List/linked_list.s | 688 +++++++++--------- Hackerearth/Acronym.cpp | 88 +-- Hackerearth/Arania Exumai Blast.cpp | 74 +- Hackerearth/Battle of Words.cpp | 122 ++-- Hackerearth/Max Profit.cpp | 70 +- Hackerearth/Old and Cold Numbers.cpp | 66 +- Hackerearth/Palindromic Grid.cpp | 180 ++--- Hackerrank/C++/BirthdayCakeCandles.cpp | 154 ++-- Hackerrank/C++/CompareTheTriplets.cpp | 19 - Hackerrank/C++/DiagonalDifference.cpp | 212 +++--- Hackerrank/C++/inputOutput.cpp | 30 +- Hackerrank/C++/insertNodeSpecificPosition.cpp | 182 ++--- Hackerrank/C++/insertNodeTailLinkedList.cpp | 138 ++-- Hackerrank/C++/mapsSTL.cpp | 76 +- Hackerrank/C++/printLinkedList.cpp | 136 ++-- Hackerrank/C++/sayHelloWorld.cpp | 18 +- Hackerrank/C++/solveMeFirst.cpp | 42 +- Hackerrank/C/Counting Sort 2.cpp | 294 ++++---- Hackerrank/C/Grid Challenge.cpp | 250 +++---- Hackerrank/C/Priyanka And Toys.cpp | 192 ++--- Hackerrank/Python/Python | 0 Hackerrank/Python/Python: Division.py | 8 - Hackerrank/Python/Simple Array Sum.py | 12 + Hackerrank/Python/Time_Conversion.py | 68 +- Hackerrank/Python/What's Your Name?.py | 9 - Hackerrank/compareTheTriplets.cpp | 216 +++--- HelloWorld/HanoiTower.c | 42 +- HelloWorld/HelloWorld.html | 13 - HelloWorld/helloworld.php | 4 +- LeetCode/First_and_last_sorted_array.java | 68 +- 56 files changed, 2602 insertions(+), 2657 deletions(-) delete mode 100644 Algorithms/JavaScript/MergeSort.js mode change 100755 => 100644 Algorithms/Python/mergesort.py mode change 100755 => 100644 Codechef/EVENEDGES.cpp mode change 100755 => 100644 Codechef/MARM.cpp mode change 100755 => 100644 Codechef/MAXLIS(CHALLENGE).cpp mode change 100755 => 100644 Codechef/MSNG.py mode change 100755 => 100644 Codechef/MSV.cpp mode change 100755 => 100644 Codechef/SAKTAN.cpp mode change 100755 => 100644 DS/C/avl_tree.c mode change 100755 => 100644 DS/Linked_List/linked_list.s delete mode 100644 Hackerrank/C++/CompareTheTriplets.cpp create mode 100644 Hackerrank/Python/Python delete mode 100644 Hackerrank/Python/Python: Division.py create mode 100644 Hackerrank/Python/Simple Array Sum.py delete mode 100644 Hackerrank/Python/What's Your Name?.py delete mode 100644 HelloWorld/HelloWorld.html diff --git a/Algorithms/C++/BozoSort.cpp b/Algorithms/C++/BozoSort.cpp index 1d385941..f5ce480e 100644 --- a/Algorithms/C++/BozoSort.cpp +++ b/Algorithms/C++/BozoSort.cpp @@ -1,43 +1,43 @@ -#include -#include -using namespace std; - -bool ifsorted(int* tab, int size) -{ - bool sorted = false; - for (int i = 1; i < size; i++) - { - if (tab[i - 1] <= tab[i]) sorted = true; - else return false; - } - return sorted; -} - -int main() // bozo sort -{ - srand(time(NULL)); - bool sorted = false; - int size = 0; - //long long int counter = 0; - cin >> size; - - int* tab = new int[size]; - - for (int i = 0; i < size; i++) - cin >> tab[i]; - - cout << endl; - while (!sorted) - { - int x = rand() % size; - int y = rand() % size; - int temp = tab[x]; - tab[x] = tab[y]; - tab[y] = temp; - sorted = ifsorted(tab, size); - //counter++; - } - //for (int i = 0; i < size; i++) - // cout << tab[i] << endl; - //cout << endl << endl << counter; +#include +#include +using namespace std; + +bool ifsorted(int* tab, int size) +{ + bool sorted = false; + for (int i = 1; i < size; i++) + { + if (tab[i - 1] <= tab[i]) sorted = true; + else return false; + } + return sorted; +} + +int main() // bozo sort +{ + srand(time(NULL)); + bool sorted = false; + int size = 0; + //long long int counter = 0; + cin >> size; + + int* tab = new int[size]; + + for (int i = 0; i < size; i++) + cin >> tab[i]; + + cout << endl; + while (!sorted) + { + int x = rand() % size; + int y = rand() % size; + int temp = tab[x]; + tab[x] = tab[y]; + tab[y] = temp; + sorted = ifsorted(tab, size); + //counter++; + } + //for (int i = 0; i < size; i++) + // cout << tab[i] << endl; + //cout << endl << endl << counter; } \ No newline at end of file diff --git a/Algorithms/C++/cNode.cpp b/Algorithms/C++/cNode.cpp index 42cf283b..d5ccb03e 100644 --- a/Algorithms/C++/cNode.cpp +++ b/Algorithms/C++/cNode.cpp @@ -1,37 +1,37 @@ -#include -#include "cNode.h" - -using namespace std; - -cNode::cNode() :data(0),priority(0) -{ -} - -cNode::cNode(int d):data(d), priority(0){ -} - -cNode::cNode(int d, int p):data(d), priority(p) -{} - -int cNode::getData(){ - return data; - } - -cNode* cNode::setData(int data){ - this->data=data; - } - -void cNode::print()const{ - cout<priority=Prior; -} - -cNode::~cNode() -{ -} +#include +#include "cNode.h" + +using namespace std; + +cNode::cNode() :data(0),priority(0) +{ +} + +cNode::cNode(int d):data(d), priority(0){ +} + +cNode::cNode(int d, int p):data(d), priority(p) +{} + +int cNode::getData(){ + return data; + } + +cNode* cNode::setData(int data){ + this->data=data; + } + +void cNode::print()const{ + cout<priority=Prior; +} + +cNode::~cNode() +{ +} diff --git a/Algorithms/C++/cNode.h b/Algorithms/C++/cNode.h index c6841970..454e83c7 100644 --- a/Algorithms/C++/cNode.h +++ b/Algorithms/C++/cNode.h @@ -1,17 +1,17 @@ -class cNode -{ - int data; - int priority; -public: - cNode *next; - cNode(); - cNode(int d); - cNode(int d, int p); - int getData(); - cNode* setData(int data); - void print()const; - int getPriority() const; - void setPriority(int prior); - ~cNode(); -}; - +class cNode +{ + int data; + int priority; +public: + cNode *next; + cNode(); + cNode(int d); + cNode(int d, int p); + int getData(); + cNode* setData(int data); + void print()const; + int getPriority() const; + void setPriority(int prior); + ~cNode(); +}; + diff --git a/Algorithms/C++/cQue.cpp b/Algorithms/C++/cQue.cpp index ee22428e..a49487b0 100644 --- a/Algorithms/C++/cQue.cpp +++ b/Algorithms/C++/cQue.cpp @@ -1,92 +1,92 @@ -#include -#include "cQue.h" - -using namespace std; - -cQue::cQue():tail(NULL) -{ -} - -cQue::cQue(cNode* &ptr):cStack(ptr),tail(top){ - } - -bool cQue::isNotEmpty()const{ - return cStack::isNotEmpty(); - } - -bool cQue::isEmpty()const{ - return cStack::isEmpty(); - } - -cNode* cQue::remove(){ - if(!top->next) - tail=NULL; - return cStack::pop(); - } - -cQue& cQue::add(cNode* &ptr){ - if(tail){ - tail->next=ptr; - tail=tail->next; - } - else - { - tail=ptr; - top=ptr; - } - tail->next=NULL; - ptr=NULL; - return *this; - } - -void cQue::print()const{ // - cStack::print(); - } - -cQue::cQue(const cQue &src){ /// - this->top=src.top; - this->tail=src.tail; - if(src.top){ - cNode *sptr,*dptr; - dptr=top=new cNode(*src.top); - sptr=top->next; - while(sptr){ - dptr->next=new cNode(*sptr); - dptr=dptr->next; - sptr=sptr->next; - } - tail=dptr; - } - } - -cQue& cQue::operator=(const cQue& obj){ - if(this==&obj) - return *this; - if(true){ - cQue temp; - temp.top=top; - temp.tail=tail; - } - if(true){ - cQue temp=obj; - top=temp.top; - tail=temp.tail; - temp.top=NULL; - temp.tail=NULL; - } - return *this; - } - -cQue::~cQue() -{ - cNode *ptr = top; - - tail = NULL; - - while (ptr) - { - ptr = ptr -> next; - delete top; - top = ptr; - } -} +#include +#include "cQue.h" + +using namespace std; + +cQue::cQue():tail(NULL) +{ +} + +cQue::cQue(cNode* &ptr):cStack(ptr),tail(top){ + } + +bool cQue::isNotEmpty()const{ + return cStack::isNotEmpty(); + } + +bool cQue::isEmpty()const{ + return cStack::isEmpty(); + } + +cNode* cQue::remove(){ + if(!top->next) + tail=NULL; + return cStack::pop(); + } + +cQue& cQue::add(cNode* &ptr){ + if(tail){ + tail->next=ptr; + tail=tail->next; + } + else + { + tail=ptr; + top=ptr; + } + tail->next=NULL; + ptr=NULL; + return *this; + } + +void cQue::print()const{ // + cStack::print(); + } + +cQue::cQue(const cQue &src){ /// + this->top=src.top; + this->tail=src.tail; + if(src.top){ + cNode *sptr,*dptr; + dptr=top=new cNode(*src.top); + sptr=top->next; + while(sptr){ + dptr->next=new cNode(*sptr); + dptr=dptr->next; + sptr=sptr->next; + } + tail=dptr; + } + } + +cQue& cQue::operator=(const cQue& obj){ + if(this==&obj) + return *this; + if(true){ + cQue temp; + temp.top=top; + temp.tail=tail; + } + if(true){ + cQue temp=obj; + top=temp.top; + tail=temp.tail; + temp.top=NULL; + temp.tail=NULL; + } + return *this; + } + +cQue::~cQue() +{ + cNode *ptr = top; + + tail = NULL; + + while (ptr) + { + ptr = ptr -> next; + delete top; + top = ptr; + } +} diff --git a/Algorithms/C++/cQue.h b/Algorithms/C++/cQue.h index 5b536ca9..91639c1f 100644 --- a/Algorithms/C++/cQue.h +++ b/Algorithms/C++/cQue.h @@ -1,18 +1,18 @@ -#pragma once -#include"cStack.h" -class cQue:protected cStack{ -protected: - cNode *tail; -public: - cQue(); - cQue(cNode* &ptr); - bool isNotEmpty()const; - bool isEmpty()const; - cNode* remove(); - cQue& add(cNode* &ptr); - void print()const; - cQue(const cQue &src); - cQue& operator=(const cQue& obj); - ~cQue(); -}; - +#pragma once +#include"cStack.h" +class cQue:protected cStack{ +protected: + cNode *tail; +public: + cQue(); + cQue(cNode* &ptr); + bool isNotEmpty()const; + bool isEmpty()const; + cNode* remove(); + cQue& add(cNode* &ptr); + void print()const; + cQue(const cQue &src); + cQue& operator=(const cQue& obj); + ~cQue(); +}; + diff --git a/Algorithms/JavaScript/MergeSort.js b/Algorithms/JavaScript/MergeSort.js deleted file mode 100644 index f2feaa21..00000000 --- a/Algorithms/JavaScript/MergeSort.js +++ /dev/null @@ -1,18 +0,0 @@ -function mergeSort (arr) { - if (arr.length < 2) { - return arr; - } - - var mid = Math.floor(arr.length / 2); - var subLeft = mergeSort(arr.slice(0, mid)); - var subRight = mergeSort(arr.slice(mid)); - - return merge(subLeft, subRight); -} - -function merge (node1, node2) { - var result = []; - while (node1.length > 0 && node2.length > 0) - result.push(node1[0] < node2[0] ? node1.shift() : node2.shift()); - return result.concat(node1.length ? node1 : node2); -} \ No newline at end of file diff --git a/Algorithms/JavaScript/leastCommonMultiple.js b/Algorithms/JavaScript/leastCommonMultiple.js index 27386e5f..9c4f0dea 100644 --- a/Algorithms/JavaScript/leastCommonMultiple.js +++ b/Algorithms/JavaScript/leastCommonMultiple.js @@ -1,17 +1,17 @@ -const leastCommonMultiple = (a,b) => { - let x = a; - let y = b - while(x !== y) { - if(x>y){ - x = x - y; - } - else { - y = y - x; - } - } - return (a * b) / x; -} - -//examples -// leastCommonMultiple(2,3); +const leastCommonMultiple = (a,b) => { + let x = a; + let y = b + while(x !== y) { + if(x>y){ + x = x - y; + } + else { + y = y - x; + } + } + return (a * b) / x; +} + +//examples +// leastCommonMultiple(2,3); // leastCommonMultiple(192,348); \ No newline at end of file diff --git a/Algorithms/PHP/fibonacci.php b/Algorithms/PHP/fibonacci.php index 05d7b247..70fff1fd 100644 --- a/Algorithms/PHP/fibonacci.php +++ b/Algorithms/PHP/fibonacci.php @@ -1,12 +1,12 @@ -"; -} -?> +"; +} +?> diff --git a/Algorithms/PHP/kadanealgo.php b/Algorithms/PHP/kadanealgo.php index 1c7f1f35..fc5d3ade 100644 --- a/Algorithms/PHP/kadanealgo.php +++ b/Algorithms/PHP/kadanealgo.php @@ -1,22 +1,22 @@ - \ No newline at end of file diff --git a/Algorithms/PHP/primeNumbers.php b/Algorithms/PHP/primeNumbers.php index 9f716017..2e2b6f5e 100644 --- a/Algorithms/PHP/primeNumbers.php +++ b/Algorithms/PHP/primeNumbers.php @@ -1,15 +1,15 @@ -1;$x--) - { - if($i%$x==0) - { - $o=false; - break; - } - } - if($o) echo $i."
"; -} -?> +1;$x--) + { + if($i%$x==0) + { + $o=false; + break; + } + } + if($o) echo $i."
"; +} +?> diff --git a/Algorithms/Python/mergesort.py b/Algorithms/Python/mergesort.py old mode 100755 new mode 100644 index 88cdd7d8..75af1fd7 --- a/Algorithms/Python/mergesort.py +++ b/Algorithms/Python/mergesort.py @@ -1,36 +1,36 @@ -def merge(left, right): - li, ri = 0, 0 - retval = [] - while li < len(left) and ri < len(right): - if left[li] < right[ri]: - retval.append(left[li]) - li += 1 - else: - retval.append(right[ri]) - ri += 1 - - retval += left[li:] - retval += right[ri:] - return retval - - -def merge_sort(array): - # base case - if len(array) <= 1: - return array - - # divide array in half and do recursion - half = len(array) // 2 - left = merge_sort(array[:half]) - right = merge_sort(array[half:]) - - return merge(left, right) - - -def sort(): - list = [5, 7, 6, 2, 1, 7, 3] - sorted_list = merge_sort(list) - print 'Array after sorting: ', sorted_list - -if __name__ == '__main__': +def merge(left, right): + li, ri = 0, 0 + retval = [] + while li < len(left) and ri < len(right): + if left[li] < right[ri]: + retval.append(left[li]) + li += 1 + else: + retval.append(right[ri]) + ri += 1 + + retval += left[li:] + retval += right[ri:] + return retval + + +def merge_sort(array): + # base case + if len(array) <= 1: + return array + + # divide array in half and do recursion + half = len(array) // 2 + left = merge_sort(array[:half]) + right = merge_sort(array[half:]) + + return merge(left, right) + + +def sort(): + list = [5, 7, 6, 2, 1, 7, 3] + sorted_list = merge_sort(list) + print 'Array after sorting: ', sorted_list + +if __name__ == '__main__': sort() \ No newline at end of file diff --git a/Codechef/DIFNEIGH.cpp b/Codechef/DIFNEIGH.cpp index 43c3b12f..376a60b4 100644 --- a/Codechef/DIFNEIGH.cpp +++ b/Codechef/DIFNEIGH.cpp @@ -1,133 +1,133 @@ -#include -using namespace std; - -int main(){ - int t; - int a[50][50]; - int i,j,k; - for(k=0;k<50;k++){ - if(k%2==0){ - for(i=k;i<50;i++){ - if((i-k)%4==0||(i-k)%4==1) - a[k][i]=1; - else - a[k][i]=2; - } - for(i=k+1;i<50;i++){ - if((i-k)%4==1||(i-k)%4==2) - a[i][k]=2; - else - a[i][k]=1; - } - } - else{ - for(i=k;i<50;i++){ - if((i-k)%4==0||(i-k)%4==1) - a[k][i]=3; - else - a[k][i]=4; - } - for(i=k+1;i<50;i++){ - if((i-k)%4==1||(i-k)%4==2) - a[i][k]=4; - else - a[i][k]=3; - } - - } - } - cin>>t; - while(t--){ - int n,m,mod; - cin>>n>>m; - // int a[n][m]; - //int i,j; - if(n>=3&&m>=3){ - cout<<4< +using namespace std; + +int main(){ + int t; + int a[50][50]; + int i,j,k; + for(k=0;k<50;k++){ + if(k%2==0){ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=1; + else + a[k][i]=2; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=2; + else + a[i][k]=1; + } + } + else{ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=3; + else + a[k][i]=4; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=4; + else + a[i][k]=3; + } + + } + } + cin>>t; + while(t--){ + int n,m,mod; + cin>>n>>m; + // int a[n][m]; + //int i,j; + if(n>=3&&m>=3){ + cout<<4< -using namespace std; -long long maxi=1000000000; - -int main(){ - int i,j,a[(int)1e6+3]={0}; - vector v; - for(i=2;i*i<=1000001;i++){ - if(a[i]==0){ - //v.push_back(i); - for(j=i*i;j<=1000000;j+=i){ - a[j]=i; - } - - } - } - for(i=2;i<1000001;i++){ - if(a[i]==0) - v.push_back(i); - } - int t; - cin>>t; - while(t--) - { - int n,k,l; - cin>>n; - - long long ans; - //cout<2999) - l=l-2999; - // cout< +using namespace std; +long long maxi=1000000000; + +int main(){ + int i,j,a[(int)1e6+3]={0}; + vector v; + for(i=2;i*i<=1000001;i++){ + if(a[i]==0){ + //v.push_back(i); + for(j=i*i;j<=1000000;j+=i){ + a[j]=i; + } + + } + } + for(i=2;i<1000001;i++){ + if(a[i]==0) + v.push_back(i); + } + int t; + cin>>t; + while(t--) + { + int n,k,l; + cin>>n; + + long long ans; + //cout<2999) + l=l-2999; + // cout< -#include -using namespace std; -int main() -{ - // slmax second last maximum - int t,slmax,max,index,it=0,min; - cin>>t; - while(t--) - { - int n,toadd,it=0; - cin>>n; - int a[n]; - for(int i=0;i>a[i]; - sort(a,a+n); - min=a[0]; - while(a[0]!=a[n-1]) - { - // max is last element - max=a[n-1]; - // second last element - index=n-2; - // find second last max - while(a[index]==max) - { - index--; - } - toadd=max-a[index]; - it=it+toadd; - for(int i=0;i +#include +using namespace std; +int main() +{ + // slmax second last maximum + int t,slmax,max,index,it=0,min; + cin>>t; + while(t--) + { + int n,toadd,it=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + sort(a,a+n); + min=a[0]; + while(a[0]!=a[n-1]) + { + // max is last element + max=a[n-1]; + // second last element + index=n-2; + // find second last max + while(a[index]==max) + { + index--; + } + toadd=max-a[index]; + it=it+toadd; + for(int i=0;i -using namespace std; -long long maxi=1000000000; -#define l long - -int main(){ - int t; - cin>>t; - while(t--){ - long n,k,x,y,z; - long i,j,gcd; - cin>>n>>k>>x>>y>>z; - long p,q; - q=2*n +1; - if(x==z){ - p=x; - gcd=__gcd(p,q); - cout<

y&&y>x){ - if(k==1) - {p=q-z;} - else if(k==2||k==4){ - p=q-2*y; - } - else{ - p=q-x; - - } - gcd=__gcd(p,q); - cout<

+using namespace std; +long long maxi=1000000000; +#define l long + +int main(){ + int t; + cin>>t; + while(t--){ + long n,k,x,y,z; + long i,j,gcd; + cin>>n>>k>>x>>y>>z; + long p,q; + q=2*n +1; + if(x==z){ + p=x; + gcd=__gcd(p,q); + cout<

y&&y>x){ + if(k==1) + {p=q-z;} + else if(k==2||k==4){ + p=q-2*y; + } + else{ + p=q-x; + + } + gcd=__gcd(p,q); + cout<

-using namespace std; - -int main(){ - int n; cin>>n; - int a[n]; - int orig[n]; - float temp; - int sum = 0; - for(int i =0; i>temp; - orig[n] = temp; - if((int)temp%2==0){ - a[i] = temp/2; - } - else{ - temp = temp/2.0; - temp += 0.5; - a[i] = (int)temp; - } - sum+=a[i]; - } - int change=1; - if(sum>0){ - for(int i =0; i0){ - a[i] -=1; - sum -=1; - } - cout<0 - for(int i =0; i0){ - // a[i] +=1; //adding 1 to ceil is wrong - // sum +=1; - //} - cout< +using namespace std; + +int main(){ + int n; cin>>n; + int a[n]; + int orig[n]; + float temp; + int sum = 0; + for(int i =0; i>temp; + orig[n] = temp; + if((int)temp%2==0){ + a[i] = temp/2; + } + else{ + temp = temp/2.0; + temp += 0.5; + a[i] = (int)temp; + } + sum+=a[i]; + } + int change=1; + if(sum>0){ + for(int i =0; i0){ + a[i] -=1; + sum -=1; + } + cout<0 + for(int i =0; i0){ + // a[i] +=1; //adding 1 to ceil is wrong + // sum +=1; + //} + cout< -using namespace std; -class Node -{ -public: - int data ; - Node *next = NULL; - Node *prev = NULL; - Node(int data) - { - this->data = data ; - } -}; -class Queue -{ - Node* front = NULL; - Node* rear = NULL; - int size = 0 ; - public : - void enqueue(int data) - { - Node *new_node = new Node(data) ; - if(front == NULL) - { - front = new_node; - rear = new_node ; - } - else - { - rear->next = new_node ; - new_node->prev = rear ; - rear = new_node ; - } - size++; - } - void dequeue() - { - if(front == NULL) - { - cout<<"Queue is Already Empty !"<next ; - x->next = NULL ; - x->prev = NULL ; - if(front != NULL) - front->prev = NULL ; - delete x ; - size-- ; - } - } - bool isEmpty() - { - if(size == 0) - return true ; - else - return false ; - } - int Size() - { - return size ; - } - int Front() - { - if(front == NULL || size == 0) - { - cout<<"Queue is Empty"<data ; - } - } - void print() - { - Node *temp = front ; - while(temp != NULL) - { - cout<data<<" "; - temp = temp->next ; - } - cout< +using namespace std; +class Node +{ +public: + int data ; + Node *next = NULL; + Node *prev = NULL; + Node(int data) + { + this->data = data ; + } +}; +class Queue +{ + Node* front = NULL; + Node* rear = NULL; + int size = 0 ; + public : + void enqueue(int data) + { + Node *new_node = new Node(data) ; + if(front == NULL) + { + front = new_node; + rear = new_node ; + } + else + { + rear->next = new_node ; + new_node->prev = rear ; + rear = new_node ; + } + size++; + } + void dequeue() + { + if(front == NULL) + { + cout<<"Queue is Already Empty !"<next ; + x->next = NULL ; + x->prev = NULL ; + if(front != NULL) + front->prev = NULL ; + delete x ; + size-- ; + } + } + bool isEmpty() + { + if(size == 0) + return true ; + else + return false ; + } + int Size() + { + return size ; + } + int Front() + { + if(front == NULL || size == 0) + { + cout<<"Queue is Empty"<data ; + } + } + void print() + { + Node *temp = front ; + while(temp != NULL) + { + cout<data<<" "; + temp = temp->next ; + } + cout< -using namespace std; -int stack[100], n=100, top=-1; -void push(int val) { - if(top>=n-1) - cout<<"Stack Overflow"<=0) { - cout<<"Stack elements are:"; - for(int i=top; i>=0; i--) - cout<>ch; - switch(ch) { - case 1: { - cout<<"Enter value to be pushed:"<>val; - push(val); - break; - } - case 2: { - pop(); - break; - } - case 3: { - display(); - break; - } - case 4: { - cout<<"Exit"< +using namespace std; +int stack[100], n=100, top=-1; +void push(int val) { + if(top>=n-1) + cout<<"Stack Overflow"<=0) { + cout<<"Stack elements are:"; + for(int i=top; i>=0; i--) + cout<>ch; + switch(ch) { + case 1: { + cout<<"Enter value to be pushed:"<>val; + push(val); + break; + } + case 2: { + pop(); + break; + } + case 3: { + display(); + break; + } + case 4: { + cout<<"Exit"< -using namespace std; - -struct queue -{ - int value; - queue *next; -}; - -void removeFromQueue(queue*& head) // remove first element from queue -{ - if (head) - { - queue* ptr = head->next; - delete head; - head = ptr; - } -} - -void addToQueue(queue*& head, int nValue) // add new value to queue -{ - if (head == nullptr) // first element - { - head = new queue; - head->value = nValue; - head->next = nullptr; - } - else // add element on the end of the queue - { - auto ptr = head; - while (ptr->next) - { - ptr = ptr->next; - } - ptr->next = new queue{ nValue, nullptr }; - } -} - -void deleteQueue(queue *&head) // delete queue -{ - while (head) - { - auto ptr = head->next; - delete head; - head = ptr; - } -} - -void printQueue(queue *head) -{ - while (head) - { - cout << head->value << endl; - head = head->next; - } -} - -int main() -{ - // TEST - queue* pHead = nullptr; - addToQueue(pHead, 231); - addToQueue(pHead, 121); - addToQueue(pHead, 251); - addToQueue(pHead, 12); - addToQueue(pHead, 14); - addToQueue(pHead, 99); - printQueue(pHead); - removeFromQueue(pHead); - removeFromQueue(pHead); - removeFromQueue(pHead); - printQueue(pHead); - deleteQueue(pHead); - - - -} +#include +using namespace std; + +struct queue +{ + int value; + queue *next; +}; + +void removeFromQueue(queue*& head) // remove first element from queue +{ + if (head) + { + queue* ptr = head->next; + delete head; + head = ptr; + } +} + +void addToQueue(queue*& head, int nValue) // add new value to queue +{ + if (head == nullptr) // first element + { + head = new queue; + head->value = nValue; + head->next = nullptr; + } + else // add element on the end of the queue + { + auto ptr = head; + while (ptr->next) + { + ptr = ptr->next; + } + ptr->next = new queue{ nValue, nullptr }; + } +} + +void deleteQueue(queue *&head) // delete queue +{ + while (head) + { + auto ptr = head->next; + delete head; + head = ptr; + } +} + +void printQueue(queue *head) +{ + while (head) + { + cout << head->value << endl; + head = head->next; + } +} + +int main() +{ + // TEST + queue* pHead = nullptr; + addToQueue(pHead, 231); + addToQueue(pHead, 121); + addToQueue(pHead, 251); + addToQueue(pHead, 12); + addToQueue(pHead, 14); + addToQueue(pHead, 99); + printQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + printQueue(pHead); + deleteQueue(pHead); + + + +} diff --git a/DS/C/avl_tree.c b/DS/C/avl_tree.c old mode 100755 new mode 100644 diff --git a/DS/Linked_List/linked_list.s b/DS/Linked_List/linked_list.s old mode 100755 new mode 100644 index c80baf84..3130391f --- a/DS/Linked_List/linked_list.s +++ b/DS/Linked_List/linked_list.s @@ -1,344 +1,344 @@ - .data -descriptor: .space 12 -theBucket: .space 80 -printMenu: .asciiz "\n1 - Insert element in the list\n2 - Update/Remove\n3 - Radix sort\n4 - Print list\n5 - Exit\nOption: " -askValue: .asciiz "\nType a value: " -whatDo: .asciiz "\nUpdate or remove? [0] Update / [1] Remove: " -newValue: .asciiz "\nType a new value: " -askIndex: .asciiz "\nType the index of element: " -msg_Inval: .asciiz "\nInvalid option\n" -msg_empty: .asciiz "\nEmpty list\n" -charEnter: .asciiz "\n" -openSquareBrac: .asciiz "Index [" -end_SquareBrac: .asciiz "] = " - .text - -main: - la $s0, descriptor - sw $zero, 0($s0) - sw $zero, 4($s0) - sw $zero, 8($s0) - move $s1, $zero - -menuOp: - li $v0, 4 - la $a0, printMenu - syscall - - li $v0, 5 - syscall - - beq $v0, 1, insert_element - beq $v0, 2, search - beq $v0, 3, order - beq $v0, 4, show_list - beq $v0, 5, exit - - j showInvalid - -insert_element: - li $v0, 4 - la $a0, askValue - syscall - - li $v0, 5 - syscall - move $t0, $v0 - - li $v0, 9 - addi $a0, $zero, 12 - syscall - - lw $t1, 4($s0) - addi $t1, $t1, 1 - sw $t1, 4($s0) - - sw $t0, 4($v0) - sw $zero, 8($v0) - - lw $s1, 8($s0) - bne $s1, $zero, insertEnd - sw $v0, 0($s0) - -insertEnd: - sw $v0, 8($s0) - sw $s1, 0($v0) - beq $s1, $zero, return - sw $v0, 8($s1) - b return - -search: - li $v0, 4 - la $a0, askIndex - syscall - li $v0, 5 - syscall - lw $t1, 0($s0) - lw $t0, 4($s0) - addi $t2, $zero, -1 - blt $v0, $t0, loop_search - li $v0, 4 - la $a0, msg_Inval - syscall - - b return - -loop_search: - move $t0, $t1 - lw $t1, 8($t1) - addi $t2, $t2, 1 - blt $t2, $v0, loop_search - - li $v0, 4 - la $a0, whatDo - syscall - - li $v0, 5 - syscall - - beq $v0, 1, remove_element - bne $v0, $zero, showInvalid - - li $v0, 4 - la $a0, newValue - syscall - - li $v0, 5 - syscall - - sw $v0, 4($t0) - b return - -remove_element: - lw $t7, 4($s0) - addi $t7, $t7, -1 - sw $t7, 4($s0) - lw $t2, 0($t0) - lw $t3, 8($t0) - beq $t2, $zero, remove_first - beq $t3, $zero, remove_last - sw $t2, 0($t3) - sw $t3, 8($t2) - - b return -remove_first: - sw $t3, 0($s0) - beq $t3, $zero, main - sw $zero, 0($t3) - - b return - -remove_last: - sw $t2, 8($s0) - beq $t2, $zero, main - sw $zero, 8($t2) - - b return - -show_list: - lw $s1, 0($s0) - beq $s1, $zero, emptyList - move $t0, $zero - -loop: - lw $t1, 4($s1) - - li $v0, 4 - la $a0, charEnter - syscall - - li $v0, 4 - la $a0, openSquareBrac - syscall - - li $v0, 1 - move $a0, $t0 - syscall - - li $v0, 4 - la $a0, end_SquareBrac - syscall - - li $v0, 1 - move $a0, $t1 - syscall - - lw $s1, 8($s1) - addi $t0, $t0, 1 - bne $s1, $zero, loop - - li $v0, 4 - la $a0, charEnter - syscall - - b return - -return: - b menuOp - - -emptyList: - li $v0, 4 - la $a0, msg_empty - syscall - j menuOp - -showInvalid: - li $v0, 4 - la $a0, msg_Inval - syscall - j menuOp - -order: - lw $t0, 4($s0) - beq $t0, $zero, emptyList - - li $t1, 4 - mult $t0, $t1 - mflo $t0 - sub $sp, $sp, $t0 - - move $s1, $sp - lw $a0, 0($s0) - jal searchBigger - - move $s4, $v0 - li $t1, 1 - -radix: - jal cleanBucket - - lw $t0, 0($s0) - la $s2, theBucket - addi $s2, $s2, 40 - li $t2, 10 - li $t4, 4 - - bgt $t1, $s4, disaloc - -fillBucket: - jal accessBucket - - lw $t3, 0($v1) - - addi $t3, $t3, 1 - sw $t3, 0($v1) - - lw $t0, 8($t0) - - bne $t0, $zero, fillBucket - - la $t0, theBucket - lw $t6, 0($t0) - addi $t0, $t0, 4 - li $t5, 1 - -sum_buckets: - lw $t7, 0($t0) - add $t6, $t6, $t7 - sw $t6, 0($t0) - addi $t0, $t0, 4 - addi $t5, $t5, 1 - blt $t5, 20, sum_buckets - - lw $t0, 8($s0) - -fill_aux: - jal accessBucket - - lw $t3, 0($v1) - - addi $t3, $t3, -1 - sw $t3, 0($v1) - - mult $t3, $t4 - mflo $t3 - sub $t3, $s1, $t3 - - lw $t5, 4($t0) - sw $t5, 0($t3) - lw $t0, 0($t0) - bne $t0, $zero, fill_aux - - lw $t0, 0($s0) - lw $t5, 4($s0) - li $t2, 0 - move $t3, $s1 - -fill_list: - lw $t4, 0($t3) - sw $t4, 4($t0) - lw $t0, 8($t0) - - addi $t3, $t3, -4 - addi $t2, $t2, 1 - - blt $t2, $t5, fill_list - mult $t5, $t2 - mflo $t5 - - li $t2, 10 - mult $t2, $t1 - mflo $t1 - - b radix - -accessBucket: - lw $t3, 4($t0) - div $t3, $t1 - mflo $t3 - - div $t3, $t2 - mfhi $t3 - - mult $t4, $t3 - mflo $t3 - - add $v1, $s2, $t3 - jr $ra - -searchBigger: - li $t7, -1 - lw $t0, 4($a0) - mult $t0, $t7 - mflo $t6 - bgt $t6, $t0, isBigger - -loopMaior: - lw $a0, 8($a0) - beq $a0, $zero, endList - lw $t6, 4($a0) - bgt $t6, $t0, isBigger - mult $t6, $t7 - mflo $t6 - bgt $t6, $t0, isBigger - b loopMaior -isBigger: - move $t0, $t6 - b loopMaior -endList: - move $v0, $t0 - jr $ra - -cleanBucket: - la $s6, theBucket - move $s7, $zero -loopBucket: - sw $zero, 0($s6) - addi $s7, $s7, 1 - addi $s6, $s6, 4 - blt $s7, 20, loopBucket - jr $ra - -disaloc: - lw $t7, 4($s0) - li $t4, 4 - mult $t4, $t7 - mflo $t7 - add $sp, $sp, $t7 - - b return - -exit: - li $v0, 10 - syscall + .data +descriptor: .space 12 +theBucket: .space 80 +printMenu: .asciiz "\n1 - Insert element in the list\n2 - Update/Remove\n3 - Radix sort\n4 - Print list\n5 - Exit\nOption: " +askValue: .asciiz "\nType a value: " +whatDo: .asciiz "\nUpdate or remove? [0] Update / [1] Remove: " +newValue: .asciiz "\nType a new value: " +askIndex: .asciiz "\nType the index of element: " +msg_Inval: .asciiz "\nInvalid option\n" +msg_empty: .asciiz "\nEmpty list\n" +charEnter: .asciiz "\n" +openSquareBrac: .asciiz "Index [" +end_SquareBrac: .asciiz "] = " + .text + +main: + la $s0, descriptor + sw $zero, 0($s0) + sw $zero, 4($s0) + sw $zero, 8($s0) + move $s1, $zero + +menuOp: + li $v0, 4 + la $a0, printMenu + syscall + + li $v0, 5 + syscall + + beq $v0, 1, insert_element + beq $v0, 2, search + beq $v0, 3, order + beq $v0, 4, show_list + beq $v0, 5, exit + + j showInvalid + +insert_element: + li $v0, 4 + la $a0, askValue + syscall + + li $v0, 5 + syscall + move $t0, $v0 + + li $v0, 9 + addi $a0, $zero, 12 + syscall + + lw $t1, 4($s0) + addi $t1, $t1, 1 + sw $t1, 4($s0) + + sw $t0, 4($v0) + sw $zero, 8($v0) + + lw $s1, 8($s0) + bne $s1, $zero, insertEnd + sw $v0, 0($s0) + +insertEnd: + sw $v0, 8($s0) + sw $s1, 0($v0) + beq $s1, $zero, return + sw $v0, 8($s1) + b return + +search: + li $v0, 4 + la $a0, askIndex + syscall + li $v0, 5 + syscall + lw $t1, 0($s0) + lw $t0, 4($s0) + addi $t2, $zero, -1 + blt $v0, $t0, loop_search + li $v0, 4 + la $a0, msg_Inval + syscall + + b return + +loop_search: + move $t0, $t1 + lw $t1, 8($t1) + addi $t2, $t2, 1 + blt $t2, $v0, loop_search + + li $v0, 4 + la $a0, whatDo + syscall + + li $v0, 5 + syscall + + beq $v0, 1, remove_element + bne $v0, $zero, showInvalid + + li $v0, 4 + la $a0, newValue + syscall + + li $v0, 5 + syscall + + sw $v0, 4($t0) + b return + +remove_element: + lw $t7, 4($s0) + addi $t7, $t7, -1 + sw $t7, 4($s0) + lw $t2, 0($t0) + lw $t3, 8($t0) + beq $t2, $zero, remove_first + beq $t3, $zero, remove_last + sw $t2, 0($t3) + sw $t3, 8($t2) + + b return +remove_first: + sw $t3, 0($s0) + beq $t3, $zero, main + sw $zero, 0($t3) + + b return + +remove_last: + sw $t2, 8($s0) + beq $t2, $zero, main + sw $zero, 8($t2) + + b return + +show_list: + lw $s1, 0($s0) + beq $s1, $zero, emptyList + move $t0, $zero + +loop: + lw $t1, 4($s1) + + li $v0, 4 + la $a0, charEnter + syscall + + li $v0, 4 + la $a0, openSquareBrac + syscall + + li $v0, 1 + move $a0, $t0 + syscall + + li $v0, 4 + la $a0, end_SquareBrac + syscall + + li $v0, 1 + move $a0, $t1 + syscall + + lw $s1, 8($s1) + addi $t0, $t0, 1 + bne $s1, $zero, loop + + li $v0, 4 + la $a0, charEnter + syscall + + b return + +return: + b menuOp + + +emptyList: + li $v0, 4 + la $a0, msg_empty + syscall + j menuOp + +showInvalid: + li $v0, 4 + la $a0, msg_Inval + syscall + j menuOp + +order: + lw $t0, 4($s0) + beq $t0, $zero, emptyList + + li $t1, 4 + mult $t0, $t1 + mflo $t0 + sub $sp, $sp, $t0 + + move $s1, $sp + lw $a0, 0($s0) + jal searchBigger + + move $s4, $v0 + li $t1, 1 + +radix: + jal cleanBucket + + lw $t0, 0($s0) + la $s2, theBucket + addi $s2, $s2, 40 + li $t2, 10 + li $t4, 4 + + bgt $t1, $s4, disaloc + +fillBucket: + jal accessBucket + + lw $t3, 0($v1) + + addi $t3, $t3, 1 + sw $t3, 0($v1) + + lw $t0, 8($t0) + + bne $t0, $zero, fillBucket + + la $t0, theBucket + lw $t6, 0($t0) + addi $t0, $t0, 4 + li $t5, 1 + +sum_buckets: + lw $t7, 0($t0) + add $t6, $t6, $t7 + sw $t6, 0($t0) + addi $t0, $t0, 4 + addi $t5, $t5, 1 + blt $t5, 20, sum_buckets + + lw $t0, 8($s0) + +fill_aux: + jal accessBucket + + lw $t3, 0($v1) + + addi $t3, $t3, -1 + sw $t3, 0($v1) + + mult $t3, $t4 + mflo $t3 + sub $t3, $s1, $t3 + + lw $t5, 4($t0) + sw $t5, 0($t3) + lw $t0, 0($t0) + bne $t0, $zero, fill_aux + + lw $t0, 0($s0) + lw $t5, 4($s0) + li $t2, 0 + move $t3, $s1 + +fill_list: + lw $t4, 0($t3) + sw $t4, 4($t0) + lw $t0, 8($t0) + + addi $t3, $t3, -4 + addi $t2, $t2, 1 + + blt $t2, $t5, fill_list + mult $t5, $t2 + mflo $t5 + + li $t2, 10 + mult $t2, $t1 + mflo $t1 + + b radix + +accessBucket: + lw $t3, 4($t0) + div $t3, $t1 + mflo $t3 + + div $t3, $t2 + mfhi $t3 + + mult $t4, $t3 + mflo $t3 + + add $v1, $s2, $t3 + jr $ra + +searchBigger: + li $t7, -1 + lw $t0, 4($a0) + mult $t0, $t7 + mflo $t6 + bgt $t6, $t0, isBigger + +loopMaior: + lw $a0, 8($a0) + beq $a0, $zero, endList + lw $t6, 4($a0) + bgt $t6, $t0, isBigger + mult $t6, $t7 + mflo $t6 + bgt $t6, $t0, isBigger + b loopMaior +isBigger: + move $t0, $t6 + b loopMaior +endList: + move $v0, $t0 + jr $ra + +cleanBucket: + la $s6, theBucket + move $s7, $zero +loopBucket: + sw $zero, 0($s6) + addi $s7, $s7, 1 + addi $s6, $s6, 4 + blt $s7, 20, loopBucket + jr $ra + +disaloc: + lw $t7, 4($s0) + li $t4, 4 + mult $t4, $t7 + mflo $t7 + add $sp, $sp, $t7 + + b return + +exit: + li $v0, 10 + syscall diff --git a/Hackerearth/Acronym.cpp b/Hackerearth/Acronym.cpp index 18fe7b5b..0a0690e3 100644 --- a/Hackerearth/Acronym.cpp +++ b/Hackerearth/Acronym.cpp @@ -1,44 +1,44 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -#define tc int t; cin>>t; while(t--) -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -int k; cin>>k; string s; -map m; -while(k--) -{ - cin>>s; - m[s]=1; -} -cin>>k; -while(--k) -{ - cin>>s; - if(m[s]==0) - cout<>s; -if(m[s]==0) - cout< +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int k; cin>>k; string s; +map m; +while(k--) +{ + cin>>s; + m[s]=1; +} +cin>>k; +while(--k) +{ + cin>>s; + if(m[s]==0) + cout<>s; +if(m[s]==0) + cout< -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -#define tc int t; cin>>t; while(t--) - -using namespace std; -int main() -{ -string s; -int i,count=0; -getline(cin,s); -for(i=0;i +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) + +using namespace std; +int main() +{ +string s; +int i,count=0; +getline(cin,s); +for(i=0;i -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -#define tc int t; cin>>t; while(t--) -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -tc{ -string s; -getline(cin,s); -int a[26]={0}; -fi(s.length()) -{ - if(s[i]!=' ') - a[s[i]-'a']++; -} -getline(cin,s); -fi(s.length()) -{ - if(s[i]!=' ') - a[s[i]-'a']--; -} -bool fir=false,sec=false; -fi(26) -{ - if(a[i]>0) - fir=true; - if(a[i]<0) - sec=true; -} -if(fir && sec) - cout<<"You draw some."<<"\n"; -else { - if(fir) - cout<<"You win some.\n"; - else - cout<<"You lose some.\n"; -} -} - - -return 0; -} +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +tc{ +string s; +getline(cin,s); +int a[26]={0}; +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']++; +} +getline(cin,s); +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']--; +} +bool fir=false,sec=false; +fi(26) +{ + if(a[i]>0) + fir=true; + if(a[i]<0) + sec=true; +} +if(fir && sec) + cout<<"You draw some."<<"\n"; +else { + if(fir) + cout<<"You win some.\n"; + else + cout<<"You lose some.\n"; +} +} + + +return 0; +} diff --git a/Hackerearth/Max Profit.cpp b/Hackerearth/Max Profit.cpp index c023f3de..a5b5e0e3 100644 --- a/Hackerearth/Max Profit.cpp +++ b/Hackerearth/Max Profit.cpp @@ -1,35 +1,35 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -using namespace std; - -int main() -{ -int n, ans=0; -scanf("%d", &n); -int a[n]; -for (int i=0; ians) -ans=a[i]-a[j]; -} -printf("%d\n", ans); -return 0; -} +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +using namespace std; + +int main() +{ +int n, ans=0; +scanf("%d", &n); +int a[n]; +for (int i=0; ians) +ans=a[i]-a[j]; +} +printf("%d\n", ans); +return 0; +} diff --git a/Hackerearth/Old and Cold Numbers.cpp b/Hackerearth/Old and Cold Numbers.cpp index a3fb51c6..f9512b62 100644 --- a/Hackerearth/Old and Cold Numbers.cpp +++ b/Hackerearth/Old and Cold Numbers.cpp @@ -1,33 +1,33 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -int t; cin>>t; -while(t--) -{ - -} - - - -return 0; -} +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--) +{ + +} + + + +return 0; +} diff --git a/Hackerearth/Palindromic Grid.cpp b/Hackerearth/Palindromic Grid.cpp index ab5ff2e1..88db7b3f 100644 --- a/Hackerearth/Palindromic Grid.cpp +++ b/Hackerearth/Palindromic Grid.cpp @@ -1,90 +1,90 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -int t; cin>>t; -while(t--){ - -int m,n; -cin>>n>>m; -int count[26]={0}; -int single = 0,pairs=0; string ent; -fi(n){cin>>ent; fj(m) ++count[ent[j]-'a'];} -fi(26) -{ - if(count[i]%2) - { - ++single; - - } - count[i]=count[i]>>1; - if(count[i]%2) - { - ++pairs; - } -} -//cout<<"P : "< +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--){ + +int m,n; +cin>>n>>m; +int count[26]={0}; +int single = 0,pairs=0; string ent; +fi(n){cin>>ent; fj(m) ++count[ent[j]-'a'];} +fi(26) +{ + if(count[i]%2) + { + ++single; + + } + count[i]=count[i]>>1; + if(count[i]%2) + { + ++pairs; + } +} +//cout<<"P : "< - -using namespace std; - -vector split_string(string); - -// Complete the birthdayCakeCandles function below. -int birthdayCakeCandles(vector ar) { - int max = *max_element(ar.begin(), ar.end()); - int count= 0; - for (int i =0; i> ar_count; - cin.ignore(numeric_limits::max(), '\n'); - - string ar_temp_temp; - getline(cin, ar_temp_temp); - - vector ar_temp = split_string(ar_temp_temp); - - vector ar(ar_count); - - for (int i = 0; i < ar_count; i++) { - int ar_item = stoi(ar_temp[i]); - - ar[i] = ar_item; - } - - int result = birthdayCakeCandles(ar); - - fout << result << "\n"; - - fout.close(); - - return 0; -} - -vector split_string(string input_string) { - string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { - return x == y and x == ' '; - }); - - input_string.erase(new_end, input_string.end()); - - while (input_string[input_string.length() - 1] == ' ') { - input_string.pop_back(); - } - - vector splits; - char delimiter = ' '; - - size_t i = 0; - size_t pos = input_string.find(delimiter); - - while (pos != string::npos) { - splits.push_back(input_string.substr(i, pos - i)); - - i = pos + 1; - pos = input_string.find(delimiter, i); - } - - splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); - - return splits; -} +#include + +using namespace std; + +vector split_string(string); + +// Complete the birthdayCakeCandles function below. +int birthdayCakeCandles(vector ar) { + int max = *max_element(ar.begin(), ar.end()); + int count= 0; + for (int i =0; i> ar_count; + cin.ignore(numeric_limits::max(), '\n'); + + string ar_temp_temp; + getline(cin, ar_temp_temp); + + vector ar_temp = split_string(ar_temp_temp); + + vector ar(ar_count); + + for (int i = 0; i < ar_count; i++) { + int ar_item = stoi(ar_temp[i]); + + ar[i] = ar_item; + } + + int result = birthdayCakeCandles(ar); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/CompareTheTriplets.cpp b/Hackerrank/C++/CompareTheTriplets.cpp deleted file mode 100644 index 2ff70b2a..00000000 --- a/Hackerrank/C++/CompareTheTriplets.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include -using namespace std; - -int main() { - // your code goes here - unsigned int a[3],A=0; - unsigned int b[3],B=0; - for (int i = 0; i<3;i++) cin>>a[i]; - for(int j =0;j<3;j++) - { - cin>>b[j]; - - if (a[j]>b[j]) A++; - else if (a[j] - -using namespace std; - -string ltrim(const string &); -string rtrim(const string &); -vector split(const string &); - -/* - * Complete the 'diagonalDifference' function below. - * - * The function is expected to return an INTEGER. - * The function accepts 2D_INTEGER_ARRAY arr as parameter. - */ - -int diagonalDifference(vector> arr) { - int d1 =0, d2 =0; - - for (int i=0; i> arr(n); - - for (int i = 0; i < n; i++) { - arr[i].resize(n); - - string arr_row_temp_temp; - getline(cin, arr_row_temp_temp); - - vector arr_row_temp = split(rtrim(arr_row_temp_temp)); - - for (int j = 0; j < n; j++) { - int arr_row_item = stoi(arr_row_temp[j]); - - arr[i][j] = arr_row_item; - } - } - - int result = diagonalDifference(arr); - - fout << result << "\n"; - - fout.close(); - - return 0; -} - -string ltrim(const string &str) { - string s(str); - - s.erase( - s.begin(), - find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) - ); - - return s; -} - -string rtrim(const string &str) { - string s(str); - - s.erase( - find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), - s.end() - ); - - return s; -} - -vector split(const string &str) { - vector tokens; - - string::size_type start = 0; - string::size_type end = 0; - - while ((end = str.find(" ", start)) != string::npos) { - tokens.push_back(str.substr(start, end - start)); - - start = end + 1; - } - - tokens.push_back(str.substr(start)); - - return tokens; -} +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +/* + * Complete the 'diagonalDifference' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY arr as parameter. + */ + +int diagonalDifference(vector> arr) { + int d1 =0, d2 =0; + + for (int i=0; i> arr(n); + + for (int i = 0; i < n; i++) { + arr[i].resize(n); + + string arr_row_temp_temp; + getline(cin, arr_row_temp_temp); + + vector arr_row_temp = split(rtrim(arr_row_temp_temp)); + + for (int j = 0; j < n; j++) { + int arr_row_item = stoi(arr_row_temp[j]); + + arr[i][j] = arr_row_item; + } + } + + int result = diagonalDifference(arr); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/Hackerrank/C++/inputOutput.cpp b/Hackerrank/C++/inputOutput.cpp index 33fe055c..24156001 100644 --- a/Hackerrank/C++/inputOutput.cpp +++ b/Hackerrank/C++/inputOutput.cpp @@ -1,15 +1,15 @@ -#include -#include -#include -#include -#include -using namespace std; - -// Problem https://www.hackerrank.com/challenges/cpp-input-and-output/problem - -int main() { - int a, b, c; - cin >> a >> b >> c; - cout << a+b+c << endl; - return 0; -} +#include +#include +#include +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-input-and-output/problem + +int main() { + int a, b, c; + cin >> a >> b >> c; + cout << a+b+c << endl; + return 0; +} diff --git a/Hackerrank/C++/insertNodeSpecificPosition.cpp b/Hackerrank/C++/insertNodeSpecificPosition.cpp index e4c9a33b..113ac0f9 100644 --- a/Hackerrank/C++/insertNodeSpecificPosition.cpp +++ b/Hackerrank/C++/insertNodeSpecificPosition.cpp @@ -1,92 +1,92 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem - -class SinglyLinkedListNode { - public: - int data; - SinglyLinkedListNode *next; - - SinglyLinkedListNode(int node_data) { - this->data = node_data; - this->next = nullptr; - } -}; - -class SinglyLinkedList { - public: - SinglyLinkedListNode *head; - SinglyLinkedListNode *tail; - - SinglyLinkedList() { - this->head = nullptr; - this->tail = nullptr; - } - - void insert_node(int node_data) { - SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); - - if (!this->head) { - this->head = node; - } else { - this->tail->next = node; - } - - this->tail = node; - } -}; - -void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { - while (node) { - fout << node->data; - - node = node->next; - - if (node) { - fout << sep; - } - } -} - -void free_singly_linked_list(SinglyLinkedListNode* node) { - while (node) { - SinglyLinkedListNode* temp = node; - node = node->next; - - free(temp); - } -} - -// Complete the insertNodeAtPosition function below. - -/* - * For your reference: - * - * SinglyLinkedListNode { - * int data; - * SinglyLinkedListNode* next; - * }; - * - */ -SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { - - SinglyLinkedListNode *curr = head, *temp; - - if (position == 0){ - temp = head; - head = new SinglyLinkedListNode(data); - head->next = temp; - } - - while (--position) curr = curr->next; - - temp = curr->next; - curr->next = new SinglyLinkedListNode(data); - curr->next->next = temp; - - return head; -} - +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtPosition function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { + + SinglyLinkedListNode *curr = head, *temp; + + if (position == 0){ + temp = head; + head = new SinglyLinkedListNode(data); + head->next = temp; + } + + while (--position) curr = curr->next; + + temp = curr->next; + curr->next = new SinglyLinkedListNode(data); + curr->next->next = temp; + + return head; +} + int main() \ No newline at end of file diff --git a/Hackerrank/C++/insertNodeTailLinkedList.cpp b/Hackerrank/C++/insertNodeTailLinkedList.cpp index 897da895..48314d18 100644 --- a/Hackerrank/C++/insertNodeTailLinkedList.cpp +++ b/Hackerrank/C++/insertNodeTailLinkedList.cpp @@ -1,70 +1,70 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list - -class SinglyLinkedListNode { - public: - int data; - SinglyLinkedListNode *next; - - SinglyLinkedListNode(int node_data) { - this->data = node_data; - this->next = nullptr; - } -}; - -class SinglyLinkedList { - public: - SinglyLinkedListNode *head; - - SinglyLinkedList() { - this->head = nullptr; - } - -}; - -void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { - while (node) { - fout << node->data; - - node = node->next; - - if (node) { - fout << sep; - } - } -} - -void free_singly_linked_list(SinglyLinkedListNode* node) { - while (node) { - SinglyLinkedListNode* temp = node; - node = node->next; - - free(temp); - } -} - -// Complete the insertNodeAtTail function below. - -/* - * For your reference: - * - * SinglyLinkedListNode { - * int data; - * SinglyLinkedListNode* next; - * }; - * - */ -SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { - if (!head) head = new SinglyLinkedListNode(data); - else { - SinglyLinkedListNode* curr = head; - while (curr->next) curr = curr->next; - curr->next = new SinglyLinkedListNode(data); - } - return head; -} - +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + + SinglyLinkedList() { + this->head = nullptr; + } + +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtTail function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { + if (!head) head = new SinglyLinkedListNode(data); + else { + SinglyLinkedListNode* curr = head; + while (curr->next) curr = curr->next; + curr->next = new SinglyLinkedListNode(data); + } + return head; +} + int main() \ No newline at end of file diff --git a/Hackerrank/C++/mapsSTL.cpp b/Hackerrank/C++/mapsSTL.cpp index 609e948e..6b8c66ee 100644 --- a/Hackerrank/C++/mapsSTL.cpp +++ b/Hackerrank/C++/mapsSTL.cpp @@ -1,39 +1,39 @@ -#include -#include -#include -#include -#include -#include -#include -using namespace std; - -//Problem https://www.hackerrank.com/challenges/cpp-maps/problem - -int main() { - /* Enter your code here. Read input from STDIN. Print output to STDOUT */ - int iQueries, iType; - long long iData; - string sName; - unordered_map mStudents; - cin >> iQueries; - while (iQueries--){ - cin >> iType; - switch (iType){ - case 1: - cin >> sName >> iData; - mStudents[sName] += iData; - break; - case 2: - cin >> sName; - mStudents[sName] = 0; - break; - case 3: - cin >> sName; - cout << mStudents[sName] << endl; - break; - default: - break; - } - } - return 0; +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/cpp-maps/problem + +int main() { + /* Enter your code here. Read input from STDIN. Print output to STDOUT */ + int iQueries, iType; + long long iData; + string sName; + unordered_map mStudents; + cin >> iQueries; + while (iQueries--){ + cin >> iType; + switch (iType){ + case 1: + cin >> sName >> iData; + mStudents[sName] += iData; + break; + case 2: + cin >> sName; + mStudents[sName] = 0; + break; + case 3: + cin >> sName; + cout << mStudents[sName] << endl; + break; + default: + break; + } + } + return 0; } \ No newline at end of file diff --git a/Hackerrank/C++/printLinkedList.cpp b/Hackerrank/C++/printLinkedList.cpp index 572c3014..69b53f5b 100644 --- a/Hackerrank/C++/printLinkedList.cpp +++ b/Hackerrank/C++/printLinkedList.cpp @@ -1,69 +1,69 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list - -class SinglyLinkedListNode { - public: - int data; - SinglyLinkedListNode *next; - - SinglyLinkedListNode(int node_data) { - this->data = node_data; - this->next = nullptr; - } -}; - -class SinglyLinkedList { - public: - SinglyLinkedListNode *head; - SinglyLinkedListNode *tail; - - SinglyLinkedList() { - this->head = nullptr; - this->tail = nullptr; - } - - void insert_node(int node_data) { - SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); - - if (!this->head) { - this->head = node; - } else { - this->tail->next = node; - } - - this->tail = node; - } -}; - -void free_singly_linked_list(SinglyLinkedListNode* node) { - while (node) { - SinglyLinkedListNode* temp = node; - node = node->next; - - free(temp); - } -} - -// Complete the printLinkedList function below. - -/* - * For your reference: - * - * SinglyLinkedListNode { - * int data; - * SinglyLinkedListNode* next; - * }; - * - */ -void printLinkedList(SinglyLinkedListNode* head) { - SinglyLinkedListNode* curr = head; - while (curr){ - cout << curr->data << endl; - curr = curr->next; - } -} - +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the printLinkedList function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +void printLinkedList(SinglyLinkedListNode* head) { + SinglyLinkedListNode* curr = head; + while (curr){ + cout << curr->data << endl; + curr = curr->next; + } +} + int main() \ No newline at end of file diff --git a/Hackerrank/C++/sayHelloWorld.cpp b/Hackerrank/C++/sayHelloWorld.cpp index c9ca033d..8da50c66 100644 --- a/Hackerrank/C++/sayHelloWorld.cpp +++ b/Hackerrank/C++/sayHelloWorld.cpp @@ -1,10 +1,10 @@ -#include -#include -using namespace std; - -// Problem https://www.hackerrank.com/challenges/cpp-hello-world/problem - -int main() { - printf("Hello, World!"); - return 0; +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-hello-world/problem + +int main() { + printf("Hello, World!"); + return 0; } \ No newline at end of file diff --git a/Hackerrank/C++/solveMeFirst.cpp b/Hackerrank/C++/solveMeFirst.cpp index ab33007a..03e2190a 100644 --- a/Hackerrank/C++/solveMeFirst.cpp +++ b/Hackerrank/C++/solveMeFirst.cpp @@ -1,22 +1,22 @@ -#include -#include -#include -#include -#include -using namespace std; - -//Problem https://www.hackerrank.com/challenges/solve-me-first/problem - -int solveMeFirst(int a, int b) { - // Hint: Type return a+b; below - return a + b; -} - -int main() { - int num1, num2; - int sum; - cin>>num1>>num2; - sum = solveMeFirst(num1,num2); - cout< +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/solve-me-first/problem + +int solveMeFirst(int a, int b) { + // Hint: Type return a+b; below + return a + b; +} + +int main() { + int num1, num2; + int sum; + cin>>num1>>num2; + sum = solveMeFirst(num1,num2); + cout< -#include -#include -#include -#include -#include -#include -#include -#include - -char* readline(); -char** split_string(char*); - -// Complete the countingSort function below. - -// Please store the size of the integer array to be returned in result_count pointer. For example, -// int a[3] = {1, 2, 3}; -// -// *result_count = 3; -// -// return a; -// -int* countingSort(int arr_count, int* arr, int* result_count) { - int flag,k=0; - int temp[100]; - * result_count=arr_count; - int *result=malloc(arr_count*sizeof(int)); - for(int i=0;i<100;i++) - temp[i]=0; - for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the countingSort function below. + +// Please store the size of the integer array to be returned in result_count pointer. For example, +// int a[3] = {1, 2, 3}; +// +// *result_count = 3; +// +// return a; +// +int* countingSort(int arr_count, int* arr, int* result_count) { + int flag,k=0; + int temp[100]; + * result_count=arr_count; + int *result=malloc(arr_count*sizeof(int)); + for(int i=0;i<100;i++) + temp[i]=0; + for(int i=0;i -#include -#include -#include -#include -#include -#include -#include -#include - -char* readline(); - -// Complete the gridChallenge function below. - -// Please either make the string static or allocate on the heap. For example, -// static char str[] = "hello world"; -// return str; -// -// OR -// -// char* str = "hello world"; -// return str; -// -char* gridChallenge(int grid_count, char** grid) { - - char* ans1="YES"; - char* ans2="NO"; - - char key; - int k; - for(int i=0;i=0&&grid[i][k]>key) - { - grid[i][k+1]=grid[i][k]; - k=k-1; - } - grid[i][k+1]=key; - } - } - - for(int i=0;igrid[j+1][i]) - return ans2; - } - } - return ans1; - -} - -int main() -{ - FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); - - char* t_endptr; - char* t_str = readline(); - int t = strtol(t_str, &t_endptr, 10); - - if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } - - for (int t_itr = 0; t_itr < t; t_itr++) { - char* n_endptr; - char* n_str = readline(); - int n = strtol(n_str, &n_endptr, 10); - - if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } - - char** grid = malloc(n * sizeof(char*)); - - for (int i = 0; i < n; i++) { - char* grid_item = readline(); - - *(grid + i) = grid_item; - } - - int grid_count = n; - - char* result = gridChallenge(grid_count, grid); - - fprintf(fptr, "%s\n", result); - } - - fclose(fptr); - - return 0; -} - -char* readline() { - size_t alloc_length = 1024; - size_t data_length = 0; - char* data = malloc(alloc_length); - - while (true) { - char* cursor = data + data_length; - char* line = fgets(cursor, alloc_length - data_length, stdin); - - if (!line) { break; } - - data_length += strlen(cursor); - - if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } - - size_t new_length = alloc_length << 1; - data = realloc(data, new_length); - - if (!data) { break; } - - alloc_length = new_length; - } - - if (data[data_length - 1] == '\n') { - data[data_length - 1] = '\0'; - } - - data = realloc(data, data_length); - - return data; -} +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the gridChallenge function below. + +// Please either make the string static or allocate on the heap. For example, +// static char str[] = "hello world"; +// return str; +// +// OR +// +// char* str = "hello world"; +// return str; +// +char* gridChallenge(int grid_count, char** grid) { + + char* ans1="YES"; + char* ans2="NO"; + + char key; + int k; + for(int i=0;i=0&&grid[i][k]>key) + { + grid[i][k+1]=grid[i][k]; + k=k-1; + } + grid[i][k+1]=key; + } + } + + for(int i=0;igrid[j+1][i]) + return ans2; + } + } + return ans1; + +} + +int main() +{ + FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); + + char* t_endptr; + char* t_str = readline(); + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + for (int t_itr = 0; t_itr < t; t_itr++) { + char* n_endptr; + char* n_str = readline(); + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char** grid = malloc(n * sizeof(char*)); + + for (int i = 0; i < n; i++) { + char* grid_item = readline(); + + *(grid + i) = grid_item; + } + + int grid_count = n; + + char* result = gridChallenge(grid_count, grid); + + fprintf(fptr, "%s\n", result); + } + + fclose(fptr); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} diff --git a/Hackerrank/C/Priyanka And Toys.cpp b/Hackerrank/C/Priyanka And Toys.cpp index bbb6296b..ece05440 100644 --- a/Hackerrank/C/Priyanka And Toys.cpp +++ b/Hackerrank/C/Priyanka And Toys.cpp @@ -1,96 +1,96 @@ -#include - -using namespace std; - -vector split_string(string); - -// Complete the toys function below. -int toys(vector w) { - sort(w.begin(),w.end()); - long int flag=0,z,count; - long int size; - while(!w.empty()) - { - count=0; - flag++; - size=w.size(); - z=w.front(); - - /*for(int i=0;i=z&&w[i]<=z+4) - count++; - - } - for(int i=0;i> n; - cin.ignore(numeric_limits::max(), '\n'); - - string w_temp_temp; - getline(cin, w_temp_temp); - - vector w_temp = split_string(w_temp_temp); - - vector w(n); - - for (int i = 0; i < n; i++) { - int w_item = stoi(w_temp[i]); - - w[i] = w_item; - } - - int result = toys(w); - - fout << result << "\n"; - - fout.close(); - - return 0; -} - -vector split_string(string input_string) { - string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { - return x == y and x == ' '; - }); - - input_string.erase(new_end, input_string.end()); - - while (input_string[input_string.length() - 1] == ' ') { - input_string.pop_back(); - } - - vector splits; - char delimiter = ' '; - - size_t i = 0; - size_t pos = input_string.find(delimiter); - - while (pos != string::npos) { - splits.push_back(input_string.substr(i, pos - i)); - - i = pos + 1; - pos = input_string.find(delimiter, i); - } - - splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); - - return splits; -} +#include + +using namespace std; + +vector split_string(string); + +// Complete the toys function below. +int toys(vector w) { + sort(w.begin(),w.end()); + long int flag=0,z,count; + long int size; + while(!w.empty()) + { + count=0; + flag++; + size=w.size(); + z=w.front(); + + /*for(int i=0;i=z&&w[i]<=z+4) + count++; + + } + for(int i=0;i> n; + cin.ignore(numeric_limits::max(), '\n'); + + string w_temp_temp; + getline(cin, w_temp_temp); + + vector w_temp = split_string(w_temp_temp); + + vector w(n); + + for (int i = 0; i < n; i++) { + int w_item = stoi(w_temp[i]); + + w[i] = w_item; + } + + int result = toys(w); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/Python/Python b/Hackerrank/Python/Python new file mode 100644 index 00000000..e69de29b diff --git a/Hackerrank/Python/Python: Division.py b/Hackerrank/Python/Python: Division.py deleted file mode 100644 index 26004077..00000000 --- a/Hackerrank/Python/Python: Division.py +++ /dev/null @@ -1,8 +0,0 @@ -#Author: Rakshit Naidu - -if __name__ == '__main__': - a = int(input()) - b = int(input()) - - print(a//b) - print(a/b) diff --git a/Hackerrank/Python/Simple Array Sum.py b/Hackerrank/Python/Simple Array Sum.py new file mode 100644 index 00000000..84830aa3 --- /dev/null +++ b/Hackerrank/Python/Simple Array Sum.py @@ -0,0 +1,12 @@ +#By NAIRITYA TALE +#Algorithms +#Data Structures + +size=int(input("Entre The Size Of Array")) #takes input as size of array +ar=[] #array declaration +arrsum=0 +for i in range(0,size): + ar.append(input()) #input in the array + arrsum=arrsum+int(ar[i]) #summation of array +print("The Sum Of The Array Is =",arrsum) #result display +exit() diff --git a/Hackerrank/Python/Time_Conversion.py b/Hackerrank/Python/Time_Conversion.py index d3aa39dd..76c06dfe 100644 --- a/Hackerrank/Python/Time_Conversion.py +++ b/Hackerrank/Python/Time_Conversion.py @@ -1,34 +1,34 @@ -# Author Name : Akshay Jain -#!/bin/python3 - -import os -import sys - -# -# Complete the timeConversion function below. -# -def timeConversion(s): - # - # Write your code here. - # - hh, mm, ssNu = s.split(':') - ss = ssNu[:2] - u = ssNu[2:] - - if u == 'AM' : - if hh == '12' : - hh = '00' - else : - if hh != '12' : - hh = (int(hh) + 12 ) - return ("{}:{}:{}".format(hh, mm, ss)) -if __name__ == '__main__': - f = open(os.environ['OUTPUT_PATH'], 'w') - - s = input() - - result = timeConversion(s) - - f.write(result + '\n') - - f.close() +# Author Name : Akshay Jain +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + # + # Write your code here. + # + hh, mm, ssNu = s.split(':') + ss = ssNu[:2] + u = ssNu[2:] + + if u == 'AM' : + if hh == '12' : + hh = '00' + else : + if hh != '12' : + hh = (int(hh) + 12 ) + return ("{}:{}:{}".format(hh, mm, ss)) +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() diff --git a/Hackerrank/Python/What's Your Name?.py b/Hackerrank/Python/What's Your Name?.py deleted file mode 100644 index 9a567bd6..00000000 --- a/Hackerrank/Python/What's Your Name?.py +++ /dev/null @@ -1,9 +0,0 @@ -#Submitted by Rakshit Naidu - -def print_full_name(a, b): - print("Hello {} {}! You just delved into python.".format(a,b)) - -if __name__ == '__main__': - first_name = input() - last_name = input() - print_full_name(first_name, last_name) diff --git a/Hackerrank/compareTheTriplets.cpp b/Hackerrank/compareTheTriplets.cpp index 33c63aa8..fa777540 100644 --- a/Hackerrank/compareTheTriplets.cpp +++ b/Hackerrank/compareTheTriplets.cpp @@ -1,108 +1,108 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/compare-the-triplets/problem - -string ltrim(const string &); -string rtrim(const string &); -vector split(const string &); - -// Complete the compareTriplets function below. -vector compareTriplets(vector a, vector b) { - - int iAliceScore = 0, iBobScore = 0; - - for (int i = 0; i < 3; ++i){ - if (a[i] > b[i]) ++iAliceScore; - else if (a[i] < b[i]) ++iBobScore; - } - - return {iAliceScore, iBobScore}; -} - -int main() -{ - ofstream fout(getenv("OUTPUT_PATH")); - - string a_temp_temp; - getline(cin, a_temp_temp); - - vector a_temp = split(rtrim(a_temp_temp)); - - vector a(3); - - for (int i = 0; i < 3; i++) { - int a_item = stoi(a_temp[i]); - - a[i] = a_item; - } - - string b_temp_temp; - getline(cin, b_temp_temp); - - vector b_temp = split(rtrim(b_temp_temp)); - - vector b(3); - - for (int i = 0; i < 3; i++) { - int b_item = stoi(b_temp[i]); - - b[i] = b_item; - } - - vector result = compareTriplets(a, b); - - for (int i = 0; i < result.size(); i++) { - fout << result[i]; - - if (i != result.size() - 1) { - fout << " "; - } - } - - fout << "\n"; - - fout.close(); - - return 0; -} - -string ltrim(const string &str) { - string s(str); - - s.erase( - s.begin(), - find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) - ); - - return s; -} - -string rtrim(const string &str) { - string s(str); - - s.erase( - find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), - s.end() - ); - - return s; -} - -vector split(const string &str) { - vector tokens; - - string::size_type start = 0; - string::size_type end = 0; - - while ((end = str.find(" ", start)) != string::npos) { - tokens.push_back(str.substr(start, end - start)); - - start = end + 1; - } - - tokens.push_back(str.substr(start)); - - return tokens; -} +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/compare-the-triplets/problem + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the compareTriplets function below. +vector compareTriplets(vector a, vector b) { + + int iAliceScore = 0, iBobScore = 0; + + for (int i = 0; i < 3; ++i){ + if (a[i] > b[i]) ++iAliceScore; + else if (a[i] < b[i]) ++iBobScore; + } + + return {iAliceScore, iBobScore}; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split(rtrim(a_temp_temp)); + + vector a(3); + + for (int i = 0; i < 3; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + string b_temp_temp; + getline(cin, b_temp_temp); + + vector b_temp = split(rtrim(b_temp_temp)); + + vector b(3); + + for (int i = 0; i < 3; i++) { + int b_item = stoi(b_temp[i]); + + b[i] = b_item; + } + + vector result = compareTriplets(a, b); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/HelloWorld/HanoiTower.c b/HelloWorld/HanoiTower.c index d21e04bf..7f20ee5b 100644 --- a/HelloWorld/HanoiTower.c +++ b/HelloWorld/HanoiTower.c @@ -1,21 +1,21 @@ -#include - -// C recursive function to solve tower of hanoi puzzle -void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) -{ - if (n == 1) - { - printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); - return; - } - towerOfHanoi(n-1, from_rod, aux_rod, to_rod); - printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); - towerOfHanoi(n-1, aux_rod, to_rod, from_rod); -} - -int main() -{ - int n = 4; // Number of disks - towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods - return 0; -} +#include + +// C recursive function to solve tower of hanoi puzzle +void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) +{ + if (n == 1) + { + printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); + return; + } + towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); + towerOfHanoi(n-1, aux_rod, to_rod, from_rod); +} + +int main() +{ + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + return 0; +} diff --git a/HelloWorld/HelloWorld.html b/HelloWorld/HelloWorld.html deleted file mode 100644 index cdb392d4..00000000 --- a/HelloWorld/HelloWorld.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/HelloWorld/helloworld.php b/HelloWorld/helloworld.php index 21f83756..b30e5a0d 100644 --- a/HelloWorld/helloworld.php +++ b/HelloWorld/helloworld.php @@ -1,3 +1,3 @@ - \ No newline at end of file diff --git a/LeetCode/First_and_last_sorted_array.java b/LeetCode/First_and_last_sorted_array.java index 3fea98c5..1c24da0f 100644 --- a/LeetCode/First_and_last_sorted_array.java +++ b/LeetCode/First_and_last_sorted_array.java @@ -1,34 +1,34 @@ -/* Problem 34. Find First and Last Position of Element in Sorted Array - * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. - * - * Your algorithm's runtime complexity must be in the order of O(log n). - * - * If the target is not found in the array, return [-1, -1]. - */ - -public class First_and_last_sorted_array { - public int[] searchRange(int[] nums, int target) { - int[] targetRange = {-1, -1}; - - for(int i = 0; i=0; i--){ - if(nums[i] == target){ - targetRange[1] = i; - break; - } - } - - return targetRange; - - } -} +/* Problem 34. Find First and Last Position of Element in Sorted Array + * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. + * + * Your algorithm's runtime complexity must be in the order of O(log n). + * + * If the target is not found in the array, return [-1, -1]. + */ + +public class First_and_last_sorted_array { + public int[] searchRange(int[] nums, int target) { + int[] targetRange = {-1, -1}; + + for(int i = 0; i=0; i--){ + if(nums[i] == target){ + targetRange[1] = i; + break; + } + } + + return targetRange; + + } +} From c6a66cc5a89bc29f3c77c74b87e91e53ee9fff9b Mon Sep 17 00:00:00 2001 From: "equinox.bot" <9652305+turtlejump@users.noreply.github.com> Date: Wed, 30 Oct 2019 14:16:03 +0800 Subject: [PATCH 273/324] Add HR Sherlock and Anagrams python solution Sherlock and Anagrams: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ Reference issue #26 --- Hackerrank/Python/sherlockAndAnagrams.py | 47 ++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Hackerrank/Python/sherlockAndAnagrams.py diff --git a/Hackerrank/Python/sherlockAndAnagrams.py b/Hackerrank/Python/sherlockAndAnagrams.py new file mode 100644 index 00000000..e99e3ad1 --- /dev/null +++ b/Hackerrank/Python/sherlockAndAnagrams.py @@ -0,0 +1,47 @@ +#Author: turtlejump +#Issue: Sherlock and Anagrams: https://www.hackerrank.com/challenges/sherlock-and-anagrams/ + +#!/bin/python3 + +import math +import os +import random +import re +import sys +from string import ascii_lowercase +# Complete the sherlockAndAnagrams function below. + +def sherlockAndAnagrams(s): + ALPHABET = ascii_lowercase + + sigs = {} + + sig = [0 for _ in ALPHABET] + for letter in s: + sig[ord(letter) - ord(ALPHABET[0])] += 1 + + for i in range(len(s)): + for j in range(i, len(s)): + sig = [0 for _ in ALPHABET] + for letter in s[i:j+1]: + sig[ord(letter) - ord(ALPHABET[0])] += 1 + sig = tuple(sig) + sigs[sig] = sigs.get(sig, 0) + 1 + res = 0 + for count in sigs.values(): + res += count * (count - 1)/2 + return int(res) + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + q = int(input()) + + for q_itr in range(q): + s = input() + + result = sherlockAndAnagrams(s) + + fptr.write(str(result) + '\n') + + fptr.close() From 3f112407929cd83eb7d7c9354d5dd9352478bf92 Mon Sep 17 00:00:00 2001 From: ShadowFax1731 Date: Wed, 30 Oct 2019 12:04:44 +0530 Subject: [PATCH 274/324] Added solutions for Staircase and Divisible Sum Pairs problem --- Algorithms/C++/BozoSort.cpp | 84 +-- Algorithms/C++/cNode.cpp | 74 +- Algorithms/C++/cNode.h | 34 +- Algorithms/C++/cQue.cpp | 184 ++--- Algorithms/C++/cQue.h | 36 +- Algorithms/JavaScript/MergeSort.js | 18 - Algorithms/JavaScript/leastCommonMultiple.js | 32 +- Algorithms/PHP/fibonacci.php | 24 +- Algorithms/PHP/kadanealgo.php | 42 +- Algorithms/PHP/primeNumbers.php | 30 +- Algorithms/Python/mergesort.py | 70 +- Codechef/DIFNEIGH.cpp | 264 +++---- Codechef/EARTSEQ.cpp | 98 +-- Codechef/EVENEDGES.cpp | 0 Codechef/MARM.cpp | 0 Codechef/MAXLIS(CHALLENGE).cpp | 0 Codechef/MSNG.py | 0 Codechef/MSV.cpp | 0 Codechef/SAKTAN.cpp | 0 Codechef/SALARY.cpp | 94 +-- Codechef/XYPIZQ.cpp | 100 +-- Codeforces/1237A.cpp | 112 +-- DS/C++/QueueWithDoublyLL.cpp | 214 +++--- DS/C++/Stack Using Array.txt | 124 ++-- DS/C++/queueCpp.cpp | 154 ++-- DS/C/avl_tree.c | 0 DS/Linked_List/linked_list.s | 688 +++++++++--------- Hackerearth/Acronym.cpp | 88 +-- Hackerearth/Arania Exumai Blast.cpp | 74 +- Hackerearth/Battle of Words.cpp | 122 ++-- Hackerearth/Max Profit.cpp | 70 +- Hackerearth/Old and Cold Numbers.cpp | 66 +- Hackerearth/Palindromic Grid.cpp | 180 ++--- Hackerrank/C++/BirthdayCakeCandles.cpp | 154 ++-- Hackerrank/C++/CompareTheTriplets.cpp | 19 - Hackerrank/C++/DiagonalDifference.cpp | 212 +++--- Hackerrank/C++/inputOutput.cpp | 30 +- Hackerrank/C++/insertNodeSpecificPosition.cpp | 182 ++--- Hackerrank/C++/insertNodeTailLinkedList.cpp | 138 ++-- Hackerrank/C++/mapsSTL.cpp | 76 +- Hackerrank/C++/printLinkedList.cpp | 136 ++-- Hackerrank/C++/sayHelloWorld.cpp | 18 +- Hackerrank/C++/solveMeFirst.cpp | 42 +- Hackerrank/C/Counting Sort 2.cpp | 294 ++++---- Hackerrank/C/Grid Challenge.cpp | 250 +++---- Hackerrank/C/Priyanka And Toys.cpp | 192 ++--- Hackerrank/Java/DivisibleSumPairs.java | 31 + Hackerrank/Java/Staircase.java | 29 + Hackerrank/Python/Python | 0 Hackerrank/Python/Python: Division.py | 8 - Hackerrank/Python/Time_Conversion.py | 68 +- Hackerrank/Python/What's Your Name?.py | 9 - Hackerrank/compareTheTriplets.cpp | 216 +++--- HelloWorld/HanoiTower.c | 42 +- HelloWorld/HelloWorld.html | 13 - HelloWorld/helloworld.php | 4 +- LeetCode/First_and_last_sorted_array.java | 68 +- 57 files changed, 2650 insertions(+), 2657 deletions(-) delete mode 100644 Algorithms/JavaScript/MergeSort.js mode change 100755 => 100644 Algorithms/Python/mergesort.py mode change 100755 => 100644 Codechef/EVENEDGES.cpp mode change 100755 => 100644 Codechef/MARM.cpp mode change 100755 => 100644 Codechef/MAXLIS(CHALLENGE).cpp mode change 100755 => 100644 Codechef/MSNG.py mode change 100755 => 100644 Codechef/MSV.cpp mode change 100755 => 100644 Codechef/SAKTAN.cpp mode change 100755 => 100644 DS/C/avl_tree.c mode change 100755 => 100644 DS/Linked_List/linked_list.s delete mode 100644 Hackerrank/C++/CompareTheTriplets.cpp create mode 100644 Hackerrank/Java/DivisibleSumPairs.java create mode 100644 Hackerrank/Java/Staircase.java create mode 100644 Hackerrank/Python/Python delete mode 100644 Hackerrank/Python/Python: Division.py delete mode 100644 Hackerrank/Python/What's Your Name?.py delete mode 100644 HelloWorld/HelloWorld.html diff --git a/Algorithms/C++/BozoSort.cpp b/Algorithms/C++/BozoSort.cpp index 1d385941..f5ce480e 100644 --- a/Algorithms/C++/BozoSort.cpp +++ b/Algorithms/C++/BozoSort.cpp @@ -1,43 +1,43 @@ -#include -#include -using namespace std; - -bool ifsorted(int* tab, int size) -{ - bool sorted = false; - for (int i = 1; i < size; i++) - { - if (tab[i - 1] <= tab[i]) sorted = true; - else return false; - } - return sorted; -} - -int main() // bozo sort -{ - srand(time(NULL)); - bool sorted = false; - int size = 0; - //long long int counter = 0; - cin >> size; - - int* tab = new int[size]; - - for (int i = 0; i < size; i++) - cin >> tab[i]; - - cout << endl; - while (!sorted) - { - int x = rand() % size; - int y = rand() % size; - int temp = tab[x]; - tab[x] = tab[y]; - tab[y] = temp; - sorted = ifsorted(tab, size); - //counter++; - } - //for (int i = 0; i < size; i++) - // cout << tab[i] << endl; - //cout << endl << endl << counter; +#include +#include +using namespace std; + +bool ifsorted(int* tab, int size) +{ + bool sorted = false; + for (int i = 1; i < size; i++) + { + if (tab[i - 1] <= tab[i]) sorted = true; + else return false; + } + return sorted; +} + +int main() // bozo sort +{ + srand(time(NULL)); + bool sorted = false; + int size = 0; + //long long int counter = 0; + cin >> size; + + int* tab = new int[size]; + + for (int i = 0; i < size; i++) + cin >> tab[i]; + + cout << endl; + while (!sorted) + { + int x = rand() % size; + int y = rand() % size; + int temp = tab[x]; + tab[x] = tab[y]; + tab[y] = temp; + sorted = ifsorted(tab, size); + //counter++; + } + //for (int i = 0; i < size; i++) + // cout << tab[i] << endl; + //cout << endl << endl << counter; } \ No newline at end of file diff --git a/Algorithms/C++/cNode.cpp b/Algorithms/C++/cNode.cpp index 42cf283b..d5ccb03e 100644 --- a/Algorithms/C++/cNode.cpp +++ b/Algorithms/C++/cNode.cpp @@ -1,37 +1,37 @@ -#include -#include "cNode.h" - -using namespace std; - -cNode::cNode() :data(0),priority(0) -{ -} - -cNode::cNode(int d):data(d), priority(0){ -} - -cNode::cNode(int d, int p):data(d), priority(p) -{} - -int cNode::getData(){ - return data; - } - -cNode* cNode::setData(int data){ - this->data=data; - } - -void cNode::print()const{ - cout<priority=Prior; -} - -cNode::~cNode() -{ -} +#include +#include "cNode.h" + +using namespace std; + +cNode::cNode() :data(0),priority(0) +{ +} + +cNode::cNode(int d):data(d), priority(0){ +} + +cNode::cNode(int d, int p):data(d), priority(p) +{} + +int cNode::getData(){ + return data; + } + +cNode* cNode::setData(int data){ + this->data=data; + } + +void cNode::print()const{ + cout<priority=Prior; +} + +cNode::~cNode() +{ +} diff --git a/Algorithms/C++/cNode.h b/Algorithms/C++/cNode.h index c6841970..454e83c7 100644 --- a/Algorithms/C++/cNode.h +++ b/Algorithms/C++/cNode.h @@ -1,17 +1,17 @@ -class cNode -{ - int data; - int priority; -public: - cNode *next; - cNode(); - cNode(int d); - cNode(int d, int p); - int getData(); - cNode* setData(int data); - void print()const; - int getPriority() const; - void setPriority(int prior); - ~cNode(); -}; - +class cNode +{ + int data; + int priority; +public: + cNode *next; + cNode(); + cNode(int d); + cNode(int d, int p); + int getData(); + cNode* setData(int data); + void print()const; + int getPriority() const; + void setPriority(int prior); + ~cNode(); +}; + diff --git a/Algorithms/C++/cQue.cpp b/Algorithms/C++/cQue.cpp index ee22428e..a49487b0 100644 --- a/Algorithms/C++/cQue.cpp +++ b/Algorithms/C++/cQue.cpp @@ -1,92 +1,92 @@ -#include -#include "cQue.h" - -using namespace std; - -cQue::cQue():tail(NULL) -{ -} - -cQue::cQue(cNode* &ptr):cStack(ptr),tail(top){ - } - -bool cQue::isNotEmpty()const{ - return cStack::isNotEmpty(); - } - -bool cQue::isEmpty()const{ - return cStack::isEmpty(); - } - -cNode* cQue::remove(){ - if(!top->next) - tail=NULL; - return cStack::pop(); - } - -cQue& cQue::add(cNode* &ptr){ - if(tail){ - tail->next=ptr; - tail=tail->next; - } - else - { - tail=ptr; - top=ptr; - } - tail->next=NULL; - ptr=NULL; - return *this; - } - -void cQue::print()const{ // - cStack::print(); - } - -cQue::cQue(const cQue &src){ /// - this->top=src.top; - this->tail=src.tail; - if(src.top){ - cNode *sptr,*dptr; - dptr=top=new cNode(*src.top); - sptr=top->next; - while(sptr){ - dptr->next=new cNode(*sptr); - dptr=dptr->next; - sptr=sptr->next; - } - tail=dptr; - } - } - -cQue& cQue::operator=(const cQue& obj){ - if(this==&obj) - return *this; - if(true){ - cQue temp; - temp.top=top; - temp.tail=tail; - } - if(true){ - cQue temp=obj; - top=temp.top; - tail=temp.tail; - temp.top=NULL; - temp.tail=NULL; - } - return *this; - } - -cQue::~cQue() -{ - cNode *ptr = top; - - tail = NULL; - - while (ptr) - { - ptr = ptr -> next; - delete top; - top = ptr; - } -} +#include +#include "cQue.h" + +using namespace std; + +cQue::cQue():tail(NULL) +{ +} + +cQue::cQue(cNode* &ptr):cStack(ptr),tail(top){ + } + +bool cQue::isNotEmpty()const{ + return cStack::isNotEmpty(); + } + +bool cQue::isEmpty()const{ + return cStack::isEmpty(); + } + +cNode* cQue::remove(){ + if(!top->next) + tail=NULL; + return cStack::pop(); + } + +cQue& cQue::add(cNode* &ptr){ + if(tail){ + tail->next=ptr; + tail=tail->next; + } + else + { + tail=ptr; + top=ptr; + } + tail->next=NULL; + ptr=NULL; + return *this; + } + +void cQue::print()const{ // + cStack::print(); + } + +cQue::cQue(const cQue &src){ /// + this->top=src.top; + this->tail=src.tail; + if(src.top){ + cNode *sptr,*dptr; + dptr=top=new cNode(*src.top); + sptr=top->next; + while(sptr){ + dptr->next=new cNode(*sptr); + dptr=dptr->next; + sptr=sptr->next; + } + tail=dptr; + } + } + +cQue& cQue::operator=(const cQue& obj){ + if(this==&obj) + return *this; + if(true){ + cQue temp; + temp.top=top; + temp.tail=tail; + } + if(true){ + cQue temp=obj; + top=temp.top; + tail=temp.tail; + temp.top=NULL; + temp.tail=NULL; + } + return *this; + } + +cQue::~cQue() +{ + cNode *ptr = top; + + tail = NULL; + + while (ptr) + { + ptr = ptr -> next; + delete top; + top = ptr; + } +} diff --git a/Algorithms/C++/cQue.h b/Algorithms/C++/cQue.h index 5b536ca9..91639c1f 100644 --- a/Algorithms/C++/cQue.h +++ b/Algorithms/C++/cQue.h @@ -1,18 +1,18 @@ -#pragma once -#include"cStack.h" -class cQue:protected cStack{ -protected: - cNode *tail; -public: - cQue(); - cQue(cNode* &ptr); - bool isNotEmpty()const; - bool isEmpty()const; - cNode* remove(); - cQue& add(cNode* &ptr); - void print()const; - cQue(const cQue &src); - cQue& operator=(const cQue& obj); - ~cQue(); -}; - +#pragma once +#include"cStack.h" +class cQue:protected cStack{ +protected: + cNode *tail; +public: + cQue(); + cQue(cNode* &ptr); + bool isNotEmpty()const; + bool isEmpty()const; + cNode* remove(); + cQue& add(cNode* &ptr); + void print()const; + cQue(const cQue &src); + cQue& operator=(const cQue& obj); + ~cQue(); +}; + diff --git a/Algorithms/JavaScript/MergeSort.js b/Algorithms/JavaScript/MergeSort.js deleted file mode 100644 index f2feaa21..00000000 --- a/Algorithms/JavaScript/MergeSort.js +++ /dev/null @@ -1,18 +0,0 @@ -function mergeSort (arr) { - if (arr.length < 2) { - return arr; - } - - var mid = Math.floor(arr.length / 2); - var subLeft = mergeSort(arr.slice(0, mid)); - var subRight = mergeSort(arr.slice(mid)); - - return merge(subLeft, subRight); -} - -function merge (node1, node2) { - var result = []; - while (node1.length > 0 && node2.length > 0) - result.push(node1[0] < node2[0] ? node1.shift() : node2.shift()); - return result.concat(node1.length ? node1 : node2); -} \ No newline at end of file diff --git a/Algorithms/JavaScript/leastCommonMultiple.js b/Algorithms/JavaScript/leastCommonMultiple.js index 27386e5f..9c4f0dea 100644 --- a/Algorithms/JavaScript/leastCommonMultiple.js +++ b/Algorithms/JavaScript/leastCommonMultiple.js @@ -1,17 +1,17 @@ -const leastCommonMultiple = (a,b) => { - let x = a; - let y = b - while(x !== y) { - if(x>y){ - x = x - y; - } - else { - y = y - x; - } - } - return (a * b) / x; -} - -//examples -// leastCommonMultiple(2,3); +const leastCommonMultiple = (a,b) => { + let x = a; + let y = b + while(x !== y) { + if(x>y){ + x = x - y; + } + else { + y = y - x; + } + } + return (a * b) / x; +} + +//examples +// leastCommonMultiple(2,3); // leastCommonMultiple(192,348); \ No newline at end of file diff --git a/Algorithms/PHP/fibonacci.php b/Algorithms/PHP/fibonacci.php index 05d7b247..70fff1fd 100644 --- a/Algorithms/PHP/fibonacci.php +++ b/Algorithms/PHP/fibonacci.php @@ -1,12 +1,12 @@ -"; -} -?> +"; +} +?> diff --git a/Algorithms/PHP/kadanealgo.php b/Algorithms/PHP/kadanealgo.php index 1c7f1f35..fc5d3ade 100644 --- a/Algorithms/PHP/kadanealgo.php +++ b/Algorithms/PHP/kadanealgo.php @@ -1,22 +1,22 @@ - \ No newline at end of file diff --git a/Algorithms/PHP/primeNumbers.php b/Algorithms/PHP/primeNumbers.php index 9f716017..2e2b6f5e 100644 --- a/Algorithms/PHP/primeNumbers.php +++ b/Algorithms/PHP/primeNumbers.php @@ -1,15 +1,15 @@ -1;$x--) - { - if($i%$x==0) - { - $o=false; - break; - } - } - if($o) echo $i."
"; -} -?> +1;$x--) + { + if($i%$x==0) + { + $o=false; + break; + } + } + if($o) echo $i."
"; +} +?> diff --git a/Algorithms/Python/mergesort.py b/Algorithms/Python/mergesort.py old mode 100755 new mode 100644 index 88cdd7d8..75af1fd7 --- a/Algorithms/Python/mergesort.py +++ b/Algorithms/Python/mergesort.py @@ -1,36 +1,36 @@ -def merge(left, right): - li, ri = 0, 0 - retval = [] - while li < len(left) and ri < len(right): - if left[li] < right[ri]: - retval.append(left[li]) - li += 1 - else: - retval.append(right[ri]) - ri += 1 - - retval += left[li:] - retval += right[ri:] - return retval - - -def merge_sort(array): - # base case - if len(array) <= 1: - return array - - # divide array in half and do recursion - half = len(array) // 2 - left = merge_sort(array[:half]) - right = merge_sort(array[half:]) - - return merge(left, right) - - -def sort(): - list = [5, 7, 6, 2, 1, 7, 3] - sorted_list = merge_sort(list) - print 'Array after sorting: ', sorted_list - -if __name__ == '__main__': +def merge(left, right): + li, ri = 0, 0 + retval = [] + while li < len(left) and ri < len(right): + if left[li] < right[ri]: + retval.append(left[li]) + li += 1 + else: + retval.append(right[ri]) + ri += 1 + + retval += left[li:] + retval += right[ri:] + return retval + + +def merge_sort(array): + # base case + if len(array) <= 1: + return array + + # divide array in half and do recursion + half = len(array) // 2 + left = merge_sort(array[:half]) + right = merge_sort(array[half:]) + + return merge(left, right) + + +def sort(): + list = [5, 7, 6, 2, 1, 7, 3] + sorted_list = merge_sort(list) + print 'Array after sorting: ', sorted_list + +if __name__ == '__main__': sort() \ No newline at end of file diff --git a/Codechef/DIFNEIGH.cpp b/Codechef/DIFNEIGH.cpp index 43c3b12f..376a60b4 100644 --- a/Codechef/DIFNEIGH.cpp +++ b/Codechef/DIFNEIGH.cpp @@ -1,133 +1,133 @@ -#include -using namespace std; - -int main(){ - int t; - int a[50][50]; - int i,j,k; - for(k=0;k<50;k++){ - if(k%2==0){ - for(i=k;i<50;i++){ - if((i-k)%4==0||(i-k)%4==1) - a[k][i]=1; - else - a[k][i]=2; - } - for(i=k+1;i<50;i++){ - if((i-k)%4==1||(i-k)%4==2) - a[i][k]=2; - else - a[i][k]=1; - } - } - else{ - for(i=k;i<50;i++){ - if((i-k)%4==0||(i-k)%4==1) - a[k][i]=3; - else - a[k][i]=4; - } - for(i=k+1;i<50;i++){ - if((i-k)%4==1||(i-k)%4==2) - a[i][k]=4; - else - a[i][k]=3; - } - - } - } - cin>>t; - while(t--){ - int n,m,mod; - cin>>n>>m; - // int a[n][m]; - //int i,j; - if(n>=3&&m>=3){ - cout<<4< +using namespace std; + +int main(){ + int t; + int a[50][50]; + int i,j,k; + for(k=0;k<50;k++){ + if(k%2==0){ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=1; + else + a[k][i]=2; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=2; + else + a[i][k]=1; + } + } + else{ + for(i=k;i<50;i++){ + if((i-k)%4==0||(i-k)%4==1) + a[k][i]=3; + else + a[k][i]=4; + } + for(i=k+1;i<50;i++){ + if((i-k)%4==1||(i-k)%4==2) + a[i][k]=4; + else + a[i][k]=3; + } + + } + } + cin>>t; + while(t--){ + int n,m,mod; + cin>>n>>m; + // int a[n][m]; + //int i,j; + if(n>=3&&m>=3){ + cout<<4< -using namespace std; -long long maxi=1000000000; - -int main(){ - int i,j,a[(int)1e6+3]={0}; - vector v; - for(i=2;i*i<=1000001;i++){ - if(a[i]==0){ - //v.push_back(i); - for(j=i*i;j<=1000000;j+=i){ - a[j]=i; - } - - } - } - for(i=2;i<1000001;i++){ - if(a[i]==0) - v.push_back(i); - } - int t; - cin>>t; - while(t--) - { - int n,k,l; - cin>>n; - - long long ans; - //cout<2999) - l=l-2999; - // cout< +using namespace std; +long long maxi=1000000000; + +int main(){ + int i,j,a[(int)1e6+3]={0}; + vector v; + for(i=2;i*i<=1000001;i++){ + if(a[i]==0){ + //v.push_back(i); + for(j=i*i;j<=1000000;j+=i){ + a[j]=i; + } + + } + } + for(i=2;i<1000001;i++){ + if(a[i]==0) + v.push_back(i); + } + int t; + cin>>t; + while(t--) + { + int n,k,l; + cin>>n; + + long long ans; + //cout<2999) + l=l-2999; + // cout< -#include -using namespace std; -int main() -{ - // slmax second last maximum - int t,slmax,max,index,it=0,min; - cin>>t; - while(t--) - { - int n,toadd,it=0; - cin>>n; - int a[n]; - for(int i=0;i>a[i]; - sort(a,a+n); - min=a[0]; - while(a[0]!=a[n-1]) - { - // max is last element - max=a[n-1]; - // second last element - index=n-2; - // find second last max - while(a[index]==max) - { - index--; - } - toadd=max-a[index]; - it=it+toadd; - for(int i=0;i +#include +using namespace std; +int main() +{ + // slmax second last maximum + int t,slmax,max,index,it=0,min; + cin>>t; + while(t--) + { + int n,toadd,it=0; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + sort(a,a+n); + min=a[0]; + while(a[0]!=a[n-1]) + { + // max is last element + max=a[n-1]; + // second last element + index=n-2; + // find second last max + while(a[index]==max) + { + index--; + } + toadd=max-a[index]; + it=it+toadd; + for(int i=0;i -using namespace std; -long long maxi=1000000000; -#define l long - -int main(){ - int t; - cin>>t; - while(t--){ - long n,k,x,y,z; - long i,j,gcd; - cin>>n>>k>>x>>y>>z; - long p,q; - q=2*n +1; - if(x==z){ - p=x; - gcd=__gcd(p,q); - cout<

y&&y>x){ - if(k==1) - {p=q-z;} - else if(k==2||k==4){ - p=q-2*y; - } - else{ - p=q-x; - - } - gcd=__gcd(p,q); - cout<

+using namespace std; +long long maxi=1000000000; +#define l long + +int main(){ + int t; + cin>>t; + while(t--){ + long n,k,x,y,z; + long i,j,gcd; + cin>>n>>k>>x>>y>>z; + long p,q; + q=2*n +1; + if(x==z){ + p=x; + gcd=__gcd(p,q); + cout<

y&&y>x){ + if(k==1) + {p=q-z;} + else if(k==2||k==4){ + p=q-2*y; + } + else{ + p=q-x; + + } + gcd=__gcd(p,q); + cout<

-using namespace std; - -int main(){ - int n; cin>>n; - int a[n]; - int orig[n]; - float temp; - int sum = 0; - for(int i =0; i>temp; - orig[n] = temp; - if((int)temp%2==0){ - a[i] = temp/2; - } - else{ - temp = temp/2.0; - temp += 0.5; - a[i] = (int)temp; - } - sum+=a[i]; - } - int change=1; - if(sum>0){ - for(int i =0; i0){ - a[i] -=1; - sum -=1; - } - cout<0 - for(int i =0; i0){ - // a[i] +=1; //adding 1 to ceil is wrong - // sum +=1; - //} - cout< +using namespace std; + +int main(){ + int n; cin>>n; + int a[n]; + int orig[n]; + float temp; + int sum = 0; + for(int i =0; i>temp; + orig[n] = temp; + if((int)temp%2==0){ + a[i] = temp/2; + } + else{ + temp = temp/2.0; + temp += 0.5; + a[i] = (int)temp; + } + sum+=a[i]; + } + int change=1; + if(sum>0){ + for(int i =0; i0){ + a[i] -=1; + sum -=1; + } + cout<0 + for(int i =0; i0){ + // a[i] +=1; //adding 1 to ceil is wrong + // sum +=1; + //} + cout< -using namespace std; -class Node -{ -public: - int data ; - Node *next = NULL; - Node *prev = NULL; - Node(int data) - { - this->data = data ; - } -}; -class Queue -{ - Node* front = NULL; - Node* rear = NULL; - int size = 0 ; - public : - void enqueue(int data) - { - Node *new_node = new Node(data) ; - if(front == NULL) - { - front = new_node; - rear = new_node ; - } - else - { - rear->next = new_node ; - new_node->prev = rear ; - rear = new_node ; - } - size++; - } - void dequeue() - { - if(front == NULL) - { - cout<<"Queue is Already Empty !"<next ; - x->next = NULL ; - x->prev = NULL ; - if(front != NULL) - front->prev = NULL ; - delete x ; - size-- ; - } - } - bool isEmpty() - { - if(size == 0) - return true ; - else - return false ; - } - int Size() - { - return size ; - } - int Front() - { - if(front == NULL || size == 0) - { - cout<<"Queue is Empty"<data ; - } - } - void print() - { - Node *temp = front ; - while(temp != NULL) - { - cout<data<<" "; - temp = temp->next ; - } - cout< +using namespace std; +class Node +{ +public: + int data ; + Node *next = NULL; + Node *prev = NULL; + Node(int data) + { + this->data = data ; + } +}; +class Queue +{ + Node* front = NULL; + Node* rear = NULL; + int size = 0 ; + public : + void enqueue(int data) + { + Node *new_node = new Node(data) ; + if(front == NULL) + { + front = new_node; + rear = new_node ; + } + else + { + rear->next = new_node ; + new_node->prev = rear ; + rear = new_node ; + } + size++; + } + void dequeue() + { + if(front == NULL) + { + cout<<"Queue is Already Empty !"<next ; + x->next = NULL ; + x->prev = NULL ; + if(front != NULL) + front->prev = NULL ; + delete x ; + size-- ; + } + } + bool isEmpty() + { + if(size == 0) + return true ; + else + return false ; + } + int Size() + { + return size ; + } + int Front() + { + if(front == NULL || size == 0) + { + cout<<"Queue is Empty"<data ; + } + } + void print() + { + Node *temp = front ; + while(temp != NULL) + { + cout<data<<" "; + temp = temp->next ; + } + cout< -using namespace std; -int stack[100], n=100, top=-1; -void push(int val) { - if(top>=n-1) - cout<<"Stack Overflow"<=0) { - cout<<"Stack elements are:"; - for(int i=top; i>=0; i--) - cout<>ch; - switch(ch) { - case 1: { - cout<<"Enter value to be pushed:"<>val; - push(val); - break; - } - case 2: { - pop(); - break; - } - case 3: { - display(); - break; - } - case 4: { - cout<<"Exit"< +using namespace std; +int stack[100], n=100, top=-1; +void push(int val) { + if(top>=n-1) + cout<<"Stack Overflow"<=0) { + cout<<"Stack elements are:"; + for(int i=top; i>=0; i--) + cout<>ch; + switch(ch) { + case 1: { + cout<<"Enter value to be pushed:"<>val; + push(val); + break; + } + case 2: { + pop(); + break; + } + case 3: { + display(); + break; + } + case 4: { + cout<<"Exit"< -using namespace std; - -struct queue -{ - int value; - queue *next; -}; - -void removeFromQueue(queue*& head) // remove first element from queue -{ - if (head) - { - queue* ptr = head->next; - delete head; - head = ptr; - } -} - -void addToQueue(queue*& head, int nValue) // add new value to queue -{ - if (head == nullptr) // first element - { - head = new queue; - head->value = nValue; - head->next = nullptr; - } - else // add element on the end of the queue - { - auto ptr = head; - while (ptr->next) - { - ptr = ptr->next; - } - ptr->next = new queue{ nValue, nullptr }; - } -} - -void deleteQueue(queue *&head) // delete queue -{ - while (head) - { - auto ptr = head->next; - delete head; - head = ptr; - } -} - -void printQueue(queue *head) -{ - while (head) - { - cout << head->value << endl; - head = head->next; - } -} - -int main() -{ - // TEST - queue* pHead = nullptr; - addToQueue(pHead, 231); - addToQueue(pHead, 121); - addToQueue(pHead, 251); - addToQueue(pHead, 12); - addToQueue(pHead, 14); - addToQueue(pHead, 99); - printQueue(pHead); - removeFromQueue(pHead); - removeFromQueue(pHead); - removeFromQueue(pHead); - printQueue(pHead); - deleteQueue(pHead); - - - -} +#include +using namespace std; + +struct queue +{ + int value; + queue *next; +}; + +void removeFromQueue(queue*& head) // remove first element from queue +{ + if (head) + { + queue* ptr = head->next; + delete head; + head = ptr; + } +} + +void addToQueue(queue*& head, int nValue) // add new value to queue +{ + if (head == nullptr) // first element + { + head = new queue; + head->value = nValue; + head->next = nullptr; + } + else // add element on the end of the queue + { + auto ptr = head; + while (ptr->next) + { + ptr = ptr->next; + } + ptr->next = new queue{ nValue, nullptr }; + } +} + +void deleteQueue(queue *&head) // delete queue +{ + while (head) + { + auto ptr = head->next; + delete head; + head = ptr; + } +} + +void printQueue(queue *head) +{ + while (head) + { + cout << head->value << endl; + head = head->next; + } +} + +int main() +{ + // TEST + queue* pHead = nullptr; + addToQueue(pHead, 231); + addToQueue(pHead, 121); + addToQueue(pHead, 251); + addToQueue(pHead, 12); + addToQueue(pHead, 14); + addToQueue(pHead, 99); + printQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + removeFromQueue(pHead); + printQueue(pHead); + deleteQueue(pHead); + + + +} diff --git a/DS/C/avl_tree.c b/DS/C/avl_tree.c old mode 100755 new mode 100644 diff --git a/DS/Linked_List/linked_list.s b/DS/Linked_List/linked_list.s old mode 100755 new mode 100644 index c80baf84..3130391f --- a/DS/Linked_List/linked_list.s +++ b/DS/Linked_List/linked_list.s @@ -1,344 +1,344 @@ - .data -descriptor: .space 12 -theBucket: .space 80 -printMenu: .asciiz "\n1 - Insert element in the list\n2 - Update/Remove\n3 - Radix sort\n4 - Print list\n5 - Exit\nOption: " -askValue: .asciiz "\nType a value: " -whatDo: .asciiz "\nUpdate or remove? [0] Update / [1] Remove: " -newValue: .asciiz "\nType a new value: " -askIndex: .asciiz "\nType the index of element: " -msg_Inval: .asciiz "\nInvalid option\n" -msg_empty: .asciiz "\nEmpty list\n" -charEnter: .asciiz "\n" -openSquareBrac: .asciiz "Index [" -end_SquareBrac: .asciiz "] = " - .text - -main: - la $s0, descriptor - sw $zero, 0($s0) - sw $zero, 4($s0) - sw $zero, 8($s0) - move $s1, $zero - -menuOp: - li $v0, 4 - la $a0, printMenu - syscall - - li $v0, 5 - syscall - - beq $v0, 1, insert_element - beq $v0, 2, search - beq $v0, 3, order - beq $v0, 4, show_list - beq $v0, 5, exit - - j showInvalid - -insert_element: - li $v0, 4 - la $a0, askValue - syscall - - li $v0, 5 - syscall - move $t0, $v0 - - li $v0, 9 - addi $a0, $zero, 12 - syscall - - lw $t1, 4($s0) - addi $t1, $t1, 1 - sw $t1, 4($s0) - - sw $t0, 4($v0) - sw $zero, 8($v0) - - lw $s1, 8($s0) - bne $s1, $zero, insertEnd - sw $v0, 0($s0) - -insertEnd: - sw $v0, 8($s0) - sw $s1, 0($v0) - beq $s1, $zero, return - sw $v0, 8($s1) - b return - -search: - li $v0, 4 - la $a0, askIndex - syscall - li $v0, 5 - syscall - lw $t1, 0($s0) - lw $t0, 4($s0) - addi $t2, $zero, -1 - blt $v0, $t0, loop_search - li $v0, 4 - la $a0, msg_Inval - syscall - - b return - -loop_search: - move $t0, $t1 - lw $t1, 8($t1) - addi $t2, $t2, 1 - blt $t2, $v0, loop_search - - li $v0, 4 - la $a0, whatDo - syscall - - li $v0, 5 - syscall - - beq $v0, 1, remove_element - bne $v0, $zero, showInvalid - - li $v0, 4 - la $a0, newValue - syscall - - li $v0, 5 - syscall - - sw $v0, 4($t0) - b return - -remove_element: - lw $t7, 4($s0) - addi $t7, $t7, -1 - sw $t7, 4($s0) - lw $t2, 0($t0) - lw $t3, 8($t0) - beq $t2, $zero, remove_first - beq $t3, $zero, remove_last - sw $t2, 0($t3) - sw $t3, 8($t2) - - b return -remove_first: - sw $t3, 0($s0) - beq $t3, $zero, main - sw $zero, 0($t3) - - b return - -remove_last: - sw $t2, 8($s0) - beq $t2, $zero, main - sw $zero, 8($t2) - - b return - -show_list: - lw $s1, 0($s0) - beq $s1, $zero, emptyList - move $t0, $zero - -loop: - lw $t1, 4($s1) - - li $v0, 4 - la $a0, charEnter - syscall - - li $v0, 4 - la $a0, openSquareBrac - syscall - - li $v0, 1 - move $a0, $t0 - syscall - - li $v0, 4 - la $a0, end_SquareBrac - syscall - - li $v0, 1 - move $a0, $t1 - syscall - - lw $s1, 8($s1) - addi $t0, $t0, 1 - bne $s1, $zero, loop - - li $v0, 4 - la $a0, charEnter - syscall - - b return - -return: - b menuOp - - -emptyList: - li $v0, 4 - la $a0, msg_empty - syscall - j menuOp - -showInvalid: - li $v0, 4 - la $a0, msg_Inval - syscall - j menuOp - -order: - lw $t0, 4($s0) - beq $t0, $zero, emptyList - - li $t1, 4 - mult $t0, $t1 - mflo $t0 - sub $sp, $sp, $t0 - - move $s1, $sp - lw $a0, 0($s0) - jal searchBigger - - move $s4, $v0 - li $t1, 1 - -radix: - jal cleanBucket - - lw $t0, 0($s0) - la $s2, theBucket - addi $s2, $s2, 40 - li $t2, 10 - li $t4, 4 - - bgt $t1, $s4, disaloc - -fillBucket: - jal accessBucket - - lw $t3, 0($v1) - - addi $t3, $t3, 1 - sw $t3, 0($v1) - - lw $t0, 8($t0) - - bne $t0, $zero, fillBucket - - la $t0, theBucket - lw $t6, 0($t0) - addi $t0, $t0, 4 - li $t5, 1 - -sum_buckets: - lw $t7, 0($t0) - add $t6, $t6, $t7 - sw $t6, 0($t0) - addi $t0, $t0, 4 - addi $t5, $t5, 1 - blt $t5, 20, sum_buckets - - lw $t0, 8($s0) - -fill_aux: - jal accessBucket - - lw $t3, 0($v1) - - addi $t3, $t3, -1 - sw $t3, 0($v1) - - mult $t3, $t4 - mflo $t3 - sub $t3, $s1, $t3 - - lw $t5, 4($t0) - sw $t5, 0($t3) - lw $t0, 0($t0) - bne $t0, $zero, fill_aux - - lw $t0, 0($s0) - lw $t5, 4($s0) - li $t2, 0 - move $t3, $s1 - -fill_list: - lw $t4, 0($t3) - sw $t4, 4($t0) - lw $t0, 8($t0) - - addi $t3, $t3, -4 - addi $t2, $t2, 1 - - blt $t2, $t5, fill_list - mult $t5, $t2 - mflo $t5 - - li $t2, 10 - mult $t2, $t1 - mflo $t1 - - b radix - -accessBucket: - lw $t3, 4($t0) - div $t3, $t1 - mflo $t3 - - div $t3, $t2 - mfhi $t3 - - mult $t4, $t3 - mflo $t3 - - add $v1, $s2, $t3 - jr $ra - -searchBigger: - li $t7, -1 - lw $t0, 4($a0) - mult $t0, $t7 - mflo $t6 - bgt $t6, $t0, isBigger - -loopMaior: - lw $a0, 8($a0) - beq $a0, $zero, endList - lw $t6, 4($a0) - bgt $t6, $t0, isBigger - mult $t6, $t7 - mflo $t6 - bgt $t6, $t0, isBigger - b loopMaior -isBigger: - move $t0, $t6 - b loopMaior -endList: - move $v0, $t0 - jr $ra - -cleanBucket: - la $s6, theBucket - move $s7, $zero -loopBucket: - sw $zero, 0($s6) - addi $s7, $s7, 1 - addi $s6, $s6, 4 - blt $s7, 20, loopBucket - jr $ra - -disaloc: - lw $t7, 4($s0) - li $t4, 4 - mult $t4, $t7 - mflo $t7 - add $sp, $sp, $t7 - - b return - -exit: - li $v0, 10 - syscall + .data +descriptor: .space 12 +theBucket: .space 80 +printMenu: .asciiz "\n1 - Insert element in the list\n2 - Update/Remove\n3 - Radix sort\n4 - Print list\n5 - Exit\nOption: " +askValue: .asciiz "\nType a value: " +whatDo: .asciiz "\nUpdate or remove? [0] Update / [1] Remove: " +newValue: .asciiz "\nType a new value: " +askIndex: .asciiz "\nType the index of element: " +msg_Inval: .asciiz "\nInvalid option\n" +msg_empty: .asciiz "\nEmpty list\n" +charEnter: .asciiz "\n" +openSquareBrac: .asciiz "Index [" +end_SquareBrac: .asciiz "] = " + .text + +main: + la $s0, descriptor + sw $zero, 0($s0) + sw $zero, 4($s0) + sw $zero, 8($s0) + move $s1, $zero + +menuOp: + li $v0, 4 + la $a0, printMenu + syscall + + li $v0, 5 + syscall + + beq $v0, 1, insert_element + beq $v0, 2, search + beq $v0, 3, order + beq $v0, 4, show_list + beq $v0, 5, exit + + j showInvalid + +insert_element: + li $v0, 4 + la $a0, askValue + syscall + + li $v0, 5 + syscall + move $t0, $v0 + + li $v0, 9 + addi $a0, $zero, 12 + syscall + + lw $t1, 4($s0) + addi $t1, $t1, 1 + sw $t1, 4($s0) + + sw $t0, 4($v0) + sw $zero, 8($v0) + + lw $s1, 8($s0) + bne $s1, $zero, insertEnd + sw $v0, 0($s0) + +insertEnd: + sw $v0, 8($s0) + sw $s1, 0($v0) + beq $s1, $zero, return + sw $v0, 8($s1) + b return + +search: + li $v0, 4 + la $a0, askIndex + syscall + li $v0, 5 + syscall + lw $t1, 0($s0) + lw $t0, 4($s0) + addi $t2, $zero, -1 + blt $v0, $t0, loop_search + li $v0, 4 + la $a0, msg_Inval + syscall + + b return + +loop_search: + move $t0, $t1 + lw $t1, 8($t1) + addi $t2, $t2, 1 + blt $t2, $v0, loop_search + + li $v0, 4 + la $a0, whatDo + syscall + + li $v0, 5 + syscall + + beq $v0, 1, remove_element + bne $v0, $zero, showInvalid + + li $v0, 4 + la $a0, newValue + syscall + + li $v0, 5 + syscall + + sw $v0, 4($t0) + b return + +remove_element: + lw $t7, 4($s0) + addi $t7, $t7, -1 + sw $t7, 4($s0) + lw $t2, 0($t0) + lw $t3, 8($t0) + beq $t2, $zero, remove_first + beq $t3, $zero, remove_last + sw $t2, 0($t3) + sw $t3, 8($t2) + + b return +remove_first: + sw $t3, 0($s0) + beq $t3, $zero, main + sw $zero, 0($t3) + + b return + +remove_last: + sw $t2, 8($s0) + beq $t2, $zero, main + sw $zero, 8($t2) + + b return + +show_list: + lw $s1, 0($s0) + beq $s1, $zero, emptyList + move $t0, $zero + +loop: + lw $t1, 4($s1) + + li $v0, 4 + la $a0, charEnter + syscall + + li $v0, 4 + la $a0, openSquareBrac + syscall + + li $v0, 1 + move $a0, $t0 + syscall + + li $v0, 4 + la $a0, end_SquareBrac + syscall + + li $v0, 1 + move $a0, $t1 + syscall + + lw $s1, 8($s1) + addi $t0, $t0, 1 + bne $s1, $zero, loop + + li $v0, 4 + la $a0, charEnter + syscall + + b return + +return: + b menuOp + + +emptyList: + li $v0, 4 + la $a0, msg_empty + syscall + j menuOp + +showInvalid: + li $v0, 4 + la $a0, msg_Inval + syscall + j menuOp + +order: + lw $t0, 4($s0) + beq $t0, $zero, emptyList + + li $t1, 4 + mult $t0, $t1 + mflo $t0 + sub $sp, $sp, $t0 + + move $s1, $sp + lw $a0, 0($s0) + jal searchBigger + + move $s4, $v0 + li $t1, 1 + +radix: + jal cleanBucket + + lw $t0, 0($s0) + la $s2, theBucket + addi $s2, $s2, 40 + li $t2, 10 + li $t4, 4 + + bgt $t1, $s4, disaloc + +fillBucket: + jal accessBucket + + lw $t3, 0($v1) + + addi $t3, $t3, 1 + sw $t3, 0($v1) + + lw $t0, 8($t0) + + bne $t0, $zero, fillBucket + + la $t0, theBucket + lw $t6, 0($t0) + addi $t0, $t0, 4 + li $t5, 1 + +sum_buckets: + lw $t7, 0($t0) + add $t6, $t6, $t7 + sw $t6, 0($t0) + addi $t0, $t0, 4 + addi $t5, $t5, 1 + blt $t5, 20, sum_buckets + + lw $t0, 8($s0) + +fill_aux: + jal accessBucket + + lw $t3, 0($v1) + + addi $t3, $t3, -1 + sw $t3, 0($v1) + + mult $t3, $t4 + mflo $t3 + sub $t3, $s1, $t3 + + lw $t5, 4($t0) + sw $t5, 0($t3) + lw $t0, 0($t0) + bne $t0, $zero, fill_aux + + lw $t0, 0($s0) + lw $t5, 4($s0) + li $t2, 0 + move $t3, $s1 + +fill_list: + lw $t4, 0($t3) + sw $t4, 4($t0) + lw $t0, 8($t0) + + addi $t3, $t3, -4 + addi $t2, $t2, 1 + + blt $t2, $t5, fill_list + mult $t5, $t2 + mflo $t5 + + li $t2, 10 + mult $t2, $t1 + mflo $t1 + + b radix + +accessBucket: + lw $t3, 4($t0) + div $t3, $t1 + mflo $t3 + + div $t3, $t2 + mfhi $t3 + + mult $t4, $t3 + mflo $t3 + + add $v1, $s2, $t3 + jr $ra + +searchBigger: + li $t7, -1 + lw $t0, 4($a0) + mult $t0, $t7 + mflo $t6 + bgt $t6, $t0, isBigger + +loopMaior: + lw $a0, 8($a0) + beq $a0, $zero, endList + lw $t6, 4($a0) + bgt $t6, $t0, isBigger + mult $t6, $t7 + mflo $t6 + bgt $t6, $t0, isBigger + b loopMaior +isBigger: + move $t0, $t6 + b loopMaior +endList: + move $v0, $t0 + jr $ra + +cleanBucket: + la $s6, theBucket + move $s7, $zero +loopBucket: + sw $zero, 0($s6) + addi $s7, $s7, 1 + addi $s6, $s6, 4 + blt $s7, 20, loopBucket + jr $ra + +disaloc: + lw $t7, 4($s0) + li $t4, 4 + mult $t4, $t7 + mflo $t7 + add $sp, $sp, $t7 + + b return + +exit: + li $v0, 10 + syscall diff --git a/Hackerearth/Acronym.cpp b/Hackerearth/Acronym.cpp index 18fe7b5b..0a0690e3 100644 --- a/Hackerearth/Acronym.cpp +++ b/Hackerearth/Acronym.cpp @@ -1,44 +1,44 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -#define tc int t; cin>>t; while(t--) -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -int k; cin>>k; string s; -map m; -while(k--) -{ - cin>>s; - m[s]=1; -} -cin>>k; -while(--k) -{ - cin>>s; - if(m[s]==0) - cout<>s; -if(m[s]==0) - cout< +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int k; cin>>k; string s; +map m; +while(k--) +{ + cin>>s; + m[s]=1; +} +cin>>k; +while(--k) +{ + cin>>s; + if(m[s]==0) + cout<>s; +if(m[s]==0) + cout< -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -#define tc int t; cin>>t; while(t--) - -using namespace std; -int main() -{ -string s; -int i,count=0; -getline(cin,s); -for(i=0;i +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) + +using namespace std; +int main() +{ +string s; +int i,count=0; +getline(cin,s); +for(i=0;i -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -#define tc int t; cin>>t; while(t--) -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -tc{ -string s; -getline(cin,s); -int a[26]={0}; -fi(s.length()) -{ - if(s[i]!=' ') - a[s[i]-'a']++; -} -getline(cin,s); -fi(s.length()) -{ - if(s[i]!=' ') - a[s[i]-'a']--; -} -bool fir=false,sec=false; -fi(26) -{ - if(a[i]>0) - fir=true; - if(a[i]<0) - sec=true; -} -if(fir && sec) - cout<<"You draw some."<<"\n"; -else { - if(fir) - cout<<"You win some.\n"; - else - cout<<"You lose some.\n"; -} -} - - -return 0; -} +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +#define tc int t; cin>>t; while(t--) +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +tc{ +string s; +getline(cin,s); +int a[26]={0}; +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']++; +} +getline(cin,s); +fi(s.length()) +{ + if(s[i]!=' ') + a[s[i]-'a']--; +} +bool fir=false,sec=false; +fi(26) +{ + if(a[i]>0) + fir=true; + if(a[i]<0) + sec=true; +} +if(fir && sec) + cout<<"You draw some."<<"\n"; +else { + if(fir) + cout<<"You win some.\n"; + else + cout<<"You lose some.\n"; +} +} + + +return 0; +} diff --git a/Hackerearth/Max Profit.cpp b/Hackerearth/Max Profit.cpp index c023f3de..a5b5e0e3 100644 --- a/Hackerearth/Max Profit.cpp +++ b/Hackerearth/Max Profit.cpp @@ -1,35 +1,35 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -#define vi vector -using namespace std; - -int main() -{ -int n, ans=0; -scanf("%d", &n); -int a[n]; -for (int i=0; ians) -ans=a[i]-a[j]; -} -printf("%d\n", ans); -return 0; -} +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +#define vi vector +using namespace std; + +int main() +{ +int n, ans=0; +scanf("%d", &n); +int a[n]; +for (int i=0; ians) +ans=a[i]-a[j]; +} +printf("%d\n", ans); +return 0; +} diff --git a/Hackerearth/Old and Cold Numbers.cpp b/Hackerearth/Old and Cold Numbers.cpp index a3fb51c6..f9512b62 100644 --- a/Hackerearth/Old and Cold Numbers.cpp +++ b/Hackerearth/Old and Cold Numbers.cpp @@ -1,33 +1,33 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -int t; cin>>t; -while(t--) -{ - -} - - - -return 0; -} +//Code by Abhishek Tiwari +//Hackerearth : https://www.hackerearth.com/@become +//Github : https://github.com/becomeahacker + +#include +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--) +{ + +} + + + +return 0; +} diff --git a/Hackerearth/Palindromic Grid.cpp b/Hackerearth/Palindromic Grid.cpp index ab5ff2e1..88db7b3f 100644 --- a/Hackerearth/Palindromic Grid.cpp +++ b/Hackerearth/Palindromic Grid.cpp @@ -1,90 +1,90 @@ -//Code by Abhishek Tiwari -//Hackerearth : https://www.hackerearth.com/@become -//Github : https://github.com/becomeahacker - -#include -typedef long long int lli; -typedef long long ll; -#define pb push_back -#define pf push_front -#define mp make_pair -#define ff first -#define ss second -#define mod 1000000007 -#define fi(n) for(int i=0;i -using namespace std; - - -int main() -{ -ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); -int t; cin>>t; -while(t--){ - -int m,n; -cin>>n>>m; -int count[26]={0}; -int single = 0,pairs=0; string ent; -fi(n){cin>>ent; fj(m) ++count[ent[j]-'a'];} -fi(26) -{ - if(count[i]%2) - { - ++single; - - } - count[i]=count[i]>>1; - if(count[i]%2) - { - ++pairs; - } -} -//cout<<"P : "< +typedef long long int lli; +typedef long long ll; +#define pb push_back +#define pf push_front +#define mp make_pair +#define ff first +#define ss second +#define mod 1000000007 +#define fi(n) for(int i=0;i +using namespace std; + + +int main() +{ +ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +int t; cin>>t; +while(t--){ + +int m,n; +cin>>n>>m; +int count[26]={0}; +int single = 0,pairs=0; string ent; +fi(n){cin>>ent; fj(m) ++count[ent[j]-'a'];} +fi(26) +{ + if(count[i]%2) + { + ++single; + + } + count[i]=count[i]>>1; + if(count[i]%2) + { + ++pairs; + } +} +//cout<<"P : "< - -using namespace std; - -vector split_string(string); - -// Complete the birthdayCakeCandles function below. -int birthdayCakeCandles(vector ar) { - int max = *max_element(ar.begin(), ar.end()); - int count= 0; - for (int i =0; i> ar_count; - cin.ignore(numeric_limits::max(), '\n'); - - string ar_temp_temp; - getline(cin, ar_temp_temp); - - vector ar_temp = split_string(ar_temp_temp); - - vector ar(ar_count); - - for (int i = 0; i < ar_count; i++) { - int ar_item = stoi(ar_temp[i]); - - ar[i] = ar_item; - } - - int result = birthdayCakeCandles(ar); - - fout << result << "\n"; - - fout.close(); - - return 0; -} - -vector split_string(string input_string) { - string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { - return x == y and x == ' '; - }); - - input_string.erase(new_end, input_string.end()); - - while (input_string[input_string.length() - 1] == ' ') { - input_string.pop_back(); - } - - vector splits; - char delimiter = ' '; - - size_t i = 0; - size_t pos = input_string.find(delimiter); - - while (pos != string::npos) { - splits.push_back(input_string.substr(i, pos - i)); - - i = pos + 1; - pos = input_string.find(delimiter, i); - } - - splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); - - return splits; -} +#include + +using namespace std; + +vector split_string(string); + +// Complete the birthdayCakeCandles function below. +int birthdayCakeCandles(vector ar) { + int max = *max_element(ar.begin(), ar.end()); + int count= 0; + for (int i =0; i> ar_count; + cin.ignore(numeric_limits::max(), '\n'); + + string ar_temp_temp; + getline(cin, ar_temp_temp); + + vector ar_temp = split_string(ar_temp_temp); + + vector ar(ar_count); + + for (int i = 0; i < ar_count; i++) { + int ar_item = stoi(ar_temp[i]); + + ar[i] = ar_item; + } + + int result = birthdayCakeCandles(ar); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/C++/CompareTheTriplets.cpp b/Hackerrank/C++/CompareTheTriplets.cpp deleted file mode 100644 index 2ff70b2a..00000000 --- a/Hackerrank/C++/CompareTheTriplets.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include -using namespace std; - -int main() { - // your code goes here - unsigned int a[3],A=0; - unsigned int b[3],B=0; - for (int i = 0; i<3;i++) cin>>a[i]; - for(int j =0;j<3;j++) - { - cin>>b[j]; - - if (a[j]>b[j]) A++; - else if (a[j] - -using namespace std; - -string ltrim(const string &); -string rtrim(const string &); -vector split(const string &); - -/* - * Complete the 'diagonalDifference' function below. - * - * The function is expected to return an INTEGER. - * The function accepts 2D_INTEGER_ARRAY arr as parameter. - */ - -int diagonalDifference(vector> arr) { - int d1 =0, d2 =0; - - for (int i=0; i> arr(n); - - for (int i = 0; i < n; i++) { - arr[i].resize(n); - - string arr_row_temp_temp; - getline(cin, arr_row_temp_temp); - - vector arr_row_temp = split(rtrim(arr_row_temp_temp)); - - for (int j = 0; j < n; j++) { - int arr_row_item = stoi(arr_row_temp[j]); - - arr[i][j] = arr_row_item; - } - } - - int result = diagonalDifference(arr); - - fout << result << "\n"; - - fout.close(); - - return 0; -} - -string ltrim(const string &str) { - string s(str); - - s.erase( - s.begin(), - find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) - ); - - return s; -} - -string rtrim(const string &str) { - string s(str); - - s.erase( - find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), - s.end() - ); - - return s; -} - -vector split(const string &str) { - vector tokens; - - string::size_type start = 0; - string::size_type end = 0; - - while ((end = str.find(" ", start)) != string::npos) { - tokens.push_back(str.substr(start, end - start)); - - start = end + 1; - } - - tokens.push_back(str.substr(start)); - - return tokens; -} +#include + +using namespace std; + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +/* + * Complete the 'diagonalDifference' function below. + * + * The function is expected to return an INTEGER. + * The function accepts 2D_INTEGER_ARRAY arr as parameter. + */ + +int diagonalDifference(vector> arr) { + int d1 =0, d2 =0; + + for (int i=0; i> arr(n); + + for (int i = 0; i < n; i++) { + arr[i].resize(n); + + string arr_row_temp_temp; + getline(cin, arr_row_temp_temp); + + vector arr_row_temp = split(rtrim(arr_row_temp_temp)); + + for (int j = 0; j < n; j++) { + int arr_row_item = stoi(arr_row_temp[j]); + + arr[i][j] = arr_row_item; + } + } + + int result = diagonalDifference(arr); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/Hackerrank/C++/inputOutput.cpp b/Hackerrank/C++/inputOutput.cpp index 33fe055c..24156001 100644 --- a/Hackerrank/C++/inputOutput.cpp +++ b/Hackerrank/C++/inputOutput.cpp @@ -1,15 +1,15 @@ -#include -#include -#include -#include -#include -using namespace std; - -// Problem https://www.hackerrank.com/challenges/cpp-input-and-output/problem - -int main() { - int a, b, c; - cin >> a >> b >> c; - cout << a+b+c << endl; - return 0; -} +#include +#include +#include +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-input-and-output/problem + +int main() { + int a, b, c; + cin >> a >> b >> c; + cout << a+b+c << endl; + return 0; +} diff --git a/Hackerrank/C++/insertNodeSpecificPosition.cpp b/Hackerrank/C++/insertNodeSpecificPosition.cpp index e4c9a33b..113ac0f9 100644 --- a/Hackerrank/C++/insertNodeSpecificPosition.cpp +++ b/Hackerrank/C++/insertNodeSpecificPosition.cpp @@ -1,92 +1,92 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem - -class SinglyLinkedListNode { - public: - int data; - SinglyLinkedListNode *next; - - SinglyLinkedListNode(int node_data) { - this->data = node_data; - this->next = nullptr; - } -}; - -class SinglyLinkedList { - public: - SinglyLinkedListNode *head; - SinglyLinkedListNode *tail; - - SinglyLinkedList() { - this->head = nullptr; - this->tail = nullptr; - } - - void insert_node(int node_data) { - SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); - - if (!this->head) { - this->head = node; - } else { - this->tail->next = node; - } - - this->tail = node; - } -}; - -void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { - while (node) { - fout << node->data; - - node = node->next; - - if (node) { - fout << sep; - } - } -} - -void free_singly_linked_list(SinglyLinkedListNode* node) { - while (node) { - SinglyLinkedListNode* temp = node; - node = node->next; - - free(temp); - } -} - -// Complete the insertNodeAtPosition function below. - -/* - * For your reference: - * - * SinglyLinkedListNode { - * int data; - * SinglyLinkedListNode* next; - * }; - * - */ -SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { - - SinglyLinkedListNode *curr = head, *temp; - - if (position == 0){ - temp = head; - head = new SinglyLinkedListNode(data); - head->next = temp; - } - - while (--position) curr = curr->next; - - temp = curr->next; - curr->next = new SinglyLinkedListNode(data); - curr->next->next = temp; - - return head; -} - +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtPosition function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtPosition(SinglyLinkedListNode* head, int data, int position) { + + SinglyLinkedListNode *curr = head, *temp; + + if (position == 0){ + temp = head; + head = new SinglyLinkedListNode(data); + head->next = temp; + } + + while (--position) curr = curr->next; + + temp = curr->next; + curr->next = new SinglyLinkedListNode(data); + curr->next->next = temp; + + return head; +} + int main() \ No newline at end of file diff --git a/Hackerrank/C++/insertNodeTailLinkedList.cpp b/Hackerrank/C++/insertNodeTailLinkedList.cpp index 897da895..48314d18 100644 --- a/Hackerrank/C++/insertNodeTailLinkedList.cpp +++ b/Hackerrank/C++/insertNodeTailLinkedList.cpp @@ -1,70 +1,70 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list - -class SinglyLinkedListNode { - public: - int data; - SinglyLinkedListNode *next; - - SinglyLinkedListNode(int node_data) { - this->data = node_data; - this->next = nullptr; - } -}; - -class SinglyLinkedList { - public: - SinglyLinkedListNode *head; - - SinglyLinkedList() { - this->head = nullptr; - } - -}; - -void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { - while (node) { - fout << node->data; - - node = node->next; - - if (node) { - fout << sep; - } - } -} - -void free_singly_linked_list(SinglyLinkedListNode* node) { - while (node) { - SinglyLinkedListNode* temp = node; - node = node->next; - - free(temp); - } -} - -// Complete the insertNodeAtTail function below. - -/* - * For your reference: - * - * SinglyLinkedListNode { - * int data; - * SinglyLinkedListNode* next; - * }; - * - */ -SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { - if (!head) head = new SinglyLinkedListNode(data); - else { - SinglyLinkedListNode* curr = head; - while (curr->next) curr = curr->next; - curr->next = new SinglyLinkedListNode(data); - } - return head; -} - +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + + SinglyLinkedList() { + this->head = nullptr; + } + +}; + +void print_singly_linked_list(SinglyLinkedListNode* node, string sep, ofstream& fout) { + while (node) { + fout << node->data; + + node = node->next; + + if (node) { + fout << sep; + } + } +} + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the insertNodeAtTail function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) { + if (!head) head = new SinglyLinkedListNode(data); + else { + SinglyLinkedListNode* curr = head; + while (curr->next) curr = curr->next; + curr->next = new SinglyLinkedListNode(data); + } + return head; +} + int main() \ No newline at end of file diff --git a/Hackerrank/C++/mapsSTL.cpp b/Hackerrank/C++/mapsSTL.cpp index 609e948e..6b8c66ee 100644 --- a/Hackerrank/C++/mapsSTL.cpp +++ b/Hackerrank/C++/mapsSTL.cpp @@ -1,39 +1,39 @@ -#include -#include -#include -#include -#include -#include -#include -using namespace std; - -//Problem https://www.hackerrank.com/challenges/cpp-maps/problem - -int main() { - /* Enter your code here. Read input from STDIN. Print output to STDOUT */ - int iQueries, iType; - long long iData; - string sName; - unordered_map mStudents; - cin >> iQueries; - while (iQueries--){ - cin >> iType; - switch (iType){ - case 1: - cin >> sName >> iData; - mStudents[sName] += iData; - break; - case 2: - cin >> sName; - mStudents[sName] = 0; - break; - case 3: - cin >> sName; - cout << mStudents[sName] << endl; - break; - default: - break; - } - } - return 0; +#include +#include +#include +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/cpp-maps/problem + +int main() { + /* Enter your code here. Read input from STDIN. Print output to STDOUT */ + int iQueries, iType; + long long iData; + string sName; + unordered_map mStudents; + cin >> iQueries; + while (iQueries--){ + cin >> iType; + switch (iType){ + case 1: + cin >> sName >> iData; + mStudents[sName] += iData; + break; + case 2: + cin >> sName; + mStudents[sName] = 0; + break; + case 3: + cin >> sName; + cout << mStudents[sName] << endl; + break; + default: + break; + } + } + return 0; } \ No newline at end of file diff --git a/Hackerrank/C++/printLinkedList.cpp b/Hackerrank/C++/printLinkedList.cpp index 572c3014..69b53f5b 100644 --- a/Hackerrank/C++/printLinkedList.cpp +++ b/Hackerrank/C++/printLinkedList.cpp @@ -1,69 +1,69 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list - -class SinglyLinkedListNode { - public: - int data; - SinglyLinkedListNode *next; - - SinglyLinkedListNode(int node_data) { - this->data = node_data; - this->next = nullptr; - } -}; - -class SinglyLinkedList { - public: - SinglyLinkedListNode *head; - SinglyLinkedListNode *tail; - - SinglyLinkedList() { - this->head = nullptr; - this->tail = nullptr; - } - - void insert_node(int node_data) { - SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); - - if (!this->head) { - this->head = node; - } else { - this->tail->next = node; - } - - this->tail = node; - } -}; - -void free_singly_linked_list(SinglyLinkedListNode* node) { - while (node) { - SinglyLinkedListNode* temp = node; - node = node->next; - - free(temp); - } -} - -// Complete the printLinkedList function below. - -/* - * For your reference: - * - * SinglyLinkedListNode { - * int data; - * SinglyLinkedListNode* next; - * }; - * - */ -void printLinkedList(SinglyLinkedListNode* head) { - SinglyLinkedListNode* curr = head; - while (curr){ - cout << curr->data << endl; - curr = curr->next; - } -} - +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/print-the-elements-of-a-linked-list + +class SinglyLinkedListNode { + public: + int data; + SinglyLinkedListNode *next; + + SinglyLinkedListNode(int node_data) { + this->data = node_data; + this->next = nullptr; + } +}; + +class SinglyLinkedList { + public: + SinglyLinkedListNode *head; + SinglyLinkedListNode *tail; + + SinglyLinkedList() { + this->head = nullptr; + this->tail = nullptr; + } + + void insert_node(int node_data) { + SinglyLinkedListNode* node = new SinglyLinkedListNode(node_data); + + if (!this->head) { + this->head = node; + } else { + this->tail->next = node; + } + + this->tail = node; + } +}; + +void free_singly_linked_list(SinglyLinkedListNode* node) { + while (node) { + SinglyLinkedListNode* temp = node; + node = node->next; + + free(temp); + } +} + +// Complete the printLinkedList function below. + +/* + * For your reference: + * + * SinglyLinkedListNode { + * int data; + * SinglyLinkedListNode* next; + * }; + * + */ +void printLinkedList(SinglyLinkedListNode* head) { + SinglyLinkedListNode* curr = head; + while (curr){ + cout << curr->data << endl; + curr = curr->next; + } +} + int main() \ No newline at end of file diff --git a/Hackerrank/C++/sayHelloWorld.cpp b/Hackerrank/C++/sayHelloWorld.cpp index c9ca033d..8da50c66 100644 --- a/Hackerrank/C++/sayHelloWorld.cpp +++ b/Hackerrank/C++/sayHelloWorld.cpp @@ -1,10 +1,10 @@ -#include -#include -using namespace std; - -// Problem https://www.hackerrank.com/challenges/cpp-hello-world/problem - -int main() { - printf("Hello, World!"); - return 0; +#include +#include +using namespace std; + +// Problem https://www.hackerrank.com/challenges/cpp-hello-world/problem + +int main() { + printf("Hello, World!"); + return 0; } \ No newline at end of file diff --git a/Hackerrank/C++/solveMeFirst.cpp b/Hackerrank/C++/solveMeFirst.cpp index ab33007a..03e2190a 100644 --- a/Hackerrank/C++/solveMeFirst.cpp +++ b/Hackerrank/C++/solveMeFirst.cpp @@ -1,22 +1,22 @@ -#include -#include -#include -#include -#include -using namespace std; - -//Problem https://www.hackerrank.com/challenges/solve-me-first/problem - -int solveMeFirst(int a, int b) { - // Hint: Type return a+b; below - return a + b; -} - -int main() { - int num1, num2; - int sum; - cin>>num1>>num2; - sum = solveMeFirst(num1,num2); - cout< +#include +#include +#include +#include +using namespace std; + +//Problem https://www.hackerrank.com/challenges/solve-me-first/problem + +int solveMeFirst(int a, int b) { + // Hint: Type return a+b; below + return a + b; +} + +int main() { + int num1, num2; + int sum; + cin>>num1>>num2; + sum = solveMeFirst(num1,num2); + cout< -#include -#include -#include -#include -#include -#include -#include -#include - -char* readline(); -char** split_string(char*); - -// Complete the countingSort function below. - -// Please store the size of the integer array to be returned in result_count pointer. For example, -// int a[3] = {1, 2, 3}; -// -// *result_count = 3; -// -// return a; -// -int* countingSort(int arr_count, int* arr, int* result_count) { - int flag,k=0; - int temp[100]; - * result_count=arr_count; - int *result=malloc(arr_count*sizeof(int)); - for(int i=0;i<100;i++) - temp[i]=0; - for(int i=0;i +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); +char** split_string(char*); + +// Complete the countingSort function below. + +// Please store the size of the integer array to be returned in result_count pointer. For example, +// int a[3] = {1, 2, 3}; +// +// *result_count = 3; +// +// return a; +// +int* countingSort(int arr_count, int* arr, int* result_count) { + int flag,k=0; + int temp[100]; + * result_count=arr_count; + int *result=malloc(arr_count*sizeof(int)); + for(int i=0;i<100;i++) + temp[i]=0; + for(int i=0;i -#include -#include -#include -#include -#include -#include -#include -#include - -char* readline(); - -// Complete the gridChallenge function below. - -// Please either make the string static or allocate on the heap. For example, -// static char str[] = "hello world"; -// return str; -// -// OR -// -// char* str = "hello world"; -// return str; -// -char* gridChallenge(int grid_count, char** grid) { - - char* ans1="YES"; - char* ans2="NO"; - - char key; - int k; - for(int i=0;i=0&&grid[i][k]>key) - { - grid[i][k+1]=grid[i][k]; - k=k-1; - } - grid[i][k+1]=key; - } - } - - for(int i=0;igrid[j+1][i]) - return ans2; - } - } - return ans1; - -} - -int main() -{ - FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); - - char* t_endptr; - char* t_str = readline(); - int t = strtol(t_str, &t_endptr, 10); - - if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } - - for (int t_itr = 0; t_itr < t; t_itr++) { - char* n_endptr; - char* n_str = readline(); - int n = strtol(n_str, &n_endptr, 10); - - if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } - - char** grid = malloc(n * sizeof(char*)); - - for (int i = 0; i < n; i++) { - char* grid_item = readline(); - - *(grid + i) = grid_item; - } - - int grid_count = n; - - char* result = gridChallenge(grid_count, grid); - - fprintf(fptr, "%s\n", result); - } - - fclose(fptr); - - return 0; -} - -char* readline() { - size_t alloc_length = 1024; - size_t data_length = 0; - char* data = malloc(alloc_length); - - while (true) { - char* cursor = data + data_length; - char* line = fgets(cursor, alloc_length - data_length, stdin); - - if (!line) { break; } - - data_length += strlen(cursor); - - if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } - - size_t new_length = alloc_length << 1; - data = realloc(data, new_length); - - if (!data) { break; } - - alloc_length = new_length; - } - - if (data[data_length - 1] == '\n') { - data[data_length - 1] = '\0'; - } - - data = realloc(data, data_length); - - return data; -} +#include +#include +#include +#include +#include +#include +#include +#include +#include + +char* readline(); + +// Complete the gridChallenge function below. + +// Please either make the string static or allocate on the heap. For example, +// static char str[] = "hello world"; +// return str; +// +// OR +// +// char* str = "hello world"; +// return str; +// +char* gridChallenge(int grid_count, char** grid) { + + char* ans1="YES"; + char* ans2="NO"; + + char key; + int k; + for(int i=0;i=0&&grid[i][k]>key) + { + grid[i][k+1]=grid[i][k]; + k=k-1; + } + grid[i][k+1]=key; + } + } + + for(int i=0;igrid[j+1][i]) + return ans2; + } + } + return ans1; + +} + +int main() +{ + FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); + + char* t_endptr; + char* t_str = readline(); + int t = strtol(t_str, &t_endptr, 10); + + if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); } + + for (int t_itr = 0; t_itr < t; t_itr++) { + char* n_endptr; + char* n_str = readline(); + int n = strtol(n_str, &n_endptr, 10); + + if (n_endptr == n_str || *n_endptr != '\0') { exit(EXIT_FAILURE); } + + char** grid = malloc(n * sizeof(char*)); + + for (int i = 0; i < n; i++) { + char* grid_item = readline(); + + *(grid + i) = grid_item; + } + + int grid_count = n; + + char* result = gridChallenge(grid_count, grid); + + fprintf(fptr, "%s\n", result); + } + + fclose(fptr); + + return 0; +} + +char* readline() { + size_t alloc_length = 1024; + size_t data_length = 0; + char* data = malloc(alloc_length); + + while (true) { + char* cursor = data + data_length; + char* line = fgets(cursor, alloc_length - data_length, stdin); + + if (!line) { break; } + + data_length += strlen(cursor); + + if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } + + size_t new_length = alloc_length << 1; + data = realloc(data, new_length); + + if (!data) { break; } + + alloc_length = new_length; + } + + if (data[data_length - 1] == '\n') { + data[data_length - 1] = '\0'; + } + + data = realloc(data, data_length); + + return data; +} diff --git a/Hackerrank/C/Priyanka And Toys.cpp b/Hackerrank/C/Priyanka And Toys.cpp index bbb6296b..ece05440 100644 --- a/Hackerrank/C/Priyanka And Toys.cpp +++ b/Hackerrank/C/Priyanka And Toys.cpp @@ -1,96 +1,96 @@ -#include - -using namespace std; - -vector split_string(string); - -// Complete the toys function below. -int toys(vector w) { - sort(w.begin(),w.end()); - long int flag=0,z,count; - long int size; - while(!w.empty()) - { - count=0; - flag++; - size=w.size(); - z=w.front(); - - /*for(int i=0;i=z&&w[i]<=z+4) - count++; - - } - for(int i=0;i> n; - cin.ignore(numeric_limits::max(), '\n'); - - string w_temp_temp; - getline(cin, w_temp_temp); - - vector w_temp = split_string(w_temp_temp); - - vector w(n); - - for (int i = 0; i < n; i++) { - int w_item = stoi(w_temp[i]); - - w[i] = w_item; - } - - int result = toys(w); - - fout << result << "\n"; - - fout.close(); - - return 0; -} - -vector split_string(string input_string) { - string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { - return x == y and x == ' '; - }); - - input_string.erase(new_end, input_string.end()); - - while (input_string[input_string.length() - 1] == ' ') { - input_string.pop_back(); - } - - vector splits; - char delimiter = ' '; - - size_t i = 0; - size_t pos = input_string.find(delimiter); - - while (pos != string::npos) { - splits.push_back(input_string.substr(i, pos - i)); - - i = pos + 1; - pos = input_string.find(delimiter, i); - } - - splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); - - return splits; -} +#include + +using namespace std; + +vector split_string(string); + +// Complete the toys function below. +int toys(vector w) { + sort(w.begin(),w.end()); + long int flag=0,z,count; + long int size; + while(!w.empty()) + { + count=0; + flag++; + size=w.size(); + z=w.front(); + + /*for(int i=0;i=z&&w[i]<=z+4) + count++; + + } + for(int i=0;i> n; + cin.ignore(numeric_limits::max(), '\n'); + + string w_temp_temp; + getline(cin, w_temp_temp); + + vector w_temp = split_string(w_temp_temp); + + vector w(n); + + for (int i = 0; i < n; i++) { + int w_item = stoi(w_temp[i]); + + w[i] = w_item; + } + + int result = toys(w); + + fout << result << "\n"; + + fout.close(); + + return 0; +} + +vector split_string(string input_string) { + string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) { + return x == y and x == ' '; + }); + + input_string.erase(new_end, input_string.end()); + + while (input_string[input_string.length() - 1] == ' ') { + input_string.pop_back(); + } + + vector splits; + char delimiter = ' '; + + size_t i = 0; + size_t pos = input_string.find(delimiter); + + while (pos != string::npos) { + splits.push_back(input_string.substr(i, pos - i)); + + i = pos + 1; + pos = input_string.find(delimiter, i); + } + + splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1)); + + return splits; +} diff --git a/Hackerrank/Java/DivisibleSumPairs.java b/Hackerrank/Java/DivisibleSumPairs.java new file mode 100644 index 00000000..ced46e79 --- /dev/null +++ b/Hackerrank/Java/DivisibleSumPairs.java @@ -0,0 +1,31 @@ +import java.util.*; +class divisibleSumPairs +{ +public static void main(String[] args) +{ +Scanner sc = new Scanner (System.in); +int n = sc.nextInt(); +int k = sc.nextInt(); +int ar[] = new int [n]; +int i; +for (i = 0; i < n; i++) +{ +ar[i] = sc.nextInt(); +} +System.out.println(divisibleSumPairs(ar, n, k)); + +int divisibleSumPairs(int ar[], int n, int k) { + int result = 0; + int i , j; + for (i = 0; i < n; i++){ + for (j = i + 1; j < n; j++){ + if ((ar[i] + ar[j]) % k == 0) + result++; + } + } + return result; + + } +sc.close(); +} +} \ No newline at end of file diff --git a/Hackerrank/Java/Staircase.java b/Hackerrank/Java/Staircase.java new file mode 100644 index 00000000..498a1ca1 --- /dev/null +++ b/Hackerrank/Java/Staircase.java @@ -0,0 +1,29 @@ +import java.util.*; +class Staircase +{ +public static void main(String[] args) +{ +Scanner sc = new Scanner (System.in); +int N = sc.nextInt(); + + for(int i=1;i<=n;i++) + { + for(int j=1;j<=n;j++) + + { + if((i+j)>n) + { + System.out.print("#"); + } + else + { + System.out.print(" "); + } + + } + System.out.println(); + + } +sc.close(); +} +} \ No newline at end of file diff --git a/Hackerrank/Python/Python b/Hackerrank/Python/Python new file mode 100644 index 00000000..e69de29b diff --git a/Hackerrank/Python/Python: Division.py b/Hackerrank/Python/Python: Division.py deleted file mode 100644 index 26004077..00000000 --- a/Hackerrank/Python/Python: Division.py +++ /dev/null @@ -1,8 +0,0 @@ -#Author: Rakshit Naidu - -if __name__ == '__main__': - a = int(input()) - b = int(input()) - - print(a//b) - print(a/b) diff --git a/Hackerrank/Python/Time_Conversion.py b/Hackerrank/Python/Time_Conversion.py index d3aa39dd..76c06dfe 100644 --- a/Hackerrank/Python/Time_Conversion.py +++ b/Hackerrank/Python/Time_Conversion.py @@ -1,34 +1,34 @@ -# Author Name : Akshay Jain -#!/bin/python3 - -import os -import sys - -# -# Complete the timeConversion function below. -# -def timeConversion(s): - # - # Write your code here. - # - hh, mm, ssNu = s.split(':') - ss = ssNu[:2] - u = ssNu[2:] - - if u == 'AM' : - if hh == '12' : - hh = '00' - else : - if hh != '12' : - hh = (int(hh) + 12 ) - return ("{}:{}:{}".format(hh, mm, ss)) -if __name__ == '__main__': - f = open(os.environ['OUTPUT_PATH'], 'w') - - s = input() - - result = timeConversion(s) - - f.write(result + '\n') - - f.close() +# Author Name : Akshay Jain +#!/bin/python3 + +import os +import sys + +# +# Complete the timeConversion function below. +# +def timeConversion(s): + # + # Write your code here. + # + hh, mm, ssNu = s.split(':') + ss = ssNu[:2] + u = ssNu[2:] + + if u == 'AM' : + if hh == '12' : + hh = '00' + else : + if hh != '12' : + hh = (int(hh) + 12 ) + return ("{}:{}:{}".format(hh, mm, ss)) +if __name__ == '__main__': + f = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + result = timeConversion(s) + + f.write(result + '\n') + + f.close() diff --git a/Hackerrank/Python/What's Your Name?.py b/Hackerrank/Python/What's Your Name?.py deleted file mode 100644 index 9a567bd6..00000000 --- a/Hackerrank/Python/What's Your Name?.py +++ /dev/null @@ -1,9 +0,0 @@ -#Submitted by Rakshit Naidu - -def print_full_name(a, b): - print("Hello {} {}! You just delved into python.".format(a,b)) - -if __name__ == '__main__': - first_name = input() - last_name = input() - print_full_name(first_name, last_name) diff --git a/Hackerrank/compareTheTriplets.cpp b/Hackerrank/compareTheTriplets.cpp index 33c63aa8..fa777540 100644 --- a/Hackerrank/compareTheTriplets.cpp +++ b/Hackerrank/compareTheTriplets.cpp @@ -1,108 +1,108 @@ -#include - -using namespace std; - -// Problem https://www.hackerrank.com/challenges/compare-the-triplets/problem - -string ltrim(const string &); -string rtrim(const string &); -vector split(const string &); - -// Complete the compareTriplets function below. -vector compareTriplets(vector a, vector b) { - - int iAliceScore = 0, iBobScore = 0; - - for (int i = 0; i < 3; ++i){ - if (a[i] > b[i]) ++iAliceScore; - else if (a[i] < b[i]) ++iBobScore; - } - - return {iAliceScore, iBobScore}; -} - -int main() -{ - ofstream fout(getenv("OUTPUT_PATH")); - - string a_temp_temp; - getline(cin, a_temp_temp); - - vector a_temp = split(rtrim(a_temp_temp)); - - vector a(3); - - for (int i = 0; i < 3; i++) { - int a_item = stoi(a_temp[i]); - - a[i] = a_item; - } - - string b_temp_temp; - getline(cin, b_temp_temp); - - vector b_temp = split(rtrim(b_temp_temp)); - - vector b(3); - - for (int i = 0; i < 3; i++) { - int b_item = stoi(b_temp[i]); - - b[i] = b_item; - } - - vector result = compareTriplets(a, b); - - for (int i = 0; i < result.size(); i++) { - fout << result[i]; - - if (i != result.size() - 1) { - fout << " "; - } - } - - fout << "\n"; - - fout.close(); - - return 0; -} - -string ltrim(const string &str) { - string s(str); - - s.erase( - s.begin(), - find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) - ); - - return s; -} - -string rtrim(const string &str) { - string s(str); - - s.erase( - find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), - s.end() - ); - - return s; -} - -vector split(const string &str) { - vector tokens; - - string::size_type start = 0; - string::size_type end = 0; - - while ((end = str.find(" ", start)) != string::npos) { - tokens.push_back(str.substr(start, end - start)); - - start = end + 1; - } - - tokens.push_back(str.substr(start)); - - return tokens; -} +#include + +using namespace std; + +// Problem https://www.hackerrank.com/challenges/compare-the-triplets/problem + +string ltrim(const string &); +string rtrim(const string &); +vector split(const string &); + +// Complete the compareTriplets function below. +vector compareTriplets(vector a, vector b) { + + int iAliceScore = 0, iBobScore = 0; + + for (int i = 0; i < 3; ++i){ + if (a[i] > b[i]) ++iAliceScore; + else if (a[i] < b[i]) ++iBobScore; + } + + return {iAliceScore, iBobScore}; +} + +int main() +{ + ofstream fout(getenv("OUTPUT_PATH")); + + string a_temp_temp; + getline(cin, a_temp_temp); + + vector a_temp = split(rtrim(a_temp_temp)); + + vector a(3); + + for (int i = 0; i < 3; i++) { + int a_item = stoi(a_temp[i]); + + a[i] = a_item; + } + + string b_temp_temp; + getline(cin, b_temp_temp); + + vector b_temp = split(rtrim(b_temp_temp)); + + vector b(3); + + for (int i = 0; i < 3; i++) { + int b_item = stoi(b_temp[i]); + + b[i] = b_item; + } + + vector result = compareTriplets(a, b); + + for (int i = 0; i < result.size(); i++) { + fout << result[i]; + + if (i != result.size() - 1) { + fout << " "; + } + } + + fout << "\n"; + + fout.close(); + + return 0; +} + +string ltrim(const string &str) { + string s(str); + + s.erase( + s.begin(), + find_if(s.begin(), s.end(), not1(ptr_fun(isspace))) + ); + + return s; +} + +string rtrim(const string &str) { + string s(str); + + s.erase( + find_if(s.rbegin(), s.rend(), not1(ptr_fun(isspace))).base(), + s.end() + ); + + return s; +} + +vector split(const string &str) { + vector tokens; + + string::size_type start = 0; + string::size_type end = 0; + + while ((end = str.find(" ", start)) != string::npos) { + tokens.push_back(str.substr(start, end - start)); + + start = end + 1; + } + + tokens.push_back(str.substr(start)); + + return tokens; +} diff --git a/HelloWorld/HanoiTower.c b/HelloWorld/HanoiTower.c index d21e04bf..7f20ee5b 100644 --- a/HelloWorld/HanoiTower.c +++ b/HelloWorld/HanoiTower.c @@ -1,21 +1,21 @@ -#include - -// C recursive function to solve tower of hanoi puzzle -void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) -{ - if (n == 1) - { - printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); - return; - } - towerOfHanoi(n-1, from_rod, aux_rod, to_rod); - printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); - towerOfHanoi(n-1, aux_rod, to_rod, from_rod); -} - -int main() -{ - int n = 4; // Number of disks - towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods - return 0; -} +#include + +// C recursive function to solve tower of hanoi puzzle +void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) +{ + if (n == 1) + { + printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod); + return; + } + towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod); + towerOfHanoi(n-1, aux_rod, to_rod, from_rod); +} + +int main() +{ + int n = 4; // Number of disks + towerOfHanoi(n, 'A', 'C', 'B'); // A, B and C are names of rods + return 0; +} diff --git a/HelloWorld/HelloWorld.html b/HelloWorld/HelloWorld.html deleted file mode 100644 index cdb392d4..00000000 --- a/HelloWorld/HelloWorld.html +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - \ No newline at end of file diff --git a/HelloWorld/helloworld.php b/HelloWorld/helloworld.php index 21f83756..b30e5a0d 100644 --- a/HelloWorld/helloworld.php +++ b/HelloWorld/helloworld.php @@ -1,3 +1,3 @@ - \ No newline at end of file diff --git a/LeetCode/First_and_last_sorted_array.java b/LeetCode/First_and_last_sorted_array.java index 3fea98c5..1c24da0f 100644 --- a/LeetCode/First_and_last_sorted_array.java +++ b/LeetCode/First_and_last_sorted_array.java @@ -1,34 +1,34 @@ -/* Problem 34. Find First and Last Position of Element in Sorted Array - * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. - * - * Your algorithm's runtime complexity must be in the order of O(log n). - * - * If the target is not found in the array, return [-1, -1]. - */ - -public class First_and_last_sorted_array { - public int[] searchRange(int[] nums, int target) { - int[] targetRange = {-1, -1}; - - for(int i = 0; i=0; i--){ - if(nums[i] == target){ - targetRange[1] = i; - break; - } - } - - return targetRange; - - } -} +/* Problem 34. Find First and Last Position of Element in Sorted Array + * Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value. + * + * Your algorithm's runtime complexity must be in the order of O(log n). + * + * If the target is not found in the array, return [-1, -1]. + */ + +public class First_and_last_sorted_array { + public int[] searchRange(int[] nums, int target) { + int[] targetRange = {-1, -1}; + + for(int i = 0; i=0; i--){ + if(nums[i] == target){ + targetRange[1] = i; + break; + } + } + + return targetRange; + + } +} From 57845d0cdbfe7375117f0b4ac08413acd4871b72 Mon Sep 17 00:00:00 2001 From: BHAVYA BORDIA Date: Wed, 30 Oct 2019 17:14:08 +0530 Subject: [PATCH 275/324] Create HelloWorld.Scala --- HelloWorld/HelloWorld.Scala | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 HelloWorld/HelloWorld.Scala diff --git a/HelloWorld/HelloWorld.Scala b/HelloWorld/HelloWorld.Scala new file mode 100644 index 00000000..04ee421d --- /dev/null +++ b/HelloWorld/HelloWorld.Scala @@ -0,0 +1,11 @@ + +// Scala program to print Hello World! +object Geeks +{ + // Main Method + def main(args: Array[String]) + { + // prints Hello World + println("Hello World!") + } +} From f23ec091818e2b5091a949e88daf68f9c4aa69a2 Mon Sep 17 00:00:00 2001 From: BHAVYA BORDIA Date: Wed, 30 Oct 2019 17:17:05 +0530 Subject: [PATCH 276/324] Hello World in ruby --- HelloWorld/hello_world.rb | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 HelloWorld/hello_world.rb diff --git a/HelloWorld/hello_world.rb b/HelloWorld/hello_world.rb new file mode 100644 index 00000000..95dc0692 --- /dev/null +++ b/HelloWorld/hello_world.rb @@ -0,0 +1,2 @@ +#Hello World in Ruby +puts "Hello World!" From 6f3328bc00bf37e5cda6d73ea9f1110612890f3a Mon Sep 17 00:00:00 2001 From: BHAVYA BORDIA Date: Wed, 30 Oct 2019 17:19:37 +0530 Subject: [PATCH 277/324] factorial using recursion in kotlin --- HelloWorld/Factorial.kt | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 HelloWorld/Factorial.kt diff --git a/HelloWorld/Factorial.kt b/HelloWorld/Factorial.kt new file mode 100644 index 00000000..e2e3e72b --- /dev/null +++ b/HelloWorld/Factorial.kt @@ -0,0 +1,10 @@ +# Finidng factorial using recursion in kotlin + fun main(args: Array) { + val number = 4 + val result: Long + result = factorial(number) + println("Factorial of $number = $result") + } + fun factorial(n: Int): Long { + return if (n == 1) n.toLong() else n*factorial(n-1) + } From 03319b770febb06cfd6fa15e929e4adf60192a82 Mon Sep 17 00:00:00 2001 From: BHAVYA BORDIA Date: Wed, 30 Oct 2019 17:21:02 +0530 Subject: [PATCH 278/324] Factorial Using Tail Recursion --- HelloWorld/factorial_tail_rec.kt | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 HelloWorld/factorial_tail_rec.kt diff --git a/HelloWorld/factorial_tail_rec.kt b/HelloWorld/factorial_tail_rec.kt new file mode 100644 index 00000000..7ff10a7e --- /dev/null +++ b/HelloWorld/factorial_tail_rec.kt @@ -0,0 +1,8 @@ + # Factorial Using Tail Recursion + fun main(args: Array) { + val number = 5 + println("Factorial of $number = ${factorial(number)}") + } + tailrec fun factorial(n: Int, run: Int = 1): Long { + return if (n == 1) run.toLong() else factorial(n-1, run*n) + } From b8cd387bc0a8475b8bc74a31857a1e5d203d77e1 Mon Sep 17 00:00:00 2001 From: BHAVYA BORDIA Date: Wed, 30 Oct 2019 17:23:16 +0530 Subject: [PATCH 279/324] factorial of a number using dowhile loop in kotlin --- HelloWorld/Factorial_DoWhileLoop.kt | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 HelloWorld/Factorial_DoWhileLoop.kt diff --git a/HelloWorld/Factorial_DoWhileLoop.kt b/HelloWorld/Factorial_DoWhileLoop.kt new file mode 100644 index 00000000..fe9b1f57 --- /dev/null +++ b/HelloWorld/Factorial_DoWhileLoop.kt @@ -0,0 +1,11 @@ +# Kotlin program to find the factorial of a number using do-while loop +fun main(args: Array) { + var number = 6 + var factorial = 1 + + do { + factorial *= number + number-- + }while(number > 0) + println("Factorial of 6 is $factorial") +} From 9604e3becd1637af6c1ba741cf4759f2d44f109c Mon Sep 17 00:00:00 2001 From: Mohammed Aamir Khan Date: Wed, 30 Oct 2019 09:36:39 -0700 Subject: [PATCH 280/324] Added Python Radix Sort Implementation in Algorithms --- Algorithms/Python/RadixSort.py | 63 ++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Algorithms/Python/RadixSort.py diff --git a/Algorithms/Python/RadixSort.py b/Algorithms/Python/RadixSort.py new file mode 100644 index 00000000..fb29faec --- /dev/null +++ b/Algorithms/Python/RadixSort.py @@ -0,0 +1,63 @@ + +edit +play_arrow + +brightness_4 +# Python program for implementation of Radix Sort + +# A function to do counting sort of arr[] according to +# the digit represented by exp. +def countingSort(arr, exp1): + + n = len(arr) + + # The output array elements that will have sorted arr + output = [0] * (n) + + # initialize count array as 0 + count = [0] * (10) + + # Store count of occurrences in count[] + for i in range(0, n): + index = (arr[i]/exp1) + count[ (index)%10 ] += 1 + + # Change count[i] so that count[i] now contains actual + # position of this digit in output array + for i in range(1,10): + count[i] += count[i-1] + + # Build the output array + i = n-1 + while i>=0: + index = (arr[i]/exp1) + output[ count[ (index)%10 ] - 1] = arr[i] + count[ (index)%10 ] -= 1 + i -= 1 + + # Copying the output array to arr[], + # so that arr now contains sorted numbers + i = 0 + for i in range(0,len(arr)): + arr[i] = output[i] + +# Method to do Radix Sort +def radixSort(arr): + + # Find the maximum number to know number of digits + max1 = max(arr) + + # Do counting sort for every digit. Note that instead + # of passing digit number, exp is passed. exp is 10^i + # where i is current digit number + exp = 1 + while max1/exp > 0: + countingSort(arr,exp) + exp *= 10 + +# Driver code to test above +arr = [ 170, 45, 75, 90, 802, 24, 2, 66] +radixSort(arr) + +for i in range(len(arr)): + print(arr[i]), \ No newline at end of file From 8f303453d9e55450e80b8c7bb181b6daab1ff6fa Mon Sep 17 00:00:00 2001 From: Breno Alves Date: Wed, 30 Oct 2019 13:39:02 -0300 Subject: [PATCH 281/324] 1234B2 from codeforces --- Codeforces/1234B2.cpp | 58 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Codeforces/1234B2.cpp diff --git a/Codeforces/1234B2.cpp b/Codeforces/1234B2.cpp new file mode 100644 index 00000000..6a75fd01 --- /dev/null +++ b/Codeforces/1234B2.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +#define pb push_back +#define mp make_pair +#define sort_ar() sort(ar.begin(), ar.end()); +#define sort_ar_inv() sort(ar.begin(), ar.end(), greater<>()); +#define FAST_IOS() ios_base::sync_with_stdio(false); +#define FAST_CIN() cin.tie(0); +#define FAST_COUT() cout.tie(0); +#define MOD 10000007 + +typedef long long ll; +const int INF = 0x3f3f3f3f; + +int k, n; + +std::deque q; +std::set s; + +void add(int ent){ + + if(s.find(ent) == s.end()){ + if(q.size() < k){ + s.insert(ent); + q.emplace_front(ent); + } else { + s.erase(q.back()); + q.pop_back(); + + s.insert(ent); + q.emplace_front(ent); + } + } +} + +int main(){ + FAST_IOS(); + FAST_CIN(); + FAST_COUT(); + + cin >> n >> k; + + for(int i = 0, ent; i < n; i++){ + cin >> ent; + add(ent); + } + + cout << q.size() << "\n"; + for(auto i : q){ + cout << i << " "; + } + + cout << "\n"; + + return 0; +} + \ No newline at end of file From f582d47eac90bafc821ade00a604db82eef0b103 Mon Sep 17 00:00:00 2001 From: Shikhar Sharma Date: Wed, 30 Oct 2019 23:38:30 +0530 Subject: [PATCH 282/324] Create ReverseInteger.cpp --- LeetCode/ReverseInteger.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/ReverseInteger.cpp diff --git a/LeetCode/ReverseInteger.cpp b/LeetCode/ReverseInteger.cpp new file mode 100644 index 00000000..f28d3a55 --- /dev/null +++ b/LeetCode/ReverseInteger.cpp @@ -0,0 +1,12 @@ +class Solution { +public: + int reverse(int x) { + long long rev = 0; + while(x){ + int d = x%10; + rev = rev*10 + d; + x = x/10; + } + return ((revINT_MAX)? 0: rev); + } +}; From fff3a8b1d4a01c62af4701ed2f7965fba88a810d Mon Sep 17 00:00:00 2001 From: D-honored <54802156+D-honored@users.noreply.github.com> Date: Thu, 31 Oct 2019 02:06:01 +0530 Subject: [PATCH 283/324] Tower of Hanoi Using Recursion --- Algorithms/C/Tower-Of-Hanoi.c | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Algorithms/C/Tower-Of-Hanoi.c diff --git a/Algorithms/C/Tower-Of-Hanoi.c b/Algorithms/C/Tower-Of-Hanoi.c new file mode 100644 index 00000000..83eafd16 --- /dev/null +++ b/Algorithms/C/Tower-Of-Hanoi.c @@ -0,0 +1,40 @@ +// Name: Bhupendra Chauhan +//Email: chauhanbhupendra145@gmail.com +/*This is a program for Tower of Hanoi using recursion. + * Number of Disks are taken as input from User. +*/ + +#include + +void TOH(int, char, char, char); + +// Driver Code +int main(){ + int n; //Number of Disks + flag: + printf("Enter the number of disks : "); + scanf("%d",&n); + if(n>0){ + printf("The sequence of moves involved in the Tower of Hanoi are :\n"); + TOH(n, 'A', 'C', 'B'); + } + else{ + printf("Number of Disks should be a Natural Number\n"); + goto flag; + } + + return 0; +} + + +//Program Of Tower Of Hanoi +void TOH(int n,char From,char To,char Aux){ + if(n==1){ + printf("Move disk %d from Tower %c to Tower %c \n",n,From,To); + return; + } + TOH(n-1,From,Aux,To); + printf("Move disk %d from Tower %c to Tower %c \n",n,From,To); + TOH(n-1,Aux,To,From); +} + From 1bfe3adee0ad2b0ef98c70af29642e3bb4113c10 Mon Sep 17 00:00:00 2001 From: D-honored <54802156+D-honored@users.noreply.github.com> Date: Thu, 31 Oct 2019 04:49:48 +0530 Subject: [PATCH 284/324] Create MUFFINS3.cpp --- Codechef/MUFFINS3.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Codechef/MUFFINS3.cpp diff --git a/Codechef/MUFFINS3.cpp b/Codechef/MUFFINS3.cpp new file mode 100644 index 00000000..02c6f8dc --- /dev/null +++ b/Codechef/MUFFINS3.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +int main() +{ ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); + + int n; + cin>>n; + while(n-->0){ + int l; + cin>>l; + cout<<(l/2+1)<<"\n"; + } + + return 0; +} From f68d8e4ac5b5423d3259ba8c328e8faf1c54f5ea Mon Sep 17 00:00:00 2001 From: D-honored <54802156+D-honored@users.noreply.github.com> Date: Thu, 31 Oct 2019 04:52:03 +0530 Subject: [PATCH 285/324] Create START01.cpp --- Codechef/START01.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Codechef/START01.cpp diff --git a/Codechef/START01.cpp b/Codechef/START01.cpp new file mode 100644 index 00000000..34d90224 --- /dev/null +++ b/Codechef/START01.cpp @@ -0,0 +1,12 @@ +#include +using namespace std; + +int main() +{ + ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); + int n; + cin>>n; + cout< Date: Wed, 30 Oct 2019 20:11:00 -0400 Subject: [PATCH 286/324] Added gemstones in ruby --- Hackerrank/Ruby/Gemstones.rb | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Hackerrank/Ruby/Gemstones.rb diff --git a/Hackerrank/Ruby/Gemstones.rb b/Hackerrank/Ruby/Gemstones.rb new file mode 100644 index 00000000..51b304fd --- /dev/null +++ b/Hackerrank/Ruby/Gemstones.rb @@ -0,0 +1,20 @@ +n = gets.strip.to_i +arr = Array.new +n.times do + arr << gets.strip +end + +result = 0 + +arr[0].chars.to_a.uniq.to_s.each_char do |chr| + common = true + arr.each do |x| + unless x.index(chr) + common = false + break + end + end + result += 1 if common +end + +print result From 44fcb1750990786fde5a24e47050c0656bd4b980 Mon Sep 17 00:00:00 2001 From: Henrique Date: Wed, 30 Oct 2019 20:12:20 -0400 Subject: [PATCH 287/324] Added problem url --- Hackerrank/Ruby/Gemstones.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Hackerrank/Ruby/Gemstones.rb b/Hackerrank/Ruby/Gemstones.rb index 51b304fd..63c278e3 100644 --- a/Hackerrank/Ruby/Gemstones.rb +++ b/Hackerrank/Ruby/Gemstones.rb @@ -1,3 +1,5 @@ +# URL: https://www.hackerrank.com/challenges/gem-stones/ + n = gets.strip.to_i arr = Array.new n.times do From c62735d9c5508a7925d5aba4968478189d478568 Mon Sep 17 00:00:00 2001 From: Henrique Date: Wed, 30 Oct 2019 20:19:42 -0400 Subject: [PATCH 288/324] Added athleteSort --- Hackerrank/Python/athleteSort.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Hackerrank/Python/athleteSort.py diff --git a/Hackerrank/Python/athleteSort.py b/Hackerrank/Python/athleteSort.py new file mode 100644 index 00000000..9014ba7a --- /dev/null +++ b/Hackerrank/Python/athleteSort.py @@ -0,0 +1,12 @@ +# URL: https://www.hackerrank.com/challenges/python-sort-sort/ + +from __future__ import print_function + +n,m = [ int(i) for i in raw_input().split() ] +arr = [ map(int, raw_input().split()) for _ in xrange(n) ] +k = int(raw_input()) + +arr.sort(key = lambda x: x[k]) + +for a in arr: + print (*a) \ No newline at end of file From ee3e7e04c28ddcc8bbd93910bc06596414308317 Mon Sep 17 00:00:00 2001 From: "equinox.bot" <9652305+LShun@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:04:48 +0800 Subject: [PATCH 289/324] Add twoStrings.py Two Strings: https://www.hackerrank.com/challenges/two-strings/ --- Hackerrank/Python/twoStrings.py | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Hackerrank/Python/twoStrings.py diff --git a/Hackerrank/Python/twoStrings.py b/Hackerrank/Python/twoStrings.py new file mode 100644 index 00000000..f6f4ac46 --- /dev/null +++ b/Hackerrank/Python/twoStrings.py @@ -0,0 +1,49 @@ +#Author: turtlejump +#Issue: Two Strings: https://www.hackerrank.com/challenges/two-strings/ + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the twoStrings function below. +def store(array, char): + loc = hash(char) % len(array) + array[loc].append(char) + +def search(array, char): + loc = hash(char) % len(array) + for i in array[loc]: + if i == char: + return True + return False + +def twoStrings(s1, s2): + map1 = [[] for i in range(len(s1))] + # store all characters into a hash table + for i in s1: + store(map1, i) + # if any of the characters inside s1 matches s2, then return 'YES' + for i in s2: + if search(map1, i) == True: + return 'YES' + return 'NO' + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + q = int(input()) + + for q_itr in range(q): + s1 = input() + + s2 = input() + + result = twoStrings(s1, s2) + + fptr.write(result + '\n') + + fptr.close() From 40ee06ccb88b875af8e3153bf5d7e88e6b815fb3 Mon Sep 17 00:00:00 2001 From: "equinox.bot" <9652305+LShun@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:26:52 +0800 Subject: [PATCH 290/324] Add HR hashTablesRansomNote.py solution Hash Tables: Ransom Note: https://www.hackerrank.com/challenges/ctci-ransom-note/ --- Hackerrank/Python/hashTablesRansomNote.py | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Hackerrank/Python/hashTablesRansomNote.py diff --git a/Hackerrank/Python/hashTablesRansomNote.py b/Hackerrank/Python/hashTablesRansomNote.py new file mode 100644 index 00000000..e1a565cd --- /dev/null +++ b/Hackerrank/Python/hashTablesRansomNote.py @@ -0,0 +1,55 @@ +#Author: turtlejump +#Issue: Hash Tables: Ransom Note: https://www.hackerrank.com/challenges/ctci-ransom-note/ + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the checkMagazine function below. +def store(array, word): + # Hash the word (then squeeze it down to a smaller size) + # Append it to the hashed location (assuming its a linked list) + array[hash(word) % len(array)].append(word) + + +def retrieve(array, word): + # Hash the word (squeeze it down to a smaller size) + loc = hash(word) % len(array) + # Loop through the particular hashed location, check for the word + for i in range(len(array[loc])): + if array[loc][i] == word: + array[loc].pop(i) + return True + return False + +def checkMagazine(magazine, note): + # Implement a hash table + # Our actual hash table + magSize = len(magazine) + mag = [[] for i in range(magSize)] + for i in magazine: + store(mag, i) + for i in note: + if retrieve(mag, i) == True: + continue + else: + print('No') + return + print('Yes') + return +if __name__ == '__main__': + mn = input().split() + + m = int(mn[0]) + + n = int(mn[1]) + + magazine = input().rstrip().split() + + note = input().rstrip().split() + + checkMagazine(magazine, note) From 854b19d9dabdebd06fd65557b493a33fb819b0cf Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:01:34 +0530 Subject: [PATCH 291/324] Create Sequences.c --- Hackerearth/Sequences.c | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Hackerearth/Sequences.c diff --git a/Hackerearth/Sequences.c b/Hackerearth/Sequences.c new file mode 100644 index 00000000..7e4b059f --- /dev/null +++ b/Hackerearth/Sequences.c @@ -0,0 +1,37 @@ +#include +inline int scan() +{ + char c = getchar_unlocked(); + int x = 0; + while(c<'0'||c>'9'){ + c=getchar_unlocked(); + } + while(c>='0'&&c<='9'){ + x=(x<<1)+(x<<3)+c-'0'; + c=getchar_unlocked(); + } + return x; +} +int main() +{ + int x,y,t; + t=scan(); + while(t--) + { + x=scan(); + y=scan(); + int ans=-1; + if(x==y) + ans=1; + if(ans!=1) + for(int i = 2; i < 21; i++) + { + if(pow(1.0*x / i, i) >= y) + { + ans=i; + break; + } + } + printf("%d\n",ans); + } +} From 33ace9d214c83729f10469cfaa6426b4e66c14f4 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:03:51 +0530 Subject: [PATCH 292/324] Create Going To Office.c --- Hackerearth/Going To Office.c | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Hackerearth/Going To Office.c diff --git a/Hackerearth/Going To Office.c b/Hackerearth/Going To Office.c new file mode 100644 index 00000000..bec034ea --- /dev/null +++ b/Hackerearth/Going To Office.c @@ -0,0 +1,16 @@ +#include +int main() +{ + long int D,Oc,Of,Od,Cs,Cb,Cm,Cd; + float O,C; + scanf("%ld",&D); + scanf("%ld%ld%ld",&Oc,&Of,&Od); + scanf("%ld%ld%ld%ld",&Cs,&Cb,&Cm,&Cd); + O=(Oc+(D-Of)*Od); + C=Cb+((D/Cs)+Cm)+(D*Cd); + if(O<=C) + printf("Online Taxi"); + else + printf("Classic Taxi"); +return 0; +} From 6397186fa85bd54cd41ce867f544648a772108cb Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:05:21 +0530 Subject: [PATCH 293/324] Create Special Sets.c --- Hackerearth/Special Sets.c | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Hackerearth/Special Sets.c diff --git a/Hackerearth/Special Sets.c b/Hackerearth/Special Sets.c new file mode 100644 index 00000000..6e6deb58 --- /dev/null +++ b/Hackerearth/Special Sets.c @@ -0,0 +1,20 @@ +#include +int main() +{ + long long int n,r,max,product,mod=1000000007,result=0,i; + scanf("%lld",&n); + if(n%2) + max=(n+1)/2; + else + max=(n+2)/2; + for(r=1;r<=max;++r) + { + product=n-2*r+2; + + for(i=n-2*r+3;i<=n-r+1;++i) + product=(product*(i%mod))%mod; + result=(result+product)%mod; + } + printf("%lld",result); + return 0; +} From 53890e805b978e163443966bd74b21d54a3ffbc8 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:06:58 +0530 Subject: [PATCH 294/324] Create Color The Boxes.c --- Hackerearth/Color The Boxes.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Hackerearth/Color The Boxes.c diff --git a/Hackerearth/Color The Boxes.c b/Hackerearth/Color The Boxes.c new file mode 100644 index 00000000..5c10b8b7 --- /dev/null +++ b/Hackerearth/Color The Boxes.c @@ -0,0 +1,12 @@ +#include +#include +int main() +{ + unsigned long int n,m,val=1,i,mod=1000000007; + scanf("%lu %lu",&n,&m); + for(i=1;i<=m;i++) { + val=(val*i)%mod; + } + printf("%lu",val); + return 0; +} From 1febffc161b66e310d6b1f864f97f2a4b2c0d338 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:09:38 +0530 Subject: [PATCH 295/324] Create 90A.cpp --- Codeforces/90A.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Codeforces/90A.cpp diff --git a/Codeforces/90A.cpp b/Codeforces/90A.cpp new file mode 100644 index 00000000..a1ed5461 --- /dev/null +++ b/Codeforces/90A.cpp @@ -0,0 +1,16 @@ +#include + +int main(){ + + int r(0), g(0), b(0); scanf("%d %d %d", &r, &g, &b); + + r = (r + 1) / 2; g = (g + 1) / 2; b = (b + 1) / 2; + + int output(0); + if(b >= g && b >= r){output = 30 + 3 * b - 1;} + else if(g >= r){output = 30 + 3 * g - 2;} + else{output = 30 + 3 * r - 3;} + + printf("%d\n", output); + return 0; +} From ec8189129ed6254d3cae3896bb9b6b22c826094b Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:10:11 +0530 Subject: [PATCH 296/324] Create 92A.cpp --- Codeforces/92A.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Codeforces/92A.cpp diff --git a/Codeforces/92A.cpp b/Codeforces/92A.cpp new file mode 100644 index 00000000..fd3464a3 --- /dev/null +++ b/Codeforces/92A.cpp @@ -0,0 +1,10 @@ +#include +#include + +int main(){ + int n, m; scanf("%d %d", &n, &m); + m %= (n * (n + 1) / 2); + int x = (sqrt(8 * m + 1) - 1)/ 2.0; + printf("%d\n", m - x * (x + 1) / 2); + return 0; +} From 43462aaff0c7c4dd6a33352acc8bf2e6d835202b Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:12:47 +0530 Subject: [PATCH 297/324] Create 103A.cpp --- Codeforces/103A.cpp | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Codeforces/103A.cpp diff --git a/Codeforces/103A.cpp b/Codeforces/103A.cpp new file mode 100644 index 00000000..683a637f --- /dev/null +++ b/Codeforces/103A.cpp @@ -0,0 +1,19 @@ +#include +#include +using namespace std; + +int main() { + + long long n; + cin >> n; + long long total(0); + for(long p = 0; p < n; p++){ + long long m; + cin >> m; + total += (m - 1) * (p + 1) + 1; + } + + cout << total << endl; + + return 0; +} From df5a06c6ae54e416dd44b95c42fcfa66745e08d1 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:14:42 +0530 Subject: [PATCH 298/324] Create 198A.cpp --- Codeforces/198A.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Codeforces/198A.cpp diff --git a/Codeforces/198A.cpp b/Codeforces/198A.cpp new file mode 100644 index 00000000..c94e96b5 --- /dev/null +++ b/Codeforces/198A.cpp @@ -0,0 +1,12 @@ +#include +using namespace std; + +int main(){ + + long long k, b, n, t; + cin >> k >> b >> n >> t; + for(long long s = k + b; s <= t && n > 0; s = k * s + b, --n); + cout << n; + + return 0; +} From 28ca8020a7becf1098643e2f5fe28af432af4ea9 Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:16:06 +0530 Subject: [PATCH 299/324] Create 314A.cpp --- Codeforces/314A.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Codeforces/314A.cpp diff --git a/Codeforces/314A.cpp b/Codeforces/314A.cpp new file mode 100644 index 00000000..5a3da171 --- /dev/null +++ b/Codeforces/314A.cpp @@ -0,0 +1,14 @@ +#include + +int main(){ + + long long n, k; scanf("%lld %lld", &n, &k); + long long total(0), count(0); + for(long long p = 1; p <= n; p++){ + long long x; scanf("%lld", &x); + if(p > 1 && total - x * (n - p) * (p - count - 1) < k){printf("%lld\n", p); ++count;} + else{total += x * (p - 1 - count);} + } + + return 0; +} From 7e50016240140c41c92afb7723ef3aa821da5cbe Mon Sep 17 00:00:00 2001 From: Idi0syncratic <56863549+Idi0syncratic@users.noreply.github.com> Date: Thu, 31 Oct 2019 18:17:23 +0530 Subject: [PATCH 300/324] Create 318A.cpp --- Codeforces/318A.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Codeforces/318A.cpp diff --git a/Codeforces/318A.cpp b/Codeforces/318A.cpp new file mode 100644 index 00000000..6c5f8d1a --- /dev/null +++ b/Codeforces/318A.cpp @@ -0,0 +1,10 @@ +#include +using namespace std; + +int main(){ + int n, k; + cin >> n >> k; + cout << ((k <= (n+1)/2) ? (2*k - 1) : (2 * (k - (n + 1)/2) ) ) << endl; + + return 0; +} From fd5cf79178890baa86ff87e5936519bc4247d046 Mon Sep 17 00:00:00 2001 From: Aarushi Date: Thu, 31 Oct 2019 19:32:38 +0530 Subject: [PATCH 301/324] Adding currency changer algo --- Algorithms/C++/currency_changer.cpp | 57 +++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Algorithms/C++/currency_changer.cpp diff --git a/Algorithms/C++/currency_changer.cpp b/Algorithms/C++/currency_changer.cpp new file mode 100644 index 00000000..4452fee0 --- /dev/null +++ b/Algorithms/C++/currency_changer.cpp @@ -0,0 +1,57 @@ +#include +#include +using namespace std; + +int currency(int *coins,int n,int amount){ + if(amount==0){ + return 0; + } + + int ans=INT_MAX; + for(int i=0;i=0){ + int smallerans=currency(coins,n,amount-coins[i]); + if(smallerans!=INT_MAX){ + ans=min(ans,smallerans+1); + } + } + } + return ans; +} + +/*int topdown(int *coins,int n,int amount,int *dp){ + if(amount==0){ + dp[amount]=0; + return dp[amount]; + } + if(dp(dp[amount])) +}*/ + +int bottomup(int *coins,int n,int amount){ + int dp[1000]; + for(int i=0;i<1000;i++){ + dp[i]=INT_MAX; + } + dp[0]=0; + + for(int rupay=1;rupay<=amount;rupay++){ + for(int i=0;i=0){ + dp[rupay]=min(dp[rupay],dp[rupay-coins[i]]+1); + } + } + } + return dp[amount]; +} + +int main(){ + int coins[]={1,7,10}; + int n=sizeof(coins)/sizeof(int); + + int amount; + cin>>amount; + + cout< Date: Thu, 31 Oct 2019 23:31:11 +0530 Subject: [PATCH 302/324] heap ds --- DS/C++/heap.cpp | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 DS/C++/heap.cpp diff --git a/DS/C++/heap.cpp b/DS/C++/heap.cpp new file mode 100644 index 00000000..36db14d3 --- /dev/null +++ b/DS/C++/heap.cpp @@ -0,0 +1,39 @@ +using namespace std; +int main() +{ + + // Initializing a vector + vector v1 = {20, 30, 40, 25, 15}; + + // Converting vector into a heap + // using make_heap() + make_heap(v1.begin(), v1.end()); + + // Displaying the maximum element of heap + // using front() + cout << "The maximum element of heap is : "; + cout << v1.front() << endl; + + // using push_back() to enter element + // in vector + v1.push_back(50); + + // using push_heap() to reorder elements + push_heap(v1.begin(), v1.end()); + + // Displaying the maximum element of heap + // using front() + cout << "The maximum element of heap after push is : "; + cout << v1.front() << endl; + + // using pop_heap() to delete maximum element + pop_heap(v1.begin(), v1.end()); + v1.pop_back(); + + // Displaying the maximum element of heap + // using front() + cout << "The maximum element of heap after pop is : "; + cout << v1.front() << endl; + + return 0; +} \ No newline at end of file From b487274671d36f15a1bf3e2cd867eb3ed63db6d9 Mon Sep 17 00:00:00 2001 From: Sourav Mondal <54900920+ask2sm@users.noreply.github.com> Date: Sat, 2 Nov 2019 18:09:32 +0530 Subject: [PATCH 303/324] Add determinenumber.cpp This is a cpp solution of hackerearth determine number problem picked from november easy 19.ref #25 --- Hackerearth/determinenumber.cpp | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Hackerearth/determinenumber.cpp diff --git a/Hackerearth/determinenumber.cpp b/Hackerearth/determinenumber.cpp new file mode 100644 index 00000000..480cf7d5 --- /dev/null +++ b/Hackerearth/determinenumber.cpp @@ -0,0 +1,45 @@ +//problem picked from Novemeber Easy 19 +#include +using namespace std; + +// function to find and print duplicates +void printDuplicates(int arr[], int n) +{ + // unordered_map to store frequencies + vector v; + unordered_map freq; + for (int i=0; i:: iterator itr; + for (itr=freq.begin(); itr!=freq.end(); itr++) + { + // if frequency is more than 1 + // print the element + if (itr->second == 1) + { + v.push_back(itr->first); + dup = false; + } + } + sort(v.begin(), v.end()); + for (auto x : v) + cout << x << " "; + // // no duplicates present + // if (dup == false) + // cout << itr->first; +} + +// Driver program to test above +int main() +{ + int n,q,p; + cin>>n; + int a[n]; + for(int i=0;i>a[i]; + } + printDuplicates(a,n); + return 0; +} From f61762ce6e0392a9c1baf6a04688073f11e4712f Mon Sep 17 00:00:00 2001 From: Sourav Mondal <54900920+ask2sm@users.noreply.github.com> Date: Sat, 2 Nov 2019 18:16:18 +0530 Subject: [PATCH 304/324] Add exchangingmoney.cpp This is an cpp implimentation of exchanging money problem of november easy 19.Ref #25 --- Hackerearth/exchangingmoney.cpp | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Hackerearth/exchangingmoney.cpp diff --git a/Hackerearth/exchangingmoney.cpp b/Hackerearth/exchangingmoney.cpp new file mode 100644 index 00000000..ea279a8a --- /dev/null +++ b/Hackerearth/exchangingmoney.cpp @@ -0,0 +1,24 @@ +//hackerearth problem picked from noveasy19 +#include +using naemespace std; +#define ll long long int +int main() +{ + int n,q,i; + cin>>n>>q; + ll a[n],p,g=0; + for(i=0;i>a[i]; + g=__gcd(a[i],g); + } + while(q--) + { + cin>>p; + if(__gcd(g,p)==g) + cout<<"YES"< Date: Fri, 7 Feb 2020 14:14:37 -0800 Subject: [PATCH 305/324] Solution for New Year Chaos Two different solutions for New Year Chaos: https://www.hackerrank.com/challenges/new-year-chaos/problem --- Hackerrank/C#/New Year Chaos | 93 ++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Hackerrank/C#/New Year Chaos diff --git a/Hackerrank/C#/New Year Chaos b/Hackerrank/C#/New Year Chaos new file mode 100644 index 00000000..b836db70 --- /dev/null +++ b/Hackerrank/C#/New Year Chaos @@ -0,0 +1,93 @@ + +/* +https://www.hackerrank.com/challenges/new-year-chaos/problem + +Two different solutions included. +*/ + +using System.CodeDom.Compiler; +using System.Collections.Generic; +using System.Collections; +using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.Serialization; +using System.Text.RegularExpressions; +using System.Text; +using System; + +class Solution { + +/* +Check if any number moved more than 2 spaces fowards. If so, too chaotic. +Otherwise, for each number, check if there are larger numbers before it. +We only need to check up to 2 indices before each number's original location. +O(n) time. O(1) space. +Because each number can only move forward twice, the inner loop's length is inversely proportional to the frequency it is executed. In one extreme, it can be executed twice with n-1 iterations each, in another, it can be executed n/2 times with 2 iterations each. +For each inner loop, we visit i - (q[i] - 2) number of elements. +For all i values where q[i] - 2 < i, the sum of all i - (q[i] - 2) < 2n. +Therefore the runtime is still linear. +*/ + static void minimumBribesLoops(int[] q) { + int result = 0; + for (int i = 0; i < q.Length; i++) { + if (q[i] > i + 3) { + System.Console.WriteLine("Too chaotic"); + return; + } + if (q[i] < i + 2) { + for (int j = Math.Max(0, q[i] - 2); j < i; j++) { + if (q[j] > q[i]) { + result += 1; + } + } + } + } + System.Console.WriteLine(result); + } + +/* +Bubble sort the array twice from tail to head, then compare to a sorted array. +This reverse the bribe operations with minimum moves. +O(n) time. O(n) space. +*/ + static void minimumBribesBubbles(int[] q) { + int[] sortedQ = new int[q.Length]; + for (int i = 0; i < q.Length; i ++) { + sortedQ[i] = i + 1; + } + + int result = 0; + for (int k = 0; k < 2; k++) { + for (int i = q.Length - 1; i > 0; i--) { + if (q[i] < q[i - 1]) { + int temp = q[i - 1]; + q[i - 1] = q[i]; + q[i] = temp; + result += 1; + } + } + } + if (!sortedQ.SequenceEqual(q)) { + System.Console.WriteLine("Too chaotic"); + } + else { + System.Console.WriteLine(result); + } + } + + static void Main(string[] args) { + int t = Convert.ToInt32(Console.ReadLine()); + + for (int tItr = 0; tItr < t; tItr++) { + int n = Convert.ToInt32(Console.ReadLine()); + + int[] q = Array.ConvertAll(Console.ReadLine().Split(' '), qTemp => Convert.ToInt32(qTemp)) + ; + minimumBribes(q); + } + } +} From 24a3b59f067bcc2aaa20d5c7f1ea61ebd92607cb Mon Sep 17 00:00:00 2001 From: matias campos Date: Fri, 28 Feb 2020 00:25:56 +0100 Subject: [PATCH 306/324] ADD: radix_bin sort with 2 list (double linked circular lists) in c language with minimal standart c lib --- Algorithms/C/radix_sort.c | 236 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 236 insertions(+) create mode 100644 Algorithms/C/radix_sort.c diff --git a/Algorithms/C/radix_sort.c b/Algorithms/C/radix_sort.c new file mode 100644 index 00000000..8a54c909 --- /dev/null +++ b/Algorithms/C/radix_sort.c @@ -0,0 +1,236 @@ +#include +#include +#include +#include + +typedef struct linked_list{ + int data; + struct linked_list *prev; + struct linked_list *next; +} linked_list_t; + +typedef struct ctrl_list{ + int size; + linked_list_t *first; +} ctrl_list_t; + +int my_getnbr(char const *str); +int get_nbr_bit(int nbits, int data); +int get_nbr_of_negs(int ac, char * const *av); +linked_list_t *create_list(int first); +linked_list_t *put_in_list(int ac, char * const*av, ctrl_list_t *ctrl); +int radix_sort(int negs, int nbits, ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b); +void swap_list(ctrl_list_t *list); +void rotate_list(ctrl_list_t *list); +void rev_rotate_list(ctrl_list_t *list); +void kick_first_of_list(ctrl_list_t *ctrl_a, linked_list_t *tmp); +void add_new_first_list(ctrl_list_t *ctrl_b, linked_list_t *tmp); +void push_list(ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b); + +void test_neg(char const *str, int *neg, int *i, int *signe) +{ + while (str[*i] == '-' || str[*i] == '+') { + if (str[*i] == '-') { + *neg = *neg + 1; + } + *i = *i + 1; + } + *neg = *neg % 2; + if (*neg == 1) { + *signe = 1; + } +} + +int my_getnbr(char const *str) +{ + int i = 0; + int neg = 0; + int signe = -1; + int to_return = 0; + int inter = 0; + + test_neg(str, &neg, &i, &signe); + while (str[i] >= '0' && str[i] <= '9' && str[i] != '\0') { + inter = str[i] - 48; + to_return = to_return * 10; + to_return = to_return - inter; + if (to_return == -2147483648 && signe == -1 || to_return > 0) { + return (0); + } + i = i + 1; + } + to_return = to_return * signe; + return (to_return); +} + +void rotate_list(ctrl_list_t *list) +{ + list->first = list->first->next; +} + +void rev_rotate_list(ctrl_list_t *list) +{ + list->first = list->first->prev; +} + +void kick_first_of_list(ctrl_list_t *ctrl_a, linked_list_t *tmp) +{ + ctrl_a->first = ctrl_a->first->prev; + ctrl_a->first->next = tmp->next; + ctrl_a->first = ctrl_a->first->next; + ctrl_a->first->prev = tmp->prev; +} + +void add_new_first_list(ctrl_list_t *ctrl_b, linked_list_t *tmp) +{ + tmp->next = ctrl_b->first; + tmp->prev = ctrl_b->first->prev; + ctrl_b->first = ctrl_b->first->prev; + ctrl_b->first->next = tmp; + ctrl_b->first = ctrl_b->first->next; + ctrl_b->first = ctrl_b->first->next; + ctrl_b->first->prev = tmp; + ctrl_b->first = ctrl_b->first->prev; +} + +void push_list(ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b) +{ + linked_list_t *tmp = ctrl_a->first; + + ctrl_a->size = (ctrl_a->size <= 0) ? 0 : ctrl_a->size - 1; + ctrl_b->size += 1; + if (ctrl_a->first == NULL) + return; + if (ctrl_a->size >= 1){ + kick_first_of_list(ctrl_a, tmp); + }else + ctrl_a->first = NULL; + if (ctrl_b->first == NULL){ + tmp->prev = tmp; + tmp->next = tmp; + ctrl_b->first = tmp; + } else { + add_new_first_list(ctrl_b, tmp); + } +} + +linked_list_t *create_list(int first) +{ + linked_list_t *list_init = malloc(sizeof(linked_list_t)); + + list_init->data = first; + list_init->prev = list_init; + list_init->next = list_init; + return(list_init); +} + +int get_nbr_bit(int nbits, int data) +{ + nbits = 0; + for (; data != 0; data >>= 1, nbits += 1); + return (nbits); +} + +int get_nbr_of_negs(int ac, char * const *av) +{ + int compt = 0; + + if (ac < 2) + return (0); + for (int i = 1; i < ac; i += 1){ + compt = (my_getnbr(av[i]) < 0) ? compt += 1 : compt; + } + return (compt); +} + +linked_list_t *put_in_list(int ac, char * const*av, ctrl_list_t *ctrl) +{ + int i = 2; + linked_list_t *elem; + linked_list_t *last = ctrl->first; + + while (i < ac){ + elem = malloc(sizeof(linked_list_t)); + elem->data = my_getnbr(av[i]); + elem->next = ctrl->first; + elem->prev = last; + last->next = elem; + ctrl->first->prev = elem; + last = elem; + i = i + 1; + } + return(ctrl->first); +} + +void swap_list(ctrl_list_t *list) +{ + linked_list_t *tmp = list->first; + linked_list_t *tmp2 = list->first->next; + + list->first = tmp2; + list->first->prev = tmp2->prev; + tmp = tmp2->next; + list->first->next = tmp; +} + +void put_negs_first(ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b, int negs) +{ + while (ctrl_b->first != NULL){ + push_list(ctrl_b, ctrl_a); + } + for (int i = 0; i < negs; i += 1){ + rev_rotate_list(ctrl_a); + } +} + +int radix_sort(int negs, int nbits, ctrl_list_t *ctrl_a, ctrl_list_t *ctrl_b) +{ + for (int i = 0; i != 32; i += 1){ + for (int size_a = ctrl_a->size; size_a > 0; size_a -= 1){ + if (((ctrl_a->first->data >> i) & 1) == 0){ + push_list(ctrl_a, ctrl_b); + } else if (ctrl_a->first != NULL){ + rotate_list(ctrl_a); + } + } + for (int size_b = ctrl_b->size; size_b > 0; size_b -= 1){ + if (((ctrl_b->first->data >> i) & 1) == 1){ + push_list(ctrl_b, ctrl_a); + } else if (ctrl_b->first != NULL){ + rotate_list(ctrl_b); + } + } + } + put_negs_first(ctrl_a, ctrl_b, negs); +} + +int check_sorted(int ac, char *const *av) +{ + for (int i = 1; i < ac; i += 1){ + if (i > 1 && my_getnbr(av[i - 1]) > my_getnbr(av[i])) + return (1); + } + return (0); +} + +int main(int ac, char * const *av) +{ + linked_list_t *list_a = NULL; + linked_list_t *list_b = NULL; + ctrl_list_t ctrl_a = {ac - 1, list_a}; + ctrl_list_t ctrl_b = {0, list_b}; + int nbits = 0; + int nb_neg = get_nbr_of_negs(ac, av); + + if (ac < 2) + return (84); + list_a = create_list(my_getnbr(av[1])); + ctrl_a.first = list_a; + list_a = put_in_list(ac, av, &ctrl_a); + if (check_sorted(ac, av) == 1){ + radix_sort(nb_neg, nbits, &ctrl_a, &ctrl_b); + } + for (int i = 0; i < ctrl_a.size ; i++, ctrl_a.first=ctrl_a.first->next) + printf("%d ", ctrl_a.first->data); + return (0); +} \ No newline at end of file From c128e89a85c68cd014631d441ae50267b33d0950 Mon Sep 17 00:00:00 2001 From: Romell Pineda Date: Thu, 5 Mar 2020 17:19:07 -0800 Subject: [PATCH 307/324] random int array generators --- HelloWorld/RandomArrayGenerator.java | 13 +++++++++++++ HelloWorld/randomIntArrayGenerator.js | 8 ++++++++ 2 files changed, 21 insertions(+) create mode 100644 HelloWorld/RandomArrayGenerator.java create mode 100644 HelloWorld/randomIntArrayGenerator.js diff --git a/HelloWorld/RandomArrayGenerator.java b/HelloWorld/RandomArrayGenerator.java new file mode 100644 index 00000000..e0bfecd0 --- /dev/null +++ b/HelloWorld/RandomArrayGenerator.java @@ -0,0 +1,13 @@ +import java.util.concurrent.ThreadLocalRandom; + +// Generate a random Java int array with ThreadLocalRandom. Specify the minimum value, maximum value, and desired length of the array. +public class RandomArrayGenerator { + public static int[] randomArrayGenerator(int minValue, int maxValue, int arrayLength) { + int[] arr = new int[arrayLength]; + for (int i = 0; i < arrayLength; i++) { + int randomInt = ThreadLocalRandom.current().nextInt(minValue, maxValue); + arr[i] = randomInt; + } + return arr; + } +} \ No newline at end of file diff --git a/HelloWorld/randomIntArrayGenerator.js b/HelloWorld/randomIntArrayGenerator.js new file mode 100644 index 00000000..9e87899e --- /dev/null +++ b/HelloWorld/randomIntArrayGenerator.js @@ -0,0 +1,8 @@ +// Generate a psuedo-random integer array of a given length and maximum value for rapid testing purposes. +function makeArrayN(length, max) { + const arr = []; + for (let i = 0; i < length; i++) { + arr.push(Math.round(Math.random() * max)); + } + return arr; +} \ No newline at end of file From 23fe382ef5110d342c9598946dce936a5e36c47b Mon Sep 17 00:00:00 2001 From: anniepineda Date: Thu, 5 Mar 2020 17:36:51 -0800 Subject: [PATCH 308/324] hello world in spanish --- HelloWorld/helloWorldSpanish.java | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 HelloWorld/helloWorldSpanish.java diff --git a/HelloWorld/helloWorldSpanish.java b/HelloWorld/helloWorldSpanish.java new file mode 100644 index 00000000..9deb563c --- /dev/null +++ b/HelloWorld/helloWorldSpanish.java @@ -0,0 +1,9 @@ +/* HelloWorld.java + */ + +public class HelloWorldSpanish +{ + public static void main(String[] args) { + System.out.println("Hola Mundo!!"); + } +} \ No newline at end of file From 64aa2e4f87d94704f502052fddb153fdf437c1f4 Mon Sep 17 00:00:00 2001 From: Dayne Daylong Date: Thu, 5 Mar 2020 17:47:35 -0800 Subject: [PATCH 309/324] =?UTF-8?q?created=20=D0=9F=D1=80=D0=B8=D0=B2?= =?UTF-8?q?=D0=B5=D1=82,=20=D0=BC=D0=B8=D1=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...321\210\320\270_\320\264\320\265\320\273\320\260.java" | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 "HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" diff --git "a/HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" "b/HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" new file mode 100644 index 00000000..5e28ec8f --- /dev/null +++ "b/HelloWorld/\320\272\320\260\320\272_\320\262\320\260\321\210\320\270_\320\264\320\265\320\273\320\260.java" @@ -0,0 +1,8 @@ +// HelloWorld.java.ru + +public class HelloWorld +{ + public static void main(String[] args) { + System.out.println("Привет, мир."); + } +} From 22a064c2ef63a3158e50903f4051b6439f18a5cd Mon Sep 17 00:00:00 2001 From: holliemaethomas <33705517+holliemaethomas@users.noreply.github.com> Date: Fri, 6 Mar 2020 12:24:35 -0800 Subject: [PATCH 310/324] Create HelloWorldInGerman --- HelloWorld/HelloWorldInGerman | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 HelloWorld/HelloWorldInGerman diff --git a/HelloWorld/HelloWorldInGerman b/HelloWorld/HelloWorldInGerman new file mode 100644 index 00000000..30fa8fac --- /dev/null +++ b/HelloWorld/HelloWorldInGerman @@ -0,0 +1,6 @@ +public class HelloWorld +{ + public static void main(String[] args) { + System.out.println("Hallo Welt"); + } +} From 3014b0e19466f0e8effdc7eaeed741f2e683d3e7 Mon Sep 17 00:00:00 2001 From: Pedro Medeiros Date: Sat, 25 Apr 2020 23:16:13 +0200 Subject: [PATCH 311/324] Added Codeforces Problem 996A - Hit the Lottery in C++ --- Codeforces/996A.cpp | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Codeforces/996A.cpp diff --git a/Codeforces/996A.cpp b/Codeforces/996A.cpp new file mode 100644 index 00000000..987915a9 --- /dev/null +++ b/Codeforces/996A.cpp @@ -0,0 +1,36 @@ +// Codeforces 2020 +// Pedro Vinicius Medeiros De Cerqueira 25.04.2020 +// Hit the Lottery : Problem 996A + + +#include + +using namespace std; + +int main(){ + int n; cin >> n; + int dollar_bills = 0; + + while (n > 0) + { + if (n >= 100) { + dollar_bills += n / 100; + n = n % 100; + } else if (n >= 20) { + dollar_bills += n / 20; + n = n % 20; + } else if (n >= 10) { + dollar_bills += n / 10; + n = n % 10; + } else if (n >= 5) { + dollar_bills += n / 5; + n = n % 5; + } else if (n < 5) { + dollar_bills += n; + n -= n; + } + } + + + cout << dollar_bills << endl; +} \ No newline at end of file From eb4a5a7d294f97e405298fa81dd28f7611643b46 Mon Sep 17 00:00:00 2001 From: Vinicius Date: Mon, 11 May 2020 12:12:37 -0300 Subject: [PATCH 312/324] new print hello world --- HelloWorld/vs_hello.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 HelloWorld/vs_hello.py diff --git a/HelloWorld/vs_hello.py b/HelloWorld/vs_hello.py new file mode 100644 index 00000000..f0b303f3 --- /dev/null +++ b/HelloWorld/vs_hello.py @@ -0,0 +1 @@ +print('Hello World!') \ No newline at end of file From e00ea164eef6b4d86c66dccc24ed3f51187d4a7c Mon Sep 17 00:00:00 2001 From: vatsa287 Date: Sat, 16 May 2020 18:37:38 +0530 Subject: [PATCH 313/324] Hackerrank-Solutions Signed-off-by: vatsa287 --- Hackerrank/Java/CountingValleys.java | 33 ++++++++ Hackerrank/Java/DesignerPdfViewer.java | 63 +++++++++++++++ Hackerrank/Java/Divisible-Sum-Pairs.java | 60 +++++++++++++++ Hackerrank/Java/Pairs.java | 61 +++++++++++++++ Hackerrank/Java/Sock-Merchant.java | 14 ++++ Hackerrank/Java/Sock-Merchant/Thumbs.db | Bin 0 -> 11776 bytes Hackerrank/Java/The-maximum-subarray.java | 89 ++++++++++++++++++++++ Hackerrank/Java/cats-and-mouse.java | 62 +++++++++++++++ Hackerrank/Java/leftRotation.java | 58 ++++++++++++++ Hackerrank/Python/DesignerPdfViewer.py | 30 ++++++++ Hackerrank/Python/Pairs.py | 37 +++++++++ Hackerrank/Python/Sock-Merchant.py | 42 ++++++++++ Hackerrank/Python/The-maximum-subarray.py | 44 +++++++++++ Hackerrank/Python/birthdayCakeCandles.py | 24 ++++++ Hackerrank/Python/findTheRunnerUp.py | 18 +++++ Hackerrank/Python/gradingStudents.py | 60 +++++++++++++++ Hackerrank/Python/listComprehensions.py | 9 +++ Hackerrank/Python/mini-max-sum.py | 18 +++++ Hackerrank/Python/plus-minus.py | 32 ++++++++ 19 files changed, 754 insertions(+) create mode 100644 Hackerrank/Java/CountingValleys.java create mode 100644 Hackerrank/Java/DesignerPdfViewer.java create mode 100644 Hackerrank/Java/Divisible-Sum-Pairs.java create mode 100644 Hackerrank/Java/Pairs.java create mode 100644 Hackerrank/Java/Sock-Merchant.java create mode 100644 Hackerrank/Java/Sock-Merchant/Thumbs.db create mode 100644 Hackerrank/Java/The-maximum-subarray.java create mode 100644 Hackerrank/Java/cats-and-mouse.java create mode 100644 Hackerrank/Java/leftRotation.java create mode 100644 Hackerrank/Python/DesignerPdfViewer.py create mode 100644 Hackerrank/Python/Pairs.py create mode 100644 Hackerrank/Python/Sock-Merchant.py create mode 100644 Hackerrank/Python/The-maximum-subarray.py create mode 100644 Hackerrank/Python/birthdayCakeCandles.py create mode 100644 Hackerrank/Python/findTheRunnerUp.py create mode 100644 Hackerrank/Python/gradingStudents.py create mode 100644 Hackerrank/Python/listComprehensions.py create mode 100644 Hackerrank/Python/mini-max-sum.py create mode 100644 Hackerrank/Python/plus-minus.py diff --git a/Hackerrank/Java/CountingValleys.java b/Hackerrank/Java/CountingValleys.java new file mode 100644 index 00000000..d2aee83e --- /dev/null +++ b/Hackerrank/Java/CountingValleys.java @@ -0,0 +1,33 @@ +//This code is contributed by Shreevatsa N, @vatsa287 + +package practice; +public class CountingValleys { + public int getValleyCount(String s) + { + int altitudeCount = 0, valleyCount = 0; + + for(int i=0; i set = new HashSet(); + int count = 0; + for(int i=0;i colors = new HashSet<>(); + int pairs = 0; + + for (int i = 0; i < n; i++) { + if (!colors.contains(c[i])) { + colors.add(c[i]); + } else { + pairs++; + colors.remove(c[i]); + } + } + + System.out.println(pairs); \ No newline at end of file diff --git a/Hackerrank/Java/Sock-Merchant/Thumbs.db b/Hackerrank/Java/Sock-Merchant/Thumbs.db new file mode 100644 index 0000000000000000000000000000000000000000..8db210095976656447f26ef4360d93aa7847652d GIT binary patch literal 11776 zcmeHt2UJtr*6t1ogc3odNC`y(qJRj&lF&gZ(L)tPnzTsoNSCf4Ei?;4C{m<10jVMg z5UY2ou z1^yzk02nwrrU9t_Vq1ON(h;ir9ce0==N2>|5czvcg-9ylbw>(BA~iJwAA z9>||#4kd${3>q?M$)F+}q9c8)Z^u(-alxwXCX{m1U!PhKDZ{EOBf%>KfQk<5z%@^f5% z@&ZwK{v^%_p*$l_bxJ`CYUaYkhYX@-R*ZXD)t*c=p=}8KR0z)c=$%RX)eW;l|FmQipH+umt;39yO`gRwJy`6a9AcLvgaXz30feIDt(r`U@}!H`+skWy}h z%M3do!bWFGH)F>?Me|!zf8;w^*gSCFl%Xbb?=awk{97evP0$~>_1WD}=2Yj}HVx!< zuZ3@{D*G7~uwcCWlxHCi!+~PYfs(LcGeW^Ni{b1P^+b73E`Mm3{QG!?MqaF?_tTYu zR$UABb8nucek|BB5&SMo&{a~}NqkV5?6a#;WruZ;YNHG3S>>lBO!9;95%%BT3>L?A z3n_1;log0k#$<#96XF`%=W>TrBg~$O^FA)!WMidERb_(&4Fu{d$bb+sO0t2p=Q09m zO9C8r#`GN;OeQl0yXv0LvF$#YaV9-&Yn!=jp8w^8`z136ETgQqd0lnWvd<=NI)Ovl z`T$gICt*JtB>-tvU5PG#n?d#Py@vw-YR8OcVxa&nj%t9S!f-0YFHN&z|Gw*m!=%x} z4Br6cqD*O_9RH;GG@{%)(rVITb0{;wYH^A6!&}Y`Sqo}uz*UTzh==bG)UA!>?r0tZ z3;8!0o+PStc#%Tcr>;T=eB2z~y;GSha{8#~@WZyg@*OF!{o?yR>C^60gY_ri%VUl( zIoZBxjmhXQ4Y5<93Fq#Z#>HYt?hGR&HK&T==iUOfMv4fbr8#Wjl4Ph8yEM&H`7$La zZNHoO;cqf0Y~z^Lf6z;+4QNchX>EyF)#=#t9d21~Q3$M$Z^J%p=P$&om7AJv1cNE1 zuImL*oEbnwb<1Skx@P-kozqV40^>9Hv@Ttw_$e{PsB09StZn-_eY2&XQ(k1g)zxmv z-B4&;mWac9%508i$A8rH9#yIvV>%C#F57rBPIUtRZN!{jVWDwxAZ2ani0c?w>0aAV z=y-Ef8?Yg~y6L$QxfZBx>+^KtaPk%0xNQ6txPvoyHMn}ygDV4Za)bkWWsWkat2OeQ z`HP2a&SQ(GCSB@j~ z*!LJT?<&E9AbssbXeB)E#YM&$c2VhcIv-Fw;Q>C)Y(Al~sNX5|7?>?-<7hZ^_b*U7 z^zpbdUubRb9$kE|-uP2Kzz9RYu)!Lis3E37L$U)!Ig2CjCj;x`*&i~+0_|v$pdcHU z%V=z8gfNGn)E#$j-EYdR468aJ{rs?RUTy8X*l%8WcL~}T&luJtEKE0o&bcLY`J1Y+ zA)-i^LT$C~On794Y1-hsq8>ZYA0{+Rv6 zK>qc!VLaiNYPM=pGBJUa{cEt3&FtU7vLi(IVzBCuo5Cg^+)LD$dq#m$!l@ar+vBek zn}w**N*D0>8iLHw@a0D_k)M&^xWqtcu$Vl$i62gki}K9*XqI1RDb-l8Fbn=NB%8=n zbTioT7#Ip@oK59sicc^oYEWNXva-q-L;Ntw_+anALfVK7n|%_i)2ee`=ti#CD_!T; zu)>V%XRa50>sPY79~9L>V2?IxFrt|IjTlUK-jeptDWu`r!RKlbcL6KD<&zj8nCX-w z6bivocI+&reilu32ym)fsiKp0sbX9vlz4Pn-%m`EYd#dbR$EzLDd9a>c1g(iI~BwC z7p-D_&gq!uN1A~T$8+*CBH|t~Ysph;4$>Ai7e{KOr)gRY>E;RVAu4C z>xcr!p2o+0k6|e}%*m&&;yh)->u@T^+11shk(c3CD%3z@#Q}3|t&BJ535CvX49`V= z(+!QB4!?4fq3v)KUP>aXNKd7p!7Du1Kh#I=O9LD`7)T>_7cO|)dS?g^cq6QM@i z!@f6?*t%KD&SvLA1Vq~1#|VjdB89Wta6B3;<<=7stY)J7nAMI#UU0P|YbKCh@;i|} zzH$4IC%NDx{T zpoM`IIhgK67tgO=JY$ddt{0Q0SAZAm$@t<=Qs;$*5!Za(+ejoMf1dM*&9w;U&zC8q zCvTpm)QN>ed`PqiiZR0T?5NAnh#Umt>jV-kzPx23!P%N zqb~@1bPUNnOBP+|cK8m8?K^XT$pq1~+Gu;o|na@NX1Jt`K-uESsfsgV&hYC5xk3YJQA`7CNE|hx-ciXcFI>~^z z^2%)ulGZltBUkv(Z)#G3Uvf3cG=aG*$`%ct#1;6(*qs7V=}et+ZHXcRphhBTH0Z=p zQ=F=>w_B?iU9cpP6otp3QCwlnMK3$~LopXcCE^wHG&A|*T4_)adJGgCL7$!PT}K&y zKJDGyEAb^<&Aci>ow%+QZJ`yz?H2A}})iL_H^Ng;{ zhIqNuz{1NvT?@RHGpSA8th1K>8*=@wI-DU^oJvgo{VemDdk}2yJ;AtYmyo@qcPAxA zh3TS{cZNb-PYZ`rOX;L*w@iuaepO)SXKE)2n|wQpnU0oKW4%+!sf8?5^!hEXEz#`U z2*MGFueJ!K^gKT`U3JNXwmW;lgX6*Iqn18>!)7{6Y=fIJfJ8}+Ax)oAj)e@QC6%aU z)ECvQcmlyKW>4rbyv}b=qrm;eHUTEHKcL%(J`yL=`?8$Gi!SPi18)SNA~YiMh@REP zMHigXO&5CH%@-GnF%z>hr=mY7G%3WzJzA6rUrOqal#k=xFxViL@vcpRAmD!7L;Tdw ziL3DS%TwJF(Qu=KR)vIwR4>8;K_SA_!uW)cL+ZWgC5T$)?DIed^_q!IZk5hJWtWIb znbbtMq2IIlJS=Zc(rFP2VyRhR`h$^~JYuR-3f0#}m4-BH=;~9*Y&bF2_aq8fAF5Ql z68gH##l`tytiQf^uVPRzHG!Rk=1&-W+Dz`);#Z0a*_|}X<+Vz;PeiHG2zaBRbFJgt z8mJlm+xKf76I}ebGaQ_nLTS<&ADL!5a-TOY^>@o{s+s6QO6M43(&r!da zSYEdYFIELhO+29*OvmC1E> zD6?nmMNE|UPAO}uvd!4%?hEMMi={}`)xn&3P#_oPGnY_cQ^lHec(CVQq227pLJU?( zM0@Iq%D=gcF!)BwB?z&gE z2w1|C(_34^@o9|`bKtp*2tcT4JN<2xa@YFTkbBfn+<36~4$xPqe`k>8{vF!!KNkwB>CE97`^N1PX^GWs?a+`Idp{b2f!f&xzeCX_Q@klFIJfP9z*jK-BLq_}PM2KGC(#l6p+U!ZqrpS@ z1>$~8NabmfVHA`q2$rB^mH3-z@#(p79n`3wGA$mAlSed&Ykf>_`|#qTqfV;)I5o6b zh5bMx%A;T@Prn=)o;m(7lrvO;%WVO7^knF>y#?>3^JXp@zFp)lqx3i7f z{pjg_(l!sYq4$x}JKbHQU9cWSlBzm?Ogy zVJJdp;DUe)$BigbI*dl{29VADxOX?Pu3FZr09=(Lys_TD&_44D;XpYoR5{xYh{>TS zUjyyDpjM<9lt0$aG6EnZ$lIJ$c3hPQL+Oz|+fr^{-bgas7zk#mic-#sl~LCy!YBdE zTK^F&dYYj&Uq^tbhAEeGBGu4TD)g4@+x*Wu1O5}U7k2`l&aD~k*1cKo?u@QqC8&=q z$+Nv1xjHEyx%`H_M6sRmM#Ns(HjAJ9LF`Y)G{kFmJ6TkKLn@v@C@dCHpi+$-)Lh2I zj6~IJKjAxWK_f>YXw@xE0k_pSd1a|w1D<;Ih8F?g%4A2iHxZ;cUNRj6789z`B!l6K zhoF?KkR~YFXph0!a6v1DHD`kSyqfJ4R!9h zCJMgU`gG@RkB|PwCZ3qsjn5|UQb-{oR$6vyULqXh^7Y~hn_0xZM*p}1(&&1Q%b1AC zViwfVGgnk%3`JxzPGMdZh7*P_D|;j?d+?bgi?ke!1$I$uJG)+E3R$+H3iIT9t!9(6 z0w#iJ*xQJ~^(X3Tt>V$e84*-&P>s)#4t9o2Peu))T;Xi3F7Yk&DeY9L_Y3B;9!*u2 zfs_q{sUK`;KAN%^!Vh7TD8#dlzDzt}9dqe<-W4GFqEp17xGegG!+X4UNfe>)-)sI(k0_Hm=P%cW#5Ze{4lY>8`40%7esKJh$%UBeXrU0!2<1QaN_~N8@w79 zs3OzES9$IgIrE|oWJH`JgXRO^Jh~QkIr8JjHSFco_KS*r3bqWW+VRBG}2HvIAQq~wp2Cwccz-3Jntog z`C$N(A?xGU6r@d(H^KrTZvKF<=(AqOb_`f?`sIl!$Ba&GM!!o;bo$E11Rb4TPagm1H@42VvGY8lGoHE1RWs&d;*4fd`Gf0a zK^fyp9I&->g>ujzw=}-VMpA`j@1~i*nM9nb@c>O^ja6?bJ{PK)Plw?xtAv#Qx-$IP zW=Sp{wyAwu5|_WSk9L=nc)}U9>rJWd)?<}+qp$GLoIIbV^eg!?nD}@_vI8xp^iWVZ z-Vp_sj#Jq_^xoNISlT;OH#uUwNF8b;-5vLh-M?>NKSuG3Ear^I6yCweB1BK{8{y%s zeH#KM-*xsLzr&qY=VlMq%esOn1P+tm`{P{`vZWLLW=?z)uF}*fh?w0iy?Vb3>1S(G zxds)=_~h_j+V{@XbUJkFW{|I~u7J)kdyXZ@ z5DzTNcY&s0gNwEv+E(_xDK%YeE;xGsup&zvtGGiB}jb~0g)T(xGnn{(H?m1{Wkzm+w&Y4y7NV(^rHs;9|N)Ux+li3hg zb)OIszvfPDHiW$RYR%+YT29YEN%n9X;KgSOfY0Rwib>*{gH}Eu)p#`Gq~BCUI>GJ1 zfv!-l^06FEud}i5)vVMat}%_jhr?M!Yakv7X;*4eHNoKdzH+yV2^vY?ze&%KGc=lM zjL=a0bYc3VmCJAqdMP0aPb8tc)NKqgr2%i97y=|QKUJZ_ekFz2-ExtJ{t}niUOyTCxYdbNbCq{w_tVISBbS} zld8v@PJ&$k-d4jkxCJ|k9n}e_9lo@w3P|DpV%*F_B8M}nGI#-zwe=1QtP2egtz@#^ z^QF99_4v_#dd7Ox)(kFZ^AfRdS^Jh`6WbH~bLy+u`{-6{iiw~3j=$n^J6mIyMnG4J znq$HCQD`8aHOmMVtGJMowava1f|HmGH`N~y$&E@62D=5Lp>YG;VU^mE>h)Eqh$#_& zGru~CCV>bdelxDy-ue8JO)hZNDA?6)zpQ7A%h$gG40|`c=|GlBxCIYUD`>rvDycy+5@= z8}uTf$3NiE)~J16PVT5uG6Jx~Ztz%t z&wf`eSANDrhZQojilcHH&8aqFo${v1A-2}Qu+zUiAfA-PLRX{CBl1{!6>s0W5N32r z);^@E)jy0KT0NJwL3lT36V$z+HjU0v9x$tj7=wB#TP8@a5I{f|&1|*IV^aFYP>;Wk zx5byuOTVj!+y;9L9WfXDptCB^WR3xeUs}HTqlv<<)@(`oLGI6}*1s#@S7p0-IU(t? zwcVuO6(C)?#q;!67!lti%b1@kkl|OvhLDZSk7SlFe(7}ZKOgqWxn(&a_v;H46f}!c zX$H@JW$HTzw{ObuO*me>C)SEpZ5Dbag5)w}Whzz&~vRM~*(k?`q z>5zC!!8Ahv-u+b!*N+EfU~O{{;tU89tN`qKN$0_>;&7FN1Sc4JqgT&G#2ILp!4S0l zZ1z>MDTEZGT{t>fnqQ+}IW%nu-owf1v>lrOQhi!{!1`s&2&&urm)>noYP8G!NRsWm zc4%r zjFwe;;4?AWGys-faTbRGOnp-+9jql=40h63Us4ObrVlHFLU&zO=Dl*~^r~*X?1>M~ z9jcv3*xdS(S-x>E?H`1dNnbKY)Oc)Z%qGAV~_!d`T& zfTdoeTG5>j9V@=pTN;^u&pnB*n-}VA56A_4J;CGc2Su zT7TxnV}Rj6>B3HqYYFoLpK|_k6YiQT8w`fc-|)XRtcRI-7d)zh+xDvT&AWSE^PF=! z*O<>qjR_RM)Yb^U4ezsE(BJWkN!lAkzT!z`9uRgjjCWF3s;_hz%1$=8dt(n#^ZAm4 zRLkx8s>cE`p^7wIzQN*6JYfrZBFj^yK@LSv_*KR7r25Y)M=98Xqdd{lE1Fj!A(u_PptiU$(mx?Ra1)>`5bGJ&ImOcxrUlM(S5Vd}rD2YOyJi2h&OlPw>DBkT&*iYProMWoL*f#;fJ>k)o5D zVPX^onb>$0O=kdrzkwp+IsyCMJ2P6JVd`JZ_!Oceuo}teE>%HJXNe*7bU3*o{m&vd zDN)c*@@!V@aH7kmTS%*9KUmuuQF9I6!OmcglsmL2Te%Bbw^LpJ=cg{`(Wxu87Z^Mn_MPS@H$iQQz^7^%6z zk#|>8MpA0)AW7pTWn!YCvZ%A=aNT;phpfFnIy-cb&b1R}`v`X@KPX|*W#G`(R`}Y0 z*4;OY+W`S{-Z8C_0nA1=r7`ppqMW3$x?<(4l+7%y%NEhY-L^~hjNC=6A@;SsXSdEz z)IDoepCHsZw7PYdpo@be8XQD?+&*k->DWIPo|`jadb<_i|F$p2;l{a)^v&R(Ip6=n QU^pK6@Az*y|JOME4}#JyOaK4? literal 0 HcmV?d00001 diff --git a/Hackerrank/Java/The-maximum-subarray.java b/Hackerrank/Java/The-maximum-subarray.java new file mode 100644 index 00000000..bb65ea24 --- /dev/null +++ b/Hackerrank/Java/The-maximum-subarray.java @@ -0,0 +1,89 @@ +//This code is contributed by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the maxSubarray function below. + static int[] maxSubarray(int[] arr) { + int ans = 0, wsum = 0, nonnegsum = 0; + //ans is the final answer when there is contigous subarray case, wsum is the subarray sum, nonnegsum is the sum of all non negative nos when we deal with non contigous elements. + ans = wsum = arr[0]; //Using Kadanes Algorithm for this case of contigous subarray. So intialize the wsum , ans as arr[0] i.e is the first element. + int ansArray[] = new int[2]; //Since we have to return the array having the result for two cases we set size as 2 which consits of the maxsum from both the est case respectiiely. + + for(int i=1;i arr[i]) + { + wsum+=arr[i]; + } + else + { + wsum = arr[i]; + } + ans = Math.max(ans,wsum); //ans is the result for maximum subarray having contigous elements. + } + Arrays.sort(arr); //Sort the array in order to find out if all elements are negative or not. If yes then the last element will be negative, + System.out.println("ans is "+ arr[0]); + if(arr[arr.length-1]<0) + { + nonnegsum = arr[arr.length-1]; //if all elements are negative then max amongst them is the last element in that sorted array. + } + else + { + for(int i=0;i=0) + nonnegsum+=arr[i]; + } + } + ansArray[0] = ans; + ansArray[1] = nonnegsum; + return ansArray; + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int t = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int tItr = 0; tItr < t; tItr++) { + int n = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + int[] arr = new int[n]; + + String[] arrItems = scanner.nextLine().split(" "); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int i = 0; i < n; i++) { + int arrItem = Integer.parseInt(arrItems[i]); + arr[i] = arrItem; + } + + int[] result = maxSubarray(arr); + + for (int i = 0; i < result.length; i++) { + bufferedWriter.write(String.valueOf(result[i])); + + if (i != result.length - 1) { + bufferedWriter.write(" "); + } + } + + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} diff --git a/Hackerrank/Java/cats-and-mouse.java b/Hackerrank/Java/cats-and-mouse.java new file mode 100644 index 00000000..83669a29 --- /dev/null +++ b/Hackerrank/Java/cats-and-mouse.java @@ -0,0 +1,62 @@ +//This code is contruibuted by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + // Complete the catAndMouse function below. + static String catAndMouse(int x, int y, int z) { + + + if(Math.abs(z-y) < Math.abs(z-x)) + { + return "Cat B"; + } + else if(Math.abs(z-y) > Math.abs(z-x)) + { + return "Cat A"; + } + else if(Math.abs(z-y) == Math.abs(z-x)) + { + return "Mouse C"; + } + + throw new IllegalArgumentException("NOT A VALID CO-ORDINATE"); + + + + } + + private static final Scanner scanner = new Scanner(System.in); + + public static void main(String[] args) throws IOException { + BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH"))); + + int q = scanner.nextInt(); + scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?"); + + for (int qItr = 0; qItr < q; qItr++) { + String[] xyz = scanner.nextLine().split(" "); + + int x = Integer.parseInt(xyz[0]); + + int y = Integer.parseInt(xyz[1]); + + int z = Integer.parseInt(xyz[2]); + + String result = catAndMouse(x, y, z); + + bufferedWriter.write(result); + bufferedWriter.newLine(); + } + + bufferedWriter.close(); + + scanner.close(); + } +} diff --git a/Hackerrank/Java/leftRotation.java b/Hackerrank/Java/leftRotation.java new file mode 100644 index 00000000..d647ce90 --- /dev/null +++ b/Hackerrank/Java/leftRotation.java @@ -0,0 +1,58 @@ +//This code is contributed by Shreevatsa N, @vatsa287 +import java.io.*; +import java.math.*; +import java.security.*; +import java.text.*; +import java.util.*; +import java.util.concurrent.*; +import java.util.regex.*; + +public class Solution { + + public void LeftRotation(int n, int k, int a[]) + { + k = k%a.length; + reverse(a,0,n-1); + reverse(a,n-k,n-1); + reverse(a,0,n-k-1); + for(int i=0;i max1: + max1 = h[ord(word[ch]) - 97] + return count * max1 +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + h = list(map(int, input().rstrip().split())) + + word = input() + + result = designerPdfViewer(h, word) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/Pairs.py b/Hackerrank/Python/Pairs.py new file mode 100644 index 00000000..6e9dafe0 --- /dev/null +++ b/Hackerrank/Python/Pairs.py @@ -0,0 +1,37 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the pairs function below. +def pairs(k, arr): + s = {}; + count=0 + for i in arr: #add all elements to the set, it does not have any duplicates present. + s[i] = i + for a in arr: #for every element in the array, check if its complement exists in the set. + g = a + k #complement = array ele + given target + if g in s: #if complement is present in the set, it means that already found and added so increment counter + count+=1 + return count; + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + nk = input().split() + + n = int(nk[0]) + + k = int(nk[1]) + + arr = list(map(int, input().rstrip().split())) + + result = pairs(k, arr) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/Sock-Merchant.py b/Hackerrank/Python/Sock-Merchant.py new file mode 100644 index 00000000..9bded289 --- /dev/null +++ b/Hackerrank/Python/Sock-Merchant.py @@ -0,0 +1,42 @@ +#This code is contributed by Shreevatsa N, @vatsa287 + +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the sockMerchant function below. +def sockMerchant(n, ar): + op = [] #remove the duplicates. + for ch in ar: + if ch not in op: + op.append(ch) + count = 0 #intialize count of pairs to 0. + for i in op: #check the count of all elements in original list. + if ar.count(i) == 1: #if the no of duplicates is 0, then no pair available. + count = count + 0 + elif ar.count(i)%2==1 and ar.count(i)>1: #if count > 1 i.e pair and odd meaning one should be removed to form a pair. + c = ar.count(i) + c=c-1 #the removal is done here + count = count + (c/2) #since no of pair is required divide by 2. + elif ar.count(i)%2==0 and ar.count(i)>1: #if count > 1 i.e pair and its even , just divide by 2 to get no of pair socks present. + count = count + ar.count(i)/2 + c = 0 #make c = 0 for next iteration so it is treated as a fresh case for next odd element. + return(int(count)) #return the non decimal part. + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input()) + + ar = list(map(int, input().rstrip().split())) + + result = sockMerchant(n, ar) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/The-maximum-subarray.py b/Hackerrank/Python/The-maximum-subarray.py new file mode 100644 index 00000000..3a7aaa2e --- /dev/null +++ b/Hackerrank/Python/The-maximum-subarray.py @@ -0,0 +1,44 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the maxSubarray function below. +def maxSubarray(arr): + wsum,ans = arr[0],arr[0] + nonnegsum = 0 + ansarray = [] + for i in range(1,len(arr)): + wsum = max(arr[i],wsum+arr[i]) + ans = max(wsum,ans) + arr.sort() + if(arr[len(arr)-1]<0): + nonnegsum = arr[len(arr)-1] + else: + for i in arr: + if i >=0: + nonnegsum+=i + ansarray.append(ans) + ansarray.append(nonnegsum) + return ansarray + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + t = int(input()) + + for t_itr in range(t): + n = int(input()) + + arr = list(map(int, input().rstrip().split())) + + result = maxSubarray(arr) + + fptr.write(' '.join(map(str, result))) + fptr.write('\n') + + fptr.close() diff --git a/Hackerrank/Python/birthdayCakeCandles.py b/Hackerrank/Python/birthdayCakeCandles.py new file mode 100644 index 00000000..1124417e --- /dev/null +++ b/Hackerrank/Python/birthdayCakeCandles.py @@ -0,0 +1,24 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the birthdayCakeCandles function below. +def birthdayCakeCandles(ar): + return(ar.count(max(ar))) +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + ar_count = int(input()) + + ar = list(map(int, input().rstrip().split())) + + result = birthdayCakeCandles(ar) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Hackerrank/Python/findTheRunnerUp.py b/Hackerrank/Python/findTheRunnerUp.py new file mode 100644 index 00000000..9e34a1bd --- /dev/null +++ b/Hackerrank/Python/findTheRunnerUp.py @@ -0,0 +1,18 @@ +#This code is contributed by Shreevatsa N, @vatsa287 + +#Given the participants score sheet for your University Sports Day, +#you are required to find the runner-up score. +#You are given scores. Store them in a list and find the score of the runner-up. + +if __name__ == '__main__': + n = int(input()) + arr = map(int, input().split()) + + listnew=[] + for i in arr: + if i not in listnew: + listnew.append(i) + listnew.sort(reverse=True) #listnew.sort() print(listnew[-1]) + print(listnew[1]) + + diff --git a/Hackerrank/Python/gradingStudents.py b/Hackerrank/Python/gradingStudents.py new file mode 100644 index 00000000..c13af7c3 --- /dev/null +++ b/Hackerrank/Python/gradingStudents.py @@ -0,0 +1,60 @@ +#This code is contributed by Shreevatsa N , @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# +# Complete the 'gradingStudents' function below. +# +# The function is expected to return an INTEGER_ARRAY. +# The function accepts INTEGER_ARRAY grades as parameter. +# + +def gradingStudents(grades): + # Write your code here + + list1 = [] + for n in grades: + print(n) + if n >= 38 and n <= 100: #check if marks is within this range + if n%5 == 3 or n%5==4 : #if the remainder with 5 is either 3 or 4 since 5rem is treated as 0 + if n%10 > 5: #unit place is greater > 5 + temp = 10-n%10 + n = n + temp #add the required difference for round off + list1.append(n) + elif n%10 < 5: + temp = 5 - n%10 + n = n + temp + list1.append(n) + elif n%5 == 0 or n%5 == 1 or n%5 == 2: #if the difference between the marks and next multiple is less than 3 + list1.append(n) + else: #if marks is out of range then no rounding up + list1.append(n) + return(list1) + + + + + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + grades_count = int(input().strip()) + + grades = [] + + for _ in range(grades_count): + grades_item = int(input().strip()) + grades.append(grades_item) + + result = gradingStudents(grades) + + fptr.write('\n'.join(map(str, result))) + fptr.write('\n') + + fptr.close() diff --git a/Hackerrank/Python/listComprehensions.py b/Hackerrank/Python/listComprehensions.py new file mode 100644 index 00000000..879a4229 --- /dev/null +++ b/Hackerrank/Python/listComprehensions.py @@ -0,0 +1,9 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +if __name__ == '__main__': + x = int(input()) + y = int(input()) + z = int(input()) + n = int(input()) + + lis = [ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if((i+j+k)!=n) ] + print(lis) diff --git a/Hackerrank/Python/mini-max-sum.py b/Hackerrank/Python/mini-max-sum.py new file mode 100644 index 00000000..a51f37b3 --- /dev/null +++ b/Hackerrank/Python/mini-max-sum.py @@ -0,0 +1,18 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the miniMaxSum function below. +def miniMaxSum(arr): + min_int = sum(arr) - max(arr) + max_int = sum(arr) - min(arr) + print(min_int, max_int) +if __name__ == '__main__': + arr = list(map(int, input().rstrip().split())) + + miniMaxSum(arr) diff --git a/Hackerrank/Python/plus-minus.py b/Hackerrank/Python/plus-minus.py new file mode 100644 index 00000000..7d89a288 --- /dev/null +++ b/Hackerrank/Python/plus-minus.py @@ -0,0 +1,32 @@ +#This code is contributed by Shreevatsa N, @vatsa287 +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# Complete the plusMinus function below. +def plusMinus(arr): + length = len(arr) + cpos , cneg ,czer = 0, 0, 0 + for i in range(0,length): + if arr[i] > 0: #counters for pos,neg and zero nus. + cpos+=1 + elif arr[i] < 0: + cneg+=1 + else: + czer+=1 + print(cpos/length) #no of pos/neg/zero nos divided by total nos. + print(cneg/length) + print(czer/length) + + + +if __name__ == '__main__': + n = int(input()) + + arr = list(map(int, input().rstrip().split())) + + plusMinus(arr) From 574bbe96cb0a07b4b3330a7c0afd8c7d363c8e0c Mon Sep 17 00:00:00 2001 From: Sneha Santhosh <45783979+Sneha-Santhosh@users.noreply.github.com> Date: Mon, 6 Jul 2020 23:42:38 -0400 Subject: [PATCH 314/324] Create 461HammingDistance.java --- LeetCode/461HammingDistance.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/461HammingDistance.java diff --git a/LeetCode/461HammingDistance.java b/LeetCode/461HammingDistance.java new file mode 100644 index 00000000..2d2d1ba0 --- /dev/null +++ b/LeetCode/461HammingDistance.java @@ -0,0 +1,18 @@ +class Solution { + public int hammingDistance(int x, int y) { + int count =0; + String newX=String.format("%32s", Integer.toBinaryString(x)).replaceAll(" ", "0"); + String newY = String.format("%32s", Integer.toBinaryString(y)).replaceAll(" ", "0"); + + for (int i=0;i Date: Sun, 2 Aug 2020 02:34:50 +0500 Subject: [PATCH 315/324] Added "Print Pretty" and "Rectangle Area" --- Hackerrank/C++/PrintPretty.cpp | 24 +++++++++++++++++ Hackerrank/C++/RectangleArea.cpp | 46 ++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 Hackerrank/C++/PrintPretty.cpp create mode 100644 Hackerrank/C++/RectangleArea.cpp diff --git a/Hackerrank/C++/PrintPretty.cpp b/Hackerrank/C++/PrintPretty.cpp new file mode 100644 index 00000000..133f2b85 --- /dev/null +++ b/Hackerrank/C++/PrintPretty.cpp @@ -0,0 +1,24 @@ +#include +#include +using namespace std; + +int main() { + int T; cin >> T; + cout << setiosflags(ios::uppercase); + cout << setw(0xf) << internal; + while (T--) { + double A; cin >> A; + double B; cin >> B; + double C; cin >> C; + std::cout << std::hex << std::left << std::showbase << std::nouppercase << (long long)A << std::endl; + + std::cout << std::right << setw(15) << setfill('_') << std::showpos << std::fixed << std::setprecision(2); + std::cout << B << std::endl; + + std::cout << std::scientific << std::uppercase << std::noshowpos << std::setprecision(9) << C << std::endl; + /* Enter your code here */ + + } + return 0; + +} \ No newline at end of file diff --git a/Hackerrank/C++/RectangleArea.cpp b/Hackerrank/C++/RectangleArea.cpp new file mode 100644 index 00000000..e416e6f9 --- /dev/null +++ b/Hackerrank/C++/RectangleArea.cpp @@ -0,0 +1,46 @@ +#include + +using namespace std; +/* + * Create classes Rectangle and RectangleArea + */ + +class Rectangle { +public: + void display() { std::cout << width << " " << height << std::endl; } + int height; + int width; +}; + +class RectangleArea : public Rectangle { + +public: + void read_input() { std::cin >> width; std::cin >> height; } + void display() { std::cout << width * height << std::endl; } +}; + + +int main() +{ + /* + * Declare a RectangleArea object + */ + RectangleArea r_area; + + /* + * Read the width and height + */ + r_area.read_input(); + + /* + * Print the width and height + */ + r_area.Rectangle::display(); + + /* + * Print the area + */ + r_area.display(); + + return 0; +} \ No newline at end of file From 53361e4775abdff313a155237628a6b1b24f2297 Mon Sep 17 00:00:00 2001 From: Marek Slowikowski Date: Fri, 7 Aug 2020 09:36:45 +0200 Subject: [PATCH 316/324] DS/C#/BinarySearchTree --- DS/C#/BinarySearchTree/.gitignore | 363 ++++++++++++++++++ DS/C#/BinarySearchTree/BinarySearchTree.sln | 34 ++ .../BinarySearchTree/BinarySearchTree.cs | 198 ++++++++++ .../BinarySearchTree/BinarySearchTree.csproj | 7 + .../BinarySearchTree/TreeNode.cs | 13 + 5 files changed, 615 insertions(+) create mode 100644 DS/C#/BinarySearchTree/.gitignore create mode 100644 DS/C#/BinarySearchTree/BinarySearchTree.sln create mode 100644 DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs create mode 100644 DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj create mode 100644 DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs diff --git a/DS/C#/BinarySearchTree/.gitignore b/DS/C#/BinarySearchTree/.gitignore new file mode 100644 index 00000000..bda3696b --- /dev/null +++ b/DS/C#/BinarySearchTree/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates +.DS_Store + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/DS/C#/BinarySearchTree/BinarySearchTree.sln b/DS/C#/BinarySearchTree/BinarySearchTree.sln new file mode 100644 index 00000000..f08ffe73 --- /dev/null +++ b/DS/C#/BinarySearchTree/BinarySearchTree.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.26124.0 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BinarySearchTree", "BinarySearchTree\BinarySearchTree.csproj", "{FE1E8F1D-0B74-40AB-AC66-082EB99A973F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x64.ActiveCfg = Debug|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x64.Build.0 = Debug|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x86.ActiveCfg = Debug|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x86.Build.0 = Debug|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|Any CPU.Build.0 = Release|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x64.ActiveCfg = Release|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x64.Build.0 = Release|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x86.ActiveCfg = Release|Any CPU + {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs new file mode 100644 index 00000000..8548a36a --- /dev/null +++ b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.cs @@ -0,0 +1,198 @@ +using System; +using System.Collections.Generic; + +namespace DataStructures +{ + public class BinarySearchTree + { + public TreeNode Root { get; set; } + + private TreeNode PrivateInsert(TreeNode root, int value) + { + if (root == null) + { + root = new TreeNode { data = value }; + return root; + } + TreeNode current = root; + if (current.data == value) + return current; + if (current.data < value) + { + if (current.Left == null) + { + current.Left = new TreeNode { data = value }; + return current.Left; + } + else + return PrivateInsert(current.Left, value); + } + else + { + if (current.Right == null) + { + current.Right = new TreeNode { data = value }; + return current.Right; + } + else + return PrivateInsert(current.Right, value); + } + } + + public TreeNode Insert(int value) => PrivateInsert(Root, value); + + private TreeNode PrivateSearch(TreeNode root, int value) + { + TreeNode current = root; + return current.data == value + ? current + : current.data < value + ? current.Left == null + ? null + : PrivateSearch(current.Left, value) + : current.Right == null + ? null + : PrivateSearch(current.Right, value); + } + + public TreeNode Search(int value) => PrivateSearch(Root, value); + + private TreeNode PrivateFindParent(TreeNode root, int value) + { + if ((root == null) || (root.data == value)) + return null; + if (root.data < value) + return root?.Left.data == value ? root : PrivateFindParent(root.Left, value); + else + return root?.Right.data == value ? root : PrivateFindParent(root.Right, value); + } + + public bool Delete(int value) + { + var toDelete = PrivateSearch(Root, value); + if (toDelete == null) + return false; + if (toDelete.Left != null) + { + // Find the biggest from smaller TreeNodes + var temporary = toDelete.Left; + while (temporary.Right != null) + temporary = temporary.Right; + toDelete.data = temporary.data; + if (temporary.Right != null) + { + temporary.data = temporary.Left.data; + // CAUTION! Proper order of assignment + temporary.Right = temporary.Left.Right; + var anotherTemp = temporary.Left.Left; + temporary.Left.Dispose(); + temporary.Left = anotherTemp; + } + } + else if (toDelete.Right != null) + { + // Find the lowest from bigger TreeNodes + var temporary = toDelete.Right; + while (temporary.Left != null) + temporary = temporary.Left; + toDelete.data = temporary.data; + if (temporary.Right != null) + { + temporary.data = temporary.Right.data; + // CAUTION! Proper order of assignment + temporary.Left = temporary.Right.Left; + var anotherTemp = temporary.Right.Right; + temporary.Right.Dispose(); + temporary.Right = anotherTemp; + } + } + else + { + var parent = PrivateFindParent(Root, value); + if (parent?.Left.data == value) + { + parent.Left.Dispose(); + parent.Left = null; + } + + else + { + parent.Right.Dispose(); + parent.Right = null; + } + } + return false; + } + + private void PrivatePreOrderTraversal(TreeNode root, Action TreeNodeAction) + { + TreeNodeAction(root); + if (root.Left != null) + PrivatePreOrderTraversal(root.Left, TreeNodeAction); + if (root.Right != null) + PrivatePreOrderTraversal(root.Right, TreeNodeAction); + } + public void PreOrderTraversal(Action TreeNodeAction) + { + PrivatePreOrderTraversal(Root, TreeNodeAction); + } + + private void PrivateInOrderTraversal(TreeNode root, Action TreeNodeAction) + { + if (root.Left != null) + PrivateInOrderTraversal(root.Left, TreeNodeAction); + TreeNodeAction(root); + if (root.Right != null) + PrivateInOrderTraversal(root.Right, TreeNodeAction); + } + public void InOrderTraversal(Action TreeNodeAction) + { + PrivateInOrderTraversal(Root, TreeNodeAction); + } + + private void PrivatePodOrderTraversal(TreeNode root, Action TreeNodeAction) + { + if (root.Left != null) + PrivatePodOrderTraversal(root.Left, TreeNodeAction); + if (root.Right != null) + PrivatePodOrderTraversal(root.Right, TreeNodeAction); + TreeNodeAction(root); + } + + public void PostOrderTraversal(Action TreeNodeAction) + { + PrivatePodOrderTraversal(Root, TreeNodeAction); + } + + private void PrivateLevelOrderTraversal(TreeNode root, int level, List> treeLevels) + { + if (treeLevels.Count < level) + treeLevels.Add(new List()); + treeLevels[level - 1].Add(root); + if (root.Left != null) + PrivateLevelOrderTraversal(root.Left, level + 1, treeLevels); + if (root.Right != null) + PrivateLevelOrderTraversal(root.Right, level + 1, treeLevels); + } + + public void LevelOrderTraversal(Action TreeNodeAction, Action levelAction) + { + List> treeLevels = new List>(); + int currentLevel = 1; + + PrivateLevelOrderTraversal(Root, currentLevel, treeLevels); + + for (int i = 0; i < treeLevels.Count; i++) + { + List listItem = treeLevels[i]; + for (int j = 0; j < listItem.Count; j++) + { + TreeNode item = listItem[j]; + TreeNodeAction(item); + } + + levelAction(); + } + } + } +} diff --git a/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj new file mode 100644 index 00000000..f51c9c8f --- /dev/null +++ b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj @@ -0,0 +1,7 @@ + + + + netstandard2.1 + + + diff --git a/DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs b/DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs new file mode 100644 index 00000000..a4f06883 --- /dev/null +++ b/DS/C#/BinarySearchTree/BinarySearchTree/TreeNode.cs @@ -0,0 +1,13 @@ +using System; + +namespace DataStructures +{ + public class TreeNode : IDisposable + { + public int data; + public TreeNode Left { get; set; } + public TreeNode Right { get; set; } + + public void Dispose() => Dispose(); + } +} From 35d772635367ac70d5a53a575af0a8700d5aa69f Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Tue, 18 Aug 2020 14:12:30 +0530 Subject: [PATCH 317/324] Delete .gitignore --- DS/C#/BinarySearchTree/.gitignore | 363 ------------------------------ 1 file changed, 363 deletions(-) delete mode 100644 DS/C#/BinarySearchTree/.gitignore diff --git a/DS/C#/BinarySearchTree/.gitignore b/DS/C#/BinarySearchTree/.gitignore deleted file mode 100644 index bda3696b..00000000 --- a/DS/C#/BinarySearchTree/.gitignore +++ /dev/null @@ -1,363 +0,0 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.rsuser -*.suo -*.user -*.userosscache -*.sln.docstates -.DS_Store - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Mono auto generated files -mono_crash.* - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -[Ww][Ii][Nn]32/ -[Aa][Rr][Mm]/ -[Aa][Rr][Mm]64/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ -[Ll]ogs/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUnit -*.VisualState.xml -TestResult.xml -nunit-*.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ - -# ASP.NET Scaffolding -ScaffoldingReadMe.txt - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_h.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*_wpftmp.csproj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Coverlet is a free, cross platform Code Coverage Tool -coverage*.json -coverage*.xml -coverage*.info - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# NuGet Symbol Packages -*.snupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx -*.appxbundle -*.appxupload - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!?*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser -*- [Bb]ackup.rdl -*- [Bb]ackup ([0-9]).rdl -*- [Bb]ackup ([0-9][0-9]).rdl - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# CodeRush personal settings -.cr/personal - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ - -# Local History for Visual Studio -.localhistory/ - -# BeatPulse healthcheck temp database -healthchecksdb - -# Backup folder for Package Reference Convert tool in Visual Studio 2017 -MigrationBackup/ - -# Ionide (cross platform F# VS Code tools) working folder -.ionide/ - -# Fody - auto-generated XML schema -FodyWeavers.xsd From 76f94e3960c00a53010ee1d0b0dd3e0bf70a2cf4 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Tue, 18 Aug 2020 14:12:47 +0530 Subject: [PATCH 318/324] Delete BinarySearchTree.sln --- DS/C#/BinarySearchTree/BinarySearchTree.sln | 34 --------------------- 1 file changed, 34 deletions(-) delete mode 100644 DS/C#/BinarySearchTree/BinarySearchTree.sln diff --git a/DS/C#/BinarySearchTree/BinarySearchTree.sln b/DS/C#/BinarySearchTree/BinarySearchTree.sln deleted file mode 100644 index f08ffe73..00000000 --- a/DS/C#/BinarySearchTree/BinarySearchTree.sln +++ /dev/null @@ -1,34 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 15 -VisualStudioVersion = 15.0.26124.0 -MinimumVisualStudioVersion = 15.0.26124.0 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BinarySearchTree", "BinarySearchTree\BinarySearchTree.csproj", "{FE1E8F1D-0B74-40AB-AC66-082EB99A973F}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x64.ActiveCfg = Debug|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x64.Build.0 = Debug|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x86.ActiveCfg = Debug|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Debug|x86.Build.0 = Debug|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|Any CPU.ActiveCfg = Release|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|Any CPU.Build.0 = Release|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x64.ActiveCfg = Release|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x64.Build.0 = Release|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x86.ActiveCfg = Release|Any CPU - {FE1E8F1D-0B74-40AB-AC66-082EB99A973F}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal From 20a3191688cb5b5780064cf04ebb18321fa7546a Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Tue, 18 Aug 2020 14:13:02 +0530 Subject: [PATCH 319/324] Delete BinarySearchTree.csproj --- .../BinarySearchTree/BinarySearchTree.csproj | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj diff --git a/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj b/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj deleted file mode 100644 index f51c9c8f..00000000 --- a/DS/C#/BinarySearchTree/BinarySearchTree/BinarySearchTree.csproj +++ /dev/null @@ -1,7 +0,0 @@ - - - - netstandard2.1 - - - From c7d4b9ab5d76f9427ab2f2dbfad6130c2a916fcf Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Tue, 18 Aug 2020 14:14:02 +0530 Subject: [PATCH 320/324] Create c-cpp.yml --- .github/workflows/c-cpp.yml | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 .github/workflows/c-cpp.yml diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml new file mode 100644 index 00000000..e3233268 --- /dev/null +++ b/.github/workflows/c-cpp.yml @@ -0,0 +1,23 @@ +name: C/C++ CI + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: configure + run: ./configure + - name: make + run: make + - name: make check + run: make check + - name: make distcheck + run: make distcheck From 0addbe36acd3fd8e6c66f4715e4da1d8dba605e5 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Tue, 18 Aug 2020 14:42:44 +0530 Subject: [PATCH 321/324] Update c-cpp.yml --- .github/workflows/c-cpp.yml | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/.github/workflows/c-cpp.yml b/.github/workflows/c-cpp.yml index e3233268..56a7fd6d 100644 --- a/.github/workflows/c-cpp.yml +++ b/.github/workflows/c-cpp.yml @@ -7,17 +7,31 @@ on: branches: [ master ] jobs: - build: + build-ubuntu: runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v1 + - name: configure + run: mkdir build && cd build && cmake -DCMAKE_CXX_FLAGS="-Werror" .. + - name: build + run: cmake --build build + - name: test + run: cd build && ctest + + build-windows: + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [windows-latest, windows-2016] + steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v1 - name: configure - run: ./configure - - name: make - run: make - - name: make check - run: make check - - name: make distcheck - run: make distcheck + run: mkdir build && cd build && cmake .. + - name: build + run: cmake --build build --config Debug + - name: test + run: cd build && ctest From e0e36f3cc069e3097eec61beafd471741babe8c7 Mon Sep 17 00:00:00 2001 From: Vichitr Gandas Date: Tue, 18 Aug 2020 15:20:56 +0530 Subject: [PATCH 322/324] Mergify: configuration update --- .mergify.yml | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 .mergify.yml diff --git a/.mergify.yml b/.mergify.yml new file mode 100644 index 00000000..fac2166e --- /dev/null +++ b/.mergify.yml @@ -0,0 +1,7 @@ +pull_request_rules: + - name: Automatic merge on approval + conditions: + - "#approved-reviews-by>=1" + actions: + merge: + method: merge From 6ac821429a52079d4966c5042847c3b4930f7ebb Mon Sep 17 00:00:00 2001 From: SaraswatAnushka Date: Sun, 15 Oct 2023 23:39:50 +0530 Subject: [PATCH 323/324] linear_Search.py --- Algorithms/Python/linear_Search.py | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Algorithms/Python/linear_Search.py diff --git a/Algorithms/Python/linear_Search.py b/Algorithms/Python/linear_Search.py new file mode 100644 index 00000000..918981e6 --- /dev/null +++ b/Algorithms/Python/linear_Search.py @@ -0,0 +1,39 @@ +#python code for linear search +MAX = 20 +#array of items on which linear search will be conducted. +intArray = [1,2,3,4,6,7,9,11,12,14,15,16,17,19,33,34,43,45,55,66] +def printline(count): + for i in range(count-1): + print("=", end="") + print("=") +#this method makes a linear search. +def find(data): + comparisons = 0 + index = -1 + #navigate through all items + for i in range(MAX): + #count the comparisons made + comparisons += 1 + + #if data found, break the loop + if data == intArray[i]: + index = i + break + print("Total comparisons made:", comparisons) + return index +def display(): + print("[", end="") + #navigate through all items + for i in range(MAX): + print(intArray[i], end=" ") + print("]") +print("Input Array: ", end="") +display() +printline(50) +#find location of 1 +location = find(55) +#if element was found +if location != -1: + print("\nElement found at location:", location+1) +else: + print("Element not found.") \ No newline at end of file From f8858938f3bdd89e110fe70aa3c6c662bae4df55 Mon Sep 17 00:00:00 2001 From: Neelam Date: Sun, 21 Sep 2025 21:53:42 +0530 Subject: [PATCH 324/324] added ignore file --- .gitignore | 5 +++++ README.md | 3 +++ 2 files changed, 8 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..d1692e30 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.idea/ +Algorithms/Algorithms.iml +DS/DS.iml +Hackerrank/Hackerrank.iml +HacktoberfestForBeginners.iml diff --git a/README.md b/README.md index 52c72f9e..9e61eb68 100644 --- a/README.md +++ b/README.md @@ -14,3 +14,6 @@ You can also contribute to problem solutions of problems available on various pl - Do follow the convention mentioned. ### PS: Do not pick a problem from an ongoing contest. + +## Note: This repo is not eligible for Hacktoberfest 2025 new contributions. +