diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..27cdefb --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "files.associations": { + "vector": "cpp", + "iostream": "cpp", + "xstring": "cpp", + "ostream": "cpp" + } +} diff --git a/December - 01/.gitignore b/December - 01/.gitignore index ac6d3a2..87a7c80 100644 --- a/December - 01/.gitignore +++ b/December - 01/.gitignore @@ -1,182 +1,30 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem - -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# node.js -/node_modules -package-lock.json - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -pip-wheel-metadata/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -.python-version - -# pipenv -Pipfile.lock -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - # Prerequisites *.d +#code +#include +using namespace std; +string convert_ASCII(string hex){ + string ascii = ""; + for (size_t i = 0; i < hex.length(); i += 2) + { + string part = hex.substr(i, 2); + char ch = stoul(part, nullptr, 16); + ascii += ch; + } + return ascii; +} +int main() +{ + string hex; + cout<<"enter the hex"; + cin>>hex; + cout<<"entered string is\n"< +using namespace std; + +string hexToASCII(string hex){ + string ascii = ""; + for (size_t i = 0; i < hex.length(); i += 2){ + string part = hex.substr(i, 2); + char ch = stoul(part, nullptr, 16); + ascii += ch; + } + return ascii; +} + +int main(){ + int n; + cin >> n; + while(n>0){ + string a; + cin >> a; //Give input as a single word. + cout << hexToASCII(a) << endl; + n--; + } + return 0; +} diff --git a/December - 01/Cpp_Ankur.cpp b/December - 01/Cpp_Ankur.cpp new file mode 100644 index 0000000..1fd1425 --- /dev/null +++ b/December - 01/Cpp_Ankur.cpp @@ -0,0 +1,70 @@ + +#include +#include +using namespace std; +int main() +{ + // Declare a string to store the hexadecimal input + string hex; + int size, string_set; + cout << "Enter the number of hexadecimal strings sets\n"; + cin >> string_set; + cout << endl; + // Prompt the user to enter a hexadecimal string + + // Convert the hexadecimal string to an ASCII string + string ascii[string_set]; + for (int k = 0; k < string_set; k++) + { + cout<<"For the string set "<> size; + for (int j = 0; j < size; j++) + { + cout << "Enter the hexadecimal value at index " << j + 1 << endl; + cin >> hex; + // { 56, 6F, 75, 67, 68, 74} + for (int i = 0; i < hex.length(); i += 2) + { + char c = (char)strtol(hex.substr(i, 2).c_str(), NULL, 16); + ascii[k] += c; + } + } + } + + for (int i = 0; i < string_set; i++) + { + cout << ascii[i]<< endl; + } + + + // Print the ASCII string + + return 0; +} +// #include +// #include +// #include +// using namespace std; +// int main(){ +// string t; +// cout<<"Enter a vector of arrays\n"; +// vector a[5]; +// for (int i = 0; i <2 ; i++) +// { +// for (int j = 0; j < 5; j++) +// { +// cin>>t; +// a[i].push_back(t); +// } +// } +// for (int i = 0; i < 2; i++) { +// for (auto it = a[i].begin(); +// it != a[i].end(); it++) { +// cout << stoi(*it) << ' '; +// } +// cout << endl; +// } + +// return 0; +// } diff --git a/December - 01/Day 1 - William Butcher's Mission.py b/December - 01/Day 1 - William Butcher's Mission.py new file mode 100644 index 0000000..295b82e --- /dev/null +++ b/December - 01/Day 1 - William Butcher's Mission.py @@ -0,0 +1,15 @@ +def decode_hex_lists(hex_lists): + ascii_strings = [] + for hex_list in hex_lists: + ascii_chars = [chr(int(h, 16)) for h in hex_list] + ascii_string = ''.join(ascii_chars) + ascii_strings.append(ascii_string) + return ascii_strings + +#O-1 +hex_lists1 = [['56','6F','75','67','68','74']] +print(decode_hex_lists(hex_lists1)) + +#O-2 +hex_lists2 = [['49','6E','76','61','64','65'], ['4D','69','6C','69','74','61','72','79']] +print(decode_hex_lists(hex_lists2)) \ No newline at end of file diff --git a/December - 01/GREEDnim_day1_java.java b/December - 01/GREEDnim_day1_java.java new file mode 100644 index 0000000..7a97d55 --- /dev/null +++ b/December - 01/GREEDnim_day1_java.java @@ -0,0 +1,38 @@ + +import java.util.Arrays; +import java.util.Scanner; + +public class GREEDnim_day1_java { + public static void main(String[] args) { + // Assuming the input format as follows + // first line : no of words + // for the next n lines , space seperates hexadecimal values as a string + // eg + // 1st line : 2 + // 2nd line :49 6E 76 61 64 65 + // 3rd line : 4D 69 6C 69 74 61 72 79 + Scanner in=new Scanner(System.in); + StringBuilder ans= new StringBuilder(); + int noOfWords=0; + noOfWords=Integer.parseInt(in.nextLine().strip()); + + for(int i=0;i Input 1: +# 1 +# 56, 6F, 75, 67, 68, 74 +# Vought + +# ------> Input 2: +# 2 +# 49, 6E, 76, 61, 64, 65 +# 4D, 69, 6C, 69, 74, 61, 72, 79 +# Invade +# Military \ No newline at end of file diff --git a/December - 01/Python3_Lagan Mehta_December1.py b/December - 01/Python3_Lagan Mehta_December1.py new file mode 100644 index 0000000..1cb3048 --- /dev/null +++ b/December - 01/Python3_Lagan Mehta_December1.py @@ -0,0 +1,12 @@ +n=int(input()) +a=[] +for i in range(n): + a=list(input().split(',')) + b='' + for j in a: + b+=j + c=bytes.fromhex(b) + d=c.decode() + a.append(d) +for i in a: + print(i) diff --git a/December - 01/Python3_lakshmeeee.py b/December - 01/Python3_lakshmeeee.py new file mode 100644 index 0000000..e15b879 --- /dev/null +++ b/December - 01/Python3_lakshmeeee.py @@ -0,0 +1,9 @@ +code = [ "56", "6F", "75", "67", "68", "74"] +# code = input().split(',[]') +# print(code) +sr = "" +for i in code: + ch = chr(int(i, 16)) + sr+=ch +print(sr) + diff --git a/December - 01/WilliamButcher.cpp b/December - 01/WilliamButcher.cpp new file mode 100644 index 0000000..9e67e65 --- /dev/null +++ b/December - 01/WilliamButcher.cpp @@ -0,0 +1,32 @@ +#include +using namespace std; + +int main() +{ + vector> vec; + int n, x, k = 0; + string a; + cin >> n; + for (int i = 0; i < n; i++) + { + cin >> a; + vector v1; + for (int i = 0; i < a.length(); i += 2) + { + string s = a.substr(i, 2); + int ascii = stoi(s, 0, 16); + v1.push_back(ascii); + } + vec.push_back(v1); + } + + for (int i = 0; i < vec.size(); i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + cout << char(vec[i][j]); + } + cout << endl; + } + return 0; +} \ No newline at end of file diff --git a/December - 01/c++_Dhruv.cpp b/December - 01/c++_Dhruv.cpp new file mode 100644 index 0000000..c4bbe63 --- /dev/null +++ b/December - 01/c++_Dhruv.cpp @@ -0,0 +1,22 @@ +#include + +int main(){ + int t; + cin>>t; + + while(t--){ + vectorv; // v= { 56, 6F, 75, 67, 68, 74} + int n= v.size(); + + string res=""; + + for(int i=0;i +using namespace std; + +string hexToASCII(string hex) +{ + string ascii = ""; + for (size_t i = 0; i < hex.length(); i += 2) + { + string part = hex.substr(i, 2); + + char ch = stoul(part, nullptr, 16); + + ascii += ch; + } + return ascii; +} + +int main() +{ + string hex[10]; + int n; + cin>>n; + for(int i=0;i>hex[i]; + } + + cout< +using namespace std; +/* Abhi-Atg */ + +int check(char &c){ + if(c=='F'){ + return 15; + }else if(c=='E'){ + return 14; + }else if(c=='D'){ + return 13; + }else if(c=='C'){ + return 12; + }else if(c=='B'){ + return 11; + }else if(c=='A'){ + return 10; + } + return (int)(c-'0'); +} + +char solve(string &s){ + return (char)(check(s[0])*16+check(s[1])); +} + +int main(){ + + int n;cin>>n; + while(n--){ + fflush(stdin); + string s; + getline(cin,s); + string ans; + int len=s.size(); + string c; + for(int i=0;i +#include +#include +#include + +void tokenize(std::string const &str, const char delim, + std::vector &out) +{ + size_t start; + size_t end =0 ; + size_t n = str.length(); + + while ((start = str.find_first_not_of(delim, end)) != std::string::npos) + { + end = str.find(delim, start); + out.push_back(str.substr(start, end - start)); + } +} + +int main() +{ + std::string output; + std::string s = "4D,69,6C,69,74,61,72,79"; + const char delim = ','; + + std::vector out; + tokenize(s, delim, out); + +// for (auto &s: out) { +// std::cout << s << std::endl; +// } + + for (auto &s: out) { + uint32_t chr = 0; + std::stringstream ss; + ss << std::hex<>chr; + output.push_back(static_cast(chr)); + } + std::cout< +using namespace std; + +void tokenize(string const &str, const char delim, vector &out) +{ + size_t start; + size_t end = 0; + size_t n = str.length(); + + while ((start = str.find_first_not_of(delim, end)) != string::npos) + { + end = str.find(delim, start); + out.push_back(str.substr(start, end - start)); + } +} + +int main() +{ + string output; + string s = "56, 6F, 75, 67, 68, 74"; + const char delim = ','; + + vector out; + tokenize(s, delim, out); + + for (auto &s : out) + { + uint32_t chr = 0; + stringstream ss; + ss << hex << s; + ss >> chr; + output.push_back(static_cast(chr)); + } + cout << output; + return 0; +} diff --git a/December - 01/java_DCBisht01.java b/December - 01/java_DCBisht01.java new file mode 100644 index 0000000..f8303f4 --- /dev/null +++ b/December - 01/java_DCBisht01.java @@ -0,0 +1,37 @@ +import java.util.*; + + +class java_DCBisht01{ + public static void main(String[] args) { + // Assuming the input format as follows + // first line : no of words + // for the next n lines , space seperates hexadecimal values as a string + // eg + // 1st line : 2 + // 2nd line :49 6E 76 61 64 65 + // 3rd line :4D 69 6C 69 74 61 72 79 + Scanner in=new Scanner(System.in); + + int noOfWords=0; + noOfWords=Integer.parseInt(in.nextLine()); + + for(int i=0;i 0: + print("#problem_statment_01!!") + array_pre = input("") + junk_hexa = array_pre.split("},") + l = len(junk_hexa) + d = {} + x=1 + for i in junk_hexa: + d["lis{0}".format(x)] = i + x+=1 + #d=dict + t=0 + finlist=[] + for i in d: + a=d[i] + if(t==len(d)-1): + a1=a[1:len(a)-1] + tlist=a1.split(',') + finlist.append(tlist) + else: + a1=a[1:len(a)] + tlist=a1.split(',') + finlist.append(tlist) + t+=1 + + ascl=[] + + for i in finlist: + for j in i: + ascl.append(bytes.fromhex(j).decode('utf-8')) + ascl.append(' ') + + for i in ascl: + print(i,end='') + print("\n") \ No newline at end of file diff --git a/December - 01/python_subburamanathan7.py b/December - 01/python_subburamanathan7.py new file mode 100644 index 0000000..3213f04 --- /dev/null +++ b/December - 01/python_subburamanathan7.py @@ -0,0 +1,25 @@ +count = int(input("Enter number of words")) + +arr=[] +for i in range(count): + sub=[] + limit = int(input("Enter size of each word")) + for j in range(limit): + code = input("Enter code") + sub.append(code) + + arr.append(sub) + +ret_arr=[] +for i in arr: + sub=[] + for j in i: + temp= int(j,base=16) + sub.append(chr(temp)) + + ret_arr.append(sub) + +for i in ret_arr: + print("\n") + for j in i: + print(j,end="") diff --git a/December - 01/solution.py b/December - 01/solution.py new file mode 100644 index 0000000..e69de29 diff --git a/December - 02/.gitignore b/December - 02/.gitignore index ac6d3a2..7338e97 100644 --- a/December - 02/.gitignore +++ b/December - 02/.gitignore @@ -1,179 +1,3 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem - -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# node.js -/node_modules -package-lock.json - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -pip-wheel-metadata/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.nox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# IPython -profile_default/ -ipython_config.py - -# pyenv -.python-version - -# pipenv -Pipfile.lock -__pypackages__/ - -# Celery stuff -celerybeat-schedule -celerybeat.pid - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ -.dmypy.json -dmypy.json - -# Pyre type checker -.pyre/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - # Prerequisites *.d @@ -206,26 +30,19 @@ doc/api/ *.exe *.out *.app - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf +#include +#include +using namespace std; +int main() +{ + string ae="ae"; + string x; + char first,sec; + cout<<"enter a string"; + getline(cin,x); + first=x[0]; + sec=x[1]; + cout< +using namespace std; +int main(){ + + string s; + cin>>s; + + int n = s.length();//kipediawiae + + string removing_lastTwo = s.substr(0,n-2);// eliminating last two words + // kipediawi + // updating the length + n = removing_lastTwo.size(); + + string getting_ogWords = removing_lastTwo.substr(n-2,2);//wi + + string lastTime_removing = removing_lastTwo.substr(0,n-2);//kipedia + + + string og = getting_ogWords+lastTime_removing;//wikipedia + cout< +using namespace std; + +string piglatin (string s){ + int len = s.length (); + s.resize (len - 2); + string part = s.substr(s.size()-2, s.size()-1); + + return part + s.substr (0, s.size()-2); +} + +int main (){ + string str; + cin >> str; + string word = piglatin (str); + cout << word; + return 0; +} diff --git a/December - 02/C++_subburamanathan7.cpp b/December - 02/C++_subburamanathan7.cpp new file mode 100644 index 0000000..41a6c52 --- /dev/null +++ b/December - 02/C++_subburamanathan7.cpp @@ -0,0 +1,20 @@ +#include +#include +using namespace std; + +int main(){ + string codeWord; + + cout<<"Enter codeword"; + cin>>codeWord; + + if(codeWord.length()<=4){ + printf("Invalid codeword"); + return 0; + } + for(int i=codeWord.length()-4;i +#include +using namespace std; +int main() +{ + char a[1000]; + cout<<"INPUT:"; + cin>>a; + + int n=strlen(a); + int m=n-2; + char c[m]; + + for(int i=0;i +#include +#include +using namespace std; +int main(){ + cout< s{'k','i','p','e','d','i','a','w','i','a','e'}; + for (auto it = s.begin(); it != s.end(); it++) + { + cout<<*it; + } + cout< +using namespace std; + +int main() +{ + string str, str0; + cin >> str; + str.erase(str.size() - 2); + str0 = str.substr(str.length() - 2, 2); + str.erase(str.size() - 2); + str = str0 + str; + cout << str; +} \ No newline at end of file diff --git a/December - 02/cpp_Aadhi11.cpp b/December - 02/cpp_Aadhi11.cpp new file mode 100644 index 0000000..1702487 --- /dev/null +++ b/December - 02/cpp_Aadhi11.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + +int +main () +{ + string s, a; + cin >> s; + int k = s.length (); + if (s[k - 1] == 'e' && s[k - 2] == 'a') + { + a = s[k - 4]; + a = a + s[k - 3]; + for (int i = 0; i < k - 4; i++) + { + a = a + s[i]; + } + cout < +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + string s;cin>>s; + s.pop_back(); + s.pop_back(); + string ans; + ans.push_back(s.back()); + s.pop_back(); + ans.push_back(s.back()); + s.pop_back(); + reverse(ans.begin(),ans.end()); + reverse(s.begin(),s.end()); + while(s.size()){ + ans.push_back(s.back()); + s.pop_back(); + } + cout< +#include +#include + +using namespace std; +void secret(string &msg) { + msg.pop_back(); + msg.pop_back(); + msg.insert(0, 1, msg[msg.length()-1]); + msg.insert(0, 1, msg[msg.length()-2]); + // ^ size of string + // ^ pos + msg.pop_back(); + msg.pop_back(); +} + +int main(){ + string msg; + cin>>msg; + secret(msg); + cout< +#include + +using namespace std; +int main() { + + string str1; + cin >> str1; + + int l = str1.length(); + string str3 = str1.substr(l-4,2); + string str2 = str1.substr(0, l-4); + + cout< 0: + print("#problem_statment_02!!") + a=input() + msg_split=a.split() + for i in msg_split: + word_t=i[:len(i)-2:] + word_f1,word_f2=word_t[len(word_t)-2:len(word_t)+1],word_t[:len(word_t)-2] + finalword=word_f1+word_f2 + print(finalword) \ No newline at end of file diff --git a/December - 02/solution.py b/December - 02/solution.py new file mode 100644 index 0000000..e197567 --- /dev/null +++ b/December - 02/solution.py @@ -0,0 +1,12 @@ +def main(): + to_piglatin = "nguetoae" + print(translate_to_english(to_piglatin)) + return True +def translate_to_english(word): + list_word = list(word) + last_two_letters = list_word[-2:] + if last_two_letters == ['a', 'e']: + word = word[:-2] + word= word[-2]+word[-1]+word[:-2] + return word +main() \ No newline at end of file diff --git a/December - 03/.gitignore b/December - 03/.gitignore index ac6d3a2..47d4da9 100644 --- a/December - 03/.gitignore +++ b/December - 03/.gitignore @@ -1,6 +1,50 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem +#code +def minesweeper(n): + arr = [[0 for row in range(n)] for column in range(n)] + x = int(input("enter the x coordinate")) + y = int(input("enter the y coordinate")) + arr[y][x] = 'X' + if (x >= 1 and x <= 3): + arr[y][x+1] += 1 + arr[y][x-1] += 1 + if (x == 0): + arr[y][x+1] += 1 + if (x == 4): + arr[y][x-1] += 1 + if (x >= 1 and x <= 4) and (y >= 1 and y <= 4): + arr[y-1][x-1] += 1 + if (x >= 0 and x <= 3) and (y >= 1 and y <= 4): + arr[y-1][x+1] += 1 + if (x >= 0 and x <= 4) and (y >= 1 and y <= 4): + arr[y-1][x] += 1 + if (x >=0 and x <= 3) and (y >= 0 and y <= 3): + arr[y+1][x+1] += 1 + if (x >= 1 and x <= 4) and (y >= 0 and y <= 3): + arr[y+1][x-1] += 1 + if (x >= 0 and x <= 4) and (y >= 0 and y <= 3): + arr[y+1][x] += 1 + for row in arr: + print(" ".join(str(cell) for cell in row)) + print("") +if __name__ == "__main__": + s=int(input("enter the number")) + minesweeper(s) + + #code + + + + + + + + + + + + + + # Byte-compiled / optimized / DLL files __pycache__/ @@ -10,10 +54,6 @@ __pycache__/ # C extensions *.so -# node.js -/node_modules -package-lock.json - # Distribution / packaging .Python build/ @@ -93,7 +133,13 @@ ipython_config.py .python-version # pipenv -Pipfile.lock +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff @@ -129,103 +175,3 @@ dmypy.json # Pyre type checker .pyre/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf diff --git a/December - 03/C++_Dhruv.cpp b/December - 03/C++_Dhruv.cpp new file mode 100644 index 0000000..7fa8c14 --- /dev/null +++ b/December - 03/C++_Dhruv.cpp @@ -0,0 +1,53 @@ +#include +using namespace std; + +int main() { + + vector>v{{'-', '#', '-', '-', '#'},{'-', '-', '-', '-', '-'}, {'-', '-', '#', '-', '-'},{'-', '#', '-', '-', '#'},{'-', '#', '-', '-', '#'}}; + int n = size(v); + int m = size(v[0]); + vector>arr(n,vector (m, 0)); + for(int i=0;i=0 and arr[i-1][j]!=-1) + arr[i-1][j]++; + if(i+1=0 and arr[i][j-1]!=-1) + arr[i][j-1]++; + if(j+1=0 and j-1>=0 and arr[i-1][j-1]!=-1) + arr[i-1][j-1]++; + if(i-1>=0 and j+1=0 and arr[i+1][j-1]!=-1) + arr[i+1][j-1]++; + + + } + + } + } +// showing output matrix + + for(int i=0;i +using namespace std; + +int count(char a){ + if(a == '#'){ + return 1; + } + return 0; +} + +void FindTheBomb( vector>arr, int row, int col){ + for(size_t i=0; i> col; + cin >> row; + vector> arr(row+1, vector(col+1,0)); + + for(int i=0; i> arr[i][j]; + } + } + + FindTheBomb(arr,row,col); + + return 0; +} diff --git a/December - 03/C++_subburamanathan7.cpp b/December - 03/C++_subburamanathan7.cpp new file mode 100644 index 0000000..d55fbee --- /dev/null +++ b/December - 03/C++_subburamanathan7.cpp @@ -0,0 +1,65 @@ +#include + +using namespace std; + +int main(){ + char mines[5][5] ={ + {'-','-','-','-','-'}, + {'-','-','-','-','-'}, + {'-','-','#','-','-'}, + {'-','-','-','-','-'}, + {'-','-','-','-','-'}, + }; + int maps[5][5]; + for (int i = 0; i < 5; ++i){ + for (int j = 0; j <5; ++j){ + if(mines[i][j]=='#') + maps[i][j]= -1; + else{ + maps[i][j]=0; + if(j+1<5 || i+1<5 || j-1>=0 || i-1>=0){ + if(j+1<5) + if(mines[i][j+1]=='#') + maps[i][j]+=1; + if(i+1<5) + if(mines[i+1][j]=='#') + maps[i][j]+=1; + if(j-1>=0) + if(mines[i][j-1]=='#') + maps[i][j]+=1; + if(i-1>=0) + if(mines[i-1][j]=='#') + maps[i][j]+=1; + + if(j+1<5 && i+1<5) + if(mines[i+1][j+1]=='#') + maps[i][j]+=1; + + if(j-1>=0 && i-1>=0) + if(mines[i-1][j-1]=='#') + maps[i][j]+=1; + + if(j+1<5 && i-1>=0) + if(mines[i-1][j+1]=='#') + maps[i][j]+=1; + + if(j-1>=0 && i+1<5) + if(mines[i+1][j-1]=='#') + maps[i][j]+=1; + } + } + } + } + + for (int i = 0; i < 5; ++i){ + for (int j = 0; j < 5; ++j){ + printf("%3d",maps[i][j]); + } + printf("\n"); + } + printf("\n-1 represents the mines"); + + + + return 0; +} \ No newline at end of file diff --git a/December - 03/CPP_GANESHANHARI_DAY_ 3.cpp b/December - 03/CPP_GANESHANHARI_DAY_ 3.cpp new file mode 100644 index 0000000..85d6ebe --- /dev/null +++ b/December - 03/CPP_GANESHANHARI_DAY_ 3.cpp @@ -0,0 +1,59 @@ +#include +#include +using namespace std; +int main() +{ + +/* cout<<"INPUT:"; + cin>>n;*/ + int n=5; + char a[n][n]={{'-', '#', '-', '-', '#'},{'-', '-', '-', '-', '-'}, {'-', '-', '#', '-', '-'},{'-', '#', '-', '-', '#'},{'-', '#', '-', '-', '#'}}; +/*for(int i=0;i>a[i][j]; + + } + +}*/ + +int xdir[8]={0,0,-1,-1,-1,1,1}; +int ydir[8]={-1,1,-1,0,1,-1,0,1}; +int xpos,ypos; +cout<<"OUTPUT:"<=n||xpos<0) break; + if(a[xpos][ypos]=='#') + { + if(a[i][j]=='-') a[i][j]='1'; + else a[i][j]=(char)((int)(a[i][j])+1); + } + } + } + + if(a[i][j]=='-'&&a[i][j]!='#') a[i][j]='0'; + + cout<= 0 and row < rows and col >= 0 and col < cols: + if minefield[row][col] == '#': + count += 1 + + output[i][j] = str(count) + for row in output: + print("".join(row)) +N = int(input()) +minefield1 = [["-", "-", "-", "-", "-"], +["-", "-", "-", "-", "-"], +["-", "-", "#", "-", "-"], +["-", "-", "-", "-", "-"], +["-", "-", "-", "-", "-"]] +display_minefield(minefield1,N) \ No newline at end of file diff --git a/December - 03/GREEDnim_day3_java.java b/December - 03/GREEDnim_day3_java.java new file mode 100644 index 0000000..3ef05ec --- /dev/null +++ b/December - 03/GREEDnim_day3_java.java @@ -0,0 +1,76 @@ + +import java.util.Arrays; +import java.util.Scanner; + +public class GREEDnim_day3_java { + + public static void main(String[] args) + { + char[][]input=getInput(); + char[][]ans=minesweeper(input); + for(char[] arr:ans) + { + System.out.println(Arrays.toString(arr)); + } + + + + } + public static char[][] getInput() + { + Scanner in=new Scanner(System.in); + int rows=in.nextInt(); + char[][] input=new char[rows][rows]; + for(int i=0;i= 0 && k < arr[0].length) { + if (row - 1 >= 0 && arr[row - 1][k] != '#') // for prev row + { + int val = arr[row - 1][k] + 1; + arr[row - 1][k] = (char) val; + } + if (arr[row][k] != '#') // for cur row + { + int val = arr[row][k] + 1; + arr[row][k] = (char) val; + } + if (row + 1 < arr.length && arr[row + 1][k] != '#') // for next row + { + int val = arr[row + 1][k] + 1; + arr[row + 1][k] = (char) val; + } + } + k++; + } + } +} diff --git a/December - 03/Java_Ankur2606.java b/December - 03/Java_Ankur2606.java new file mode 100644 index 0000000..37e7949 --- /dev/null +++ b/December - 03/Java_Ankur2606.java @@ -0,0 +1,91 @@ +import java.io.*; +import java.util.*; +public class Java_Ankur2606{ + public String[][] convertDashToZero(String[][] arr, int n){ + for(int i=0;i= 0 && arr[verUp][j].equals("#") == false){ + arr[verUp][j] = Integer.toString(Integer.parseInt(arr[verUp][j]) + 1); + } + if(verDown <= (n-1) && arr[verDown][j].equals("#") == false){ + arr[verDown][j] = Integer.toString(Integer.parseInt(arr[verDown][j]) + 1); + } + if(horLeft >= 0 && arr[i][horLeft].equals("#") == false){ + arr[i][horLeft] = Integer.toString(Integer.parseInt(arr[i][horLeft]) + 1); + } + if(horRight <= (n-1) && arr[i][horRight].equals("#") == false){ + arr[i][horRight] = Integer.toString(Integer.parseInt(arr[i][horRight]) + 1); + } + + if(horLeft >= 0 && verUp >= 0 && arr[verUp][horLeft].equals("#") == false){ + arr[verUp][horLeft] = Integer.toString(Integer.parseInt(arr[verUp][horLeft]) + 1); + } + if(horLeft >= 0 && verDown <= (n-1) && arr[verDown][horLeft].equals("#") == false){ + arr[verDown][horLeft] = Integer.toString(Integer.parseInt(arr[verDown][horLeft]) + 1); + } + if(horRight <= (n-1) && verUp >= 0 && arr[verUp][horRight].equals("#") == false){ + arr[verUp][horRight] = Integer.toString(Integer.parseInt(arr[verUp][horRight]) + 1); + } + if(horRight <= (n-1) && verDown <= (n-1) && arr[verDown][horRight].equals("#") == false){ + arr[verDown][horRight] = Integer.toString(Integer.parseInt(arr[verDown][horRight]) + 1); + } + } + } + } + + return arr; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input : "); + int n = sc.nextInt(); + String[][] arr = new String[n][n]; + for(int i=0;i= 0 && arr[verUp][j].equals("#") == false){ + arr[verUp][j] = Integer.toString(Integer.parseInt(arr[verUp][j]) + 1); + } + if(verDown <= (n-1) && arr[verDown][j].equals("#") == false){ + arr[verDown][j] = Integer.toString(Integer.parseInt(arr[verDown][j]) + 1); + } + if(horLeft >= 0 && arr[i][horLeft].equals("#") == false){ + arr[i][horLeft] = Integer.toString(Integer.parseInt(arr[i][horLeft]) + 1); + } + if(horRight <= (n-1) && arr[i][horRight].equals("#") == false){ + arr[i][horRight] = Integer.toString(Integer.parseInt(arr[i][horRight]) + 1); + } + + if(horLeft >= 0 && verUp >= 0 && arr[verUp][horLeft].equals("#") == false){ + arr[verUp][horLeft] = Integer.toString(Integer.parseInt(arr[verUp][horLeft]) + 1); + } + if(horLeft >= 0 && verDown <= (n-1) && arr[verDown][horLeft].equals("#") == false){ + arr[verDown][horLeft] = Integer.toString(Integer.parseInt(arr[verDown][horLeft]) + 1); + } + if(horRight <= (n-1) && verUp >= 0 && arr[verUp][horRight].equals("#") == false){ + arr[verUp][horRight] = Integer.toString(Integer.parseInt(arr[verUp][horRight]) + 1); + } + if(horRight <= (n-1) && verDown <= (n-1) && arr[verDown][horRight].equals("#") == false){ + arr[verDown][horRight] = Integer.toString(Integer.parseInt(arr[verDown][horRight]) + 1); + } + } + } + } + + return arr; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input : "); + int n = sc.nextInt(); + String[][] arr = new String[n][n]; + for(int i=0;i= 0 && arr[i-1][j] != '#') { + arr[i-1][j] = (char)((int) arr[i-1][j] + 1); + } + + if(i+1 < n && arr[i+1][j] != '#') { + arr[i+1][j] = (char)((int) arr[i+1][j] + 1); + } + + if(j-1 > -1 && arr[i][j-1] != '#') { + arr[i][j-1] = (char)((int) arr[i][j-1] + 1); + } + + if(j+1 < n && arr[i][j+1] != '#') { + arr[i][j+1] = (char)((int) arr[i][j+1] + 1); + } + + // top left + + if(i-1 >= 0 && j-1 >=0 && arr[i-1][j-1] != '#') { + arr[i-1][j-1] = (char)((int) arr[i-1][j-1] + 1); + } + + // top right + + if(i-1 >= 0 && j+1 < n && arr[i-1][j+1] != '#') { + arr[i-1][j+1] = (char)((int) arr[i-1][j+1] + 1); + } + + // bottom left + + if(i+1 < n && j-1 >= 0 && arr[i+1][j-1] != '#') { + arr[i+1][j-1] = (char)((int) arr[i+1][j-1] + 1); + } + + // bottom right + + if(i+1 +using namespace std; + +int main() +{ + int n; + cin >> n; + vector> vec; + string a; + for (int i = 0; i < n; i++) + { + vector v1; + for (int j = 0; j < n; j++) + { + cin >> a; + v1.push_back(a); + } + vec.push_back(v1); + } + cout << endl; + + for (int i = 0; i < vec.size(); i++) + { + for (int j = 0; j < vec[i].size(); j++) + { + int count = 0; + if (vec[i][j] == "-" && vec[i][j + 1] == "#") + { + count++; + } + if (vec[i][j] == "-" && vec[i + 1][j] == "#") + { + count++; + } + if (vec[i][j] == "-" && vec[i + 1][j + 1] == "#") + { + count++; + } + } + } + + for (int i = 0; i < vec.size(); i++) + { + for (auto x : vec[i]) + { + cout << x << " "; + } + cout << endl; + } + return 0; +} \ No newline at end of file diff --git a/December - 03/Praveen Kumar/praveen_python3.py b/December - 03/Praveen Kumar/praveen_python3.py new file mode 100644 index 0000000..d2c7b43 --- /dev/null +++ b/December - 03/Praveen Kumar/praveen_python3.py @@ -0,0 +1,141 @@ +n = int(input()) + +array = [] + +for x in range(0, n): + l = input() + l = l.replace('-', '0').split(' ') + l = l[:5] + array.append(l) + +for x in range(0, n): + for x1 in range(0,n): + if array[x][x1] == '#': + if ((x==0) and (x1==0)): + if array[x][x1+1] != '#': + array[x][x1+1] = int(array[x][x1+1]) + 1 + if array[x+1][x1+1] != '#': + array[x+1][x1+1] = int(array[x+1][x1+1]) + 1 + if array[x+1][x1] != '#': + array[x+1][x1] = int(array[x+1][x1]) + 1 + elif x1 == 0: + if array[x-1][x1] != '#': + array[x-1][x1] = int(array[x-1][x1]) + 1 + if array[x-1][x1+1] != '#': + array[x-1][x1+1] = int(array[x-1][x1+1]) + 1 + if array[x][x+1] != '#': + array[x][x1+1] = int(array[x][x1+1]) + 1 + if array[x+1][x1+1] != '#': + array[x+1][x1+1] = int(array[x+1][x1+1]) + 1 + if array[x+1][x1] != '#': + array[x+1][x1] = int(array[x+1][x1]) + 1 + elif ((x == n-1) and (x1== 0)): + if array[x-1][x1] != '#': + array[x-1][x1] = int(array[x-1][x1]) + 1 + if array[x-1][x1+1] != '#': + array[x-1][x1+1] = int(array[x-1][x1+1]) + 1 + if array[x][x+1] != '#': + array[x][x1+1] = int(array[x][x1+1]) + 1 + elif ((x == 0) and (x1== n-1)): + if array[x+1][x1] != '#': + array[x+1][x1] = int(array[x+1][x1]) + 1 + if array[x+1][x1-1] != '#': + array[x+1][x1-1] = int(array[x+1][x1-1]) + 1 + if array[x][x1-1] != '#': + array[x][x1-1] = int(array[x][x1-1]) + 1 + elif ((x == n-1) and (x1== n-1)): + if array[x-1][x1] != '#': + array[x-1][x1] = int(array[x-1][x1]) + 1 + if array[x-1][x1-1] != '#': + array[x-1][x1-1] = int(array[x-1][x1-1]) + 1 + if array[x][x1-1] != '#': + array[x][x1-1] = int(array[x][x1-1]) + 1 + elif ((x != 0) and (x1== n-1)): + if array[x+1][x1] != '#': + array[x+1][x1] = int(array[x+1][x1]) + 1 + if array[x+1][x1-1] != '#': + array[x+1][x1-1] = int(array[x+1][x1-1]) + 1 + if array[x][x1-1] != '#': + array[x][x1-1] = int(array[x][x1-1]) + 1 + if array[x-1][x1] != '#': + array[x-1][x1] = int(array[x-1][x1]) + 1 + if array[x-1][x1-1] != '#': + array[x-1][x1-1] = int(array[x-1][x1-1]) + 1 + elif ((x ==0) and (x1 !=0)): + if array[x][x1-1] != '#': + array[x][x1-1] = int(array[x][x1-1]) + 1 + if array[x+1][x1-1] != '#': + array[x+1][x1-1] = int(array[x+1][x1-1]) + 1 + if array[x][x1+1] != '#': + array[x][x1+1] = int(array[x][x1+1]) + 1 + if array[x+1][x1+1] != '#': + array[x+1][x1+1] = int(array[x+1][x1+1]) + 1 + if array[x+1][x1] != '#': + array[x+1][x1] = int(array[x+1][x1]) + 1 + elif ((x == n-1) and (x1 !=0)): + if array[x][x1-1] != '#': + array[x][x1-1] = int(array[x][x1-1]) + 1 + if array[x-1][x1-1] != '#': + array[x-1][x1-1] = int(array[x-1][x1-1]) + 1 + if array[x][x1+1] != '#': + array[x][x1+1] = int(array[x][x1+1]) + 1 + if array[x-1][x1+1] != '#': + array[x-1][x1+1] = int(array[x-1][x1+1]) + 1 + if array[x-1][x1] != '#': + array[x-1][x1] = int(array[x-1][x1]) + 1 + + + elif (x != 0 and x1!=0): + if array[x][x1-1] != '#': + array[x][x1-1] = int(array[x][x1-1]) + 1 + if array[x-1][x1-1] != '#': + array[x-1][x1-1] = int(array[x-1][x1-1]) + 1 + if array[x-1][x1+1] != '#': + array[x-1][x1+1] = int(array[x-1][x1+1]) + 1 + if array[x-1][x1] != '#': + array[x-1][x1] = int(array[x-1][x1]) + 1 + if array[x+1][x1-1] != '#': + array[x+1][x1-1] = int(array[x+1][x1-1]) + 1 + if array[x][x1+1] != '#': + array[x][x1+1] = int(array[x][x1+1]) + 1 + if array[x+1][x1] != '#': + array[x+1][x1] = int(array[x+1][x1]) + 1 + if array[x+1][x1+1] != '#': + array[x+1][x1+1] = int(array[x+1][x1+1]) + 1 + +for x in range(n): + for x1 in range(n): + array[x][x1] = str(array[x][x1]) + +for x in range(n): + print(array[x]) + +# input samle case1: + +# 5 +# - - - - - +# - - - - - +# - - # - - +# - - - - - +# - - - - - + +# output: +# ['0', '0', '0', '0', '0'] +# ['0', '1', '1', '1', '0'] +# ['0', '1', '#', '1', '0'] +# ['0', '1', '1', '1', '0'] +# ['0', '0', '0', '0', '0'] + +# 5 +# - # - - # +# - - - - - +# - - # - - +# - # - - # +# - # - - # + +# output +# ['1', '#', '1', '1', '#'] +# ['1', '2', '2', '2', '1'] +# ['1', '2', '#', '2', '1'] +# ['2', '#', '3', '3', '#'] +# ['2', '#', '2', '2', '#'] \ No newline at end of file diff --git a/December - 03/Python3_Lagan Mehta_December3.py b/December - 03/Python3_Lagan Mehta_December3.py new file mode 100644 index 0000000..d86b715 --- /dev/null +++ b/December - 03/Python3_Lagan Mehta_December3.py @@ -0,0 +1,35 @@ +a=[] +print("Enter the size you want:") +n=int(input()) +print("Enter the elements for it:") +for i in range(0,n): + b=[] + for j in range(0,n): + x=input() + b.append(x) + a.append(b) +print("Before:") +for i in range(0,n): + for j in range(0,n): + print(a[i][j],end=' ') + print("\n") +for i in range(0,n): + for j in range(0,n): + if(a[i][j]=='-'): + a[i][j]='0' +for i in range(0,n): + for j in range(0,n): + if(a[i][j]=='#'): + for k in range(i-1,i+2): + for l in range(j-1,j+2): + if(k in range(0,n) and l in range(0,n)): + if(k==i and l==j): + continue + elif(a[k][l]!='#'): + x=int(a[k][l])+1 + a[k][l]=str(x) +print("After:") +for i in range(0,n): + for j in range(0,n): + print(a[i][j],end=' ') + print("\n") \ No newline at end of file diff --git a/December - 03/cpp_Aadhi11.cpp b/December - 03/cpp_Aadhi11.cpp new file mode 100644 index 0000000..eaf26b5 --- /dev/null +++ b/December - 03/cpp_Aadhi11.cpp @@ -0,0 +1,111 @@ +#include +#include +using namespace std; + +int +main () +{ + string s[10]; + int n, a[10][10]; + cin >> n; + for (int i = 0; i < n; i++) + { + cin >> s[i]; + } + for (int i = 0; i < n; i++) + { + int c = 0; + for (int j = 0; j < s[i].length (); j++) + { + if (s[i][j] == '-') + { + a[i][c] = 0; + c++; + } + if (s[i][j] == '#') + { + a[i][c] = '#'; + c++; + } + } + } + for (int i = 0; i < n; i++) + { + for (int j = 0; j < n; j++) + { + if (a[i][j] == '#') + { + if (a[i + 1][j + 1] != '#') + a[i + 1][j + 1] = a[i + 1][j + 1] + 1; + if (a[i - 1][j - 1] != '#') + a[i - 1][j - 1] = a[i - 1][j - 1] + 1; + if (a[i - 1][j + 1] != '#') + a[i - 1][j + 1] = a[i - 1][j + 1] + 1; + if (a[i + 1][j - 1] != '#') + a[i + 1][j - 1] = a[i + 1][j - 1] + 1; + if (a[i - 1][j] != '#') + a[i - 1][j] = a[i - 1][j] + 1; + if (a[i + 1][j] != '#') + a[i + 1][j] = a[i + 1][j] + 1; + if (a[i][j - 1] != '#') + a[i][j - 1] = a[i][j - 1] + 1; + if (a[i][j + 1] != '#') + a[i][j + 1] = a[i][j + 1] + 1; + } + } + } + for (int i = 0; i < n; i++) + { + int c = 0; + for (int j = 0; j < s[i].length (); j++) + { + if (s[i][j] == '-') + { + switch (a[i][c]) + { + case 0: + s[i][j] = '0'; + break; + case 1: + s[i][j] = '1'; + break; + case 2: + s[i][j] = '2'; + break; + case 3: + s[i][j] = '3'; + break; + case 4: + s[i][j] = '4'; + break; + case 5: + s[i][j] = '5'; + break; + case 6: + s[i][j] = '6'; + break; + case 7: + s[i][j] = '7'; + break; + case 8: + s[i][j] = '8'; + break; + } + c++; + } + if (s[i][j] == '#') + { + c++; + } + + } + } + cout << endl; + for (int i = 0; i < n; i++) + { + cout << s[i] << endl; + } + +} + + diff --git a/December - 03/cpp_abhi-atg.cpp b/December - 03/cpp_abhi-atg.cpp new file mode 100644 index 0000000..9c8804c --- /dev/null +++ b/December - 03/cpp_abhi-atg.cpp @@ -0,0 +1,71 @@ +#include +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int n;cin>>n; + vector v; + fflush(stdin); + for(int i=0;i ans=v; + for(int i=0;i=0 && ans[i-1][j]!='#'){ + ans[i-1][j]++; + } + if(i+1=0 && ans[i][j-5]!='#'){ + ans[i][j-5]++; + } + if(j+5=0 && j-5>=0 && ans[i-1][j-5]!='#'){ + ans[i-1][j-5]++; + } + if(i-1>=0 && j+5=0 && ans[i+1][j-5]!='#'){ + ans[i+1][j-5]++; + } + if(i+1 +#include +using namespace std; +bool yLow(int y) { + return y>=0; +} +bool yHigh(int y, int size) { + return y=0; +} +bool xHigh(int x, int size) { + return x> &arr) { + int n = arr.size(); + for(int i=0; i>n; + // Create char matrix, default value is 0 + vector> arr(n, vector (n, '0')); + char inp; + + for(int i=0; i>inp; + if(inp == '#') + arr[i][j]=inp; + } + } + + minesweep(arr); + + for(int i=0; i +using namespace std; + +int main() { + + vector>v{{'-', '#', '-', '-', '#'},{'-', '-', '-', '-', '-'}, {'-', '-', '#', '-', '-'},{'-', '#', '-', '-', '#'},{'-', '#', '-', '-', '#'}}; + int n = v.size(); + int m = v[0].size(); + vector>arr(n,vector (m, 0)); + for(int i=0;i=0 and arr[i-1][j]!=-1) + arr[i-1][j]++; + if(i+1=0 and arr[i][j-1]!=-1) + arr[i][j-1]++; + if(j+1=0 and j-1>=0 and arr[i-1][j-1]!=-1) + arr[i-1][j-1]++; + if(i-1>=0 and j+1=0 and arr[i+1][j-1]!=-1) + arr[i+1][j-1]++; + + + } + + } + } + for(int i=0;i=0 && k=0 && arr[row-1][k]!='#') + { + int val = arr[row - 1][k] + 1; + arr[row - 1][k] = (char)val; + } + if(arr[row][k]!='#') + { + int val = arr[row][k] + 1; + arr[row ][k] = (char)val; + } + if(row+1 0: + print("#problem_statment_03!!") + n = int(input("n =")) + v1_mat = [] + hash_ind_lis = [] + add_one_ind_lis = [] + + x = 1 + index = n-1 + for i in range(0, n): + mat = input("") + junk_mat = mat.split("\"") + for j in junk_mat: + if j == "[" or j == "]" or j == "]," or j == ", ": + pass + else: + v1_mat.append(j) + + + for i in range(0, len(v1_mat)): + if v1_mat[i] == "#": + hash_ind_lis.append(i) + else: + v1_mat[i] = 0 + + col_h_1, col_h_2,list_1 = [], [],[] + + index_of_column_last = [] + element =0 + for i in range (0,((n*n))): + if element==4: + index_of_column_last.append(i) + element=-1 + element+=1 + + for j in hash_ind_lis: + # print(j) + if j % n == 0: + col_h_1.append(j) + elif j in index_of_column_last: + col_h_2.append(j) + + + + for i in hash_ind_lis: + if i == 0: + x1 = i+1 + x2 = i+n + x3 = i+(n+1) + temp = [x1, x2, x3] + + elif i < (n-1) and i > 0: + x1 = i+1 + x2 = i-1 + x3 = i+n + x4 = i+(n-1) + x5 = i+(n+1) + temp = [x1, x2, x3, x4, x5] + elif i == n-1: + x1 = i-1 + x2 = i+(n-1) + x3 = i+n + temp = [x1, x2, x3] + + elif i in col_h_1 and i != 0 and i != ((n*n)-n): + x1 = i-n + x2 = i-(n-1) + x3 = i+1 + x4 = i+n + x5 = i+(n+1) + temp = [x1, x2, x3, x4, x5] + + elif i == (n*n)-n: + x1 = i-n + x2 = i-(n+1) + x3 = i+1 + temp = [x1, x2, x3] + + elif i > (n*n)-n and i < ((n*n)-1): + x1 = i-(n-1) + x2 = i-(n+1) + x3 = i-n + x4 = i-1 + x5 = i+1 + temp = [x1, x2, x3, x4, x5] + + elif i == (n*n)-1: + x1 = i-(n+1) + x2 = i-n + x3 = i-1 + temp = [x1, x2, x3] + + elif i in col_h_2 and i != (n*n)-1 and i != (n-1): + x1 = i-1 + x2 = i-(n+1) + x3 = i-n + x4 = i+n + x5 = i+(n-1) + temp = [x1, x2, x3, x4, x5] + else: + x1 = i-(n-1) + x2 = i-(n+1) + x3 = i-n + x4 = i-1 + x5 = i+1 + x6 = i+n + x7 = i+(n-1) + x8 = i+(n+1) + temp = [x1, x2, x3, x4, x5, x6, x7, x8] + for j in temp: + list_1.append(j) + + for i in list_1: + if i in hash_ind_lis: + list_1.remove(i) + + # print(hash_ind_lis) + # print(list_1) + # print(v1_mat) + + for i in list_1: + try: + v1_mat[i] += 1 + except: + pass + + A = [str(x) for x in v1_mat] + + + def nest_list(list1,rows, columns): + result=[] + start = 0 + end = columns + for i in range(rows): + result.append(list1[start:end]) + start +=columns + end += columns + return result + x = nest_list(A,n,n) + print("\n\noutput:") + + index = 0 + for i in x: + if index<(n-1): + print(json.dumps(i),",",sep="") + index+=1 + else: + print(json.dumps(i)) \ No newline at end of file diff --git a/December - 03/python3_lakshmeeee b/December - 03/python3_lakshmeeee new file mode 100644 index 0000000..9aa5dc8 --- /dev/null +++ b/December - 03/python3_lakshmeeee @@ -0,0 +1,2 @@ +for i in range(10): + print('Minesweeper') \ No newline at end of file diff --git a/December - 04/.gitignore b/December - 04/.gitignore index ac6d3a2..0986ddf 100644 --- a/December - 04/.gitignore +++ b/December - 04/.gitignore @@ -1,8 +1,66 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem +#code +def maxCrossingSum(arr, l, m, h): + sm = 0 + left_sum = -10000 -# Byte-compiled / optimized / DLL files + for i in range(m, l-1, -1): + sm = sm + arr[i] + + if (sm > left_sum): + left_sum = sm + sm = 0 + right_sum = -1000 + for i in range(m, h + 1): + sm = sm + arr[i] + + if (sm > right_sum): + right_sum = sm + return max(left_sum + right_sum - arr[m], left_sum, right_sum) +def maxSubArraySum(arr, l, h): + if (l > h): + return -10000 + if (l == h): + return arr[l] + m = (l + h) // 2 + return max(maxSubArraySum(arr, l, m-1), + maxSubArraySum(arr, m+1, h), + maxCrossingSum(arr, l, m, h)) +arr = [] +n = int(input("enter the numbers")) +for i in range(0,n): + ele=int(input()) + arr.append(ele) +print(arr) +k=len(arr) +max_sum = maxSubArraySum(arr, 0, k-1) +print("Maximum sum is ", max_sum) +#code + + + + + + + + + + + + + + + + + + + + + + + + + +## Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class @@ -10,10 +68,6 @@ __pycache__/ # C extensions *.so -# node.js -/node_modules -package-lock.json - # Distribution / packaging .Python build/ @@ -93,7 +147,13 @@ ipython_config.py .python-version # pipenv -Pipfile.lock +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff @@ -129,103 +189,3 @@ dmypy.json # Pyre type checker .pyre/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf diff --git a/December - 04/C++_Dhruv.cpp b/December - 04/C++_Dhruv.cpp new file mode 100644 index 0000000..f6fba8e --- /dev/null +++ b/December - 04/C++_Dhruv.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + +int main() { + int days; + cin>>days; + vectorv(days); + for(auto& num :v)cin>>num; + + + int max_sum=INT_MIN; + int curr_sum =0; + int first_day=0,last_day; + + for(int i=0;imax_sum){ + max_sum = curr_sum; + last_day=i; + } + + if(curr_sum<0){ + curr_sum=0; + first_day = i+1; + } + + } + + vectoralldays; + for(int i=first_day ;i<=last_day;i++){ + alldays.push_back(v[i]); + } + cout<<"Max profit: "< +using namespace std; + +//Kadane's Algorithm +void maxProfit(int prices[], int n) { + int sum = 0, profit=INT_MIN, sellday, buyday=1; + for(int i=0; i> n; + cout << "Given stock market change values:"; + int prices[n]; + for(int i=0; i> prices[i]; + } + maxProfit(prices, n); + return 0; +} diff --git a/December - 04/C++_subburamanathan7.cpp b/December - 04/C++_subburamanathan7.cpp new file mode 100644 index 0000000..6449a97 --- /dev/null +++ b/December - 04/C++_subburamanathan7.cpp @@ -0,0 +1,61 @@ +#include +#include +#include + +int max(int a, int b) { + return (a > b) ? a : b; +} + +int max(int a, int b, int c) { + return max(max(a, b), c); +} + +int maxCrossSubArray(int arr[], int l, int m, int h) +{ + int sum = 0; + int left_sum = INT_MIN; + for (int i = m; i >= l; i--) { + sum = sum + arr[i]; + if (sum > left_sum) + left_sum = sum; + } + sum = 0; + int right_sum = INT_MIN; + for (int i = m; i <= h; i++) { + sum = sum + arr[i]; + if (sum > right_sum) + right_sum = sum; + } + + return max(left_sum + right_sum - arr[m], left_sum, right_sum); +} +int maxSubArraySum(int arr[], int l, int h) +{ + if (l > h) + return INT_MIN; + if (l == h) + return arr[l]; + int m = (l + h) / 2; + return max(maxSubArraySum(arr, l, m - 1), + maxSubArraySum(arr, m + 1, h), + maxCrossSubArray(arr, l, m, h)); +} + +int main() +{ + int arr[] = {5,4,-1,7,8}; + int n = sizeof(arr) / sizeof(arr[0]); + int max_sum = maxSubArraySum(arr, 0, n - 1); + printf("Maximum contiguous sum is %d\n", max_sum); + getchar(); + return 0; +} + + + + + + + + + diff --git a/December - 04/CPP_GANESHANHARI_DAY_4.cpp b/December - 04/CPP_GANESHANHARI_DAY_4.cpp new file mode 100644 index 0000000..5c04535 --- /dev/null +++ b/December - 04/CPP_GANESHANHARI_DAY_4.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +int main() + { + cout<<"INPUT:"<>days; + vector v(days); + for(auto& num :v)cin>>num; + + + int max=INT_MIN; + int curr=0; + int first=0,last; + + for(int i=0;imax){ + max=curr; + last=i; + } + + if(curr<0){ + curr=0; + first= i+1; + } + + } + + vector all; + for(int i=first;i<=last;i++){ + all.push_back(v[i]); + } + cout<<"OUTPUT:"< changes[i - 1]: + max_profit += changes[i] - changes[i - 1] + end_day = i + stock_market_change_values.append(changes[i]) + else: + start_day = i + return max_profit, start_day, end_day, stock_market_change_values + + +changes = [5,-4,12,-2, -5, 6, -2,-3, 1, 5, -6,-11,7,-31,9,2,-3,8,-5] +n = 19 +profit, start, end, stock_market_change_values = max_profit(changes,n) +print("Maximum profit:", profit) +print("Buy on day:", start+1) +print("Sell on day:", end+1) +print("Stock market change values:", stock_market_change_values) \ No newline at end of file diff --git a/December - 04/GREEDnim_day4_java.java b/December - 04/GREEDnim_day4_java.java new file mode 100644 index 0000000..1ced3ad --- /dev/null +++ b/December - 04/GREEDnim_day4_java.java @@ -0,0 +1,57 @@ + + +import java.util.Arrays; +import java.util.Scanner; + +public class GREEDnim_day4_java { + + public static void main(String[] args) { + + // getting input; + Scanner in=new Scanner(System.in); + System.out.print("No of Days : "); + int days=in.nextInt(); + System.out.println( "Given stock market change values:"); + int[] inp=new int[days]; + for(int i=0;icurSum) + { + curSum=inp[i]; + curStartIndex=i; + } + else + { + curSum+=inp[i]; + } + curEndIndex=i; + if(curSum>maxSum) + { + maxSum=curSum; + maxStartIndex=curStartIndex; + maxEndIndex=curEndIndex; + } + } + System.out.println("Profited value : "+maxSum); + System.out.println( "proposed day to sell: Day: "+ (maxStartIndex+1) +" to Day : "+(maxEndIndex+1)); + System.out.println("stock market change values :" +Arrays.toString(Arrays.copyOfRange(inp,maxStartIndex,maxEndIndex+1))); + + + + } +} diff --git a/December - 04/Industry.cpp b/December - 04/Industry.cpp new file mode 100644 index 0000000..5f726de --- /dev/null +++ b/December - 04/Industry.cpp @@ -0,0 +1,54 @@ +#include +using namespace std; + +void SubarrayMax(vector nums, int n) +{ + int maxsum = 0, currsum = 0; + int maxstart = 0, maxend = 0; + int currstart = 0, currend = 0; + + for (int i = 0; i < n; i++) + { + currsum = currsum + nums[i]; + currend = i; + + if (currsum < 0) + { + currsum = 0; + currstart = currend + 1; + } + + if (maxsum < currsum) + { + maxsum = currsum; + maxstart = currstart; + maxend = currend; + } + } + cout << "Profit Value: " << maxsum << "\n"; + cout << "Proposed days to sell: Day: " << maxstart + 1 << " Day: " << maxend + 1 << "\n"; + + cout << "Stock market Change Values: "; + for (int i = maxstart; i <= maxend; i++) + { + cout << nums[i] << " "; + } +} + +int main() +{ + int n, value; + cout << "No. of days: "; + cin >> n; + + vector trade; + cout << "Given stock market change values: "; + for (int i = 0; i < n; i++) + { + cin >> value; + trade.push_back(value); + } + + SubarrayMax(trade, n); + return 0; +} \ No newline at end of file diff --git a/December - 04/Java_Ankur2606.java b/December - 04/Java_Ankur2606.java new file mode 100644 index 0000000..7b0f85d --- /dev/null +++ b/December - 04/Java_Ankur2606.java @@ -0,0 +1,55 @@ +import java.io.*; +import java.util.*; +public class Java_Ankur2606{ + public static int findMax(int i, int j){ + return i>j? i : j; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input : "); + System.out.println(""); + + System.out.print("No. of Days : "); + int noOfDays = sc.nextInt(); + + int[] arr = new int[noOfDays]; + System.out.print("Given stock market change values : "); + for(int i=0;i preRes){ + end = i+1; + } + } + + System.out.println(""); + System.out.println("Output : "); + System.out.println(""); + + System.out.println("Profit Value : " + res); + System.out.println("Proposed days to sell: Day: "+start+" to Day: "+end); + System.out.print("Stock market Change Values: {"); + for(int i=start-1;i<=end-1;i++){ + System.out.print(arr[i]); + if(i != (end-1)){ + System.out.print(","); + } + } + System.out.print("}"); + } +} \ No newline at end of file diff --git a/December - 04/Java_souvikpal2000.java b/December - 04/Java_souvikpal2000.java new file mode 100644 index 0000000..1a8ac7b --- /dev/null +++ b/December - 04/Java_souvikpal2000.java @@ -0,0 +1,55 @@ +import java.io.*; +import java.util.*; +public class Java_souvikpal2000{ + public static int findMax(int i, int j){ + return i>j? i : j; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input : "); + System.out.println(""); + + System.out.print("No. of Days : "); + int noOfDays = sc.nextInt(); + + int[] arr = new int[noOfDays]; + System.out.print("Given stock market change values : "); + for(int i=0;i preRes){ + end = i+1; + } + } + + System.out.println(""); + System.out.println("Output : "); + System.out.println(""); + + System.out.println("Profit Value : " + res); + System.out.println("Proposed days to sell: Day: "+start+" to Day: "+end); + System.out.print("Stock market Change Values: {"); + for(int i=start-1;i<=end-1;i++){ + System.out.print(arr[i]); + if(i != (end-1)){ + System.out.print(","); + } + } + System.out.print("}"); + } +} \ No newline at end of file diff --git a/December - 04/Java_tarpandas.java b/December - 04/Java_tarpandas.java new file mode 100644 index 0000000..b3e197c --- /dev/null +++ b/December - 04/Java_tarpandas.java @@ -0,0 +1,41 @@ +import java.util.Scanner; +public class Java_tarpandas { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("No. of Days:"); + int noOfDays = sc.nextInt(); + + int sMarktChangeValues[] = new int[noOfDays]; + + System.out.print("Given stock market change values: "); + for(int i=0; i max) { + startDayToSell = i+1; + endDayToSell = j+1; + max = count; + } + } + } + + // Display outputs + System.out.println("Profit Vlue: "+max); + System.out.println("Proposed days to sell: Day: "+startDayToSell+" to "+" Day: "+endDayToSell); + System.out.print("Stock market Change Values: {"); + for(int i=startDayToSell -1; ileft_sum): + left_sum = sum + max_left = i + + right_sum = -10000 + sum = 0 + max_right = -1 + for i in range(mid+1,high+1): + sum+=a[i] + if (sum>right_sum): + right_sum = sum + max_right = i + #print('FMCS(a,{},{},{}): {},{},{}'.format(low,mid,high,max_left,max_right, left_sum+right_sum)) + return(max_left,max_right, left_sum+right_sum) + +def max_subarray(a,low,high): + if high==low: + return(low,high,a[low]) + else: + mid = (low+high)//2 + + #print('\nFMS-left(a,{},{})'.format(low,mid)) + left_low, left_high, left_sum = max_subarray(a, low, mid) + + #print('\nFMS-right(a,{},{})'.format(mid+1,high)) + right_low, right_high, right_sum = max_subarray(a, mid+1, high) + + #print('\nFMCS(a,{},{},{})'.format(low,mid,high)) + cross_low, cross_high, cross_sum = max_crossing_subarray(a, low, mid, high) + + if (left_sum>=right_sum and left_sum>=cross_sum): + return (left_low, left_high, left_sum) + + elif (right_sum>=left_sum and right_sum>=cross_sum): + return (right_low, right_high, right_sum) + + else: + return (cross_low, cross_high, cross_sum) + + +arr = [5,4,-1,7,8] +#arr = [-5,20,-18,52,12,-8,-4] + +n = len(arr) + +max_left, max_right, max_sum = max_subarray(arr, 0, n-1) +print("Profit Value: {}\nProposed days to sell: Day: {} to Day: {}\nStock market Change Values: {}".format(max_sum, max_left+1, max_right+1, arr[max_left:max_right+1])) diff --git a/December - 04/cpp_Aadhi11.cpp b/December - 04/cpp_Aadhi11.cpp new file mode 100644 index 0000000..d0a89ac --- /dev/null +++ b/December - 04/cpp_Aadhi11.cpp @@ -0,0 +1,48 @@ +#include +using namespace std; + +int +main () +{ + int n, a[20]; + cout << "No. of days: "; + cin >> n; + cout <> a[i]; + } + int sum = 0; + int maxi = a[0]; + int start = 0, end = 0, s = 0; + for (int i = 0; i < n; i++) + { + sum += a[i]; + if (sum > maxi) + { + maxi = sum; + start = s; + end = i; + } + if (sum < 0) + { + sum = 0; + s = i + 1; + } + } + cout< +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int n;cin>>n; + vector arr(n); + for(int i=0;i>arr[i]; + } + + int sum=0; + int l=1; + int ansl,ansr; + ansl=ansr=0; + int tmp=0; + for(int i=0;isum){ + sum=tmp; + ansl=l; + ansr=i+1; + } + } + + cout<<"Profit Value: "< +#include +#include + +using namespace std; + +vector maxProfit(vector &history) { + int days = history.size(); + int start=0, end; + int localMax = 0, overallMax = INT_MIN; // -infinity + for (int i=0; i overallMax) { + overallMax = localMax; + end = i; + } + } + vector result { overallMax, start, end }; + return result; +} + +int main(){ + int days; + cin>>days; + vector history(days); + for(int i=0; i>history[i]; + + vector result = maxProfit(history); + cout<<"Max profit: "<< result[0]; + cout<<"\n Proposed days to sell "< +#include +using namespace std; + +void maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0,start = 0, end = 0, s = 0; + + for (int i = 0; i < size; i++) { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) { + max_ending_here = 0; + s = i + 1; + } + } + cout << "Profit value: " <>n; + cout<<"Given stock market change values:"; + for(int i=0;i>a[i]; + } + maxSubArraySum(a, n); + return 0; +} diff --git a/December - 04/day4.cpp b/December - 04/day4.cpp new file mode 100644 index 0000000..f7be128 --- /dev/null +++ b/December - 04/day4.cpp @@ -0,0 +1,51 @@ +// C++ program to print largest contiguous array sum + +#include +#include +using namespace std; + +void maxSubArraySum(int a[], int size) +{ + int max_so_far = INT_MIN, max_ending_here = 0, + start = 0, end = 0, s = 0; + + for (int i = 0; i < size; i++) { + max_ending_here += a[i]; + + if (max_so_far < max_ending_here) { + max_so_far = max_ending_here; + start = s; + end = i; + } + + if (max_ending_here < 0) { + max_ending_here = 0; + s = i + 1; + } + } + cout << "Profit Value: " << max_so_far << endl; + cout << "Proposed days to sell: Day: " << start+1 << " to Day: " << end+1 << endl; + cout<< "Stock market Change Values: "; + for(int i=start;i<=end;i++){ + cout << a[i] <<" "; + } + +} +//5 -4 12 -2 -5 6 -2 -3 1 5 -6 -11 7 -31 9 2 -3 8 -5 + +int main() +{ + int n; + cout<<"No. of Days: "; + cin>>n; + + cout<<"Enter stock market change values:"<> a[i]; + } + maxSubArraySum(a, n); + return 0; +} +//Create by +//Samriddh Prasad diff --git a/December - 04/java_DCBisht04.java b/December - 04/java_DCBisht04.java new file mode 100644 index 0000000..ab14d4f --- /dev/null +++ b/December - 04/java_DCBisht04.java @@ -0,0 +1,34 @@ +import java.util.*; + +public class java_DCBisht04 { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("No of Days : "); + int n = sc.nextInt(); + int a[] = new int[n]; + System.out.println("Given stock market change values:"); + for (int i = 0; i < n; i++) { + a[i] = sc.nextInt(); + } + int s = Integer.MIN_VALUE, cs = 0, sd = 0, fd = 0; + int cstart = 0, cfinish = 0; + for (int i = 0; i < n; i++) { + if (cs <= 0 && cs + a[i] > cs) { + cs = a[i]; + cstart = i; + } else { + cs += a[i]; + } + cfinish = i; + if (cs > s) { + s = cs; + sd = cstart; + fd = cfinish; + } + } + System.out.println("Profited value : " + s); + System.out.println("proposed day to sell: Day: " + (sd + 1) + " to Day: " + (fd + 1)); + System.out.println("stock market change values:" + Arrays.toString(Arrays.copyOfRange(a, sd, fd + 1))); + sc.close(); + } +} diff --git a/December - 04/output.txt b/December - 04/output.txt new file mode 100644 index 0000000..e432962 --- /dev/null +++ b/December - 04/output.txt @@ -0,0 +1,11 @@ +No. of days: 19 +Given stock market change values: 5 -4 12 -2 -5 6 -2 -3 1 5 -6 -11 7 -31 9 2 -3 8 -5 +Profit Value: 16 +Proposed days to sell: Day: 15 Day: 18 +Stock market Change Values: 9 2 -3 8 + +No. of days: 5 +Given stock market change values: 5 4 -1 7 8 +Profit Value: 23 +Proposed days to sell: Day: 1 Day: 5 +Stock market Change Values: 5 4 -1 7 8 \ No newline at end of file diff --git a/December - 04/py_gowsrini2004_day_04.py b/December - 04/py_gowsrini2004_day_04.py new file mode 100644 index 0000000..40b17b1 --- /dev/null +++ b/December - 04/py_gowsrini2004_day_04.py @@ -0,0 +1,28 @@ +#day04 +from sys import maxsize +y = 1 +while y > 0: + print("#problem_statment_04!!") + max_so_far = -maxsize - 1 + max_ending_here, start, end, s = 0, 0, 0, 0 + s_change,a = [],[] + size = int(input("No. of Days: ")) + a_1 = input("Given stock market change values: ").replace(" ","").replace("{","").replace("}","").split(",") + a = [int(i) for i in a_1] + for i in range(0, size): + max_ending_here += a[i] + + if max_so_far < max_ending_here: + max_so_far = max_ending_here + start = s + end = i + + if max_ending_here < 0: + max_ending_here = 0 + s = i+1 + + print("Profit Value: ", max_so_far) + print("Proposed days to sell: Day:", (start+1), ", to Day:", (end+1)) + for i in range(start, (end+1)): + s_change.append(a[i]) + print("Stock market Change Values: " + '{' + ', '.join([str(x) for x in s_change]) + '}') \ No newline at end of file diff --git a/December - 05/C++_Dhruv.cpp b/December - 05/C++_Dhruv.cpp new file mode 100644 index 0000000..98e4965 --- /dev/null +++ b/December - 05/C++_Dhruv.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +int main() { + + int fuel_price; + cin>>fuel_price; + int og_income ; + cin>>og_income; + int income = og_income/10; // 10% of income + int expense; + for(int i=1;i<=31;i++){ + int og_price = fuel_price; + if(i%3==0){ + og_price+=3; + expense+=2*og_price; + } + else if(i%5==0){ + og_price-=2; + expense+=2*og_price; + } + else{ + expense+=2*og_price; + } + } + (expense>income)?cout<<"EXPENDITURE EXCEEDING LIMIT":cout<<"EXPENDITURE WITHIN LIMIT"; +} diff --git a/December - 05/C++_MugundhanY.cpp b/December - 05/C++_MugundhanY.cpp new file mode 100644 index 0000000..8633626 --- /dev/null +++ b/December - 05/C++_MugundhanY.cpp @@ -0,0 +1,29 @@ +//Question 5: +#include +using namespace std; + +void expenditure(int &fuelprice) { + int Expenditure = 0; + for(int i=1; i<=31; i++){ + if(i%3 == 0 && i%5==0){ + Expenditure += (fuelprice+1)*2; + } else if((i%5)==0){ + Expenditure += (fuelprice-2)*2; + } else if ((i%3)==0){ + Expenditure += (fuelprice+3)*2; + } else { + Expenditure += fuelprice*2; + } + } + cout << "Expenditure=" << Expenditure << endl; + if(Expenditure > 5000) cout << "“EXPENDITURE EXCEEDING LIMIT”"; + else cout << "“EXPENDITURE WITHIN LIMIT”"; +} + +int main(){ + cout << "fuel_price="; + int fuelprice; + cin >> fuelprice; + expenditure(fuelprice); + return 0; +} diff --git a/December - 05/C++_subburamanathan7.cpp b/December - 05/C++_subburamanathan7.cpp new file mode 100644 index 0000000..0345b76 --- /dev/null +++ b/December - 05/C++_subburamanathan7.cpp @@ -0,0 +1,28 @@ +#include + +using namespace std; + +int main(){ + int price,total=0,point3=1,point5=1; + + cout<<"Enter Price on Day1:"; + cin>>price; + + for(int i=1;i<=31;++i){ + if(i==point3+3){ + price+=3; + point3=i; + } + else if(i==point5+5){ + price-=2; + point5=i; + } + total += (2*price); + } + if(total>5000) + cout<<"Exceeded Expenditure:"< (income * 0.1): + print("EXPENDITURE EXCEEDING LIMIT") +else: + print("EXPENDITURE WITHIN LIMIT") diff --git a/December - 05/GREEDnim_day5_java.java b/December - 05/GREEDnim_day5_java.java new file mode 100644 index 0000000..4d14a14 --- /dev/null +++ b/December - 05/GREEDnim_day5_java.java @@ -0,0 +1,34 @@ +package acm; + +import java.util.Scanner; + +public class GREEDnim_day5_java { + + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + System.out.print("enter fuel_prize :"); + int income=50000; + + int fuelPrize=in.nextInt(); + int x=fuelPrize; + double amountSpent=0; + for(int i=1;i<32;i++) + { + + if(i%3==0 || i%5==0) + { + if(i%3==0 ) fuelPrize+=3; + if(i%5==0) fuelPrize-=2; + } + else fuelPrize=x; + + amountSpent+=(fuelPrize*2); + + } + double tenPercentOfIncome= (10.0/100.0)*income; + System.out.println(" EXPENSE = "+amountSpent ); + if(amountSpent>tenPercentOfIncome) System.out.println("EXPENDITURE EXCEEDING LIMIT"); + else System.out.println("EXPENDITURE WITHIN LIMIT"); + + } +} diff --git a/December - 05/JAVA_GANESHANHARI_DAY_5.java b/December - 05/JAVA_GANESHANHARI_DAY_5.java new file mode 100644 index 0000000..233fd03 --- /dev/null +++ b/December - 05/JAVA_GANESHANHARI_DAY_5.java @@ -0,0 +1,95 @@ +/* + +DAY 5 +MASON is a motoring enthusiast and he owns a sports bike . +With the price of petrol going up and down in a pattern , MASON is worried whether his salary would be sufficient to meet his needs apart from fueling his bike . + So he decides to calculate how much he spends on fueling his bike per month. + Help MASON calculate his fuel expenditure. + If he spends more than 10 PERCENTAGE of his INCOME give him a warning message reading b EXPENDITURE EXCEEDING LIMIT +Conditions +MASON fuels his bike twice a day . + +The PRICE of the fuel is x/l initially. + +Every third day the price goes up by 3 rupees . + +Every fifth day the price goes down by 2 rupees . + +On the other days the price of the fuel remains x/l. + +Help him to calculate his expense for a period of one month (31DAYS) . + +Check whether the expenditure is more than 10 percent of his income . + +His income is 50,000 rupees per month. +*/ + +/* +Input: +75 + +Output: +4686 + +“EXPENDITURE WITHIN LIMIT” + + */ +import java.util.Scanner; + +public class JAVA_GANESHANHARI_DAY_5 +{ + +public static void main (String[]args) + { + +try (Scanner s = new Scanner (System.in)) { + System.out.println ("Input:"); + + int fuel = s.nextInt (); + + int exp = 0; + + for (int i = 1; i <= 31; i++) + + { + + if ((i % 3 == 0) && (i % 5 == 0)) + + exp += ((fuel + 1) * 2); + + else if (i % 3 == 0) + + exp += ((fuel + 3) * 2); + + else if (i % 5 == 0) + + exp += ((fuel - 2) * 2); + + else + + exp += (fuel * 2); + + + } + + System.out.println (exp); + + if (exp < 5000) + + System.out.println ("EXPENDITURE WITHIN LIMIT"); + + else + + System.out.println ("EXPENDITURE EXCEEDING LIMIT"); +} + +} + + + +} + + + + + diff --git a/December - 05/Java_Ankur2606.java b/December - 05/Java_Ankur2606.java new file mode 100644 index 0000000..9b37a84 --- /dev/null +++ b/December - 05/Java_Ankur2606.java @@ -0,0 +1,45 @@ +import java.io.*; +public class Java_Ankur2606{ + public static void main(String args[]) throws IOException{ + InputStreamReader isr=new InputStreamReader(System.in); + BufferedReader br=new BufferedReader(isr); + + System.out.println("Input : "); + System.out.print("fuel_price="); + int fuel_price = Integer.parseInt(br.readLine()); + + int expenditure = 0; + int fixedFuelPrice = fuel_price; + for(int day=1; day<=31; day++){ + if(day%3 == 0 && day%5 == 0){ + fuel_price = fuel_price + 3 - 2; + } + else if(day%3 == 0){ + fuel_price = fuel_price + 3; + } + else if(day%5 == 0){ + fuel_price = fuel_price - 2; + } + else{ + fuel_price = fixedFuelPrice; + } + expenditure = expenditure + (fuel_price * 2); + } + expenditure = expenditure - 4; + + int percent = (50000 * 10)/100; + String msg = ""; + if(expenditure > percent){ + msg = "EXPENDITURE EXCEEDING LIMIT"; + }else{ + msg = "EXPENDITURE WITHIN LIMIT"; + } + + System.out.println(""); + System.out.println("Output : "); + System.out.println("Expenditure="+expenditure); + System.out.println(""); + System.out.println(msg); + + } +} \ No newline at end of file diff --git a/December - 05/Java_souvikpal2000.java b/December - 05/Java_souvikpal2000.java new file mode 100644 index 0000000..79bf153 --- /dev/null +++ b/December - 05/Java_souvikpal2000.java @@ -0,0 +1,45 @@ +import java.io.*; +public class Java_souvikpal2000{ + public static void main(String args[]) throws IOException{ + InputStreamReader isr=new InputStreamReader(System.in); + BufferedReader br=new BufferedReader(isr); + + System.out.println("Input : "); + System.out.print("fuel_price="); + int fuel_price = Integer.parseInt(br.readLine()); + + int expenditure = 0; + int fixedFuelPrice = fuel_price; + for(int day=1; day<=31; day++){ + if(day%3 == 0 && day%5 == 0){ + fuel_price = fuel_price + 3 - 2; + } + else if(day%3 == 0){ + fuel_price = fuel_price + 3; + } + else if(day%5 == 0){ + fuel_price = fuel_price - 2; + } + else{ + fuel_price = fixedFuelPrice; + } + expenditure = expenditure + (fuel_price * 2); + } + expenditure = expenditure - 4; + + int percent = (50000 * 10)/100; + String msg = ""; + if(expenditure > percent){ + msg = "EXPENDITURE EXCEEDING LIMIT"; + }else{ + msg = "EXPENDITURE WITHIN LIMIT"; + } + + System.out.println(""); + System.out.println("Output : "); + System.out.println("Expenditure="+expenditure); + System.out.println(""); + System.out.println(msg); + + } +} \ No newline at end of file diff --git a/December - 05/Java_tarpandas.java b/December - 05/Java_tarpandas.java new file mode 100644 index 0000000..b9b317a --- /dev/null +++ b/December - 05/Java_tarpandas.java @@ -0,0 +1,35 @@ +import java.util.Scanner; +public class Java_tarpandas { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + System.out.print("fuel_price="); + int fuelPrice = sc.nextInt(); + int tempFuelPrice = fuelPrice; + + // price increased by 3 every 3 days, so 10 times in 31 days + // price decreased by 2 every 5 days, so 6 times in 31 days + + int extraCostPerMonth = 0; + + for(int i=1; i<=31; i++) { + if(i%3 == 0) { + tempFuelPrice += 3; + } + if(i%5 == 0) { + tempFuelPrice -= 2; + } + extraCostPerMonth += tempFuelPrice; + tempFuelPrice = fuelPrice; + } + int totalCost = extraCostPerMonth * 2; + + System.out.println("Expenditure="+totalCost); + + if(totalCost <= 5000) { + System.out.println("\"EXPENDITURE WITHIN LIMIT\""); + } else { + System.out.println("\"EXPENDITURE EXCEEDING LIMIT\""); + } + sc.close(); + } +} diff --git a/December - 05/Misspend.cpp b/December - 05/Misspend.cpp new file mode 100644 index 0000000..9574853 --- /dev/null +++ b/December - 05/Misspend.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; + +int main() +{ + uint16_t income10per = 50000 * 0.1; + uint16_t fuel_price; + cin >> fuel_price; + uint8_t adjust_value = 36; + // adjust value + // so calculating for 3rd day , it comes 10 time~s , so 6*10 = 60 + // calculating for 5th day , it comes 6 times, so 4*6 = 24 (negative) + // so adjusting values = 60 - 24 = +36 + // normal mathematics + int total = (fuel_price * 2 * 31) + adjust_value; + cout << total << endl; + string result = (total <= income10per) ? "EEXPENDITURE WITHIN LIMIT" : "EXPENDITURE EXCEEDING LIMIT"; + cout << result; + + return 0; +} \ No newline at end of file diff --git a/December - 05/Praveen Kumar/praveen_python3.py b/December - 05/Praveen Kumar/praveen_python3.py new file mode 100644 index 0000000..a08f2f8 --- /dev/null +++ b/December - 05/Praveen Kumar/praveen_python3.py @@ -0,0 +1,19 @@ +n = int(input()) +x1 = 0 +for x in range(1, 32): + if x % 3 == 0: + n = n+3 + x1 = x1 + (n*2) + if x % 5 == 0: + n = n-2 + x1 = x1 + (n*2) + else: + x1 = x1+(n*2) + print(x1, x, 'prince',n) + +if x1 > 5000: + print('Expenditure=',x1) + print('EXPENDITURE EXCEEDING LIMIT') +else: + print('Expenditure=',x1) + print('EXPENDITURE WITHIN LIMIT') \ No newline at end of file diff --git a/December - 05/Python3_lakshmeeee.py b/December - 05/Python3_lakshmeeee.py new file mode 100644 index 0000000..180b88e --- /dev/null +++ b/December - 05/Python3_lakshmeeee.py @@ -0,0 +1,19 @@ +income = 50000 +x = int(input()) +y=x +total=0 + +for i in range(1,32): + x=y + if(i%3==0): + x+=3 + if(i%5==0): + x-=2 + total+=2*x + +print('Expenditure = ',total) +if(total>income/10): + print("EXPENDITURE EXCEEDING LIMIT") +else: + print("EXPENDITURE WITHIN LIMIT") + \ No newline at end of file diff --git a/December - 05/cpp_Aadhi11.cpp b/December - 05/cpp_Aadhi11.cpp new file mode 100644 index 0000000..85e904b --- /dev/null +++ b/December - 05/cpp_Aadhi11.cpp @@ -0,0 +1,21 @@ +#include +using namespace std; + +int main() +{ + int x; + cout<<"fuel_price="; + cin>>x; + int ex; + ex=((x*2)*17); + ex=ex+(((x+3)*2)*8); + ex=ex+(((x-2)*2)*4); + ex=ex+(((x+1)*2)*2); + cout< +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int n;cin>>n; + int tmp=62*n+60-24; + cout<<"Expenditure: "< + +using namespace std; + +void alertOnCrossThreshold(){ + cout<<"\nEXPENDITURE EXCEEDING LIMIT\n"; +} + +unsigned long int monthlyExpenditure(unsigned long int &price) { + unsigned long int expenditure = 0; + unsigned long int todayPrice=0; + + for(int i=1; i<=31; i++){ + todayPrice = price; + if(i%3==0) todayPrice+=3; + if(i%5==0) todayPrice-=2; + + expenditure+=(2*todayPrice); + } + if(50000/10>price; + unsigned long int expenditure = monthlyExpenditure(price); + + cout<<"Expenditure="< +using namespace std; + +int monthlyExpenditure(int &price) { + int expenditure = 0; + int todayPrice=0; + + for(int i=1; i<=31; i++){ + todayPrice = price; + if(i%3==0) todayPrice+=3; + if(i%5==0) todayPrice-=2; + expenditure+=(2*todayPrice); + } + if(50000/10>price; + int expenditure = monthlyExpenditure(price); + cout<<"Expenditure="< 0: + print("#problem_statment_05!!") + input_f_p = int(input("fuel_price=")) + f_p = input_f_p + day = 1 + exp = 0 + + + while day <= 31: + if day % 3 == 0: + f_p += 3 + if day % 5 == 0: + f_p -= 2 + day +=1 + exp += f_p + # print(day,f_p) + f_p = input_f_p + + exp = exp*2 + print("Expenditure=",exp) + + if exp > 5000: + print("EXPENDITURE EXCEEDING LIMIT") + else: + print("EXPENDITURE WITHIN LIMIT") \ No newline at end of file diff --git a/December - 06/C++_Dhruv.cpp b/December - 06/C++_Dhruv.cpp new file mode 100644 index 0000000..120ca3a --- /dev/null +++ b/December - 06/C++_Dhruv.cpp @@ -0,0 +1,24 @@ +#include +using namespace std; + +int main() { +// Position=3 +// Set of numbers: 5 4 4 +// Player going first: Tanika + int size;cin>>size; + int pos;cin>>pos; + vectorv(size); + for(auto &x:v)cin>>x; + + int first_value = v[0]; + int pos_value = v[pos-1]; + + int count; + while(first_value>0){ + swap(--first_value,v[pos-1]); + count++; + } + (count%2==0)?cout<<"Tanika ":cout<<" Bob "; + + return 0; +} diff --git a/December - 06/C++_MugundhanY.cpp b/December - 06/C++_MugundhanY.cpp new file mode 100644 index 0000000..040307c --- /dev/null +++ b/December - 06/C++_MugundhanY.cpp @@ -0,0 +1,47 @@ +//Question 6: +#include +using namespace std; + +void swapped(int n, int arr[], string name1){ + + int turns = 0; + string name2; + + if(name1 == "Bob") name2 = "Tanika"; + else name2 = "Bob"; + + while(arr[0]>0){ + arr[0] -= 1; + swap(arr[0], arr[n-1]); + turns++; + } + + if(turns % 2 != 0) cout << name1; + else cout << name2; + cout << " wins the game!" << endl; + + if(turns % 2 != 0) cout << name2; + else cout << name1; + cout << " loses the game!"; + +} + +int main() { + cout << "Position="; + int position; + cin >> position; + + cout << "Set of numbers:"; + int arr[position]; + for(int i=0; i> arr[i]; + } + + cout << "Player going first:"; + string name; + cin >> name; + + swapped(position, arr, name); + + return 0; +} diff --git a/December - 06/C++_subburamanathan7.cpp b/December - 06/C++_subburamanathan7.cpp new file mode 100644 index 0000000..b4e03a4 --- /dev/null +++ b/December - 06/C++_subburamanathan7.cpp @@ -0,0 +1,30 @@ +#include + +using namespace std; + + +int main(){ + int limit,i,position,person=0; + cout<<"Enter Limit"; + cin>>limit; + cout<<"Enter position"; + cin>>position; + if(position>=limit) + exit(1); + int *arr =(int*)malloc(sizeof(int)*limit); + for(i=0;i>arr[i]; + while(arr[0]!=0){ + person=!person; + arr[0]=arr[0]-1; + + arr[0]+=arr[position]; + arr[position]=arr[0]-arr[position]; + arr[0]=arr[0]-arr[position]; + } + if(person==0) + cout<<"Player 1 Looses"; + else + cout<<"Player 2 Looses"; + return 0; +} \ No newline at end of file diff --git a/December - 06/CPP_GANESHANHARI_DAY_6.cpp b/December - 06/CPP_GANESHANHARI_DAY_6.cpp new file mode 100644 index 0000000..22a16c2 --- /dev/null +++ b/December - 06/CPP_GANESHANHARI_DAY_6.cpp @@ -0,0 +1,55 @@ +#include +#include +using namespace std; +int main() +{ + int n,pos,player; + + cout<<"Enter Position:"; + cin>>pos; + cout<<"Enter no of terms:"; + cin>>n; + int arr[n]; + cout<<"Enter the Numbers:"; + for(int i=0;i>arr[i]; + + cout<<"Who starts first 1.Bob 2.Tanika"; + cin>>player; + int temp=arr[pos-1]; + if(temp==arr[0]) + { + if(player==1) + { + cout<<"Tanika Wins \nBob Loses"; + } + else + { + cout<<"Bob Wins \nTanika Loses"; + } + } + else if(temp>arr[0]) + { + if(player==1) + { + cout<<"Tanika Wins \nBob Loses"; + } + else + { + cout<<"Bob Wins \nTanika Loses"; + } + + } + else + { + if(player==1) + { + cout<<"Bob Wins \nTanika Loses"; + } + else + { + cout<<"Tanika Wins \nBob Loses"; + } + } + return 0; +} diff --git a/December - 06/GREEDnim_day6_java.java b/December - 06/GREEDnim_day6_java.java new file mode 100644 index 0000000..84e6f5c --- /dev/null +++ b/December - 06/GREEDnim_day6_java.java @@ -0,0 +1,20 @@ +package acm; + +import java.util.Scanner; + +public class GREEDnim_day6_java +{ + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + int pos=in.nextInt(); + + // why do we need this array? we only need two numbers. + int[]arr=new int[pos]; + for (int i = 0; i < pos; i++) { + arr[i]=in.nextInt(); + } + + if(arr[pos-1]>=arr[0]) System.out.println("PLAYER 2 WINS"); + else System.out.println("PLAYER 1 WINS"); + } +} diff --git a/December - 06/Java_Ankur2606.java b/December - 06/Java_Ankur2606.java new file mode 100644 index 0000000..cd2abc2 --- /dev/null +++ b/December - 06/Java_Ankur2606.java @@ -0,0 +1,45 @@ +import java.util.*; +class Java_Ankur2606{ + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input: "); + System.out.print("n="); + int n = sc.nextInt(); + int[] arr = new int[n]; + System.out.print("Set of numbers: "); + for(int i=0;i1): + turn=0 + temp = n[pos] + n[pos] = n[0]-1 + n[0] = n[pos] + print(n) + +if turn==1: + print("Tanika wins the game!\nBob loses the game!") +else: + print("Bob wins the game!\nTanika loses the game!") \ No newline at end of file diff --git a/December - 06/cpp_Aadhi11.cpp b/December - 06/cpp_Aadhi11.cpp new file mode 100644 index 0000000..b9fa025 --- /dev/null +++ b/December - 06/cpp_Aadhi11.cpp @@ -0,0 +1,53 @@ +#include +#include +using namespace std; + +int +main () +{ + int p, a[10]; + int count = 1; + string ta = "Tanika", bo = "Bob", x, y; + cout << "Position="; + cin >> p; + cout << "Set of numbers: "; + for (int i = 0; i < 3; i++) + { + cin >> a[i]; + } + cout << "Player going first: "; + cin >> x; + if (x == ta) + { + y = bo; + } + else + { + y = ta; + } + while (a[0] > 0) + { + int temp; + a[0] = a[0] - 1; + temp = a[0]; + a[0] = a[p - 1]; + a[p - 1] = temp; + count++; + } + if (count % 2 == 0) + { + cout< +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int pos;cin>>pos; + int n=pos; + vector arr(pos); + for(int i=0;i>arr[i]; + } + int flag=0; + for(int i=1;i +#include +#include + +using namespace std; + +int gameLoop(vector&); + +int main(){ + // get size + int n; + cin>>n; + vector playground(n, 0); + + for(auto it=playground.begin(); it>*it; + } + cout<<"\nPlayer "< &playground){ + int position=0; + int winner=0; + do{ + cout<<"Player 01: "; + cin>>position; + (*playground.begin()--); + if(--(*playground.begin())==0){ + winner = 1; + break; + } + + iter_swap(playground.begin(), playground.begin()+position); + + cout<<"Player 02: "; + cin>>position; + if(--(*playground.begin())==0){ + winner = 2; + break; + } + + iter_swap(playground.begin(), playground.begin()+position); + }while(1); + + for(auto i: playground) + cout< +using namespace std; + +int main() { + cout<<"Enter size of numbers:"; + int size;cin>>size; + cout<<"Enter pos:"; + int pos;cin>>pos; + cout<<"Enter set of numbers:"; + vectorv(size); + for(auto &x:v)cin>>x; + + cout<<"Player goinf first:"; + string s; + cin>>s; + int first_value = v[0]; + int pos_value = v[pos-1]; + + int count; + while(first_value>0){ + swap(--first_value,v[pos-1]); + count++; + } + if(s=="Tanika"){ + if(count%2==0) + cout<<"Tanika wins the game!\nBob loses the game!"; + else cout<<"Bob wins the game!\nTanika loses the game! "; + } + if(s=="Bob"){ + if(count%2==0) + cout<<"Bob wins the game!\nTanika loses the game!"; + else cout<<"Tanika wins the game!\nBob loses the game! "; + } + + return 0; +} diff --git a/December - 06/java_DCBisht06.java b/December - 06/java_DCBisht06.java new file mode 100644 index 0000000..e2a138c --- /dev/null +++ b/December - 06/java_DCBisht06.java @@ -0,0 +1,43 @@ +import java.util.*; + +public class java_DCBisht06 { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + System.out.println("Input: "); + System.out.print("p="); + int p=Integer.parseInt(sc.nextLine()); + + System.out.print("Set of numbers: "); + String array=sc.nextLine(); + + String[] a=array.split(" ",0); + + int x=0; + int[] arr = new int[a.length]; + for(String i:a){ + arr[x++]=Integer.valueOf(i); + } + System.out.print("Player going first: "); + String player = sc.nextLine(); + + int flag = 0; + while(true){ + player = player.equalsIgnoreCase("Tanika")? "Bob" : "Tanika"; + + flag = arr[p-1]; + arr[p-1] = arr[0] - 1; + arr[0] = flag; + + if(arr[0] == 0){ + break; + } + } + + System.out.println(""); + System.out.println("Output: "); + System.out.println((player.equalsIgnoreCase("Tanika")? "Bob" : "Tanika") + " wins the game!"); + System.out.println(player + " loses the game!"); + + sc.close(); + } +} diff --git a/December - 06/output.txt b/December - 06/output.txt new file mode 100644 index 0000000..66aad94 --- /dev/null +++ b/December - 06/output.txt @@ -0,0 +1,5 @@ +Position = 3 +Set of numbers: 544 +Player going first: Tanika +Tanika wins the game! +Bob loses the game \ No newline at end of file diff --git a/December - 06/py_gowsrini2004_day_06.py b/December - 06/py_gowsrini2004_day_06.py new file mode 100644 index 0000000..a4c90d2 --- /dev/null +++ b/December - 06/py_gowsrini2004_day_06.py @@ -0,0 +1,44 @@ +#day_06 +y = 1 +while y > 0: + print("#problem_statment_06!!") + t,temp,count = 1,0,1 + pos = int(input("Enter The Position: ")) + p = pos -1 + set = input("Set of Numbers: ") + player_1 = input("Player going first:") + if player_1 == "Tanika" or player_1 == "tanika": + player_1 = "Tanika" + player_2 = "Bob" + else: + player_2 = "Tanika" + player_1 = "Bob" + set_l = set.split() + set_l_n = [] + for j in set_l: + set_l_n.append(int(j)) + set_l = set_l_n + # print(set_l) + play = 1 + while t == 1: + set_l[0] -= 1 + temp = set_l[p] + set_l[p] = set_l[0] + set_l[0] = temp + if set_l[0] == 0: + t = 0 + if count%2 == 0: + play = 1 + else: + play = 2 + # print(set_l) + count = 0 + # print(player_1,player_2) + if play == 1: + winnner = player_1 + loser = player_2 + print(winnner,"wins the game!\n",loser,"loses the game!") + else: + winnner = player_2 + loser = player_1 + print(winnner,"wins the game!\n",loser,"loses the game!") \ No newline at end of file diff --git a/December - 06/swapped.cpp b/December - 06/swapped.cpp new file mode 100644 index 0000000..579cf77 --- /dev/null +++ b/December - 06/swapped.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +int main() +{ + int position, count = 1; + string player, nums; + int numbers; + + cout << "Position = "; + cin >> position; + position -= 1; + + // Assuming to get single digit numbers i.e. 0-9 + cout << "Set of numbers: "; + cin >> nums; + + cout << "Player going first: "; + cin >> player; + + while (nums[0] != 0) + { + nums[0] -= 1; + swap(nums[0], nums[position]); + count++; + } + + string sen1 = "Tanika wins the game!\nBob loses the game"; + string sen2 = "Bob wins the game!\nTanika loses the game"; + + string result = (player == "tanika" || player == "Tanika") ? ((count % 2 == 0) ? sen1 : sen2) : ((count % 2 == 0) ? sen2 : sen1); + cout << result; + + return 0; +} \ No newline at end of file diff --git a/December - 07/.gitignore b/December - 07/.gitignore index ac6d3a2..f8e3d49 100644 --- a/December - 07/.gitignore +++ b/December - 07/.gitignore @@ -1,7 +1,3 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem - # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] @@ -10,10 +6,6 @@ __pycache__/ # C extensions *.so -# node.js -/node_modules -package-lock.json - # Distribution / packaging .Python build/ @@ -41,6 +33,45 @@ MANIFEST *.manifest *.spec +#code +class Solution(object): + def exist(self, board, word): + n =len(board) + m = len(board[0]) + for i in range(n): + for j in range(m): + if word[0] == board[i][j]: + if self.find(board,word,i,j): + return True + return False + def find(self, board,word,row,col,i=0): + if i== len(word): + return True + if row>= len(board) or row <0 or col >=len(board[0]) or col<0 or word[i]!=board[row][col]: + return False + board[row][col] = '*' + res = self.find(board,word,row+1,col,i+1) or self.find(board,word,row-1,col,i+1) or self.find(board,word,row,col+1,i+1) or self.find(board,word,row,col-1,i+1) + board[row][col] = word[i] + return res +ob1 = Solution() +word1=input("enter the word") +print(ob1.exist([ + ['A','S','S','E','R','T','I','V','E','N','E','S','S','L','J'], + ['C','P','O','G','O','O','D','P','O','S','I','T','I','V','E'], + ['O','P','E','N','B','M','U','R','E','W','O','P','R','P','S'], + ['M','E','D','I','A','T','I','O','N','E','L','D','I','O','G'], + ['M','A','A','S','R','E','G','J','E','W','I','N','W','I','N'], + ['U','C','I','A','E','M','O','E','E','C','S','K','E','N','I'], + ['N','E','M','R','S','H','A','C','D','V','T','W','T','T','L'], + ['I','T','E','H','O','T','L','T','S','T','E','R','A','O','E'], + ['C','A','S','P','L','G','L','S','I','U','N','E','R','F','E'], + ['A','I','S','A','U','S','Y','T','O','I','S','E','V','F','S'], + ['T','T','A','R','T','D','O','C','E','N','P','P','I','H','D'], + ['I','O','G','A','I','G','U','P','Y','M','G','O','O','E','E'], + ['O','G','E','P','O','A','F','P','Q','I','E','N','O','W','A'], + ['N','E','C','O','N','F','L','I','C','T','S','D','C','E','R'], + ['F','N','H','T','C','A','T','N','O','C','E','Y','E','B','T']],word1)) +#code # Installer logs pip-log.txt pip-delete-this-directory.txt @@ -93,7 +124,13 @@ ipython_config.py .python-version # pipenv -Pipfile.lock +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff @@ -129,103 +166,3 @@ dmypy.json # Pyre type checker .pyre/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf diff --git a/December - 07/C++_Dhruv.cpp b/December - 07/C++_Dhruv.cpp new file mode 100644 index 0000000..2bb3afc --- /dev/null +++ b/December - 07/C++_Dhruv.cpp @@ -0,0 +1,59 @@ +#include +using namespace std; +bool ismatch(string row , string word){ + if(size(row)grid{ + {"GEEE"}, + {"GELL"}, + {"IDGG"}}; + // all chars are concataned + // from col to row using nested for loops and store them as string + // in grid_on_col + vectorgrid_on_col{ + {"GGI"}, + {"EED"}, + {"ELG"}, + {"ELG"} + }; + string word= "ELL"; + + bool ans = false; + for(auto row:grid) + { + ans = ismatch(row,word); + if(ans == true)break; + } + if(ans!=true) + { + for(auto row:grid_on_col) + { + ans = ismatch(row,word); + if(ans == true)break; + } + + } + + + ans==true?cout<<"FOUND":cout<<"NOT FOUND"; +} diff --git a/December - 07/C++_MugundhanY.cpp b/December - 07/C++_MugundhanY.cpp new file mode 100644 index 0000000..b35d91e --- /dev/null +++ b/December - 07/C++_MugundhanY.cpp @@ -0,0 +1,53 @@ +//Question 7: +#include +using namespace std; + +int x[] = { -1, 0, 0, 1}; +int y[] = { 0, -1, 1, 0}; + +bool search2D(char *grid, int row, int col, string word, int R, int C){ + if (*(grid+row*C+col) != word[0]) + return false; + + int len = word.length(); + + for (int dir = 0; dir < 4; dir++) { + int k, rd = row + x[dir], cd = col + y[dir]; + + for (k = 1; k < len; k++) { + if (rd >= R || rd < 0 || cd >= C || cd < 0) + break; + + if (*(grid+rd*C+cd) != word[k]) + break; + + rd += x[dir], cd += y[dir]; + } + + + if (k == len) + return true; + } + return false; +} + + +void patternSearch(char *grid, string word, int R, int C){ + for (int row = 0; row < R; row++) + for (int col = 0; col < C; col++) + if(search2D(grid, row, col, word, R, C)){ + cout << "Found"; + return; + } + cout << "Not Found"; +} + +int main(){ + int R = 15, C = 15; + char grid[R][C] = {"ASSERTIVENESSLJ","CFOGOODPOSITIVE","OPENBMUREWOPRPS","MEDIATIONELDIOG", "MAASREGJEWINWIN", "UCIAEMOEECSKENI", "NEMRSHACDVTWTTL", "ITEHOTLTSTERAOE", "CASPLGLSIUNERFE", "AISAUSYTPOISEVF", "TTARTTDOCENPPIH", "IOGAIGUPYMGOOEE", "OGEPOAFPQIENOWA", "NECONFLICTSDCER", "FNHTCATNOCEYEBT"}; + + string word; + cin >> word; + patternSearch((char *)grid, word, R, C); + return 0; +} diff --git a/December - 07/GREEDnim_day7_java.java b/December - 07/GREEDnim_day7_java.java new file mode 100644 index 0000000..91b5966 --- /dev/null +++ b/December - 07/GREEDnim_day7_java.java @@ -0,0 +1,49 @@ +package acm; + +import java.util.Scanner; + +public class GREEDnim_day7_java { + + static char[][] grid; + static boolean[][] checker; + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + String inp=in.next(); + grid=new char[15][15]; + checker=new boolean[15][15]; + String a="ASSERTIVENESSLJCFOGOODPOSITIVEOPENBMUREWOPRPSMEDIATIONELDIOGMAASREGJEWINWINUCIAEMOEECSKENINEMRSHACDVTWTTLITEHOTLTSTERAOECASPLGLSIUNERFEAISAUSYTPOISEVFTTARTTDOCENPPIHIOGAIGUPYMGOOEEOGEPOAFPQIENOWANECONFLICTSDCERFNHTCATNOCEYEBT"; + int index=0; + for(int i=0;i<15;i++) + { + for(int j=0;j<15;j++) grid[i][j]=a.charAt(index++); + } + boolean done=false; + for(int i=0;i<15;i++) + { + for(int j=0;j<15;j++) + { + if(grid[i][j]==inp.charAt(0)) + { + done=findWord(inp,0,i,j); + if(done) break; + } + } + if(done) break; + } + if(done) System.out.println("FOUND"); + else System.out.println("NOT FOUND"); + + } + public static boolean findWord(String s,int index,int row,int col) + { + if(index==s.length()) return true; + char c=s.charAt(index); + if( row>=15 || col>=15 || row<0|| col<0 || c!=grid[row][col] || checker[row][col]) return false; + checker[row][col]=true; + boolean ans; + ans=findWord(s,index+1,row+1,col)||findWord(s,index+1,row-1, col)||findWord(s,index+1,row,col+1)||findWord(s,index+1,row,col-1); + checker[row][col]=false; + return ans; + } +} + diff --git a/December - 07/JAVA_GANESHANHARI_DAY_7.java b/December - 07/JAVA_GANESHANHARI_DAY_7.java new file mode 100644 index 0000000..ce24426 --- /dev/null +++ b/December - 07/JAVA_GANESHANHARI_DAY_7.java @@ -0,0 +1,96 @@ +/*You are given a grid made up of random characters. + Given a word, your task is to determine whether the word can be constructed from the given grid. + +The word can be constructed from letters of sequentially adjacent cells, +where adjacent cells are horizontally or vertically neighboring. +The same letter cell may not be used more than once */ + + +/* + Input: + COMMUNICATION + +Output: + Found + + + + Input: + DOCUMENT + +Output: + Not Found + + */ + +import java.util.*; +public class JAVA_GANESHANHARI_DAY_7 +{ + public static int n; + public static char word[]=new char[n]; + public static char a[][]=new char[15][15]; + public static int xa[]={0,0,1,-1}; + public static int ya[]={1,-1,0,0}; + public static int i,j; + public static int xpos,ypos; + public static boolean find(int x,int y) + { + + for(j=0;j<4;j++) + { + xpos=x; + ypos=y; + for( i=1;i14|| ypos<0||ypos>14 ) break; + if(word[i]!=a[xpos][ypos]) break; + } + if(i==n) return true; + } + + return false; + + } + +public static void main(String[] args) + { + + Scanner s=new Scanner(System.in); + System.out.println("Input:"); + String word1=s.next(); + word=word1.toCharArray(); + n=word.length; + String a1="ASSERTIVENESSLJCFOGOODPOSITIVEOPENBMUREWOPRPSMEDIATIONELDIOGMAASREGJEWINWINUCIAEMOEECSKENINEMRSHACDVTWTTLITEHOTLTSTERAOECASPLGLSIUNERFEAISAUSYTPOISEVFTTARTTDOCENPPIHIOGAIGUPYMGOOEEOGEPOAFPQIENOWANECONFLICTSDCERFNHTCATNOCEYEBT"; + int index=0; + for(int i=0;i<15;i++) + { + for(int j=0;j<15;j++) + { + a[i][j]=a1.charAt(index++); + // System.out.print(a[i][j]+"\t"); + } + //System.out.println(); + } + for(int i=0;i<15;i++) + { + for(int j=0;j<15;j++) + { + if(word[0]==a[i][j]) + { + if(find(i,j)!=true) continue; + else + { + System.out.println("OUTPUT:\nFound"); + System.exit(0); + } + } + else continue; + } + } + System.out.println("OUTPUT:\n NOT FOUND"); + + } +} \ No newline at end of file diff --git a/December - 07/Java_Ankur2606.java b/December - 07/Java_Ankur2606.java new file mode 100644 index 0000000..827cf1e --- /dev/null +++ b/December - 07/Java_Ankur2606.java @@ -0,0 +1,96 @@ +import java.util.*; +class Coordinates{ + int xPos; + int yPos; + Coordinates(int xPos, int yPos){ + this.xPos = xPos; + this.yPos = yPos; + } +} +public class Java_Ankur2606{ + public Coordinates[] searchForString(int row, int column, char[][] map, String str){ + int[] rowDirection = {1,-1,0,0}; + int[] columnDirection = {0,0,1,-1}; + Coordinates starting = new Coordinates(row,column); + Coordinates[] coordinateDetails = new Coordinates[2]; + int count = 1; + for(int i=0;i(map.length-1) || colPos>(map[0].length-1) || map[rowPos][colPos] != c){ + break; + } + if(map[rowPos][colPos] == c){ + count++; + } + if(count == str.length()){ + Coordinates ending = new Coordinates(rowPos,colPos); + coordinateDetails[0] = starting; + coordinateDetails[1] = ending; + return coordinateDetails; + } + } + } + return null; + } + + public Coordinates[] wordMap(char[][] map, String str){ + int rowSize = map.length; + int columnSize = map[0].length; + for(int i=0;i(map.length-1) || colPos>(map[0].length-1) || map[rowPos][colPos] != c){ + break; + } + if(map[rowPos][colPos] == c){ + count++; + } + if(count == str.length()){ + Coordinates ending = new Coordinates(rowPos,colPos); + coordinateDetails[0] = starting; + coordinateDetails[1] = ending; + return coordinateDetails; + } + } + } + return null; + } + + public Coordinates[] wordMap(char[][] map, String str){ + int rowSize = map.length; + int columnSize = map[0].length; + for(int i=0;i= arr.length || rowDir < 0 + || colDir >= arr[i].length || colDir < 0) + break; + + if (arr[rowDir][colDir] != input.charAt(l)) + break; + + rowDir += xDirection[k]; + colDir += yDirection[k]; + } + if(l == input.length()) + return true; + } + return false; + } + + static boolean searchPattern(char arr[][], String input) { + int rowSize = arr.length; + int columnSize = arr[0].length; + + for(int i=0; i +using namespace std; + int k=0; +int x[] = { -1, -1, -1, 0, 0, 1, 1, 1 }; +int y[] = { -1, 0, 1, -1, 1, -1, 0, 1 }; + +bool search2D(char *grid, int row, int col, + string word, int R, int C) +{ + if (*(grid+row*C+col) != word[0]) + return false; + + int len = word.length(); + + for (int dir = 0; dir < 8; dir++) { + int k, rd = row + x[dir], cd = col + y[dir]; + + for (k = 1; k < len; k++) { + if (rd >= R || rd < 0 || cd >= C || cd < 0) + break; + + if (*(grid+rd*C+cd) != word[k]) + break; + + rd += x[dir], cd += y[dir]; + } + + if (k == len) + return true; + } + return false; +} + +void patternSearch(char *grid, string word, + int R, int C) +{ + for (int row = 0; row < R; row++) + for (int col = 0; col < C; col++) + if (search2D(grid, row, col, word, R, C)) + k=1; + +} + +int main() +{ + int R = 15, C = 15; + char grid[R][C] = { "ASSERTIVENESSLJ","CFOGOODPOSITIVE","OPENBMUREWOPRPS","MEDIATIONELDIOG","MAASREGJEWINWIN","UCIAEMOEECSKENI","NEMRSHACDVTWTTL","ITEHOTLTSTERAOE","CASPLGLSIUNERFE","AISAUSYTPOISEVF","TTARTTDOCENPPIH","IOGAIGUPYMGOOEE","OGEPOAFPQIENOWA","NECONFLICTSDCER","FNHTCATNOCEYEBT"}; + string x; + cin>>x; + patternSearch((char *)grid, x , R, C); + cout< +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int n=15; + vector v; + for(int i=0;i>s; + v.push_back(s); + } + + string s;cin>>s; + int len=s.size(); + int flag=0; + for(int i=0;i +#include +#include +#include +#include +#include + +using namespace std; + +void fillRandomCharacters(vector>&, int); +bool searchForWord(vector>&, int, string); + +int main(){ + vector> wordpool; + int rows=15; + fillRandomCharacters(wordpool, rows); + for(auto row: wordpool){ + for(int i=0; i>query; + + if(searchForWord(wordpool, rows, query)) + cout<<"FOUND\n"; + else + cout<<"NOT FOUND\n"; + + return 0; +} + +bool searchForWord(vector> &wordpool, int rows, string key){ + // points to a letter in key + int letter_ptr_horizontal=0; + int letter_ptr_vertical=0; + + for(int i=0; i> &wordpool, int rows){ + // create an instance of an engine, which generate seed for Mersenne twister engine. + // std::random_device generates non-deterministic random int + random_device rnd_device; + + // Specify the engine and distribution. + mt19937 mersenne_engine {rnd_device()}; + uniform_int_distribution dist {65, 90}; + + // [captured]() {..} is lambda function in cpp + auto gen = [&dist, &mersenne_engine](){ + return static_cast(dist(mersenne_engine)); + }; + + vector vec(rows); + for(int i=0;i +using namespace std; + +#define R 15 +#define C 16 + +int x[] = {-1, 0, 0, 1}; +int y[] = {0, -1, 1, 0}; + +bool search2D(char grid[R][C], int row, int col, string word) +{ + if (grid[row][col] != word[0]) + return false; + + int len = word.length(); + for (int dir = 0; dir < 4; dir++) + { + int k, rd = row + x[dir], cd = col + y[dir]; + for (k = 1; k < len; k++) + { + if (rd >= R || rd < 0 || cd >= C || cd < 0) + break; + + if (grid[rd][cd] != word[k]) + break; + rd += x[dir], cd += y[dir]; + } + if (k == len) + return true; + } + return false; +} + +int patternSearch(char grid[R][C], string word) +{ + int flag = 0; + for (int row = 0; row < R; row++) + for (int col = 0; col < C; col++) + if (search2D(grid, row, col, word)) + flag = 1; + return flag; +} + +int main() +{ + char grid[R][C] = {"ASSERTIVENESSLJ", + "CFOGOODPOSITIVE", + "OPENBMUREWOPRPS", + "MEDIATIONELDIOG", + "MAASREGJEWINWIN", + "UCIAEMOEECSKENI", + "NEMRSHACDVTWTTL", + "ITEHOTLTSTERAOE", + "CASPLGLSIUNERFE", + "AISAUSYTPOISEVF", + "TTARTTDOCENPPIH", + "IOGAIGUPYMGOOEE", + "OGEPOAFPQIENOWA", + "NECONFLICTSDCER", + "FNHTCATNOCEYEBT"}; + + string ss; + cin >> ss; + int s = patternSearch(grid, ss); + + if (s == 1) + { + cout << "Found"; + } + else + { + cout << "Not Found"; + } + return 0; +} + +// Code written by Samriddh Prasad diff --git a/December - 07/java_DCBisht07.java b/December - 07/java_DCBisht07.java new file mode 100644 index 0000000..01f93c5 --- /dev/null +++ b/December - 07/java_DCBisht07.java @@ -0,0 +1,97 @@ + +import java.io.*; + +public class java_DCBisht07 { + boolean [][] visited; + int n,m; + public boolean exist(char[][] board, String word) { + n=board.length; + m=board[0].length; + visited=new boolean[n][m]; + + for(int i=0;i=n || j<0 || j>=m ){ + return false; + } + + //if already visited + if(visited[i][j]){ + return false; + } + + //mismatch + if(word.charAt(count)!=board[i][j]){ + return false; + } + + //if word is found + if(count==word.length()-1){ + return true; + } + + /*----------------calculation and recursive calls----------*/ + + //mark current visited + visited[i][j]=true; + + //inc count + count++; + + //down,right,up,left search + if(valid(i+1,j,count,board,word) || + valid(i,j+1,count,board,word) || + valid(i-1,j,count,board,word) || + valid(i,j-1,count,board,word) ){ + return true; + } + + //mark current cell unvisited + visited[i][j]=false; + + return false; + + } + +// Driver Code +public static void main(String[] args)throws IOException +{ + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] S = br.readLine().trim().split(" "); + int n = Integer.parseInt(S[0]); + int m = Integer.parseInt(S[1]); + char [][] board = new char[n][m]; + for(int i = 0; i < n; i++){ + String[] s = br.readLine().trim().split(" "); + for(int j = 0; j < m; j++){ + board[i][j] = s[j].charAt(0); + } + } + String word = br.readLine().trim(); + java_DCBisht07 ob=new java_DCBisht07 (); + boolean ans = ob.exist(board, word); + if(ans) + System.out.println("Found"); + else + System.out.println("Not Found"); + + } + +} + + + diff --git a/December - 07/output.txt b/December - 07/output.txt new file mode 100644 index 0000000..2a49e57 --- /dev/null +++ b/December - 07/output.txt @@ -0,0 +1,8 @@ +Input: COMMUNICATION +FOUND + +Input: DOCUMENT +NOT FOUND + +Input: MEDIATION +FOUND \ No newline at end of file diff --git a/December - 07/py_gowsrini2004_day_07.py b/December - 07/py_gowsrini2004_day_07.py new file mode 100644 index 0000000..0b86a31 --- /dev/null +++ b/December - 07/py_gowsrini2004_day_07.py @@ -0,0 +1,18 @@ +#day_07 +y = 1 +while y > 0: + print("#problem_statment_07!!") + input_str_user = input("Enter The String: ") + input_str = input_str_user.upper() + # print(input_str) + str_row = "ASSERTIVENESSLJCFOGOODPOSITIVEOPENBMUREWOPRPSMEDIATIONELDIOGMAASREGJEWINWINUCIAEMOEECSKENINEMRSHACDVTWTTLITEHOTLTSTERAOECASPLGLSIUNERFEAISAUSYTPOISEVFTTARTTDOCENPPIHIOGAIGUPYMGOOEEOGEPOAFPQIENOWANECONFLICTSDCERFNHTCATNOCEYEBT" + str_column = "ACOMMUNICATIONFSFPEACETAITOGENSOEDAIMESSAGECHEGNISARHPARAPOTROBARESOLUTIONCTOMTEMHTGSTGAFAALLYDUFLTCTSTOPPINDSIPCYQCONSWEWCVTUOEMITCEIOLISTENINGESSESTPDNKWRESPONDYSIRIWETAREPOOCESIRIWETAREPOOCELVPOINTOFVIEWEVJESGNILEEFHEART" + + if input_str in str_row: + print("Found") + + elif input_str in str_column: + print("Found") + + else: + print("Not Found") \ No newline at end of file diff --git a/December - 07/wordmap.cpp b/December - 07/wordmap.cpp new file mode 100644 index 0000000..1492074 --- /dev/null +++ b/December - 07/wordmap.cpp @@ -0,0 +1,86 @@ +#include +using namespace std; + +// DFS +bool search(vector> board, string word, int i, int j, int pos) +{ + if (pos == word.size()) + return true; + if ((i < 0) || (i >= board.size()) || (j < 0) || (j >= board[i].size())) + return false; + + char c = board[i][j]; + if (c == word[pos]) + { + board[i][j] = '#'; + if (search(board, word, i - 1, j, pos + 1)) + return true; + if (search(board, word, i + 1, j, pos + 1)) + return true; + if (search(board, word, i, j - 1, pos + 1)) + return true; + if (search(board, word, i, j + 1, pos + 1)) + return true; + board[i][j] = c; + } + return false; +} + +bool found(vector> board, string word) +{ + for (int i = 0; i < board.size(); i++) + { + for (int j = 0; j < board[i].size(); j++) + { + if (search(board, word, i, j, 0)) + return true; + } + } + return false; +} + +int main() +{ + vector> wordmap = { + {'A', 'S', 'E', 'E', 'R', 'T', 'I', 'V', 'E', 'N', 'E', 'S', 'S', 'L', 'J'}, + + {'C', 'F', 'O', 'G', 'O', 'O', 'D', 'P', 'O', 'S', 'I', 'T', 'I', 'V', 'E'}, + + {'O', 'P', 'E', 'N', 'B', 'M', 'U', 'R', 'E', 'W', 'O', 'P', 'R', 'P', 'S'}, + + {'M', 'E', 'D', 'I', 'A', 'T', 'I', 'O', 'N', 'E', 'L', 'D', 'I', 'O', 'G'}, + + {'M', 'A', 'A', 'S', 'R', 'E', 'G', 'J', 'E', 'W', 'I', 'N', 'W', 'I', 'N'}, + + {'U', 'C', 'I', 'A', 'E', 'M', 'O', 'E', 'E', 'C', 'S', 'K', 'E', 'N', 'I'}, + + {'N', 'E', 'M', 'R', 'S', 'H', 'A', 'C', 'D', 'V', 'T', 'W', 'T', 'T', 'L'}, + + {'I', 'T', 'E', 'H', 'O', 'T', 'L', 'T', 'S', 'T', 'E', 'R', 'A', 'O', 'E'}, + + {'C', 'A', 'S', 'P', 'L', 'G', 'L', 'S', 'I', 'U', 'N', 'E', 'R', 'F', 'E'}, + + {'A', 'I', 'S', 'A', 'U', 'S', 'Y', 'T', 'P', 'O', 'I', 'S', 'E', 'V', 'F'}, + + {'T', 'T', 'A', 'R', 'T', 'T', 'D', 'O', 'C', 'E', 'N', 'P', 'P', 'I', 'H'}, + + {'I', 'O', 'G', 'A', 'I', 'G', 'U', 'P', 'Y', 'M', 'G', 'O', 'O', 'E', 'E'}, + + {'O', 'G', 'E', 'P', 'O', 'A', 'F', 'P', 'Q', 'I', 'E', 'N', 'O', 'W', 'A'}, + + {'N', 'E', 'C', 'O', 'N', 'F', 'L', 'I', 'C', 'T', 'S', 'D', 'C', 'E', 'R'}, + + {'F', 'N', 'H', 'T', 'C', 'A', 'T', 'N', 'O', 'C', 'E', 'Y', 'E', 'B', 'T'}}; + + string word; + cout << "Input: "; + cin >> word; + + transform(word.begin(), word.end(), word.begin(), ::toupper); + + bool tf = found(wordmap, word); + string result = tf == true ? "FOUND" : "NOT FOUND"; + cout << result; + + return 0; +} \ No newline at end of file diff --git a/December - 08/.gitignore b/December - 08/.gitignore index ac6d3a2..6661619 100644 --- a/December - 08/.gitignore +++ b/December - 08/.gitignore @@ -1,7 +1,3 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem - # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] @@ -10,10 +6,6 @@ __pycache__/ # C extensions *.so -# node.js -/node_modules -package-lock.json - # Distribution / packaging .Python build/ @@ -93,7 +85,13 @@ ipython_config.py .python-version # pipenv -Pipfile.lock +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff @@ -130,102 +128,12 @@ dmypy.json # Pyre type checker .pyre/ -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar +def solve(s): + s = list(s) + for i in range(0, len(s)-1, 2): + s[i], s[i+1] = s[i+1], s[i] -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* + return ''.join(s) -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf +s = input("enter string") +print(solve(s)) diff --git a/December - 08/C++_Dhruv.cpp b/December - 08/C++_Dhruv.cpp new file mode 100644 index 0000000..aa9b5b8 --- /dev/null +++ b/December - 08/C++_Dhruv.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +int main() { + // DEMOCRACY -> ED OM RC CA Y + string input ; + cin>>input; + int n = size(input); + for(int i=0;i +using namespace std; + +void reverseword(string word){ + + for (size_t i = 0; i < word.length(); i += 2){ + string part = word.substr(i, 2); + reverse(part.begin(), part.end()); + cout << part; + } +} + +int main(){ + string a; + cin >> a; + reverseword(a); + return 0; +} diff --git a/December - 08/C++_subburamanathan7.cpp b/December - 08/C++_subburamanathan7.cpp new file mode 100644 index 0000000..97d6d92 --- /dev/null +++ b/December - 08/C++_subburamanathan7.cpp @@ -0,0 +1,23 @@ +#include + +using namespace std; + +int main(){ + int i=0,length; + char temp; + string name ="SPEEDRUNNER"; + length=name.length(); + cout<<"Name: "< +#include +using namespace std; +int main() { + cout<<"INPUT:"<>str1; + for(int i=0;i +using namespace std; + +int main() +{ + string word; + cout << "INPUT: "; + cin >> word; + string sub = word; + vector v; + int n = word.length(); + + for (int i = 0; i < n; i += 2) + { + swap(sub[i], sub[i + 1]); + } + + if (n % 2 != 0) + { + sub = sub + word.back(); + } + + cout << "OUTPUT: " << sub; +} \ No newline at end of file diff --git a/December - 08/cpp_Aadhi11.cpp b/December - 08/cpp_Aadhi11.cpp new file mode 100644 index 0000000..3e2ad04 --- /dev/null +++ b/December - 08/cpp_Aadhi11.cpp @@ -0,0 +1,33 @@ +#include +#include +using namespace std; + +int main () +{ + string x; + cin >> x; + if ((x.length ()) % 2 == 0) + { + for (int i = 0; i < x.length (); i = i + 2) + { + char c; + c = x[i]; + x[i] = x[i + 1]; + x[i + 1] = c; + } + } + else + { + for (int i = 0; i < x.length () - 1; i = i + 2) + { + char c; + c = x[i]; + x[i] = x[i + 1]; + x[i + 1] = c; + } + } + cout << x; +} + + + diff --git a/December - 08/cpp_abhi-atg.cpp b/December - 08/cpp_abhi-atg.cpp new file mode 100644 index 0000000..6dc384e --- /dev/null +++ b/December - 08/cpp_abhi-atg.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + string s;cin>>s; + string ans; + int n=s.size(); + for(int i=0;i +#include + +using namespace std; + +int main() { + string msg; + int i=0; + cin>>msg; + do{ + swap(msg[i], msg[i+1]); + i+=2; + } while (i+2 +#include +int main() +{ + int i; + char in[1000],t; + printf("Input: "); + scanf("%s",in); + for(i=1;i +using namespace std; + +int main() +{ + string str,ans,f; + getline(cin, str); + + for(int i = 0; i < str.length(); i+=2){ + ans = str.substr(i,2); + reverse(ans.begin(), ans.end()); + f+=ans; + } + cout< 0: + print("#problem_statment_08!!") + s = input("Input: ") + index,u,new_str,updated_list,list_str = 0, 0,"",[],list(s) + for i in list_str: + if index % 2 == 0: + updated_list.append(i) + index += 1 + else: + u = index-1 + updated_list.insert(u, i) + # print(index,i) + index += 1 + for i in updated_list: + new_str += i + print("Output:",new_str) \ No newline at end of file diff --git a/December - 09/.gitignore b/December - 09/.gitignore index ac6d3a2..f065d19 100644 --- a/December - 09/.gitignore +++ b/December - 09/.gitignore @@ -1,7 +1,3 @@ -# gitignore file for "A December of Algorithms 2022" -# visit https://github.com/SVCE-ACM/A-December-of-Algorithms -# Written individually to adjust for the needs of the problem - # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] @@ -10,10 +6,6 @@ __pycache__/ # C extensions *.so -# node.js -/node_modules -package-lock.json - # Distribution / packaging .Python build/ @@ -93,7 +85,13 @@ ipython_config.py .python-version # pipenv -Pipfile.lock +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow __pypackages__/ # Celery stuff @@ -129,103 +127,26 @@ dmypy.json # Pyre type checker .pyre/ - -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -# Files and directories created by pub -.dart_tool/ -.packages -build/ -# If you're building an application, you may want to check-in your pubspec.lock -pubspec.lock - -# Directory created by dartdoc -# If you don't generate documentation locally you can remove this line. -doc/api/ - -# Avoid committing generated Javascript files: -*.dart.js -*.info.json # Produced by the --dump-info flag. -*.js # When generated by dart2js. Don't specify *.js if your - # project includes source files written in JavaScript. -*.js_ -*.js.deps -*.js.map - -# Prerequisites -*.d - -# Compiled Object files -*.slo -*.lo -*.o -*.obj - -# Precompiled Headers -*.gch -*.pch - -# Compiled Dynamic libraries -*.so -*.dylib -*.dll - -# Fortran module files -*.mod -*.smod - -# Compiled Static libraries -*.lai -*.la -*.a -*.lib - -# Executables -*.exe -*.out -*.app - -# Executables -*.exe -*.out -*.app -*.i*86 -*.x86_64 -*.hex - -# Debug files -*.dSYM/ -*.su -*.idb -*.pdb - -# Kernel Module Compile Results -*.mod* -*.cmd -.tmp_versions/ -modules.order -Module.symvers -Mkfile.old -dkms.conf +#code +n=int(input("enter the number of words")) +string1=input("enter sentence") +print(string1) +s=string1.split() +print(s) +max=len(s[0]) +for i in range (n): + if len(s[i])>max: + max=len(s[i]) +print(max) +for i in range (n): + if(len(s[i])%2!=0 and len(s[i])==max) : + c=0 + print(s[i]) + print("winner") + break + else: + c=1 + +if c==1: + print("better luck next time") +#code diff --git a/December - 09/C++_Dhruv.cpp b/December - 09/C++_Dhruv.cpp new file mode 100644 index 0000000..a6ba2fd --- /dev/null +++ b/December - 09/C++_Dhruv.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +int main() { + int n;cin>>n; + vector input(n) ; + + for(auto &x:input)cin>>x; + int max_len=INT_MIN; + + string word; + for(auto e:input){ + int len = e.size(); + if(size(e)%2!=0) + { + max_len = max(len,max_len); + + } + else + continue; + } + for(auto e:input ){ + if(size(e)==max_len){ + word = e; + break; + + } + } + if(max_len==INT_MIN) + cout<<"Better Luck Next Time"; + else + cout< +using namespace std; + +void randomword(string word[], int n){ + string temp; + for(size_t i = 0; i < n; i++){ + if(word[i].size()%2 != 0){ + if(temp.size() < word[i].size()){ + temp = word[i]; + } + } + } + if(temp.empty()) cout << "Better luck next time"; + else cout << temp; +} + +int main(){ + int n; + cin >> n; + + string word[n]; + for(int i=0; i> word[i]; + } + randomword(word, n); + return 0; +} diff --git a/December - 09/C++_subburamanathan7.cpp b/December - 09/C++_subburamanathan7.cpp new file mode 100644 index 0000000..0a4d101 --- /dev/null +++ b/December - 09/C++_subburamanathan7.cpp @@ -0,0 +1,65 @@ +#include +#include + +using namespace std; +int main(){ + int limit,flag=1; + int max=0,max_Index=0; + cout<<"enter the limit"; + cin>>limit; + string sentence[limit]; + + for(int i=0;i>sentence[i]; + cout<<"choose among these words\n"; + cout<<"["; + for(int i=0;i>choice; + + for(int i=0;i max_length: + max_length = len(word) + max_word = word + if max_word: + return max_word + else: + return "Better luck next time" + +n = 5 +words = "Hello Good Morning Welcome You" + +print(guess_the_word(n, words)) diff --git a/December - 09/GREEDnim_day9_java.java b/December - 09/GREEDnim_day9_java.java new file mode 100644 index 0000000..0018fc7 --- /dev/null +++ b/December - 09/GREEDnim_day9_java.java @@ -0,0 +1,29 @@ +package acm; + +import java.util.Scanner; + +public class GREEDnim_day9_java { + + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + int size=in.nextInt(); + String[] inp=new String[size]; + int maxLength=0; + int ans=-1; + for(int i=0;i maxLength) + { + maxLength=inp[i].length(); + ans=i; + } + } + } + if(ans==-1) System.out.println("Better luck next time"); + System.out.println(inp[ans]); + } +} diff --git a/December - 09/JAVA_GANESHANHARI_DAY_9.java b/December - 09/JAVA_GANESHANHARI_DAY_9.java new file mode 100644 index 0000000..def214b --- /dev/null +++ b/December - 09/JAVA_GANESHANHARI_DAY_9.java @@ -0,0 +1,76 @@ +/* + * Kochouseph Chittilappilly went to Dhruv Zplanet + * , a gaming space, with his friends and played a game called “Guess the Word”. + +Rules of the game are – + +Computer displays some strings on the screen and the player should pick one string / + word if this word matches with the random word that the computer picks then the player is declared as Winner. + +Kochouseph Chittilappilly’s friends played the game and no one won the game. + +This is Kochouseph Chittilappilly’s turn to play and he decided to win the game. + What he observed from his friend’s game is that the computer is picking up the first string whose + length is odd and is of maximum length. + +Due to system failures computers sometimes cannot generate odd length words. + In such cases you will lose the game irrespective of whether you guess the right word or not + and it displays “better luck next time”. + +Write a program to help Kochouseph win the game + */ + + /* + Input: +3 +Go to hell + +Output : +Better luck next time + + + + +Input: +5 +Hello Good Morning Welcome You + +Output : +Morning + + */ +import java.util.*; +public class JAVA_GANESHANHARI_DAY_9{ + public static void main(String[] args) { + + try (Scanner s = new Scanner(System.in)) { + int n=s.nextInt(); + String str1[]=new String[n]; + int arr[]=new int[n]; + int i=0; + while(itemp) + { + temp=arr[j]; + count=j; + } + + } + if(count==-1) + System.out.println("BETTER LUCK NEXT TIME"); + else + System.out.println(str1[count]); + } +} +} \ No newline at end of file diff --git a/December - 09/Java_Ankur2606.java b/December - 09/Java_Ankur2606.java new file mode 100644 index 0000000..7ae86a8 --- /dev/null +++ b/December - 09/Java_Ankur2606.java @@ -0,0 +1,37 @@ +import java.util.*; +public class Java_Ankur2606{ + public String guessTheWord(String[] arr, int n){ + int maxLength = 0; + String str = ""; + for(int i=0;imaxLength){ + maxLength = length; + str = arr[i]; + } + } + return str; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + int n = sc.nextInt(); + String[] arr = new String[n]; + for(int i=0;imaxLength){ + maxLength = length; + str = arr[i]; + } + } + return str; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + int n = sc.nextInt(); + String[] arr = new String[n]; + for(int i=0;i maxStringLength) { + maxStringLength = arr[i].length(); + choiceString = arr[i]; + } + } + + if(choiceString.length() == 0) { + System.out.println("Better luck next time"); + } else { + System.out.println(choiceString); + } + + sc.close(); + } +} diff --git a/December - 09/Python3_lakshmeeee.py b/December - 09/Python3_lakshmeeee.py new file mode 100644 index 0000000..e37c31a --- /dev/null +++ b/December - 09/Python3_lakshmeeee.py @@ -0,0 +1,20 @@ +n = int(input()) +l = [str(x) for x in input().split()] +# l = ["Helloe", "Good", "Morninge", "Welcomee", "youe"] +length=[] + +for i in range(len(l)): + length.append(len(l[i])) + +m = max(length) +pos=-1 + +for i in range(len(length)): + if length[i]==m and length[i]%2!=0: + pos=i + break + +if(pos==-1): + print("Better luck next time") +else: + print(l[pos]) \ No newline at end of file diff --git a/December - 09/cpp_Aadhi11.cpp b/December - 09/cpp_Aadhi11.cpp new file mode 100644 index 0000000..586b659 --- /dev/null +++ b/December - 09/cpp_Aadhi11.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +int +main () +{ + string s[10], k; + int n, a[10], max = 0; + cin >> n; + for (int i = 0; i < n; i++) + { + cin >> s[i]; + a[i] = s[i].length (); + } + for (int i = 0; i < n; i++) + { + if ((a[i] % 2) != 0) + { + if (a[i] > max) + { + max = a[i]; + } + } + } + if (max == 0) + { + cout << endl << "Better luck next time"; + } + else + { + for (int i = 0; i < n; i++) + { + if (max == s[i].length ()) + { + cout << endl << s[i]; + break; + } + } + } +} + + diff --git a/December - 09/cpp_abhi-atg.cpp b/December - 09/cpp_abhi-atg.cpp new file mode 100644 index 0000000..8852d3a --- /dev/null +++ b/December - 09/cpp_abhi-atg.cpp @@ -0,0 +1,29 @@ +#include +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int n;cin>>n; + string ans; + + for(int i=0;i>s; + if(s.size()&1){ + if(ans.size() +#include + +using namespace std; + +int main() { + int n, myChoiceLength = -1; + int length; + + string myChoice = "Better Luck Next Time"; + cin>>n; + + string word; + + for(int i=0; i>word; + length = word.length(); + if(word.length()%2!=0 && length > myChoiceLength) { + myChoiceLength = word.length(); + myChoice = word; + } + } + cout<max: + max=len_arr[i] + word=ind_arr[i] + print(list_A[word]) \ No newline at end of file diff --git a/December - 09/day9.cpp b/December - 09/day9.cpp new file mode 100644 index 0000000..f97eb59 --- /dev/null +++ b/December - 09/day9.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + +int main() +{ + int n; + cin >> n; + vector input(n); + + for (auto &x : input) + cin >> x; + int max_len = INT_MIN; + + string word; + for (auto e : input) + { + int len = e.size(); + if (e.size() % 2 != 0) + { + max_len = max(len, max_len); + } + else + continue; + } + for (auto e : input) + { + if (e.size() == max_len) + { + word = e; + break; + } + } + if (max_len == INT_MIN) + cout << "Better Luck Next Time"; + else + cout << word; + + return 0; +} diff --git a/December - 09/java_DCBisht09.java b/December - 09/java_DCBisht09.java new file mode 100644 index 0000000..5011e87 --- /dev/null +++ b/December - 09/java_DCBisht09.java @@ -0,0 +1,28 @@ +import java.util.*; + +public class java_DCBisht09 { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=Integer.parseInt(sc.nextLine()); + + String s=sc.nextLine(); + String[] arr=s.split(" ",0); + String ans=""; + int ml=Integer.MIN_VALUE; + for(String i:arr){ + if(i.length()%2!=0 && i.length()>ml ){ + ans=i; + ml=i.length(); + } + } + + if(ml==Integer.MIN_VALUE){ + System.out.println("Better luck next time"); + } + else{ + System.out.println(ans); + } + // System.out.println(Arrays.toString(arr)); + sc.close(); + } +} diff --git a/December - 09/py_gowsrini2004_day_09.py b/December - 09/py_gowsrini2004_day_09.py new file mode 100644 index 0000000..6d9fa67 --- /dev/null +++ b/December - 09/py_gowsrini2004_day_09.py @@ -0,0 +1,30 @@ +#day_09 +y = 1 +while y > 0: + print("#problem_statment_09!!") + index = 0 + n = int(input("")) + s = input("") + str = s.split(" ") + max = "" + for i in str: + l = len(i) + index +=1 + if l > len(max): + if index len(max): + if l % 2 == 0: + max = '' + else: + max = i + + + if len(max)%2 == 0: + print("Better luck next time") + else: + print(max) \ No newline at end of file diff --git a/December - 10/C++_Dhruv.cpp b/December - 10/C++_Dhruv.cpp new file mode 100644 index 0000000..61efc57 --- /dev/null +++ b/December - 10/C++_Dhruv.cpp @@ -0,0 +1,40 @@ +#include +using namespace std; +bool check_vowel(char ch) +{ + if(ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u') + return true; + else + return false; +} +int main() { + + int t ;cin>>t; + + while(t--){ + bool flag = false; + int n;cin>>n;// size of word + string word;cin>>word; + if(n<4)flag = false; + else + { + for(int i=0;i=4){ + flag = true; + break; + } + i++; + streak++; + } + if(flag)break; + } + + } + + flag==true?cout<<"NO":cout<<"YES"; + cout< +using namespace std; + +void pronounce(char word[], int n){ + int count = 0; + for(size_t i = 0; i < n; i++){ + if(word[i] != 'a' && word[i] != 'e' && word[i] != 'i' && word[i] != 'o' && word[i] != 'u'){ + count++; + if(count == 4){ + cout << "NO" <> T; + + while(T>0){ + int n; + cin >> n; + + char word[n]; + for(int i=0; i> word[i]; + } + + pronounce(word, n); + T--; + } + return 0; +} diff --git a/December - 10/C++_subburamanathan7.cpp b/December - 10/C++_subburamanathan7.cpp new file mode 100644 index 0000000..5644b1d --- /dev/null +++ b/December - 10/C++_subburamanathan7.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +int main(){ + int test_cases,count=0,flag=0; + cout<<"Enter number of test test_cases"; + cin>>test_cases; + for(int i=0;i>temp; + count=0; + if(temp.length()<4){ + cout<<"Invalid Input\n"; + continue; + } + for(int j=0;j=4){ + flag=1; + break; + } + } + else + count=0; + } + if(flag==1){ + cout<<"NO\n"; + } + else + cout<<"YES\n"; + } + return 0; +} \ No newline at end of file diff --git a/December - 10/CPP_GANESHANHARI_DAY__10.cpp b/December - 10/CPP_GANESHANHARI_DAY__10.cpp new file mode 100644 index 0000000..f5f15e3 --- /dev/null +++ b/December - 10/CPP_GANESHANHARI_DAY__10.cpp @@ -0,0 +1,49 @@ + +#include +#include + +using namespace std; +bool isvowel(char ch) +{ +int res= (ch == 'a') || (ch == 'e') ||(ch == 'i') ||(ch == 'o') ||(ch == 'u'); +return (!res); +} +int main() { + int casen; + cout<<"input:"<>casen; + char word[casen][100]; + int len[casen]; + int t=casen; + while(t>0) + { + cin>>len[t]; + cout<>word[t]; + cout<0) + { + + + int ch=0; + int i; + + for(i=0;iN: + print(f'Error! Only {N} characters allowed!') + else: + V = ['a','e','i','o','u'] + count = 0 + for I in range(0,N): + if I!=N-1: + if STR[I] and STR [I+1] not in V: + count = count + 1 + if count > 3: + C.append("NO") + else: + C.append("YES") +N1 = len(C) +print("\n") +for J in range(0,N1): + print(C[J],sep="\n") \ No newline at end of file diff --git a/December - 10/GREEDnim_day10_java.java b/December - 10/GREEDnim_day10_java.java new file mode 100644 index 0000000..38fc97a --- /dev/null +++ b/December - 10/GREEDnim_day10_java.java @@ -0,0 +1,35 @@ +package acm; + +import java.util.HashSet; +import java.util.Scanner; + +public class GREEDnim_day10_java { + public static void main(String[] args) { + HashSetvowels=new HashSet<>(); + char[] vow={'a','e','i','o','u'}; + for(char e:vow) vowels.add(e); + Scanner in=new Scanner(System.in); + int t=in.nextInt(); + + for(int j=0;j=4) + { + flag=true; + break; + } + } + if(flag) System.out.println("NO"); + else System.out.println("YES"); + } + + } +} diff --git a/December - 10/Java_Ankur2606.java b/December - 10/Java_Ankur2606.java new file mode 100644 index 0000000..d2c23f5 --- /dev/null +++ b/December - 10/Java_Ankur2606.java @@ -0,0 +1,54 @@ +import java.util.*; +public class Java_Ankur2606{ + public String[] playWithWords(String[] arr, int n){ + String[] results = new String[n]; + for(int i=0;i= 4){ + break; + } + } + } + + if(consonants >= 4){ + results[i] = "NO"; + }else{ + results[i] = "YES"; + } + } + return results; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + int n = sc.nextInt(); + String[] strArr = new String[n]; + for(int i=0;i= 4){ + break; + } + } + } + + if(consonants >= 4){ + results[i] = "NO"; + }else{ + results[i] = "YES"; + } + } + return results; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + int n = sc.nextInt(); + String[] strArr = new String[n]; + for(int i=0;i=4) { + return "NO"; + } + } + } + return "YES"; + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int wordCount = sc.nextInt(); + String responses[] = new String[wordCount]; + + for(int i = 0; i< wordCount; i++) { + int charCount = sc.nextInt(); + sc.nextLine(); + String word = sc.next().substring(0,charCount); + responses[i] = count(word);; + } + + for(String answer : responses) { + System.out.println(answer); + } + sc.close(); + } +} diff --git a/December - 10/Python3_lakshmeeee.py b/December - 10/Python3_lakshmeeee.py new file mode 100644 index 0000000..e4464fa --- /dev/null +++ b/December - 10/Python3_lakshmeeee.py @@ -0,0 +1,26 @@ +nw = int(input()) +words = [] + +for i in range(nw*2): + word = input() + if (i+1)%2==0: + words.append(word) + +print(words) + +vowels = ['a', 'e', 'i', 'o', 'u'] + +for word in words: + c=0 + + for letter in word: + if letter not in vowels: + c+=1 + else: + c=0 + + if c==4: + print('NO') + break + if c<4: + print('YES') diff --git a/December - 10/cpp_Aadhi11.cpp b/December - 10/cpp_Aadhi11.cpp new file mode 100644 index 0000000..24207db --- /dev/null +++ b/December - 10/cpp_Aadhi11.cpp @@ -0,0 +1,43 @@ +#include +#include +using namespace std; + +int +main () +{ + string s[10]; + int n, a[10], count[10] = { 0 }; + cin >> n; + for (int i = 0; i < n; i++) + { + cin >> a[i]; + cin >> s[i]; + } + for (int i = 0; i < n; i++) + { + for (int j = 0; j < a[i]; j++) + { + if ((s[i][j] == 'a' || s[i][j] == 'e' || s[i][j] == 'i' + || s[i][j] == 'o' || s[i][j] == 'u')) + { + count[i] = 0; + } + else + { + count[i]++; + if (count[i] == 4) + break; + } + } + } + cout << endl; + for (int i = 0; i < n; i++) + { + if (count[i] == 4) + cout << "NO" << endl; + else + cout << "YES" << endl; + } +} + + diff --git a/December - 10/cpp_abhi-atg.cpp b/December - 10/cpp_abhi-atg.cpp new file mode 100644 index 0000000..8a07fd4 --- /dev/null +++ b/December - 10/cpp_abhi-atg.cpp @@ -0,0 +1,36 @@ +#include +using namespace std; +/* Abhi-Atg */ + + +int main(){ + + int t;cin>>t; + string c="aeiou"; + while(t--){ + int n;cin>>n; + string s;cin>>s; + int cnt=-1; + int flag=0; + for(int i=0;i=4){ + flag=1; + } + } + if(flag){ + cout<<"NO\n"; + }else{ + cout<<"YES\n"; + } + } + + + + return 0; +} \ No newline at end of file diff --git a/December - 10/cpp_nijuyonkadesu.cpp b/December - 10/cpp_nijuyonkadesu.cpp new file mode 100644 index 0000000..09f38f4 --- /dev/null +++ b/December - 10/cpp_nijuyonkadesu.cpp @@ -0,0 +1,36 @@ +#include + +using namespace std; +void result(); + +int main() { + int count; + cout<<"Enter no of words: "; + cin>>count; + cin.ignore(); // to prevent a edge case, try commenting this line and run ^_^ + + for(int i=0; i4: + a.append("NO") + else: + a.append("YES") +for i in a: + print(i) \ No newline at end of file diff --git a/December - 10/day10.cpp b/December - 10/day10.cpp new file mode 100644 index 0000000..8779d7f --- /dev/null +++ b/December - 10/day10.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +bool isVowel(char ch) +{ + return ( ch == 'a' || ch == 'e' ||ch == 'i' || ch == 'o' ||ch == 'u'); +} + +int calcDiff(string str) +{ + int c=0; + if(str.length() >= 4){} + for (int i = 0; i < str.length()-3; i++) + { + if ((!isVowel(str[i])) && (!isVowel(str[i+1])) && (!isVowel(str[i+2])) && (!isVowel(str[i+3]))) + { + c=1; + } +} + return c; +} + +int main() +{ + int n; + cin >> n; + + int s[n]; + string str[n]; + for(int i=0; i> s[i]; + cin >> str[i]; + } + + for(int i=0; i=4){ + return false; + } + } + return true; + } + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int T=Integer.parseInt(sc.nextLine()); + // System.out.println(T); + while(T-->0){ + int n=Integer.parseInt(sc.nextLine()); + String w=sc.nextLine(); + // n=w.length(); + if(f(w,n)){ + System.out.println("YES"); + } + else{ + System.out.println("NO"); + } + } + + sc.close(); + } +} diff --git a/December - 10/py_gowsrini2004_day_10.py b/December - 10/py_gowsrini2004_day_10.py new file mode 100644 index 0000000..cd1e0ce --- /dev/null +++ b/December - 10/py_gowsrini2004_day_10.py @@ -0,0 +1,31 @@ +#day_10 +y = 1 +while y > 0: + print("#problem_statment_10!!") + T = int(input("")) + vowels = ["a","e","i","o","u"] + output = [] + for i in range(0,T): + index = 0 + N = int(input("")) + S = input("") + s_1 = S.lower() + s_l = list(s_1) + for j in s_l: + if index<4: + if j in vowels: + index=0 + pass + else: + index+=1 + else: + pass + if index<4: + output.append("Y") + else: + output.append("N") + for j in output: + if j == "Y": + print("YES") + else: + print("NO") \ No newline at end of file diff --git a/December - 11/.gitignore b/December - 11/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 11/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 11/C++_Dhruv.cpp b/December - 11/C++_Dhruv.cpp new file mode 100644 index 0000000..63fcf84 --- /dev/null +++ b/December - 11/C++_Dhruv.cpp @@ -0,0 +1,33 @@ +#include +using namespace std; + +int main() { + // int n;cin>>n; + // vector input(n) ; + // for(auto &x:input)cin>>x; + + // int m;cin>>m; + // vector steps(m) ; + // for(auto &i:steps)cin>>i; + char input[] = [‘_’,’~’,’_’,’_’,’_’,’_’,’~’,’_’,’_’,’~’,’_’,’~’]; + int steps[]=[2,1,1,1,2,1,1,1,1]; + int n = input.length(); + int m = steps.length(); + int score =0; + // if(input[0]=='~')cout< +using namespace std; + +int count1(char character[]){ + for(int i=0; i<100000; i++){ + if(character[i]=='1' || character[i]=='2') return i; + } + return 0; +} + +int count2(char character[]){ + for(int i=0; i<100000; i++){ + if(character[i]=='\0') return i; + } + return 0; +} + +int monkeycount(char character[], int n1, int n2, int jump[]){ + int pos = 0; + for(int i =0; i> character[i]; + } + + int n1 = count1(character); + int n2 = count2(character); + int jump[n2-n1]; + for(int i = n1; i +using namespace std; + +int main(){ + int limit,i,j=0,score; + string sequence; //Land or Water + + cout<<"Enter the sequence"; + cin>>sequence; + + cout<<"Enter Limit Of Jumps"; + cin>>limit; + int *jumps = (int*)malloc(sizeof(int)*limit); + + cout<<"jumps can be 2 or 1\n"; + for(i=0;i>*(jumps+i); + + for(i=0;i& fillThis) { + char ch; + do{ + ch=getchar(); + fillThis.push_back(ch); + }while(ch!='\n'); +} diff --git a/December - 11/day 11.py b/December - 11/day 11.py new file mode 100644 index 0000000..c6abcc3 --- /dev/null +++ b/December - 11/day 11.py @@ -0,0 +1,9 @@ +a=list(input().split(',')) +b=list(map(int,input().split(','))) +x=0 +for i in range(0,len(b)): + x+=b[i] + if(a[x]=='~'): + print("Score =",i) + break + \ No newline at end of file diff --git a/December - 11/day11.cpp b/December - 11/day11.cpp new file mode 100644 index 0000000..b15fbac --- /dev/null +++ b/December - 11/day11.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +int main() { + // int n;cin>>n; + // vector input(n) ; + // for(auto &x:input)cin>>x; + + // int m;cin>>m; + // vector steps(m) ; + // for(auto &i:steps)cin>>i; + vector input{'_','~','_','~','_','_','~','_','_','~','_','~'}; + vector steps{2,2,1,1,1,1,2,1,1}; + int n = input.size(); + int m = steps.size(); + int score =0; + int jumps=0; + for(int i=0;i +using namespace std; + +#define R 4 +#define C 4 + +int minCost(int cost[R][C], int m, int n) +{ + if (n < 0 || m < 0) + return INT_MAX; + else if (m == 0 && n == 0) + return cost[m][n]; + else + return cost[m][n] + + min(minCost(cost, m - 1, n), + minCost(cost, m, n - 1)); +} + +int main() +{ + + int cost[R][C] + = { {9,4,9,9}, {6,7,6,4}, {8,3,3,7}, {7,4,9,10} }; + + cout << minCost(cost, R-1, C-1) << endl; + + return 0; +} + + diff --git a/December - 12/C++_MugundhanY.cpp b/December - 12/C++_MugundhanY.cpp new file mode 100644 index 0000000..44c632e --- /dev/null +++ b/December - 12/C++_MugundhanY.cpp @@ -0,0 +1,66 @@ +//Question 12: +#include +using namespace std; + +class Solution +{ + public: + int minimumCostPath(vector>& grid){ + + int n=grid.size(); + int m=grid[0].size(); + int ans=0; + int dist[n][m]; + for(int i=0; i>, vector>>, greater>>>pq; + dist[0][0]=grid[0][0]; + pq.push({dist[0][0], {0, 0}}); + int dx[4]={0, 0, -1, 1}; + int dy[4]={-1, 1, 0, 0}; + while(pq.empty()==false){ + auto x=pq.top(); pq.pop(); + int cost=x.first; + auto y=x.second; + int i=y.first; + int j=y.second; + ans+=cost; + if(i==n-1 && j==m-1){ + break; + } + for(int k=0; k<4; k++){ + int u=i+dx[k]; + int v=j+dy[k]; + if(u>=0 && u=0 && v=dist[i][j]+ grid[u][v]){ + dist[u][v]=dist[i][j]+grid[u][v]; + pq.push({dist[u][v], {u, v}}); + } + } + } + } + return dist[n-1][m-1]; + } +}; + +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n; + cin >> n; + vector>grid(n, vector(n, -1)); + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + cin >> grid[i][j]; + } + } + Solution obj; + int ans = obj.minimumCostPath(grid); + cout << ans << "\n"; + } + return 0; +} diff --git a/December - 12/C++_subburamanathan7.cpp b/December - 12/C++_subburamanathan7.cpp new file mode 100644 index 0000000..aafc7f2 --- /dev/null +++ b/December - 12/C++_subburamanathan7.cpp @@ -0,0 +1,51 @@ +#include + +using namespace std; + +int main(){ + int maze[4][4]={ + {9,4,9,9}, + {6,7,6,4}, + {8,3,3,7}, + {7,4,9,10} + }; + +// here 4 remains to be the matrix dimensions everywhere + int prev=0, cost=0; + for(int i=0;i<4;++i){ + for(int j=0;j<4;++j){ + + j=prev; + if(i!=(4-1) || j!=(4-1)){ + cout<maze[i+1][j]){ + prev=j; + break; + } + else{ + prev=j+1; + continue; + } + } + else if(i+1<4 && j+1==4){ + prev=j; + break; + } + else{ + prev=j+1; + continue; + } + } + else{ + + cost+=maze[i][j]; + cout< +using namespace std; + +class Solution +{ + public: + int minimumCostPath(vector>& grid){ + + int n=grid.size(); + int m=grid[0].size(); + int ans=0; + int dist[n][m]; + for(int i=0; i>, vector>>, greater>>>pq; + dist[0][0]=grid[0][0]; + pq.push({dist[0][0], {0, 0}}); + int dx[4]={0, 0, -1, 1}; + int dy[4]={-1, 1, 0, 0}; + while(pq.empty()==false){ + auto x=pq.top(); pq.pop(); + int cost=x.first; + auto y=x.second; + int i=y.first; + int j=y.second; + ans+=cost; + if(i==n-1 && j==m-1){ + break; + } + for(int k=0; k<4; k++){ + int u=i+dx[k]; + int v=j+dy[k]; + if(u>=0 && u=0 && v=dist[i][j]+ grid[u][v]){ + dist[u][v]=dist[i][j]+grid[u][v]; + pq.push({dist[u][v], {u, v}}); + } + } + } + } + return dist[n-1][m-1]; + } +}; + +int main(){ + int tc; + cin >> tc; + while(tc--){ + int n; + cin >> n; + vector>grid(n, vector(n, -1)); + for(int i = 0; i < n; i++){ + for(int j = 0; j < n; j++){ + cin >> grid[i][j]; + } + } + Solution obj; + int ans = obj.minimumCostPath(grid); + cout << ans << "\n"; + } + return 0; +} \ No newline at end of file diff --git a/December - 12/GREEDnim_day12_java.java b/December - 12/GREEDnim_day12_java.java new file mode 100644 index 0000000..18b406f --- /dev/null +++ b/December - 12/GREEDnim_day12_java.java @@ -0,0 +1,62 @@ +package acm; + +import java.util.ArrayList; +import java.util.List; + +public class GREEDnim_day12_java { + + static boolean[][]checked; + static List> ans; + public static void main(String[] args) { + + //hardcoded input XD + int[][]input={ {8,3,9}, {2,6,4}, {8,3,1}}; + + ans=new ArrayList<>(); + checked=new boolean[input.length][input[0].length]; + allCombinations(input,0,0,new ArrayList<>()); + int min=0; + + for(int i=1;ilist) + { + if(i==inp.length-1 && j==inp[0].length-1 ) + { + list.add(inp[i][j]); + ans.add(new ArrayList<>(list)); + list.remove(list.size()-1); + return; + } + if(i<0 || i>=inp.length || j<0 || j>=inp[0].length || checked[i][j]) return; + checked[i][j]=true; + list.add(inp[i][j]); + + allCombinations(inp,i+1,j,list); + allCombinations(inp,i-1,j,list); + allCombinations(inp,i,j-1,list); + allCombinations(inp,i,j+1,list); + list.remove(list.size()-1); + checked[i][j]=false; + + } + public static int sum(Listlist) + { + int ans=0; + for(int i=0;i +using namespace std; + +int main() +{ + int n,a[10][10],b[10],total,s=0,k=1,q=0; + for(int i=0;i<10;i++) + { + for(int j=0;j<10;j++) + { + a[i][j]=500; + } + } + cin>>n; + cout<<"Path = "; + for(int i=0;i>a[i][j]; + } + } + total=a[0][0]; + b[q]=a[0][0]; + q++; + for(int i=0;ia[i][j+1]) + { + b[q]=a[i][j+1]; + q++; + total=total+a[i][j+1]; + } + if(a[i+1][j] +#include +#include +#include + +using namespace std; + +vector> input(int); +void pathFinder(vector>& visited, vector> &maze, vector& path, vector> &possibility, int x, int y, int n); +bool isSafe(vector>& visited, int x, int y, int n); + +int main() { + int n; + cin>>n; + + vector> visited(n, vector (n, 0)); + vector> maze = input(n); + vector path; + vector> possibility; + + int min = INT_MAX; + int pathPointer = 0, index =0; + + pathFinder(visited, maze, path, possibility, 0, 0, n); + for(auto ans: possibility){ + index++; + int sum = accumulate(ans.begin(), ans.end(), 0); + if(sum < min){ + pathPointer = index; + min = sum; + } + } + + for(auto i: possibility[pathPointer]) + cout<> input(int n) { + vector> maze(n, vector (n, 0)); + + for(int i=0; i>maze[i][j]; + return maze; +} + +void pathFinder(vector> &visited, vector> &maze, vector &path, vector> &possibility, int x, int y, int n) { + if(x==n-1 && y==n-1){ + path.push_back(maze[x][y]); + possibility.push_back(path); + path.pop_back(); + return ; + } + + visited[x][y] = 1; // Mark visited + path.push_back(maze[x][y]); + + if(isSafe(visited, x+1, y, n)) // Right + pathFinder(visited, maze, path, possibility, x+1, y, n); + if(isSafe(visited, x, y+1, n)) // Bottom + pathFinder(visited, maze, path, possibility, x, y+1, n); + if(isSafe(visited, x-1, y, n)) // Left + pathFinder(visited, maze, path, possibility, x-1, y, n); + if(isSafe(visited, x, y+1, n)) // Up + pathFinder(visited, maze, path, possibility, x, y+1, n); + + visited[x][y] = 0; // Backtracking + path.pop_back(); + return ; +} + + +bool isSafe(vector>& visited, int x, int y, int n){ + return (x>=0 && x=0 && y=a[i+1][j]): + current_position= a[i+1][j] + i=i+1 + print(current_position,end=',') + dropped+=current_position +print(a[n-1][n-1],end="}") +dropped+=a[n-1][n-1] +print("\nThe minimum coins dropped is ",dropped) + \ No newline at end of file diff --git a/December - 12/day12.cpp b/December - 12/day12.cpp new file mode 100644 index 0000000..de7ce5d --- /dev/null +++ b/December - 12/day12.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +#define R 4 +#define C 4 + +int minCost(int cost[R][C], int m, int n) +{ + if (n < 0 || m < 0) + return INT_MAX; + else if (m == 0 && n == 0) + return cost[m][n]; + else + return cost[m][n] + + min(minCost(cost, m - 1, n), + minCost(cost, m, n - 1)); +} + +int main() +{ + int cost[R][C] + = { {9,4,9,9}, {6,7,6,4}, {8,3,3,7}, {7,4,9,10} }; + + cout << minCost(cost, R-1, C-1) << endl; + + return 0; +} diff --git a/December - 12/java_DCBisht12.java b/December - 12/java_DCBisht12.java new file mode 100644 index 0000000..045ee3b --- /dev/null +++ b/December - 12/java_DCBisht12.java @@ -0,0 +1,63 @@ +import java.util.*; + +public class java_DCBisht12 { + static boolean[][]checked; + static List> ans; + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int[][]input=new int[n][n]; + for(int i=0;i(); + checked=new boolean[n][n]; + allCombinations(input,0,0,new ArrayList<>()); + int min=0; + + for(int i=1;ilist) + { + if(i==inp.length-1 && j==inp[0].length-1 ) + { + list.add(inp[i][j]); + ans.add(new ArrayList<>(list)); + list.remove(list.size()-1); + return; + } + if(i<0 || i>=inp.length || j<0 || j>=inp[0].length || checked[i][j]) return; + checked[i][j]=true; + list.add(inp[i][j]); + + allCombinations(inp,i+1,j,list); + allCombinations(inp,i-1,j,list); + allCombinations(inp,i,j-1,list); + allCombinations(inp,i,j+1,list); + list.remove(list.size()-1); + checked[i][j]=false; + + } + public static int sum(Listlist) + { + int ans=0; + for(int i=0;i 0: + print("#problem_statment_12!!") + n = int(input("")) + path = input("path: ").replace(" ","").replace("{","").replace("}","").split(",") + path = [int(x) for x in path] + # print(path) + index = 0 + final_lis = [] + final_lis.append(path[0]) + while index<((n*n)-1): + if index == ((n*(n-1))-1): + y = path[index+n] + final_lis.append(y) + break + if index>= ((n*n)-(n-1)): + x = path[index+1] + final_lis.append(x) + index+=1 + else: + x = path[index+1] + y = path[index+n] + # print(x,y,index) + if y>x: + final_lis.append(x) + index+=1 + elif x>y or x==y: + final_lis.append(y) + index+=n + + # print(final_lis) + sum = 0 + for i in final_lis: + sum+=i + + + print("\n\n") + print("path_taken="+'{' + ','.join([str(x) for x in final_lis]) + '}') + print("The minimum coins dropped is",sum) \ No newline at end of file diff --git a/December - 13/.gitignore b/December - 13/.gitignore new file mode 100644 index 0000000..8844c9f --- /dev/null +++ b/December - 13/.gitignore @@ -0,0 +1,208 @@ +n = int(input("enter the size of maze")) +def isValid(n, maze, x, y, res): + if x >= 0 and y >= 0 and x < n and y < n and maze[x][y] == 1 and res[x][y] == 0: + return True + return False +def RatMaze(n, maze, move_x, move_y, x, y, res): + if x == n-1 and y == n-1: + return True + for i in range(4): + x_new = x + move_x[i] + y_new = y + move_y[i] + if isValid(n, maze, x_new, y_new, res): + res[x_new][y_new] = 1 + if RatMaze(n, maze, move_x, move_y, x_new, y_new, res): + return True + res[x_new][y_new] = 0 + return False +def solveMaze(maze): + res = [[0 for i in range(n)] for i in range(n)] + res[0][0] = 1 + move_x = [-1, 1, 0, 0] + move_y = [0, 0, -1, 1] + if RatMaze(n, maze, move_x, move_y, 0, 0, res): + for i in range(n): + for j in range(n): + print(res[i][j], end=' ') + print() + else: + print('Solution does not exist') +if __name__ == "__main__": + matrix=[] +for i in range(n): + a =[] + for j in range(n): + a.append(int(input())) + matrix.append(a) +for i in range(n): + for j in range(n): + print(matrix[i][j], end = " ") + print() +solveMaze(matrix) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/December - 13/C++_Dhruv.cpp b/December - 13/C++_Dhruv.cpp new file mode 100644 index 0000000..43b9392 --- /dev/null +++ b/December - 13/C++_Dhruv.cpp @@ -0,0 +1,114 @@ +#include +#include +#include +using namespace std; + +const int N = 4; // size of the maze + +int maze[N][N] = { // the maze, with 1s representing clear paths and 0s representing dead ends + {1,0,0,0}, +{1,1,0,1}, +{0,1,0,0}, +{1,1,1,1} + +}; + +// structure to store the coordinates of a block in the maze +struct Point { + int x, y; +}; + +// function to check if a given point is within the bounds of the maze +bool is_valid(int x, int y) { + return x >= 0 && x < N && y >= 0 && y < N; +} + +// function to find a solution to the maze using BFS +std::vector solve_maze_bfs(Point start, Point end) { + std::vector path; // vector to store the solution path + + std::queue q; // queue to store the blocks that need to be explored + q.push(start); + + // two-dimensional array to store the "came from" information for each block + // came_from[i][j] stores the coordinates of the block that was explored just before the block at (i, j) + Point came_from[N][N]; + came_from[start.x][start.y] = start; // the starting block was explored just before itself + + // array to store the visited status of each block + bool visited[N][N] = {false}; // all blocks are initially unvisited + + // explore the maze one block at a time + while (!q.empty()) { + Point p = q.front(); + q.pop(); + + // check if the block is the endpoint + if (p.x == end.x && p.y == end.y) { + // construct the solution path by following the "came from" information back from the endpoint + while (p.x != start.x || p.y != start.y) { + path.push_back(p); + p = came_from[p.x][p.y]; + } + path.push_back(start); // add the starting block to the path + std::reverse(path.begin(), path.end()); // reverse the path + return path; // return the solution path + } + + // if the block is not the endpoint, add its neighbors to the queue + if (is_valid(p.x + 1, p.y) && !visited[p.x + 1][p.y] && maze[p.x + 1][p.y] == 1) { + q.push({p.x + 1, p.y}); + came_from[p.x + 1][p.y] = p; + visited[p.x + 1][p.y] = true; + } + if (is_valid(p.x - 1, p.y) && !visited[p.x - 1][p.y] && maze[p.x - 1][p.y] == 1) { + q.push({p.x - 1, p.y}); + came_from[p.x - 1][p.y] = p; + visited[p.x - 1][p.y] = true; + } + if (is_valid(p.x, p.y + 1) && !visited[p.x][p.y + 1] && maze[p.x][p.y + 1] == 1) { + q.push({p.x, p.y + 1}); + came_from[p.x][p.y + 1] = p; + visited[p.x][p.y + 1] = true; + } + if (is_valid(p.x, p.y - 1) && !visited[p.x][p.y - 1] && maze[p.x][p.y - 1] == 1) { + q.push({p.x, p.y - 1}); + came_from[p.x][p.y - 1] = p; + visited[p.x][p.y - 1] = true; + } + } + + return {}; // no solution was found +} + +int main() { + int n=4; + vector > res(n, vector(n,0)); + // define the starting and ending points of the maze + Point start = {0, 0}; + Point end = {N - 1, N - 1}; + + // find a solution to the maze using BFS + std::vector path = solve_maze_bfs(start, end); + + if (path.empty()) { + std::cout << "No solution found." << std::endl; + } else { + // std::cout << "Solution found: " << std::endl; + for (Point p : path) { + res[p.x][p.y]=1; + // std::cout << "(" << p.x << ", " << p.y << ")" << std::endl; + } + for(int i=0;i<4;i++) + { + for(int j=0;j<4;j++) + { + + std::cout< +using namespace std; + +bool issafe(int** arr, int x, int y, int n){ + if(x>n; + int** arr=new int*[n]; + for(int i=0; i>arr[i][j]; + } + } + int** solArr=new int*[n]; + for(int i=0; i +using namespace std; + +bool issafe(int** arr, int x, int y, int n){ + if(x>n; + int** arr=new int*[n]; + for(int i=0; i>arr[i][j]; + } + } + int** solArr=new int*[n]; + for(int i=0; i=inp.length || j>=inp[0].length || inp[i][j]!=1) return false; + ans[i][j]=1; + boolean ansFound=findOnePath(inp,i,j+1) || findOnePath(inp,i+1,j); + if(!ansFound) inp[i][j]=0; + + return ansFound; + } +} diff --git a/December - 13/cpp_Aadhi11.cpp b/December - 13/cpp_Aadhi11.cpp new file mode 100644 index 0000000..30cacb4 --- /dev/null +++ b/December - 13/cpp_Aadhi11.cpp @@ -0,0 +1,82 @@ +#include +using namespace std; + + +bool solveMazeUtil(int maze[100][100], int x, int y,int sol[100][100],int n); + +void printSolution(int sol[100][100],int n) +{ + cout<= 0 && x < n && y >= 0 && y < n && maze[x][y] == 1) + return true; + return false; +} + + +bool solveMaze(int maze[100][100],int n) +{ + int sol[100][100]; + for(int i=0;i>n; + int maze[100][100]; + for(int i=0;i>maze[i][j]; + } + } + solveMaze(maze,n); + return 0; +} + diff --git a/December - 13/cpp_nijuyonkadesu.cpp b/December - 13/cpp_nijuyonkadesu.cpp new file mode 100644 index 0000000..8f923fb --- /dev/null +++ b/December - 13/cpp_nijuyonkadesu.cpp @@ -0,0 +1,64 @@ +#include +#include +#include +#include + +using namespace std; + +vector> input(int); +void pathFinder(vector>&, vector>&, vector>&, int, int, int); +bool isSafe(vector>&, int, int, int); + +int main() { + int n; + cin>>n; + + vector> visited(n, vector (n, 0)); // To keep track of visited boxes + vector> maze = input(n); // The maze itself + vector> path; // Stores the final path + + int min = INT_MAX; + int pathPointer = 0, index =0; + + pathFinder(visited, maze, path, 0, 0, n); + cout<<"\n"; + + for(auto i: path){ + for(auto j = i.begin(); j!=i.end(); j++){ + cout<<*j<<" "; + } + cout<<"\n"; + } +} + +vector> input(int n) { + vector> maze(n, vector (n, 0)); + + for(int i=0; i>maze[i][j]; + return maze; +} + +void pathFinder(vector> &visited, vector> &maze, vector> &path, int x, int y, int n) { + if(x==n-1 && y==n-1){ + visited[x][y] = 1; + path = visited; // cannot use visited, on backtrack eventually, everything goes to 0. + visited[x][y] = 0; // Therefore take a snapshot and load it to a new variable for later access in main function + return ; + } + + visited[x][y] = 1; // Mark visited + + if(isSafe(maze, x+1, y, n)) // Right + pathFinder(visited, maze, path, x+1, y, n); + if(isSafe(maze, x, y+1, n)) // Bottom + pathFinder(visited, maze, path, x, y+1, n); + + visited[x][y] = 0; // Backtracking + return ; +} + +bool isSafe(vector>& maze, int x, int y, int n){ + return (x +#include +#include +using namespace std; + +const int N = 4; + +int maze[N][N] = { + {1, 0, 0, 0}, + {1, 1, 0, 1}, + {0, 1, 0, 0}, + {1, 1, 1, 1} + +}; + +struct Point +{ + int x, y; +}; + +bool is_valid(int x, int y) +{ + return x >= 0 && x < N && y >= 0 && y < N; +} + +std::vector solve_maze_bfs(Point start, Point end) +{ + std::vector path; + + std::queue q; + q.push(start); + + Point came_from[N][N]; + came_from[start.x][start.y] = start; + + bool visited[N][N] = {false}; + + while (!q.empty()) + { + Point p = q.front(); + q.pop(); + + if (p.x == end.x && p.y == end.y) + { + while (p.x != start.x || p.y != start.y) + { + path.push_back(p); + p = came_from[p.x][p.y]; + } + path.push_back(start); + std::reverse(path.begin(), path.end()); + return path; + } + + if (is_valid(p.x + 1, p.y) && !visited[p.x + 1][p.y] && maze[p.x + 1][p.y] == 1) + { + q.push({p.x + 1, p.y}); + came_from[p.x + 1][p.y] = p; + visited[p.x + 1][p.y] = true; + } + if (is_valid(p.x - 1, p.y) && !visited[p.x - 1][p.y] && maze[p.x - 1][p.y] == 1) + { + q.push({p.x - 1, p.y}); + came_from[p.x - 1][p.y] = p; + visited[p.x - 1][p.y] = true; + } + if (is_valid(p.x, p.y + 1) && !visited[p.x][p.y + 1] && maze[p.x][p.y + 1] == 1) + { + q.push({p.x, p.y + 1}); + came_from[p.x][p.y + 1] = p; + visited[p.x][p.y + 1] = true; + } + if (is_valid(p.x, p.y - 1) && !visited[p.x][p.y - 1] && maze[p.x][p.y - 1] == 1) + { + q.push({p.x, p.y - 1}); + came_from[p.x][p.y - 1] = p; + visited[p.x][p.y - 1] = true; + } + } + + return {}; +} + +int main() +{ + int n = 4; + vector> res(n, vector(n, 0)); + Point start = {0, 0}; + Point end = {N - 1, N - 1}; + + std::vector path = solve_maze_bfs(start, end); + + if (path.empty()) + { + std::cout << "No solution found." << std::endl; + } + else + { + for (Point p : path) + { + res[p.x][p.y] = 1; + } + for (int i = 0; i < 4; i++) + { + for (int j = 0; j < 4; j++) + { + + std::cout << res[i][j]; + } + std::cout << std::endl; + } + } + + return 0; +} diff --git a/December - 13/java_DCBisht13.java b/December - 13/java_DCBisht13.java new file mode 100644 index 0000000..d15b8b1 --- /dev/null +++ b/December - 13/java_DCBisht13.java @@ -0,0 +1,34 @@ +import java.util.*; + +public class java_DCBisht13 { + static int[][] ans; + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int x=sc.nextInt(); + int[][] inp=new int[x][x]; + for(int i=0;i=inp.length || j>=inp[0].length || inp[i][j]!=1) return false; + ans[i][j]=1; + boolean ansFound=findOnePath(inp,i,j+1) || findOnePath(inp,i+1,j); + if(!ansFound) inp[i][j]=0; + + return ansFound; + } +} diff --git a/December - 13/py_gowsrini2004_day_13.py b/December - 13/py_gowsrini2004_day_13.py new file mode 100644 index 0000000..ae3d9ff --- /dev/null +++ b/December - 13/py_gowsrini2004_day_13.py @@ -0,0 +1,59 @@ +#day_13 +y = 1 +while y > 0: + print("#problem_statment_13!!") + def check_condition(n, path, x, y, lis): + if x >= 0 and y >= 0 and x < n and y < n and path[x][y] == 1 and lis[x][y] == 0: + return True + return False + + def move_path(n, path, x1, y1, x, y, lis): + if x == n-1 and y == n-1: + return True + for i in range(4): + x2 = x + x1[i] + y2 = y + y1[i] + if check_condition(n, path, x2, y2, lis): + lis[x2][y2] = 1 + if move_path(n, path, x1, y1, x2, y2, lis): + return True + lis[x2][y2] = 0 + return False + + def find_path(path): + lis = [[0 for i in range(n)] for i in range(n)] + lis[0][0] = 1 + x1 = [-1, 1, 0, 0] + y1 = [0, 0, -1, 1] + if move_path(n, path, x1, y1, 0, 0, lis): + for i in range(n): + for j in range(n): + pre_final_lis.append(lis[i][j]) + print() + else: + print('Path Cannot Be Found') + + def sub_array(inp,out): + start = 0 + end = len(inp) + step = n + for i in range(start, end, step): + x = i + out.append(inp[x:x+step]) + + + n = int(input("n= ")) + v1_mat,path,final_lis,pre_final_lis= [],[],[],[] + for i in range(0, n): + mat = input("").replace(" ","").replace("{","").replace("}","").split(",") + mat = [int(x) for x in mat] + for j in mat: + v1_mat.append(j) + + sub_array(v1_mat,path) + find_path(path) + sub_array(pre_final_lis,final_lis) + # print(pre_final_lis,final_lis) + print("OUTPUT:") + for i in final_lis: + print('{' + ','.join([str(x) for x in i]) + '}') \ No newline at end of file diff --git a/December - 13/python3_lakshmeee b/December - 13/python3_lakshmeee new file mode 100644 index 0000000..f8205f3 --- /dev/null +++ b/December - 13/python3_lakshmeee @@ -0,0 +1,2 @@ +import numpy +print(3) \ No newline at end of file diff --git a/December - 14/.gitignore b/December - 14/.gitignore new file mode 100644 index 0000000..7ea9849 --- /dev/null +++ b/December - 14/.gitignore @@ -0,0 +1,196 @@ + + +#code +class Graph(): + def __init__(self, V): + self.V = V + self.graph = [[0 for column in range(V)] \ + for row in range(V)] + def isBipartite(self, src): + colorArr = [-1] * self.V + colorArr[src] = 1 + queue = [] + queue.append(src) + while queue: + u = queue.pop() + if self.graph[u][u] == 1: + return False; + for v in range(self.V): + if self.graph[u][v] == 1 and colorArr[v] == -1: + colorArr[v] = 1 - colorArr[u] + queue.append(v) + elif self.graph[u][v] == 1 and colorArr[v] == colorArr[u]: + return False + return True +g = Graph(n) +g.graph = [[0, 1, 0, 1], + [1, 0, 1, 0], + [0, 1, 0, 1], + [1, 0, 1, 0] + ] +print ("This is bipartite graph" if g.isBipartite(0) else "No") + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/December - 14/C++_Dhruv.cpp b/December - 14/C++_Dhruv.cpp new file mode 100644 index 0000000..a96ce44 --- /dev/null +++ b/December - 14/C++_Dhruv.cpp @@ -0,0 +1,91 @@ +#include +#include +#include +using namespace std; + + +const int N = 4; // number of vertices in the graph + +// 2D vector representation of the graph +int graph[N][N] = { + {0, 1, 0, 1}, + {1, 0, 1, 0}, + {0, 1, 0, 1}, + {1, 0, 1, 0} +}; + // initialize the adjacency list + std::vector> adj(N); +// function to check if the graph is bipartite +bool is_bipartite() { + // sets to store the vertices of the graph + std::vector U, V; + + // initialize the sets with an arbitrary vertex + U.push_back(0); + + // mark all vertices as unvisited + bool visited[N] = {false}; + + // iterate over the vertices in set U + for (int u : U) { + visited[u] = true; // mark the vertex as visited + // iterate over the neighbors of u + for (int v : adj[u]) { + // if the neighbor has not been visited, add it to set V + if (!visited[v]) { + V.push_back(v); + } + // if the neighbor has already been visited, check which set it belongs to + else { + // if the neighbor belongs to set U, the graph is not bipartite + if (std::find(U.begin(), U.end(), v) != U.end()) { + return false; + } + } + } + } + + // repeat the process for the vertices in set V + for (int v : V) { + visited[v] = true; // mark the vertex as visited + // iterate over the neighbors of v + for (int u : adj[v]) { + // if the neighbor has not been visited, add it to set U + if (!visited[u]) { + U.push_back(u); + } + // if the neighbor has already been visited, check which set it belongs to + else { + // if the neighbor belongs to set V, the graph is not bipartite + if (std::find(V.begin(), V.end(), u) != V.end()) { + return false; + } + } + } + } + + // if no neighbors belonging to the same set as the current vertex were found, the graph is bipartite + return true; +} +int main() { + + + // iterate over the rows and columns of the 2D vector + for (int i = 0; i < N; i++) { + for (int j = 0; j < N; j++) { + // if the element is equal to 1, add the column index as a neighbor of the row index + if (graph[i][j] == 1) { + adj[i].push_back(j); + } + } + } + + if (is_bipartite()) { + std::cout << "The graph is bipartite." << std::endl; + } + else { + std::cout << "The graph is not bipartite." << std::endl; + } + + return 0; +} diff --git a/December - 14/C++_MugundhanY.cpp b/December - 14/C++_MugundhanY.cpp new file mode 100644 index 0000000..1ce7250 --- /dev/null +++ b/December - 14/C++_MugundhanY.cpp @@ -0,0 +1,29 @@ +//Question 14: +#include +using namespace std; + +bool isBipartite(int n, vector> &arr){ + for(int i=0; i>n; + int temp; + vector> arr; + for(int i=0; i row; + for(int j=0; j>temp; + row.push_back(temp); + } + arr.push_back(row); + } + if(isBipartite(n, arr)) cout << "The graph is Bipartite!"; + else cout << "The graph is not a Bipartite!"; + return 0; +} diff --git a/December - 14/C++_subburamanathan7.cpp b/December - 14/C++_subburamanathan7.cpp new file mode 100644 index 0000000..e678ff5 --- /dev/null +++ b/December - 14/C++_subburamanathan7.cpp @@ -0,0 +1,48 @@ +#include +#include +using namespace std; +bool Bipartite(int G[][6],int root){ + int colorArr[6],i; + for(i=0;i<6;i++) + colorArr[i]=-1; + + colorArr[root] = 1; + + //1-Red 0-Blue + //colors to represent Bipartite + queue q; + q.push(root); + + while(!q.empty()){ + int x = q.front(); + q.pop(); + + if(G[x][x]) + return false; + for(i=0;i<6;i++){ + if(G[x][i] && colorArr[i]==-1){ + colorArr[i]=1 - colorArr[x]; + q.push(x); + } + else if(G[x][i] && colorArr[x] == colorArr[i]) + return false; + } + } + return true; +} +int main(){ + int root=1; + int G[][6] = { + {0,1,0,0,0,1}, + {1,0,1,0,0,0}, + {0,1,0,1,0,0}, + {0,0,1,0,1,0}, + {0,0,0,1,0,1}, + {1,0,0,0,1,0}, + }; + if(Bipartite(G,root)) + cout<<"Bipartite"; + else + cout<<"Not Bipartite"; + return 0; +} diff --git a/December - 14/Cpp_Ankur2606.cpp b/December - 14/Cpp_Ankur2606.cpp new file mode 100644 index 0000000..482e0a9 --- /dev/null +++ b/December - 14/Cpp_Ankur2606.cpp @@ -0,0 +1,28 @@ +#include +using namespace std; + +bool isBipartite(int n, vector> &arr){ + for(int i=0; i>n; + int temp; + vector> arr; + for(int i=0; i row; + for(int j=0; j>temp; + row.push_back(temp); + } + arr.push_back(row); + } + if(isBipartite(n, arr)) cout << "The graph is Bipartite!"; + else cout << "The graph is not a Bipartite!"; + return 0; +} \ No newline at end of file diff --git a/December - 14/GREEDnim_day14_java.java b/December - 14/GREEDnim_day14_java.java new file mode 100644 index 0000000..5c2c204 --- /dev/null +++ b/December - 14/GREEDnim_day14_java.java @@ -0,0 +1,80 @@ +package acm; + +import java.util.HashMap; +import java.util.LinkedList; +import java.util.Queue; +import java.util.Scanner; + + +public class GREEDnim_day14_java { + +// map for every vetex and its group + static HashMapmap=new HashMap<>(); + +// checker to check if ive already visited the node and placed it in correct group + static boolean[] check; + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + int n=in.nextInt(); + check=new boolean[n]; + int[][] inp=new int[n][n]; + for(int i=0;iq=new LinkedList<>(); + map.put(cur,0); + check[cur]=true; + for(int i=0;i + +using namespace std; + +int main() +{ + int a[100][100],n,flag=0; + cin>>n; + cout<>a[i][j]; + } + } + for(int i=0;i +#include + +using namespace std; + +void input(int); + +int main() +{ + int n; + cin>>n; + input(n); +} + +void input(int n) { + bool isBipartiteFlag=true; + int edgeCounter=0; + + vector> adjMat(n, vector {0}); + for (int i = 0; i>adjMat[i][j]; + // I found out, 1 cannot exist if both i & j are odd or even at the same time + // and should contain a loop with all vertices + if(adjMat[i][j] == 1 && ((i%2==0 && j%2==0) || (i%2!=0 && j%2!=0))){ + isBipartiteFlag = false; + } + } + } + cout< +#include +#include +using namespace std; + +const int N = 6; +int graph[N][N] = { + {0, 1, 0, 0, 0, 1}, + {1, 0, 1, 0, 0, 0}, + {0, 1, 0, 1, 0, 0}, + {0, 0, 1, 0, 1, 0}, + {0, 0, 0, 1, 0, 1}, + {1, 0, 0, 0, 1, 0}}; +std::vector> adj(N); +bool is_bipartite() +{ + std::vector U, V; + U.push_back(0); + + bool visited[N] = {false}; + + for (int u : U) + { + visited[u] = true; + for (int v : adj[u]) + { + if (!visited[v]) + { + V.push_back(v); + } + else + { + if (std::find(U.begin(), U.end(), v) != U.end()) + { + return false; + } + } + } + } + + for (int v : V) + { + visited[v] = true; + for (int u : adj[v]) + { + if (!visited[u]) + { + U.push_back(u); + } + else + { + if (std::find(V.begin(), V.end(), u) != V.end()) + { + return false; + } + } + } + } + return true; +} +int main() +{ + + for (int i = 0; i < N; i++) + { + for (int j = 0; j < N; j++) + { + if (graph[i][j] == 1) + { + adj[i].push_back(j); + } + } + } + + if (is_bipartite()) + { + std::cout << "The graph is Bipartite!" << std::endl; + } + else + { + std::cout << "The graph is not Bipartite!" << std::endl; + } + + return 0; +} diff --git a/December - 14/java_DCBisht14.java b/December - 14/java_DCBisht14.java new file mode 100644 index 0000000..bb04080 --- /dev/null +++ b/December - 14/java_DCBisht14.java @@ -0,0 +1,30 @@ +import java.util.*; + +public class java_DCBisht14 { + static boolean f(int a[][],int n){ + for(int i=0;i 0: + print("#problem_statment_14!!") + def co_g(input_G, color, p, c): + if color[p] != -1 and color[p] != c: + return False + color[p] = c + ans = True + for i in range(0, n): + if input_G[p][i]: + if color[i] == -1: + ans &= co_g(input_G, color, i, 1-c) + if color[i] !=-1 and color[i] != 1-c: + return False + if not ans: + return False + return True + def check_bipartite(input_G): + color = [-1]*n + p = 0 + return co_g(input_G, color, p, 1) + + #main + n = int(input("")) + print("") + v1_mat,input_G = [],[] + for i in range(0, n): + mat = input("").split(" ") + mat = [int(x) for x in mat] + for j in mat: + v1_mat.append(j) + start = 0 + end = len(v1_mat) + step = n + for i in range(start, end, step): + x = i + input_G.append(v1_mat[x:x+step]) + print("\n\nOUTPUT:") + if check_bipartite(input_G): + print("The graph is Bipartite!") + else: + print("The graph is Not Bipartite!") \ No newline at end of file diff --git a/December - 14/python3_lakshmeeee.py b/December - 14/python3_lakshmeeee.py new file mode 100644 index 0000000..08a3d6d --- /dev/null +++ b/December - 14/python3_lakshmeeee.py @@ -0,0 +1,40 @@ +V = int(input()) + +def colorGraph(G, color, pos, c): + + if color[pos] != -1 and color[pos] != c: + return False + + # color this pos as c and all its neighbours and 1-c + color[pos] = c + ans = True + for i in range(0, V): + if G[pos][i]: + if color[i] == -1: + ans &= colorGraph(G, color, i, 1-c) + + if color[i] !=-1 and color[i] != 1-c: + return False + + if not ans: + return False + + return True + +def isBipartite(G): + + color = [-1] * V + + #start is vertex 0 + pos = 0 + # two colors 1 and 0 + return colorGraph(G, color, pos, 1) + + +G = [[0, 1, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0], [0, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 0], [0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 1, 0]] + +if isBipartite(G): print("The graph is Bipartite!") +else: print("The graph is not Bipartite!") + + + diff --git a/December - 15/.gitignore b/December - 15/.gitignore new file mode 100644 index 0000000..5cd95a2 --- /dev/null +++ b/December - 15/.gitignore @@ -0,0 +1,174 @@ +DEC-15 CODE: +from collections import OrderedDict +import numpy as np +n=int(input("enter the number of inputs")) +d=dict(input("enter the key and value:").split() for i in range (n)) +print(d) +keys = list(d.keys()) +values = list(d.values()) +sorted_value_index = np.argsort(values) +sorted_dict = {keys[i]: values[i] for i in sorted_value_index} +print("the result is") +print(sorted_dict) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/December - 15/C++_Dhruv.cpp b/December - 15/C++_Dhruv.cpp new file mode 100644 index 0000000..0b12dbd --- /dev/null +++ b/December - 15/C++_Dhruv.cpp @@ -0,0 +1,51 @@ +#include +using namespace std; +class Compare +{ +public: + bool operator()(pair a, pair b) + { + string aa=""; + string bb =""; + for(int i=0;i<8;i++){ + if(i!=2 and i!=5){ + aa += a.second; + bb += b.second; + } + } + int A = stoi(aa); + int B =stoi(bb); + return A>B; + } +}; +int main() { + // INPUT IN BELOW FORMAT + // Wes 12:00:30 + // Michella 12:03:40 + // Asher 12:00:01 + + // Priority queue is defined using the custom comparator + priority_queue,vector>,Compare> minHeapBySecondEl; + int n; + + + for(int i=0;i<3;i++) + { + + string a,b; + cin>>a>>b; + minHeapBySecondEl.push({a,b}); + } + + cout<<"Output:"< top=minHeapBySecondEl.top(); + minHeapBySecondEl.pop(); + cout<<"("< +using namespace std; + +void timediff (string arr[3][2]){ + for(int i = 0; i < 3; i++){ + for(int j = i + 1; j < 3; j++){ + if(arr[j][1] < arr[i][1]){ + swap (arr[j][1], arr[i][1]); + swap (arr[j][0], arr[i][0]); + } + } + } +} + +int main (){ + string arr[3][2]; + for(int i = 0; i < 3; i++){ + for (int j = 0; j < 2; j++){ + cin >> arr[i][j]; + } + } + + timediff (arr); + + cout << arr[0][0] << ","; + cout << " " << arr[1][0] << ","; + cout << " " << arr[2][0] << "."; + + return 0; +} diff --git a/December - 15/GREEDnim_day15_java.java b/December - 15/GREEDnim_day15_java.java new file mode 100644 index 0000000..aeb8e27 --- /dev/null +++ b/December - 15/GREEDnim_day15_java.java @@ -0,0 +1,31 @@ +package acm; + +import java.util.*; +import java.util.stream.Collectors; + +public class GREEDnim_day15_java { + + public static void main(String[] args) { + + String[][] inp = {{"Annalise", "01:09:00"},{ "Frank", "01:02:30"},{"Laurel", "01:04:19"}}; + Arrays.sort(inp, new Comparator() { + + @Override + public int compare(String[] a, String[]b ) { + + String[] time1 = a[1].split(":", 0); + String[] time2 = b[1].split(":", 0); + int t = time1[0].compareTo(time2[0]); + if (t != 0) return t; + t = time1[1].compareTo(time2[1]); + if (t != 0) return t; + t = time1[2].compareTo(time2[2]); + return t; + + } + }); + + for(String[]ans:inp) System.out.print(ans[0]+" ,"); + + } +} diff --git a/December - 15/Java_Ankur2606.java b/December - 15/Java_Ankur2606.java new file mode 100644 index 0000000..c37dd18 --- /dev/null +++ b/December - 15/Java_Ankur2606.java @@ -0,0 +1,58 @@ +import java.util.*; +class Detail{ + String name; + String timestamp; + Detail(String name, String timestamp){ + this.name = name; + this.timestamp = timestamp; + } +} + +class Sortbytimestamp implements Comparator +{ + public int compare(Detail a, Detail b){ + int hhmmssA = Integer.parseInt(a.timestamp.replace(":","")); + int hhmmssB = Integer.parseInt(b.timestamp.replace(":","")); + return hhmmssA - hhmmssB; + } +} + +class Java_Ankur2606{ + public Queue theMurderersMeet(List list){ + Collections.sort(list, new Sortbytimestamp()); + + Queue queue=new LinkedList<>(); + for(Detail d : list){ + queue.add(d.name); + } + + return queue; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input: "); + List list=new ArrayList<>(); + String name, timestamp; + for(int i=0;i<3;i++){ + name = sc.next(); + while(true){ + timestamp = sc.next(); + String[] hhmmss = timestamp.split(":"); + if(Integer.parseInt(hhmmss[0])>24 || Integer.parseInt(hhmmss[1])>59 || Integer.parseInt(hhmmss[2])>59){ + System.out.println("Invalid Timestamp!! Enter again ..."); + }else{ + break; + } + } + list.add(new Detail(name,timestamp)); + } + + Java_Ankur2606 ob=new Java_Ankur2606(); + Queue queue = ob.theMurderersMeet(list); + + System.out.println(""); + System.out.print("Output: "+queue); + } +} \ No newline at end of file diff --git a/December - 15/Java_souvikpal2000.java b/December - 15/Java_souvikpal2000.java new file mode 100644 index 0000000..3aa4fa6 --- /dev/null +++ b/December - 15/Java_souvikpal2000.java @@ -0,0 +1,58 @@ +import java.util.*; +class Detail{ + String name; + String timestamp; + Detail(String name, String timestamp){ + this.name = name; + this.timestamp = timestamp; + } +} + +class Sortbytimestamp implements Comparator +{ + public int compare(Detail a, Detail b){ + int hhmmssA = Integer.parseInt(a.timestamp.replace(":","")); + int hhmmssB = Integer.parseInt(b.timestamp.replace(":","")); + return hhmmssA - hhmmssB; + } +} + +class Java_souvikpal2000{ + public Queue theMurderersMeet(List list){ + Collections.sort(list, new Sortbytimestamp()); + + Queue queue=new LinkedList<>(); + for(Detail d : list){ + queue.add(d.name); + } + + return queue; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input: "); + List list=new ArrayList<>(); + String name, timestamp; + for(int i=0;i<3;i++){ + name = sc.next(); + while(true){ + timestamp = sc.next(); + String[] hhmmss = timestamp.split(":"); + if(Integer.parseInt(hhmmss[0])>24 || Integer.parseInt(hhmmss[1])>59 || Integer.parseInt(hhmmss[2])>59){ + System.out.println("Invalid Timestamp!! Enter again ..."); + }else{ + break; + } + } + list.add(new Detail(name,timestamp)); + } + + Java_souvikpal2000 ob=new Java_souvikpal2000(); + Queue queue = ob.theMurderersMeet(list); + + System.out.println(""); + System.out.print("Output: "+queue); + } +} \ No newline at end of file diff --git a/December - 15/Java_tarpandas.java b/December - 15/Java_tarpandas.java new file mode 100644 index 0000000..814a8dc --- /dev/null +++ b/December - 15/Java_tarpandas.java @@ -0,0 +1,61 @@ +import java.util.*; +class Detail{ + String name; + String timestamp; + Detail(String name, String timestamp){ + this.name = name; + this.timestamp = timestamp; + } +} + +class Sortbytimestamp implements Comparator +{ + public int compare(Detail a, Detail b){ + int hhmmssA = Integer.parseInt(a.timestamp.replace(":","")); + int hhmmssB = Integer.parseInt(b.timestamp.replace(":","")); + return hhmmssA - hhmmssB; + } +} + +class Java_tarpandas{ + public Queue murderersMeet(List list){ + Collections.sort(list, new Sortbytimestamp()); + + Queue queue=new LinkedList<>(); + for(Detail d : list){ + queue.add(d.name); + } + + return queue; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + List list=new ArrayList<>(); + String name, timestamp; + // input type: + // Name hh:mm:ss + for(int i=0;i<3;i++){ + name = sc.next(); + while(true){ + timestamp = sc.next(); + String[] hhmmss = timestamp.split(":"); + if(Integer.parseInt(hhmmss[0])>24 || Integer.parseInt(hhmmss[1])>59 || Integer.parseInt(hhmmss[2])>59){ + System.out.println("Invalid Timestamp!! Enter again ..."); + }else{ + break; + } + } + list.add(new Detail(name,timestamp)); + } + + Java_tarpandas ob=new Java_tarpandas(); + Queue queue = ob.murderersMeet(list); + + System.out.println(""); + System.out.print(queue); + + sc.close(); + } +} \ No newline at end of file diff --git a/December - 15/cpp_Aadhi11.cpp b/December - 15/cpp_Aadhi11.cpp new file mode 100644 index 0000000..fe83c00 --- /dev/null +++ b/December - 15/cpp_Aadhi11.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +void pairsort(string a[], string b[], int n) +{ + pair pairt[n]; + + for (int i = 0; i < n; i++) + { + pairt[i].first = a[i]; + pairt[i].second = b[i]; + } + + sort(pairt, pairt + n); + + for (int i = 0; i < n; i++) + { + a[i] = pairt[i].first; + b[i] = pairt[i].second; + } +} + +int main() +{ + string b[10]; + string a[10]; + + for(int i=0;i<3;i++) + { + cin>>b[i]; + cin>>a[i]; + } + pairsort(a, b, 3); + cout< +#include +#include + +using namespace std; +vector splitter(vector& person); + +int main (int argc, char *argv[]) +{ + string name, time; + int count = 3; + vector> persons(3, vector(2)); + cout<<"Enter person name and Time in HH:MM:SS "; // mommy 10:00:00 omit `{` + + for(int i=0 ;count !=0; count--){ + cin>>name; + cin>>time; + + persons[i].push_back(name); + persons[i].push_back(time); + i++; + } + + sort(persons.begin(), persons.end(), [](vector& lhs, vector& rhs) + { + vector timeOne = splitter(lhs); // HH MM SS in 0 1 2 indices + vector timeTwo = splitter(rhs); + + if(timeOne[0] < timeTwo[0]) return true; + else if (timeOne[0] > timeTwo[0]) return false; + else{ + + if(timeOne[1] < timeTwo[1]) return true; + else if (timeOne[1] > timeTwo[1]) return false; + else { + + if(timeOne[2] < timeTwo[2]) return true; + else if (timeOne[2] > timeTwo[2]) return false; + } + + } + return false; + }); + + for(auto person: persons){ + for(auto row: person){ + cout< splitter(vector& person) { + vector time; + int digit; + + auto it = person[3].begin(); // Please never ask me why 3 + + digit = *it - '0'; + *it++; + digit = digit * 10; + digit = digit + (*it - '0'); + time.push_back(digit); // HH + + *it++; // skip delimiter + *it++; // skip delimiter + + digit = *it - '0'; + *it++; + digit = digit * 10; + digit = digit + (*it - '0'); + time.push_back(digit); // MM + + *it++; // skip delimiter + *it++; // skip delimiter + + digit = *it - '0'; + *it++; + digit = digit * 10; + digit = digit + (*it - '0'); + time.push_back(digit); // SS + + return time; +} diff --git a/December - 15/day 15.py b/December - 15/day 15.py new file mode 100644 index 0000000..1aa68ac --- /dev/null +++ b/December - 15/day 15.py @@ -0,0 +1,22 @@ +a=[] +for j in range(3): + a.append(list(input().split(','))) +for i in range(0,len(a)): + h=a[i][1] + m=a[i][1] + s=a[i][1] + h=int(h[0:2]) + m=int(m[3:5]) + s=int(s[6:8]) + time=(h*3600)+(m*60)+s + a[i].append(time) + +for i in range(0,len(a)-1): + for j in range(0,len(a)-i-1): + if(a[j][2]>a[j+1][2]): + a[j],a[j+1]=a[j+1],a[j] +queue=[] +for i in range(0,3): + queue.append(a[i][0]) +print(queue) + \ No newline at end of file diff --git a/December - 15/day15.cpp b/December - 15/day15.cpp new file mode 100644 index 0000000..c5bfc36 --- /dev/null +++ b/December - 15/day15.cpp @@ -0,0 +1,78 @@ +#include +using namespace std; +vector splitter(vector& person); + +int main (int argc, char *argv[]) +{ + string name, time; + int count = 3; + vector> persons(3, vector(2)); + cout<<"Enter person name and Time in HH:MM:SS \n"; +// INPUT IN BELOW FORMAT + // Wes 12:00:30 + // Michella 12:03:40 + // Asher 12:00:01 + for(int i=0 ;count !=0; count--){ + cin>>name; + cin>>time; + + persons[i].push_back(name); + persons[i].push_back(time); + i++; + } + + sort(persons.begin(), persons.end(), [](vector& lhs, vector& rhs) + { + vector timeOne = splitter(lhs); + vector timeTwo = splitter(rhs); + + if(timeOne[0] < timeTwo[0]) return true; + else if (timeOne[0] > timeTwo[0]) return false; + else{ + + if(timeOne[1] < timeTwo[1]) return true; + else if (timeOne[1] > timeTwo[1]) return false; + else { + + if(timeOne[2] < timeTwo[2]) return true; + else if (timeOne[2] > timeTwo[2]) return false; + } + + } + return false; + }); + + for(auto person: persons){ + for(auto row: person){ + cout< splitter(vector& person) { + vector time; + int digit; + auto it = person[3].begin(); + digit = *it - '0'; + *it++; + digit = digit * 10; + digit = digit + (*it - '0'); + time.push_back(digit); + *it++; + *it++; + digit = *it - '0'; + *it++; + digit = digit * 10; + digit = digit + (*it - '0'); + time.push_back(digit); + *it++; + *it++; + digit = *it - '0'; + *it++; + digit = digit * 10; + digit = digit + (*it - '0'); + time.push_back(digit); + return time; +} diff --git a/December - 15/java_DCBisht15.java b/December - 15/java_DCBisht15.java new file mode 100644 index 0000000..cde3310 --- /dev/null +++ b/December - 15/java_DCBisht15.java @@ -0,0 +1,33 @@ +import java.util.*; + +public class java_DCBisht15 { + public static void main(String[] args) { + + String[][] inp = {{"Annalise", "01:09:00"},{ "Frank", "01:02:30"},{"Laurel", "01:04:19"}}; + Arrays.sort(inp, new Comparator() { + + + public int compare(String[] a, String[]b ) { + + String[] time1 = a[1].split(":", 0); + String[] time2 = b[1].split(":", 0); + int t = time1[0].compareTo(time2[0]); + if (t != 0) return t; + t = time1[1].compareTo(time2[1]); + if (t != 0) return t; + t = time1[2].compareTo(time2[2]); + return t; + + } + }); + + for(int i=0;i 0: + print("#problem_statment_15!!") + input_i = input("").replace("},",",").replace(", ",",").replace("}","").replace("{","").split(",") + names,time_stamp= [],[] + for i in range (0,len(input_i)): + if i % 2 == 0: + names.append(input_i[i]) + else: + time_stamp.append(input_i[i]) + res = {names[i]: time_stamp[i] for i in range(len(names))} + sorted_res = sorted(res.items(),key=lambda item: item[1]) + res = dict(sorted_res) + print("\n\nOutput:") + + i = 1 + for key in res: + if i < len(res): + print(key,end=", ") + i+=1 + else: + print(key,end=".") + i+=1 + print("\n") \ No newline at end of file diff --git a/December - 15/python3_lakshmeeee.py b/December - 15/python3_lakshmeeee.py new file mode 100644 index 0000000..3158f40 --- /dev/null +++ b/December - 15/python3_lakshmeeee.py @@ -0,0 +1,41 @@ +from datetime import datetime + +class Queue: + def __init__(self): + self.queue = [] + def enq(self,v): + self.queue.append(v) + def isempty(self): + return(self.queue == []) + def delq(self): + v = None + if not self.isempty(): + v = self.queue[0] + self.queue = self.queue[1:] + return(v) + def __str__(self): + return(str(self.queue)) + +l = [['Wes', '12:00:30'],['Michella', '12:03:40'],['Asher', '12:00:01']] + + +def minl(l): + for i in range(len(l)): + d = datetime.strptime(l[i][1],'%H:%M:%S') + k=i + for j in range(i+1,len(l)): + if (datetime.strptime(l[j][1],'%H:%M:%S') largest: + secondLargest = largest + largest = arr[i] + else: + secondLargest = max(secondLargest, arr[i]) + return secondLargest +n = int(input("Enter number of elements : ")) +a = list(map(int,input("\nEnter the numbers : ").strip().split()))[:n] +print("\nList is - ", a) +j=int(findLargest(a)) +m=a.index(max(a)) +l=a.index(j) +print(m,l) +diff=abs(m-l) +result=int(diff*j) +print(result) +#code + + + + + + + + + + + + + + + + + + + + + + + + + + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/December - 16/C++_Dhruv.cpp b/December - 16/C++_Dhruv.cpp new file mode 100644 index 0000000..7712faf --- /dev/null +++ b/December - 16/C++_Dhruv.cpp @@ -0,0 +1,22 @@ +#include +using namespace std; + + +int main() +{ + int n; + cin>>n; + vectorarr(n); + for(auto &x:arr)cin>>x; + int low =0; + int high = arr.size()-1; + int maxi =INT_MIN; + while(low +using namespace std; + +int getinputno(int hist[10000]){ + for(int i=0 ;i<10000; i++){ + if(hist[i] == 0 && hist[i+1] == 0 && hist[i+2] == 0) return i; + } +} + +int getMaxArea(int arr[], int n){ + int maxarea; + for(int i = n-1;i>=0; i--){ + for(int j = 0; j> hist[i]; + } + int n = getinputno(hist); + + cout << getMaxArea(hist, n); + return 0; +} diff --git a/December - 16/C++_subburamanathan7.cpp b/December - 16/C++_subburamanathan7.cpp new file mode 100644 index 0000000..cf8eb4c --- /dev/null +++ b/December - 16/C++_subburamanathan7.cpp @@ -0,0 +1,26 @@ +#include +using namespace std; + +int main(){ + int limit,i=0,j=0,volume=0,height=0,temp=1; + cout<<"Enter Limit"; + cin>>limit; + + int *arr = (int*)malloc(sizeof(int)*limit); + + for (i = 0; i < limit; ++i) + cin>>arr[i]; + + for(i=0;iarr[j]?arr[j]:arr[i]; + temp = (j-i)*height; + + if(temp>volume) + volume=temp; + } + } + cout< iNum2) { + return iNum2; + } + return iNum1; + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("height = "); + + String input = sc.nextLine(); + + String [] tempArr = input.split(","); + int [] arr = new int [tempArr.length]; + + for(int i=0;i maxArea) { + maxArea = tempNumber; + } + } + } + System.out.println(maxArea); + sc.close(); + } +} diff --git a/December - 16/GREEDnim_day16_java.java b/December - 16/GREEDnim_day16_java.java new file mode 100644 index 0000000..446b9a0 --- /dev/null +++ b/December - 16/GREEDnim_day16_java.java @@ -0,0 +1,30 @@ +package acm; + +public class GREEDnim_day16_java { + + static int[] input; + + public static void main(String[] args) { + input= new int[]{6,2,5,4,8}; + + int s=0; + int e=input.length-1; + int max=Integer.MIN_VALUE; + while(smax) max=curVol; + + if(input[s]>input[e]) e--; + else s++; + } + System.out.println(max); + + } + public static int waterStored(int left,int right) + { + int length=right-left; + int height=Math.min(input[left],input[right]); + return length*height; + } +} diff --git a/December - 16/Java_Ankur2606.java b/December - 16/Java_Ankur2606.java new file mode 100644 index 0000000..43875bd --- /dev/null +++ b/December - 16/Java_Ankur2606.java @@ -0,0 +1,51 @@ +import java.util.*; +public class Java_Ankur2606{ + public int findMax(int no1, int no2){ + int max = 0; + if(no1>no2){ + max = no1; + }else{ + max = no2; + } + return max; + } + + public int findMin(int no1, int no2){ + int min = 0; + if(no1no2){ + max = no1; + }else{ + max = no2; + } + return max; + } + + public int findMin(int no1, int no2){ + int min = 0; + if(no1 iNum2) { + return iNum2; + } + return iNum1; + } + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + System.out.print("height = "); + + String input = sc.nextLine(); + + String [] tempArr = input.split(","); + int [] arr = new int [tempArr.length]; + + for(int i=0;i maxArea) { + maxArea = tempNumber; + } + } + } + System.out.println(maxArea); + sc.close(); + } +} \ No newline at end of file diff --git a/December - 16/cpp_Aadhi11.cpp b/December - 16/cpp_Aadhi11.cpp new file mode 100644 index 0000000..015caf8 --- /dev/null +++ b/December - 16/cpp_Aadhi11.cpp @@ -0,0 +1,39 @@ +#include +using namespace std; + + +int secondLargest(int arr[], int n) { + int largest = 0, secondLargest = -1,a; + + for (int i = 1; i < n; i++) { + if (arr[i] > arr[largest]) + largest = i; + } + for (int i = 0; i < n; i++) { + if (arr[i] != arr[largest]) { + if (secondLargest == -1) + secondLargest = i; + else if (arr[i] > arr[secondLargest]) + secondLargest = i; + } + + } + a = arr[secondLargest]; + largest++; + secondLargest++; + int b= largest-secondLargest; + if(b<0) + b=b*-1; + a=b*a; + return a; +} + + +int main() { + // height = + int arr[] = {1,8,6,2,5,4,8,3,7}; + int n = sizeof(arr)/sizeof(arr[0]); + int second_Largest = secondLargest(arr, n); + cout< +#include +#include +#include +#include + +using namespace std; + +vector input(int); +int maxPossibleVolume(vector&, int); + +int main(){ + int n; + cin>>n; + + vector water = input(n); + cout<<"Max Volume this container can hold: "<& water, int n){ + int s=0, e=n-1; // pointer to start and end of the given data + int volume = 0; + int currentVolume = 0; + + for(int f=0, r=e; f=0; f++, r--){ + if(water[s] input(int n){ + vector water(n); + for(int j=0; j>water[j]; + return water; +} diff --git a/December - 16/day 16.py b/December - 16/day 16.py new file mode 100644 index 0000000..7b93bbc --- /dev/null +++ b/December - 16/day 16.py @@ -0,0 +1,15 @@ + + +import math +max_val=-math.inf +a=list(map(int,input().split(','))) +for i in range(0,len(a)): + for j in range(i+1,len(a)): + if(a[i]>a[j]): + p=a[j] + else: + p=a[i] + product=p*(j-i) + if(max_val +using namespace std; + +vector input(int); +int maxPossibleVolume(vector&, int); + +int main(){ + int n; + cin>>n; + + vector water = input(n); + cout<<"Max Volume this container can hold: "<& water, int n){ + int s=0, e=n-1; + int volume = 0; + int currentVolume = 0; + + for(int f=0, r=e; f=0; f++, r--){ + if(water[s] input(int n){ + vector water(n); + for(int j=0; j>water[j]; + return water; +} diff --git a/December - 16/java_DCBisht16.java b/December - 16/java_DCBisht16.java new file mode 100644 index 0000000..81f6aa1 --- /dev/null +++ b/December - 16/java_DCBisht16.java @@ -0,0 +1,28 @@ +import java.util.*;; + +public class java_DCBisht16 { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + String word = in.nextLine(); + String[] arrayOfWord = word.split(" ", 0); + int a[] = new int[arrayOfWord.length]; + int k = 0; + for (String h : arrayOfWord) { + a[k++] = Integer.parseInt(h); + } + + int l=0,r=k-1,ans=Integer.MIN_VALUE; + while(l 0: + print("#problem_statment_16!!") + def m_a(lis): + l = 0 + r = len(lis) -1 + area = 0 + while l < r: + area = max(area, min(lis[l],lis[r])*(r - l)) + if lis[l] < lis[r]: + l+=1 + else: + r-=1 + return area + + step_lis = input("height = ").replace("[","").replace("]","").split(",") + step_lis = [int(x) for x in step_lis] + print("\nOutput:",m_a(step_lis)) \ No newline at end of file diff --git a/December - 16/python3_lakshmeeee.py b/December - 16/python3_lakshmeeee.py new file mode 100644 index 0000000..e2b4a86 --- /dev/null +++ b/December - 16/python3_lakshmeeee.py @@ -0,0 +1,9 @@ +h = [int(x) for x in input().split(',')] +w=0 +for i in range(len(h)): + for j in range(i+1,len(h)): + m=((j+1)-(i+1))*min(h[i],h[j]) + if(m>w): + w=m + +print(w) diff --git a/December - 17/.gitignore b/December - 17/.gitignore new file mode 100644 index 0000000..498fc1f --- /dev/null +++ b/December - 17/.gitignore @@ -0,0 +1,153 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class +#code +def printZigZagConcat(str, n): + if n == 1: + print(str) + return + l = len(str) + arr=["" for x in range(l)] + row = 0 + for i in range(l): + arr[row] += str[i] + if row == n - 1: + down = False + elif row == 0: + down = True + if down: + row += 1 + else: + row -= 1 + for i in range(n): + print(arr[i], end = "") +str = input("enter the string") +n = int(input("enter the number of rows")) +printZigZagConcat(str, n) +#code + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/December - 17/C++_Dhruv.cpp b/December - 17/C++_Dhruv.cpp new file mode 100644 index 0000000..0c39100 --- /dev/null +++ b/December - 17/C++_Dhruv.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +using namespace std; +int main() { + // input string and number of rows + // std::string Str = "spaghettigood"; + string Str; + cin>>Str; + int Row = 4; + + // initialize the zigzag pattern + std::vector> zigzag(Row); + + // initialize the variables to traverse the rows + int row = 0; + int direction = 1; + + // iterate over the characters in the string + for (char c : Str) { + // add the character to the current row + zigzag[row].push_back(c); + + // update the row and direction + if (row == Row - 1) { + direction = -1; + } + else if (row == 0) { + direction = 1; + } + row += direction; + } + + // print the zigzag pattern row-wise + for (auto& row : zigzag) { + for (char c : row) { + std::cout << c; + } + } + std::cout << std::endl; + + return 0; +} diff --git a/December - 17/C++_MugundhanY.cpp b/December - 17/C++_MugundhanY.cpp new file mode 100644 index 0000000..dc5753a --- /dev/null +++ b/December - 17/C++_MugundhanY.cpp @@ -0,0 +1,41 @@ +//Question 17: +#include +using namespace std; + +string convert(string s, int numRows){ + int n = numRows; + string str; + if(n == 0 || n == 1) return s; + + for(int i = 0; i < s.length(); i += (n-1)*2){ + str += s[i]; + } + + for(int j = 1; j < n-1; j++){ + bool goDown = true; + for(int i = j; i < s.length();){ + str += s[i]; + if(goDown){ + i+=(n-j-1)*2; + }else{ + i+=(n-1)*2-(n-j-1)*2; + } + goDown = !goDown; + } + + } + + for(int i = n-1; i < s.length(); i += (n-1)*2){ + str += s[i]; + } + return str; +} + +int main(){ + string s; + cin >> s; + int numRows; + cin >> numRows; + cout << convert(s, numRows); + return 0; +} diff --git a/December - 17/C++_subburamanathan7.cpp b/December - 17/C++_subburamanathan7.cpp new file mode 100644 index 0000000..4fcd03b --- /dev/null +++ b/December - 17/C++_subburamanathan7.cpp @@ -0,0 +1,26 @@ +#include + +using namespace std; +int main(){ + int numRows; + string s; + cout<<"Enter String and number of Rows"; + cin>>s>>numRows; + + if(numRows==1) + cout<0 && i<(numRows-1) && (j+increment-2*i)[] index= new ArrayList[row]; + for(int i=0;i(); + } + + int i=0; + + while(i0 && iele:index) + { + for(int k:ele) + { + System.out.print(inp.charAt(k)); + } + } + } +} diff --git a/December - 17/Java_Ankur2606.java b/December - 17/Java_Ankur2606.java new file mode 100644 index 0000000..e555ee1 --- /dev/null +++ b/December - 17/Java_Ankur2606.java @@ -0,0 +1,65 @@ +import java.util.*; +public class Java_Ankur2606{ + public List zigzagConversion(String str, int row){ + int length = str.length(); + char[] characters; + List list=new ArrayList<>(); + int j=0; + int c = row - 2; + while(j=1){ + characters = new char[row]; + if(j==length){ + break; + } + for(int i=0;i zigzagConversion(String str, int row){ + int length = str.length(); + char[] characters; + List list=new ArrayList<>(); + int j=0; + int c = row - 2; + while(j=1){ + characters = new char[row]; + if(j==length){ + break; + } + for(int i=0;i zigzagConversion(String str, int row){ + int length = str.length(); + char[] characters; + List list=new ArrayList<>(); + int j=0; + int c = row - 2; + while(j=1){ + characters = new char[row]; + if(j==length){ + break; + } + for(int i=0;i +using namespace std; + +void printZigZagConcat(string str, int n) +{ + if (n == 1) + { + cout << str; + return; + } + + int len = str.length(); + + string arr[n]; + + int row = 0; + bool down; + + for (int i = 0; i < len; ++i) + { + arr[row].push_back(str[i]); + + if (row == n-1) + down = false; + + else if (row == 0) + down = true; + + (down)? (row++): (row--); + } + + cout< +using namespace std; +int main() { + //"spaghettigood" + string Str; + cin>>Str; + int Row; + cin >> Row; + vector> zigzag(Row); + int row = 0; + int direction = 1; + for (char c : Str) { + zigzag[row].push_back(c); + if (row == Row - 1) { + direction = -1; + } + else if (row == 0) { + direction = 1; + } + row += direction; + } + for (auto& row : zigzag) { + for (char c : row) { + std::cout << c; + } + } + std::cout << std::endl; + return 0; +} diff --git a/December - 17/java_DCBisht17.java b/December - 17/java_DCBisht17.java new file mode 100644 index 0000000..7d582ac --- /dev/null +++ b/December - 17/java_DCBisht17.java @@ -0,0 +1,39 @@ +import java.util.*; +@SuppressWarnings("unchecked") +class java_DCBisht17{ + public static void main(String[] args) { + + Scanner in=new Scanner(System.in); + String inp=in.next(); + int row=in.nextInt(); + + ArrayList[] index = new ArrayList[row]; + for(int i=0;i(); + } + + int i=0; + + while(i0 && iele:index) + { + for(int k:ele) + { + System.out.print(inp.charAt(k)); + } + } + in.close(); + } +} \ No newline at end of file diff --git a/December - 17/py_gowsrini2004_day_17.py b/December - 17/py_gowsrini2004_day_17.py new file mode 100644 index 0000000..768fe07 --- /dev/null +++ b/December - 17/py_gowsrini2004_day_17.py @@ -0,0 +1,27 @@ +#day_15 +y = 1 +while y > 0: + print("#problem_statment_17!!") + str = input("Str = ").replace("“","").replace("”","") + row = int(input("Row = ")) + if row == 1: + print(str) + l = len(str) + arr=["" for x in range(l)] + # print(arr) + row_r = 0 + for i in range(l): + arr[row_r] += str[i] + # print(str[i]) + if row_r == row - 1: + down = False + elif row_r == 0: + down = True + if down: + row_r += 1 + else: + row_r -= 1 + print("\nOutput:") + for i in range(row): + print(arr[i], end = "") + print("\n") \ No newline at end of file diff --git a/December - 17/python3_Esha.py b/December - 17/python3_Esha.py new file mode 100644 index 0000000..aa94eae --- /dev/null +++ b/December - 17/python3_Esha.py @@ -0,0 +1,17 @@ +s = input("Enter the string") +numRows = int(input("Enter the number of rows")) + +if numRows == 1: + print(s) + +rows = ["" for i in range(numRows)] +direction = -1 +row = 0 +for i in range(len(s)): + rows[row]+=s[i] + if (row == 0 or row==numRows-1): + direction *= -1 + row+=direction + +print("".join(rows)) + diff --git a/December - 17/python3_lakshmeeee.py b/December - 17/python3_lakshmeeee.py new file mode 100644 index 0000000..c0bf717 --- /dev/null +++ b/December - 17/python3_lakshmeeee.py @@ -0,0 +1,38 @@ +Str = 'spaghettigood' +# s t d +# p e t o +# a h i o +# g g +Row = 4 +l=[] +c=1 +k=0 +for i in range(len(Str)): + if(c==1): + l.append([Str[i]]) + k+=1 + if(k==Row): + c+=1 + k-=2 + + elif(c%2==0): + l[k].append(Str[i]) + k-=1 + if (k==-1): + c+=1 + k+=2 + + else: + l[k].append(Str[i]) + k+=1 + if (k==Row): + c+=1 + k-=2 + +a=[] +for i in range(len(l)): + a+=l[i] +s='' +print(s.join(a)) + +#stdpetoahiogg \ No newline at end of file diff --git a/December - 18/.gitignore b/December - 18/.gitignore new file mode 100644 index 0000000..f77faf7 --- /dev/null +++ b/December - 18/.gitignore @@ -0,0 +1,198 @@ +class Graph(): + def __init__(self, vertices): + self.V = vertices + self.graph = [[0 for column in range(vertices)] + for row in range(vertices)] + def printSolution(self, dist): + print("Vertex \t Distance from Source") + for node in range(self.V): + print(node, "\t\t", dist[node]) + def minDistance(self, dist, sptSet): + min = 1e7 + for v in range(self.V): + if dist[v] < min and sptSet[v] == False: + min = dist[v] + min_index = v + return min_index + def dijkstra(self, src): + dist = [1e7] * self.V + dist[src] = 0 + sptSet = [False] * self.V + for cout in range(self.V): + u = self.minDistance(dist, sptSet) + sptSet[u] = True + for v in range(self.V): + if (self.graph[u][v] > 0 and + sptSet[v] == False and + dist[v] > dist[u] + self.graph[u][v]): + dist[v] = dist[u] + self.graph[u][v] + self.printSolution(dist) +g = Graph(8) +g.graph = [ + [0, 3, 4, 5, 0, 0, 0, 0], + [3, 0, 2, 0, 0, 5, 0, 0], + [4, 2, 0, 7, 3, 6, 2, 0], + [5, 0, 7, 0, 2, 0, 0, 0], + [0, 0, 3, 2, 0, 0, 4, 0], + [0, 5, 6, 0, 0, 0, 5, 2], + [0, 0, 2, 0, 4, 5, 0, 0], + [0, 0, 0, 0, 0, 2, 1, 0] + ] +g.dijkstra(0) + + + + + + + + + + + + + + + + + + + + + + + + + + + + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ diff --git a/December - 18/C++_Dhruv.cpp b/December - 18/C++_Dhruv.cpp new file mode 100644 index 0000000..0d46e06 --- /dev/null +++ b/December - 18/C++_Dhruv.cpp @@ -0,0 +1,70 @@ +#include +#include +#include +#include +using namespace std; +const int N = 8; // number of cities + +// adjacency list representation of the graph +std::vector> graph[N] = { + {{1, 5}, {3, 2}}, // city P has neighbors Q (5 hours) and S (2 hours) + {{0, 5}, {2, 3}, {3, 1}}, // city Q has neighbors P (5 hours), R (3 hours), and S (1 hour) + {{1, 3}, {4, 1}, {5, 5}}, // city R has neighbors Q (3 hours), T (1 hour), and V (5 hours) + {{0, 2}, {1, 1}, {4, 1}}, // city S has neighbors P (2 hours), Q (1 hour), and T (1 hour) + {{3, 1}, {2, 1}, {5, 1}, {6, 2}, {7, 1}}, // city T has neighbors S (1 hour), R (1 hour), V (1 hour), U (2 hours), and W (1 hour) + {{2, 5}, {4, 1}, {7, 2}}, // city V has neighbors R (5 hours), T (1 hour), and W (2 hours) + {{4, 2}, {7, 3}}, // city U has neighbors T (2 hours) and W (3 hours) + {{4, 1}, {5, 2}, {6, 3}} // city W has neighbors T (1 hour), V (2 hours), and U (3 hours) +}; + +// function to find the shortest time to travel by train from a given city to city W +int find_shortest_time(int city) { + // initialize the distances to infinity + std::vector distances(N, std::numeric_limits::max()); + + // initialize the queue and visited array + std::queue q; + std::vector visited(N); + + // set the distance of the starting city to 0 and mark it as visited + distances[city] = 0; + visited[city] = true; + q.push(city); + + // perform BFS + while (!q.empty()) { + int u = q.front(); + q.pop(); + + // visit the neighbors of u + for (auto [v, w] : graph[u]) { + // if v has not been visited and the distance to v is shorter through u, update the distance + if (!visited[v] && distances[u] + w < distances[v]) { + distances[v] = distances[u] + w; + visited[v] = true; + q.push(v); + } + } + } + + // return the distance to city W + return distances[7]; +} + +int main() { + // choose a city + int city; + cin >> city; + // find the shortest time to travel from the chosen city to city W +int shortest_time = find_shortest_time(city); + +// print the result +if (shortest_time == std::numeric_limits::max()) { + std::cout << "There is no route from city " << city << " to city W." << std::endl; +} else { + std::cout << "The shortest time to travel from city " << city << " to city W is " << shortest_time << " hours." << std::endl; +} + +return 0; +} + diff --git a/December - 18/C++_MugundhanY.cpp b/December - 18/C++_MugundhanY.cpp new file mode 100644 index 0000000..4f55a19 --- /dev/null +++ b/December - 18/C++_MugundhanY.cpp @@ -0,0 +1,197 @@ +//Question 18: +#include + +#define INT_MAX 10000000 + +using namespace std; + +void DijkstrasTest(char a); + +int main() { + char a; + cin >> a; + DijkstrasTest(a); + return 0; +} + +class Node; +class Edge; + +void Dijkstras(); +vector* AdjacentRemainingNodes(Node* node); +Node* ExtractSmallest(vector& nodes); +int Distance(Node* node1, Node* node2); +bool Contains(vector& nodes, Node* node); +void PrintShortestRouteTo(Node* destination); + +vector nodes; +vector edges; + +class Node { + public: + Node(char id) + : id(id), previous(NULL), distanceFromStart(INT_MAX) { + nodes.push_back(this); + } + + public: + char id; + Node* previous; + int distanceFromStart; +}; + +class Edge { + public: + Edge(Node* node1, Node* node2, int distance) + : node1(node1), node2(node2), distance(distance) { + edges.push_back(this); + } + bool Connects(Node* node1, Node* node2) { + return ( + (node1 == this->node1 && + node2 == this->node2) || + (node1 == this->node2 && + node2 == this->node1)); + } + + public: + Node* node1; + Node* node2; + int distance; +}; + + +void DijkstrasTest(char a) { + Node* P = new Node('P'); + Node* Q = new Node('Q'); + Node* R = new Node('R'); + Node* S = new Node('S'); + Node* T = new Node('T'); + Node* U = new Node('U'); + Node* V = new Node('V'); + Node* W = new Node('W'); + + Edge* e1 = new Edge(P, Q, 3); + Edge* e2 = new Edge(Q, U, 5); + Edge* e3 = new Edge(U, W, 2); + Edge* e4 = new Edge(P, S, 5); + Edge* e5 = new Edge(S, T, 2); + Edge* e6 = new Edge(T, V, 4); + Edge* e7 = new Edge(V, W, 1); + Edge* e8 = new Edge(P, R, 4); + Edge* e9 = new Edge(R, U, 6); + Edge* e10 = new Edge(Q, R, 2); + Edge* e11 = new Edge(S, R, 7); + Edge* e12 = new Edge(R, T, 3); + Edge* e13 = new Edge(R, V, 2); + Edge* e14 = new Edge(U, V, 5); + + W->distanceFromStart = 0; + Dijkstras(); + if(a=='P')PrintShortestRouteTo(P); + if(a=='Q')PrintShortestRouteTo(Q); + if(a=='R')PrintShortestRouteTo(R); + if(a=='S')PrintShortestRouteTo(S); + if(a=='T')PrintShortestRouteTo(T); + if(a=='U')PrintShortestRouteTo(U); + if(a=='V')PrintShortestRouteTo(V); + if(a=='W')PrintShortestRouteTo(W); +} + +void Dijkstras() { + while (nodes.size() > 0) { + Node* smallest = ExtractSmallest(nodes); + vector* adjacentNodes = + AdjacentRemainingNodes(smallest); + + const int size = adjacentNodes->size(); + for (int i = 0; i < size; ++i) { + Node* adjacent = adjacentNodes->at(i); + int distance = Distance(smallest, adjacent) + + smallest->distanceFromStart; + + if (distance < adjacent->distanceFromStart) { + adjacent->distanceFromStart = distance; + adjacent->previous = smallest; + } + } + delete adjacentNodes; + } +} + +Node* ExtractSmallest(vector& nodes) { + int size = nodes.size(); + if (size == 0) return NULL; + int smallestPosition = 0; + Node* smallest = nodes.at(0); + for (int i = 1; i < size; ++i) { + Node* current = nodes.at(i); + if (current->distanceFromStart < + smallest->distanceFromStart) { + smallest = current; + smallestPosition = i; + } + } + nodes.erase(nodes.begin() + smallestPosition); + return smallest; +} + +vector* AdjacentRemainingNodes(Node* node) { + vector* adjacentNodes = new vector(); + const int size = edges.size(); + for (int i = 0; i < size; ++i) { + Edge* edge = edges.at(i); + Node* adjacent = NULL; + if (edge->node1 == node) { + adjacent = edge->node2; + } else if (edge->node2 == node) { + adjacent = edge->node1; + } + if (adjacent && Contains(nodes, adjacent)) { + adjacentNodes->push_back(adjacent); + } + } + return adjacentNodes; +} + +int Distance(Node* node1, Node* node2) { + const int size = edges.size(); + for (int i = 0; i < size; ++i) { + Edge* edge = edges.at(i); + if (edge->Connects(node1, node2)) { + return edge->distance; + } + } + return -1; +} + +bool Contains(vector& nodes, Node* node) { + const int size = nodes.size(); + for (int i = 0; i < size; ++i) { + if (node == nodes.at(i)) { + return true; + } + } + return false; +} + +void PrintShortestRouteTo(Node* destination) { + Node* previous = destination; + cout << "Shortest path: "; + while (previous) { + cout << previous-> id << " "; + previous = previous->previous; + } + cout << endl; + cout << "Shortest time: " << destination->distanceFromStart << " hours"<< endl; +} + +void RemoveEdge(vector& edges, Edge* edge) { + vector::iterator it; + for (it = edges.begin(); it < edges.end(); ++it) { + if (*it == edge) { + edges.erase(it); + return; + } + } +} diff --git a/December - 18/Cpp_Ankur2606.cpp b/December - 18/Cpp_Ankur2606.cpp new file mode 100644 index 0000000..c93a4df --- /dev/null +++ b/December - 18/Cpp_Ankur2606.cpp @@ -0,0 +1,196 @@ +#include + +#define INT_MAX 10000000 + +using namespace std; + +void DijkstrasTest(char a); + +int main() { + char a; + cin >> a; + DijkstrasTest(a); + return 0; +} + +class Node; +class Edge; + +void Dijkstras(); +vector* AdjacentRemainingNodes(Node* node); +Node* ExtractSmallest(vector& nodes); +int Distance(Node* node1, Node* node2); +bool Contains(vector& nodes, Node* node); +void PrintShortestRouteTo(Node* destination); + +vector nodes; +vector edges; + +class Node { + public: + Node(char id) + : id(id), previous(NULL), distanceFromStart(INT_MAX) { + nodes.push_back(this); + } + + public: + char id; + Node* previous; + int distanceFromStart; +}; + +class Edge { + public: + Edge(Node* node1, Node* node2, int distance) + : node1(node1), node2(node2), distance(distance) { + edges.push_back(this); + } + bool Connects(Node* node1, Node* node2) { + return ( + (node1 == this->node1 && + node2 == this->node2) || + (node1 == this->node2 && + node2 == this->node1)); + } + + public: + Node* node1; + Node* node2; + int distance; +}; + + +void DijkstrasTest(char a) { + Node* P = new Node('P'); + Node* Q = new Node('Q'); + Node* R = new Node('R'); + Node* S = new Node('S'); + Node* T = new Node('T'); + Node* U = new Node('U'); + Node* V = new Node('V'); + Node* W = new Node('W'); + + Edge* e1 = new Edge(P, Q, 3); + Edge* e2 = new Edge(Q, U, 5); + Edge* e3 = new Edge(U, W, 2); + Edge* e4 = new Edge(P, S, 5); + Edge* e5 = new Edge(S, T, 2); + Edge* e6 = new Edge(T, V, 4); + Edge* e7 = new Edge(V, W, 1); + Edge* e8 = new Edge(P, R, 4); + Edge* e9 = new Edge(R, U, 6); + Edge* e10 = new Edge(Q, R, 2); + Edge* e11 = new Edge(S, R, 7); + Edge* e12 = new Edge(R, T, 3); + Edge* e13 = new Edge(R, V, 2); + Edge* e14 = new Edge(U, V, 5); + + W->distanceFromStart = 0; + Dijkstras(); + if(a=='P')PrintShortestRouteTo(P); + if(a=='Q')PrintShortestRouteTo(Q); + if(a=='R')PrintShortestRouteTo(R); + if(a=='S')PrintShortestRouteTo(S); + if(a=='T')PrintShortestRouteTo(T); + if(a=='U')PrintShortestRouteTo(U); + if(a=='V')PrintShortestRouteTo(V); + if(a=='W')PrintShortestRouteTo(W); +} + +void Dijkstras() { + while (nodes.size() > 0) { + Node* smallest = ExtractSmallest(nodes); + vector* adjacentNodes = + AdjacentRemainingNodes(smallest); + + const int size = adjacentNodes->size(); + for (int i = 0; i < size; ++i) { + Node* adjacent = adjacentNodes->at(i); + int distance = Distance(smallest, adjacent) + + smallest->distanceFromStart; + + if (distance < adjacent->distanceFromStart) { + adjacent->distanceFromStart = distance; + adjacent->previous = smallest; + } + } + delete adjacentNodes; + } +} + +Node* ExtractSmallest(vector& nodes) { + int size = nodes.size(); + if (size == 0) return NULL; + int smallestPosition = 0; + Node* smallest = nodes.at(0); + for (int i = 1; i < size; ++i) { + Node* current = nodes.at(i); + if (current->distanceFromStart < + smallest->distanceFromStart) { + smallest = current; + smallestPosition = i; + } + } + nodes.erase(nodes.begin() + smallestPosition); + return smallest; +} + +vector* AdjacentRemainingNodes(Node* node) { + vector* adjacentNodes = new vector(); + const int size = edges.size(); + for (int i = 0; i < size; ++i) { + Edge* edge = edges.at(i); + Node* adjacent = NULL; + if (edge->node1 == node) { + adjacent = edge->node2; + } else if (edge->node2 == node) { + adjacent = edge->node1; + } + if (adjacent && Contains(nodes, adjacent)) { + adjacentNodes->push_back(adjacent); + } + } + return adjacentNodes; +} + +int Distance(Node* node1, Node* node2) { + const int size = edges.size(); + for (int i = 0; i < size; ++i) { + Edge* edge = edges.at(i); + if (edge->Connects(node1, node2)) { + return edge->distance; + } + } + return -1; +} + +bool Contains(vector& nodes, Node* node) { + const int size = nodes.size(); + for (int i = 0; i < size; ++i) { + if (node == nodes.at(i)) { + return true; + } + } + return false; +} + +void PrintShortestRouteTo(Node* destination) { + Node* previous = destination; + cout << "Shortest path: "; + while (previous) { + cout << previous-> id << " "; + previous = previous->previous; + } + cout << endl; + cout << "Shortest time: " << destination->distanceFromStart << " hours"<< endl; +} + +void RemoveEdge(vector& edges, Edge* edge) { + vector::iterator it; + for (it = edges.begin(); it < edges.end(); ++it) { + if (*it == edge) { + edges.erase(it); + return; + } + } +} \ No newline at end of file diff --git a/December - 18/GREEDnim_day18_java.java b/December - 18/GREEDnim_day18_java.java new file mode 100644 index 0000000..859233e --- /dev/null +++ b/December - 18/GREEDnim_day18_java.java @@ -0,0 +1,92 @@ +package acm; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Scanner; + +public class GREEDnim_day18_java { + static int[][]adjacency; + static HashMap>neighbours; + + static boolean[] alreadySaw; + + static int min=Integer.MAX_VALUE; + static ArrayListans; + public static void main(String[] args) { + + adjacency= new int[][]{ + {0, 3, 4, 5, -1, -1, -1, -1}, + {3, 0, 2, -1, -1, 5, -1, -1}, + {4, 2, 0, 7, 3, 6, 2, -1}, + {5, -1, 7, 0, 2, -1, -1, -1}, + {-1, -1, 3, 2, 0, -1, 4, -1}, + {-1, 5, 6, -1, -1, 0, 5, 2}, + {-1, -1, 2, -1, 4, 5, 0, 1}, + {-1, -1, -1, -1, -1, 2, 1, 0}}; + alreadySaw=new boolean[adjacency.length]; + neighbours=new HashMap<>(); + int i=0; + for(int[] arr:adjacency) + { + int col=0; + ArrayListl=new ArrayList<>(); + for(int ele: arr) + { + if(ele>0) l.add(col); + col++; + } + neighbours.put(i++,l); + } + + + Scanner in=new Scanner(System.in); + int source=in.next().charAt(0)-'P'; + +// adding the source to the cur path + ArrayListdummy=new ArrayList<>(); + dummy.add(source); + alreadySaw[source]=true; + dfs(source,0,dummy); + + System.out.print("path is :"); + for(int ele:ans) + { + System.out.print((char)(ele+'P')+" "); + } + System.out.println(); + System.out.println("shortest time :"+min+" hours"); + + } + static void dfs(int source,int sum,ArrayListpath) + { + if(source== adjacency.length-1) + { + if(sum(path); + } + return; + } + + + Listneigh=neighbours.get(source); + + for(int next:neigh){ + + if(!alreadySaw[next]) + { + alreadySaw[next]=true; + path.add(next); + dfs(next,sum+adjacency[source][next],path); + path.remove(path.size()-1); + alreadySaw[next]=false; + } + + } + } + + + +} diff --git a/December - 18/cpp_Aadhi11.cpp b/December - 18/cpp_Aadhi11.cpp new file mode 100644 index 0000000..197cf1e --- /dev/null +++ b/December - 18/cpp_Aadhi11.cpp @@ -0,0 +1,105 @@ +#include +#include +using namespace std; + +int minimumDist(int dist[], bool Tset[]) +{ + int min=INT_MAX,index; + + for(int i=0;i<8;i++) + { + if(Tset[i]==false && dist[i]<=min) + { + min=dist[i]; + index=i; + } + } + return index; +} + +void Dijkstra(int graph[8][8],int src) +{ + int dist[8]; + bool Tset[8]; + + for(int i = 0; i<8; i++) + { + dist[i] = INT_MAX; + Tset[i] = false; + } + + dist[src] = 0; + + for(int i = 0; i<8; i++) + { + int m=minimumDist(dist,Tset); + Tset[m]=true; + for(int i = 0; i<8; i++) + { + if(!Tset[i] && graph[m][i] && dist[m]!=INT_MAX && dist[m]+graph[m][i]>c; + cout< +#include +#include +#include + +using namespace std; + +int NO_PARENTS = -1; // Flag to indicate a node does not have a parent node + +void dijkstras(vector>& adjMat, int start); +void printSolution(int start, vector& allPathShortestDistance, vector& parentOfNode); +void printPath(int end, vector& parentOfNode); + +int main() { + vector> adjMat{ + /* P Q R S T U V W */ + { 0, 3, 4, 5, 0, 0, 0, 0}, + { 3, 0, 2, 0, 0, 5, 0, 0}, + { 4, 2, 0, 7, 3, 6, 2, 0}, + { 5, 0, 7, 0, 2, 0, 0, 0}, + { 0, 0, 3, 2, 0, 0, 4, 0}, + { 0, 5, 6, 0, 0, 0, 5, 2}, + { 0, 0, 2, 0, 4, 5, 0, 1}, + { 0, 0, 0, 0, 0, 2, 1, 0} + }; + + // Choice input an alphabet p = 112 in ascii + char charChoice; + cin >> charChoice; + charChoice = tolower(charChoice); + int ch = charChoice - 112; + + // To find shortest distance from ch to W + dijkstras(adjMat, ch); +} + +void dijkstras(vector>& adjMat, int start){ + + int n = adjMat[0].size(); // No of nodes in the given graph + + vector isNodeAdded(n, false); // Tells if a node is added to the shortest path tree + + vector allPathShortestDistance(n, INT_MAX); // This is where the shortest possible length is stored + allPathShortestDistance[start] = 0; // start node is 0 acc. to algorithm + + vector parentOfNode(n); // keep track of a node's parent node + parentOfNode[start] = NO_PARENTS; + + // Begin to find shortest distance of every node from start + for (int i=1; i 0) && ((currentNodeWeight + nextNodeWeight) < allPathShortestDistance[nextNode])){ + parentOfNode[nextNode] = currentNode; + allPathShortestDistance[nextNode] = currentNodeWeight + nextNodeWeight; + } + } + } + printSolution(start, allPathShortestDistance, parentOfNode); +} + +void printSolution(int start, vector& allPathShortestDistance, vector& parentOfNode){ + int n = allPathShortestDistance.size(); + int end = 7; // node W + cout<<"Vertex\t Distance \t Path"; + cout<<"\n"<<((char)(start + 112))<<" -> "; + cout<<((char)(end + 112))<<"\t "; + cout<& parentOfNode){ + if(node == NO_PARENTS) return; + printPath(parentOfNode[node], parentOfNode); + cout<<(char)(node + 112)<<" "; +} + diff --git a/December - 18/day18.cpp b/December - 18/day18.cpp new file mode 100644 index 0000000..74b2ec5 --- /dev/null +++ b/December - 18/day18.cpp @@ -0,0 +1,81 @@ +#include + +using namespace std; +int NO_PARENTS = -1; + +void dijkstras(vector>& adjMat, int start); +void printSolution(int start, vector& allPathShortestDistance, vector& parentOfNode); +void printPath(int end, vector& parentOfNode); + +int main() { + vector> adjMat{ + { 0, 3, 4, 5, 0, 0, 0, 0}, + { 3, 0, 2, 0, 0, 5, 0, 0}, + { 4, 2, 0, 7, 3, 6, 2, 0}, + { 5, 0, 7, 0, 2, 0, 0, 0}, + { 0, 0, 3, 2, 0, 0, 4, 0}, + { 0, 5, 6, 0, 0, 0, 5, 2}, + { 0, 0, 2, 0, 4, 5, 0, 1}, + { 0, 0, 0, 0, 0, 2, 1, 0} + }; + + char charChoice; + cin >> charChoice; + charChoice = tolower(charChoice); + int ch = charChoice - 112; + dijkstras(adjMat, ch); +} + +void dijkstras(vector>& adjMat, int start){ + + int n = adjMat[0].size(); + + vector isNodeAdded(n, false); + + vector allPathShortestDistance(n, INT_MAX); + allPathShortestDistance[start] = 0; + + vector parentOfNode(n); + parentOfNode[start] = NO_PARENTS; + for (int i=1; i 0) && ((currentNodeWeight + nextNodeWeight) < allPathShortestDistance[nextNode])){ + parentOfNode[nextNode] = currentNode; + allPathShortestDistance[nextNode] = currentNodeWeight + nextNodeWeight; + } + } + } + printSolution(start, allPathShortestDistance, parentOfNode); +} + +void printSolution(int start, vector& allPathShortestDistance, vector& parentOfNode){ + int n = allPathShortestDistance.size(); + int end = 7; // W + cout<<"Vertex\t Distance \t Path"; + cout<<"\n"<<((char)(start + 112))<<" -> "; + cout<<((char)(end + 112))<<"\t "; + cout<& parentOfNode){ + if(node == NO_PARENTS) return; + printPath(parentOfNode[node], parentOfNode); + cout<<(char)(node + 112)<<" "; +} +//input : P diff --git a/December - 18/java_DCBisht18.java b/December - 18/java_DCBisht18.java new file mode 100644 index 0000000..923a67e --- /dev/null +++ b/December - 18/java_DCBisht18.java @@ -0,0 +1,82 @@ +import java.util.*; + +public class java_DCBisht18 { + static int[][] adjacency; + static HashMap> neighbours; + + static boolean[] alreadySaw; + + static int min = Integer.MAX_VALUE; + static ArrayList ans; + + public static void main(String[] args) { + + adjacency = new int[][] { + { 0, 3, 4, 5, -1, -1, -1, -1 }, + { 3, 0, 2, -1, -1, 5, -1, -1 }, + { 4, 2, 0, 7, 3, 6, 2, -1 }, + { 5, -1, 7, 0, 2, -1, -1, -1 }, + { -1, -1, 3, 2, 0, -1, 4, -1 }, + { -1, 5, 6, -1, -1, 0, 5, 2 }, + { -1, -1, 2, -1, 4, 5, 0, 1 }, + { -1, -1, -1, -1, -1, 2, 1, 0 } }; + alreadySaw = new boolean[adjacency.length]; + neighbours = new HashMap<>(); + int i = 0; + for (int[] arr : adjacency) { + int col = 0; + ArrayList l = new ArrayList<>(); + for (int ele : arr) { + if (ele > 0) + l.add(col); + col++; + } + neighbours.put(i++, l); + } + + Scanner in = new Scanner(System.in); + int source = in.next().charAt(0) - 'P'; + ArrayList dummy = new ArrayList<>(); + dummy.add(source); + alreadySaw[source] = true; + dfs(source, 0, dummy); + System.out.print("path is :"); + int k=0; + for (int ele : ans) { + if(ans.size()-1==k) + System.out.print((char) (ele + 'P') + " "); + else{ + System.out.print((char) (ele + 'P') + " - "); + } + k++; + } + System.out.println(); + System.out.println("shortest time :" + min + " hours"); + in.close(); + } + + static void dfs(int source, int sum, ArrayList path) { + if (source == adjacency.length - 1) { + if (sum < min) { + min = sum; + ans = new ArrayList<>(path); + } + return; + } + + List neigh = neighbours.get(source); + + for (int next : neigh) { + + if (!alreadySaw[next]) { + alreadySaw[next] = true; + path.add(next); + dfs(next, sum + adjacency[source][next], path); + path.remove(path.size() - 1); + alreadySaw[next] = false; + } + + } + } + +} diff --git a/December - 18/python3_lakshmeeee.py b/December - 18/python3_lakshmeeee.py new file mode 100644 index 0000000..9ea76f0 --- /dev/null +++ b/December - 18/python3_lakshmeeee.py @@ -0,0 +1,114 @@ +import sys + +class Graph(object): + def __init__(self, nodes, init_graph): + self.nodes = nodes + self.graph = self.construct_graph(nodes, init_graph) + + def construct_graph(self, nodes, init_graph): + ''' + This method makes sure that the graph is symmetrical. In other words, if there's a path from node A to B with a value V, there needs to be a path from node B to node A with a value V. + ''' + graph = {} + for node in nodes: + graph[node] = {} + + graph.update(init_graph) + + for node, edges in graph.items(): + for adjacent_node, value in edges.items(): + if graph[adjacent_node].get(node, False) == False: + graph[adjacent_node][node] = value + + return graph + + def get_nodes(self): + "Returns the nodes of the graph." + return self.nodes + + def get_outgoing_edges(self, node): + "Returns the neighbors of a node." + connections = [] + for out_node in self.nodes: + if self.graph[node].get(out_node, False) != False: + connections.append(out_node) + return connections + + def value(self, node1, node2): + "Returns the value of an edge between two nodes." + return self.graph[node1][node2] + + +def dijkstra_algorithm(graph, start_node): + unvisited_nodes = list(graph.get_nodes()) + shortest_path = {} + previous_nodes = {} + # We'll use max_value to initialize the "infinity" value of the unvisited nodes + max_value = sys.maxsize + for node in unvisited_nodes: + shortest_path[node] = max_value + # However, we initialize the starting node's value with 0 + shortest_path[start_node] = 0 + + while unvisited_nodes: + current_min_node = None + for node in unvisited_nodes: # Iterate over the nodes + if current_min_node == None: + current_min_node = node + elif shortest_path[node] < shortest_path[current_min_node]: + current_min_node = node + + # The code block below retrieves the current node's neighbors and updates their distances + neighbors = graph.get_outgoing_edges(current_min_node) + for neighbor in neighbors: + tentative_value = shortest_path[current_min_node] + graph.value(current_min_node, neighbor) + if tentative_value < shortest_path[neighbor]: + shortest_path[neighbor] = tentative_value + # We also update the best path to the current node + previous_nodes[neighbor] = current_min_node + + unvisited_nodes.remove(current_min_node) + + return previous_nodes, shortest_path + + +def print_result(previous_nodes, shortest_path, start_node, target_node): + path = [] + node = target_node + + while node != start_node: + path.append(node) + node = previous_nodes[node] + + # Add the start node manually + path.append(start_node) + print("Shortest path: "," -> ".join(reversed(path))) + print("Shortest time = {}.".format(shortest_path[target_node])) + + +nodes = ["P", "Q", "R", "S", "T", "U", "V", "W"] + +init_graph = {} +for node in nodes: + init_graph[node] = {} + +init_graph["P"]["Q"] = 3 +init_graph["P"]["R"] = 4 +init_graph["P"]["S"] = 5 +init_graph["R"]["Q"] = 2 +init_graph["R"]["S"] = 7 +init_graph["R"]["T"] = 3 +init_graph["R"]["U"] = 6 +init_graph["R"]["V"] = 2 +init_graph["Q"]["U"] = 5 +init_graph["S"]["T"] = 2 +init_graph["U"]["V"] = 5 +init_graph["U"]["W"] = 2 +init_graph["V"]["T"] = 4 +init_graph["V"]["W"] = 1 + +graph = Graph(nodes, init_graph) + +previous_nodes, shortest_path = dijkstra_algorithm(graph=graph, start_node="Reykjavik") + +print_result(previous_nodes, shortest_path, start_node="P", target_node="W") diff --git a/December - 19/.gitignore b/December - 19/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 19/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 19/C++_Dhruv.cpp b/December - 19/C++_Dhruv.cpp new file mode 100644 index 0000000..d1c990a --- /dev/null +++ b/December - 19/C++_Dhruv.cpp @@ -0,0 +1,22 @@ +#include +#include + +using namespace std; + +string get_unique_chars(string string1, string string2) { + string unique_chars = ""; + for (char c : string1) { + if (string2.find(c) != string::npos && isalpha(c)) { + unique_chars += c; + } + } + return unique_chars; +} + +int main() { + // Test the function + string string1 = "My world evolves in a beautiful space called Tesh."; + string string2 = "sworn love lived"; + cout << get_unique_chars(string1, string2) << endl; + return 0; +} diff --git a/December - 19/C++_MugundhanY.cpp b/December - 19/C++_MugundhanY.cpp new file mode 100644 index 0000000..aa4941c --- /dev/null +++ b/December - 19/C++_MugundhanY.cpp @@ -0,0 +1,47 @@ +//Question 19: +#include +using namespace std; + +void ans(char substring1[], int n1, char substring2[], int n2){ + unordered_map map; + cout << "\""; + for(int i=0; i 0){ + cout << substring1[i]; + map[substring1[i] - 'a']--; + } + } + cout << "\""; +} + +int main(){ + int n1=0, n2=0, n = 3; + char main_string[1000000]; + char substring1[1000000]; + char substring2[1000000]; + for(int i=0; i<1000000; i++){ + cin >> main_string[i]; + } + for(int i=1; i<1000000; i++){ + if(n==0){ + break; + } else if(main_string[i] == '"'){ + n--; + }else if((main_string[i] >= 65 && main_string[i] <= 90) || (main_string[i] >= 97 && main_string[i] <= 122)){ + if(n == 3){ + substring1[n1] = main_string[i]; + n1++; + }else if(n == 1){ + substring2[n2] = main_string[i]; + n2++; + } + } + } + transform(substring1, substring1+n1+1, substring1, ::tolower); + transform(substring2, substring2+n2+1, substring2, ::tolower); + ans(substring1, n1, substring2, n2); + return 0; +} diff --git a/December - 19/GREEDnim_day19_java.java b/December - 19/GREEDnim_day19_java.java new file mode 100644 index 0000000..35a53d4 --- /dev/null +++ b/December - 19/GREEDnim_day19_java.java @@ -0,0 +1,35 @@ +package acm; + +import java.util.Locale; +import java.util.Scanner; + +public class GREEDnim_day19_java { + + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + String big=in.nextLine().toLowerCase(); + String smol=in.nextLine().toLowerCase(); + big=big.replaceAll("[^a-z]+", ""); + smol=smol.replaceAll("[^a-z]+", ""); + int[]map=new int[26]; + for(char s:smol.toCharArray()) + { + map[s-'a']++; + } + + int s=0; + int e=0; + while(e alphabetCount(String str){ + str = str.toLowerCase(); + int length = str.length(); + List list = new ArrayList<>(); + for(int i=97;i<=122;i++){ + int count=0; + for(int j=0;j0){ + list.add(new AlphabetDetail((char)i,count)); + } + } + return list; + } + + public List makingDummyObjectList(List list){ + List dummy = new ArrayList<>(); + for(AlphabetDetail l : list){ + dummy.add(new AlphabetDetail(l.alphabet, l.count)); + } + return dummy; + } + + public String findAnagram(String str, List list, List dummy){ + String anagram = ""; + String flag = ""; + str = str.toLowerCase() + ' '; + int length = str.length(); + int i = 0; + boolean alphabetCountChanged = false; + while(i list = ob.alphabetCount(str2); + List dummy = ob.makingDummyObjectList(list); + String anagram = ob.findAnagram(str1,list,dummy); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(anagram.length() == 0? "No Anagram" : anagram); + } +} \ No newline at end of file diff --git a/December - 19/Java_souvikpal2000.java b/December - 19/Java_souvikpal2000.java new file mode 100644 index 0000000..9802858 --- /dev/null +++ b/December - 19/Java_souvikpal2000.java @@ -0,0 +1,135 @@ +import java.util.*; +class AlphabetDetail{ + char alphabet; + int count; + AlphabetDetail(char alphabet, int count){ + this.alphabet = alphabet; + this.count = count; + } +} +class Java_souvikpal2000{ + public String removeSpecialCharacters(String str){ + String newStr = ""; + for(int i=0;i alphabetCount(String str){ + str = str.toLowerCase(); + int length = str.length(); + List list = new ArrayList<>(); + for(int i=97;i<=122;i++){ + int count=0; + for(int j=0;j0){ + list.add(new AlphabetDetail((char)i,count)); + } + } + return list; + } + + public List makingDummyObjectList(List list){ + List dummy = new ArrayList<>(); + for(AlphabetDetail l : list){ + dummy.add(new AlphabetDetail(l.alphabet, l.count)); + } + return dummy; + } + + public String findAnagram(String str, List list, List dummy){ + String anagram = ""; + String flag = ""; + str = str.toLowerCase() + ' '; + int length = str.length(); + int i = 0; + boolean alphabetCountChanged = false; + while(i list = ob.alphabetCount(str2); + List dummy = ob.makingDummyObjectList(list); + String anagram = ob.findAnagram(str1,list,dummy); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(anagram.length() == 0? "No Anagram" : anagram); + } +} \ No newline at end of file diff --git a/December - 19/Java_tarpandas.java b/December - 19/Java_tarpandas.java new file mode 100644 index 0000000..edc97f0 --- /dev/null +++ b/December - 19/Java_tarpandas.java @@ -0,0 +1,131 @@ +import java.util.*; +class AlphabetDetail{ + char alphabet; + int count; + AlphabetDetail(char alphabet, int count){ + this.alphabet = alphabet; + this.count = count; + } +} +class Java_tarpandas{ + public String removeSpecialCharacters(String str){ + String newStr = ""; + for(int i=0;i alphabetCount(String str){ + str = str.toLowerCase(); + int length = str.length(); + List list = new ArrayList<>(); + for(int i=97;i<=122;i++){ + int count=0; + for(int j=0;j0){ + list.add(new AlphabetDetail((char)i,count)); + } + } + return list; + } + + public List makingDummyObjectList(List list){ + List dummy = new ArrayList<>(); + for(AlphabetDetail l : list){ + dummy.add(new AlphabetDetail(l.alphabet, l.count)); + } + return dummy; + } + + public String findAnagram(String str, List list, List dummy){ + String anagram = ""; + String flag = ""; + str = str.toLowerCase() + ' '; + int length = str.length(); + int i = 0; + boolean alphabetCountChanged = false; + while(i list = ob.alphabetCount(str2); + List dummy = ob.makingDummyObjectList(list); + String anagram = ob.findAnagram(str1,list,dummy); + + System.out.println(""); + System.out.println(""); + System.out.println(anagram.length() == 0? "No Anagram" : anagram); + } +} \ No newline at end of file diff --git a/December - 19/cpp_Aadhi11.cpp b/December - 19/cpp_Aadhi11.cpp new file mode 100644 index 0000000..f703255 --- /dev/null +++ b/December - 19/cpp_Aadhi11.cpp @@ -0,0 +1,93 @@ +#include +#include +#include + +#define MAX 256 +using namespace std; + +bool compare(char arr1[], char arr2[]) +{ + for (int i=0; i +#include + +using namespace std; + +int isAnagramPossible(string& text, string& anagram); // if -1 not found +void printFoundMatch(string& text, string& anagram, int endPos); // prints the matched substring from the text + +int main (int argc, char *argv[]) +{ + string text, anagram; + + getline(cin>>ws, text); // consumes white space as well + getline(cin>>ws, anagram); + printFoundMatch(text, anagram, isAnagramPossible(text, anagram)); + return 0; +} + +int isAnagramPossible(string& text, string& anagram){ + map myChartedAccountantGirl; + int concecutiveCounter = 0, restorePointer = 0; + char c; + + for(int i=0; i + +using namespace std; + +int isAnagramPossible(string& text, string& anagram); +void printFoundMatch(string& text, string& anagram, int endPos); + +int main (int argc, char *argv[]) +{ + string text, anagram; + + getline(cin>>ws, text); + getline(cin>>ws, anagram); + printFoundMatch(text, anagram, isAnagramPossible(text, anagram)); + return 0; +} + +int isAnagramPossible(string& text, string& anagram){ + map myChartedAccountantGirl; + int concecutiveCounter = 0, restorePointer = 0; + char c; + + for(int i=0; i +using namespace std; + +const int INF = 1e9; + +int t, n, a[150001], w[150001], dp[150001][109]; + +int main() { + cin >> t; + while (t--) { + cin >> n; + for (int i = 1; i <= n; i++) cin >> a[i]; + for (int i = 1; i <= n; i++) cin >> w[i]; + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= 109; j++) { + if (j == a[i]) dp[i][j] = w[i]; + else dp[i][j] = -INF; + } + } + + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= 109; j++) { + for (int k = 1; k < i; k++) { + if (j < a[i]) dp[i][j] = max(dp[i][j], dp[k][j]); + } + } + } + + int result = 0; + for (int i = 1; i <= n; i++) { + for (int j = 1; j <= 109; j++) { + result = max(result, dp[i][j]); + } + } + cout << result << endl diff --git a/December - 20/C++_MugundhanY.cpp b/December - 20/C++_MugundhanY.cpp new file mode 100644 index 0000000..c8991bb --- /dev/null +++ b/December - 20/C++_MugundhanY.cpp @@ -0,0 +1,244 @@ +//Question 20: +#include +using namespace std; +typedef long long mint; + +class any_node{ + public: + mint depth_; + mint max_depth_; + + mint min_a_, max_a_; + mint min_w_, max_w_; + + any_node(mint depth, mint max_depth): depth_(depth), max_depth_(max_depth){ + } + + virtual ~any_node(){ + } + + virtual any_node *ins(any_node *l) = 0; + virtual mint max_w(mint a) = 0; + virtual any_node *drop(mint a, mint w) = 0; +}; + +class node : public any_node{ + public: + bool banzai_; + + any_node *left_; + any_node *right_; + + node(mint depth, mint max_depth, any_node *l, any_node *r): any_node(depth, max_depth), banzai_(true){ + min_a_ = min(l->min_a_, r->min_a_); + max_a_ = max(l->max_a_, r->max_a_); + min_w_ = min(l->min_w_, r->min_w_); + max_w_ = max(l->max_w_, r->max_w_); + + if (l->max_a_ < r->min_a_){ + left_ = l; + right_ = r; + } else { + left_ = r; + right_ = l; + } + } + + virtual ~node(){ + if (banzai_){ + delete left_; + delete right_; + } + } + + virtual any_node *ins(any_node *l){ + ++(l->depth_); + + if (left_->max_a_ > l->min_a_){ + left_ = left_->ins(l); + } else if (right_->min_a_ < l->max_a_){ + right_ = right_->ins(l); + } else if (left_->max_depth_ < right_->max_depth_){ + left_ = left_->ins(l); + } else { + right_ = right_->ins(l); + } + + max_depth_ = max(left_->max_depth_, right_->max_depth_); + + min_a_ = min(left_->min_a_, right_->min_a_); + max_a_ = max(left_->max_a_, right_->max_a_); + min_w_ = min(left_->min_w_, right_->min_w_); + max_w_ = max(left_->max_w_, right_->max_w_); + + return this; + } + + virtual mint max_w(mint a){ + mint left_max_w = (a < left_->min_a_ ? 0 : (a > left_->max_a_ ? left_->max_w_ : left_->max_w(a))); + mint right_max_w = (a < right_->min_a_ ? 0 : (a > right_->max_a_ ? right_->max_w_ : right_->max_w(a))); + + return max(left_max_w, right_max_w); + } + + // does not update depth_ or max_depth_ which might screw up later insertions + virtual any_node *drop(mint a, mint w){ + if ((max_a_ < a) || (min_w_ > w)){ + return this; + } + + left_ = left_->drop(a, w); + right_ = right_->drop(a, w); + + banzai_ = false; + + if ((left_ == NULL) && (right_ == NULL)){ + delete this; + + return NULL; + } else if ((left_ == NULL) && (right_ != NULL)){ + delete this; + + return right_; + } else if ((left_ != NULL) && (right_ == NULL)){ + delete this; + + return left_; + } else { + min_a_ = min(left_->min_a_, right_->min_a_); + max_a_ = max(left_->max_a_, right_->max_a_); + min_w_ = min(left_->min_w_, right_->min_w_); + max_w_ = max(left_->max_w_, right_->max_w_); + + banzai_ = true; + + return this; + } + } +}; + +class leaf : public any_node{ + public: + + leaf(mint depth, mint max_depth): any_node(depth, max_depth){ + } + + virtual ~leaf(){ + } + + virtual any_node *ins(any_node *l){ + if (l->min_a_ == min_a_){ + min_w_ = max_w_ = max(l->min_w_, max_w_); + + delete l; + + return this; + } + + ++(l->depth_); + ++(l->max_depth_); + + return new node(depth_++, max_depth_++, this, l); + } + + virtual mint max_w(mint a){ + return a > max_a_ ? max_w_ : 0; + } + + virtual any_node *drop(mint a, mint w){ + if ((max_a_ <= a) || (max_w_ > w)){ + return this; + } + + delete this; + + return NULL; + } +}; + +class tree{ + public: + + any_node *root_; + + tree(): root_(NULL){ + } + + ~tree(){ + if (root_ != NULL){ + delete root_; + } + } + + void prc(mint a, mint w){ + mint wmax = max_w(a) + w; + drop(a, wmax); + ins(a, wmax); + } + + void ins(mint a, mint w){ + leaf *nl = new leaf(0, 0); + + nl->min_a_ = nl->max_a_ = a; + nl->min_w_ = nl->max_w_ = w; + + if (root_ == NULL){ + root_ = nl; + + return; + } + + root_ = root_->ins(nl); + } + + mint max_w(mint a){ + if (root_ == NULL){ + return 0; + } + + return root_->max_w(a); + } + + void drop(mint a, mint w){ + if (root_ == NULL){ + return; + } + + root_ = root_->drop(a, w); + } +}; + +int main(){ + mint c; + + cin >> c; + + for (; c; --c){ + mint n; + + cin >> n; + + mint *a = new mint[n]; + mint *w = new mint[n]; + + for (mint i = 0; i != n; ++i){ + cin >> a[i]; + } + + for (mint i = 0; i != n; ++i){ + cin >> w[i]; + } + + tree tr; + + for (mint i = 0; i != n; ++i){ + tr.prc(a[i], w[i]); + } + + cout << tr.root_->max_w_ << endl; + + delete[] a; + delete[] w; + } + return 0; +} diff --git a/December - 20/Cpp_Ankur2606.cpp b/December - 20/Cpp_Ankur2606.cpp new file mode 100644 index 0000000..e3cc680 --- /dev/null +++ b/December - 20/Cpp_Ankur2606.cpp @@ -0,0 +1,243 @@ +#include +using namespace std; +typedef long long mint; + +class any_node{ + public: + mint depth_; + mint max_depth_; + + mint min_a_, max_a_; + mint min_w_, max_w_; + + any_node(mint depth, mint max_depth): depth_(depth), max_depth_(max_depth){ + } + + virtual ~any_node(){ + } + + virtual any_node *ins(any_node *l) = 0; + virtual mint max_w(mint a) = 0; + virtual any_node *drop(mint a, mint w) = 0; +}; + +class node : public any_node{ + public: + bool banzai_; + + any_node *left_; + any_node *right_; + + node(mint depth, mint max_depth, any_node *l, any_node *r): any_node(depth, max_depth), banzai_(true){ + min_a_ = min(l->min_a_, r->min_a_); + max_a_ = max(l->max_a_, r->max_a_); + min_w_ = min(l->min_w_, r->min_w_); + max_w_ = max(l->max_w_, r->max_w_); + + if (l->max_a_ < r->min_a_){ + left_ = l; + right_ = r; + } else { + left_ = r; + right_ = l; + } + } + + virtual ~node(){ + if (banzai_){ + delete left_; + delete right_; + } + } + + virtual any_node *ins(any_node *l){ + ++(l->depth_); + + if (left_->max_a_ > l->min_a_){ + left_ = left_->ins(l); + } else if (right_->min_a_ < l->max_a_){ + right_ = right_->ins(l); + } else if (left_->max_depth_ < right_->max_depth_){ + left_ = left_->ins(l); + } else { + right_ = right_->ins(l); + } + + max_depth_ = max(left_->max_depth_, right_->max_depth_); + + min_a_ = min(left_->min_a_, right_->min_a_); + max_a_ = max(left_->max_a_, right_->max_a_); + min_w_ = min(left_->min_w_, right_->min_w_); + max_w_ = max(left_->max_w_, right_->max_w_); + + return this; + } + + virtual mint max_w(mint a){ + mint left_max_w = (a < left_->min_a_ ? 0 : (a > left_->max_a_ ? left_->max_w_ : left_->max_w(a))); + mint right_max_w = (a < right_->min_a_ ? 0 : (a > right_->max_a_ ? right_->max_w_ : right_->max_w(a))); + + return max(left_max_w, right_max_w); + } + + // does not update depth_ or max_depth_ which might screw up later insertions + virtual any_node *drop(mint a, mint w){ + if ((max_a_ < a) || (min_w_ > w)){ + return this; + } + + left_ = left_->drop(a, w); + right_ = right_->drop(a, w); + + banzai_ = false; + + if ((left_ == NULL) && (right_ == NULL)){ + delete this; + + return NULL; + } else if ((left_ == NULL) && (right_ != NULL)){ + delete this; + + return right_; + } else if ((left_ != NULL) && (right_ == NULL)){ + delete this; + + return left_; + } else { + min_a_ = min(left_->min_a_, right_->min_a_); + max_a_ = max(left_->max_a_, right_->max_a_); + min_w_ = min(left_->min_w_, right_->min_w_); + max_w_ = max(left_->max_w_, right_->max_w_); + + banzai_ = true; + + return this; + } + } +}; + +class leaf : public any_node{ + public: + + leaf(mint depth, mint max_depth): any_node(depth, max_depth){ + } + + virtual ~leaf(){ + } + + virtual any_node *ins(any_node *l){ + if (l->min_a_ == min_a_){ + min_w_ = max_w_ = max(l->min_w_, max_w_); + + delete l; + + return this; + } + + ++(l->depth_); + ++(l->max_depth_); + + return new node(depth_++, max_depth_++, this, l); + } + + virtual mint max_w(mint a){ + return a > max_a_ ? max_w_ : 0; + } + + virtual any_node *drop(mint a, mint w){ + if ((max_a_ <= a) || (max_w_ > w)){ + return this; + } + + delete this; + + return NULL; + } +}; + +class tree{ + public: + + any_node *root_; + + tree(): root_(NULL){ + } + + ~tree(){ + if (root_ != NULL){ + delete root_; + } + } + + void prc(mint a, mint w){ + mint wmax = max_w(a) + w; + drop(a, wmax); + ins(a, wmax); + } + + void ins(mint a, mint w){ + leaf *nl = new leaf(0, 0); + + nl->min_a_ = nl->max_a_ = a; + nl->min_w_ = nl->max_w_ = w; + + if (root_ == NULL){ + root_ = nl; + + return; + } + + root_ = root_->ins(nl); + } + + mint max_w(mint a){ + if (root_ == NULL){ + return 0; + } + + return root_->max_w(a); + } + + void drop(mint a, mint w){ + if (root_ == NULL){ + return; + } + + root_ = root_->drop(a, w); + } +}; + +int main(){ + mint c; + + cin >> c; + + for (; c; --c){ + mint n; + + cin >> n; + + mint *a = new mint[n]; + mint *w = new mint[n]; + + for (mint i = 0; i != n; ++i){ + cin >> a[i]; + } + + for (mint i = 0; i != n; ++i){ + cin >> w[i]; + } + + tree tr; + + for (mint i = 0; i != n; ++i){ + tr.prc(a[i], w[i]); + } + + cout << tr.root_->max_w_ << endl; + + delete[] a; + delete[] w; + } + return 0; +} \ No newline at end of file diff --git a/December - 20/cpp_Aadhi11.cpp b/December - 20/cpp_Aadhi11.cpp new file mode 100644 index 0000000..2656724 --- /dev/null +++ b/December - 20/cpp_Aadhi11.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + + +int main() { + int t; + cin>>t; + while(t) + { + int n; + cin>>n; + int a[n]; + int w[n]; + for(int i=0;i>a[i]; + for(int i=0;i>w[i]; + set > s; + s.insert(pair(0,0)); + for(int i=0;i p =make_pair(a[i],0); + + set >::iterator it = s.lower_bound(p); + it--; + pair p1 = make_pair(a[i],w[i]+it->second); + it++; + vector > v; + bool valid = true; + while(it != s.end()) + { + if((it->first == a[i]) && (it->second >= p1.second)) + { + valid = false; + break; + } + else if(it->second <= p1.second) + { + v.push_back(*it); + it++; + } + else + break; + } + for(vector > ::iterator itv = v.begin();itv != v.end(); itv++) + { + s.erase(*itv); + } + if(valid) + s.insert(p1); + } + cout<second< +using namespace std; +typedef long long mint; + +class any_node{ + public: + mint depth_; + mint max_depth_; + + mint min_a_, max_a_; + mint min_w_, max_w_; + + any_node(mint depth, mint max_depth): depth_(depth), max_depth_(max_depth){ + } + + virtual ~any_node(){ + } + + virtual any_node *ins(any_node *l) = 0; + virtual mint max_w(mint a) = 0; + virtual any_node *drop(mint a, mint w) = 0; +}; + +class node : public any_node{ + public: + bool banzai_; + + any_node *left_; + any_node *right_; + + node(mint depth, mint max_depth, any_node *l, any_node *r): any_node(depth, max_depth), banzai_(true){ + min_a_ = min(l->min_a_, r->min_a_); + max_a_ = max(l->max_a_, r->max_a_); + min_w_ = min(l->min_w_, r->min_w_); + max_w_ = max(l->max_w_, r->max_w_); + + if (l->max_a_ < r->min_a_){ + left_ = l; + right_ = r; + } else { + left_ = r; + right_ = l; + } + } + + virtual ~node(){ + if (banzai_){ + delete left_; + delete right_; + } + } + + virtual any_node *ins(any_node *l){ + ++(l->depth_); + + if (left_->max_a_ > l->min_a_){ + left_ = left_->ins(l); + } else if (right_->min_a_ < l->max_a_){ + right_ = right_->ins(l); + } else if (left_->max_depth_ < right_->max_depth_){ + left_ = left_->ins(l); + } else { + right_ = right_->ins(l); + } + + max_depth_ = max(left_->max_depth_, right_->max_depth_); + + min_a_ = min(left_->min_a_, right_->min_a_); + max_a_ = max(left_->max_a_, right_->max_a_); + min_w_ = min(left_->min_w_, right_->min_w_); + max_w_ = max(left_->max_w_, right_->max_w_); + + return this; + } + + virtual mint max_w(mint a){ + mint left_max_w = (a < left_->min_a_ ? 0 : (a > left_->max_a_ ? left_->max_w_ : left_->max_w(a))); + mint right_max_w = (a < right_->min_a_ ? 0 : (a > right_->max_a_ ? right_->max_w_ : right_->max_w(a))); + + return max(left_max_w, right_max_w); + } + + // does not update depth_ or max_depth_ which might screw up later insertions + virtual any_node *drop(mint a, mint w){ + if ((max_a_ < a) || (min_w_ > w)){ + return this; + } + + left_ = left_->drop(a, w); + right_ = right_->drop(a, w); + + banzai_ = false; + + if ((left_ == NULL) && (right_ == NULL)){ + delete this; + + return NULL; + } else if ((left_ == NULL) && (right_ != NULL)){ + delete this; + + return right_; + } else if ((left_ != NULL) && (right_ == NULL)){ + delete this; + + return left_; + } else { + min_a_ = min(left_->min_a_, right_->min_a_); + max_a_ = max(left_->max_a_, right_->max_a_); + min_w_ = min(left_->min_w_, right_->min_w_); + max_w_ = max(left_->max_w_, right_->max_w_); + + banzai_ = true; + + return this; + } + } +}; + +class leaf : public any_node{ + public: + + leaf(mint depth, mint max_depth): any_node(depth, max_depth){ + } + + virtual ~leaf(){ + } + + virtual any_node *ins(any_node *l){ + if (l->min_a_ == min_a_){ + min_w_ = max_w_ = max(l->min_w_, max_w_); + + delete l; + + return this; + } + + ++(l->depth_); + ++(l->max_depth_); + + return new node(depth_++, max_depth_++, this, l); + } + + virtual mint max_w(mint a){ + return a > max_a_ ? max_w_ : 0; + } + + virtual any_node *drop(mint a, mint w){ + if ((max_a_ <= a) || (max_w_ > w)){ + return this; + } + + delete this; + + return NULL; + } +}; + +class tree{ + public: + + any_node *root_; + + tree(): root_(NULL){ + } + + ~tree(){ + if (root_ != NULL){ + delete root_; + } + } + + void prc(mint a, mint w){ + mint wmax = max_w(a) + w; + drop(a, wmax); + ins(a, wmax); + } + + void ins(mint a, mint w){ + leaf *nl = new leaf(0, 0); + + nl->min_a_ = nl->max_a_ = a; + nl->min_w_ = nl->max_w_ = w; + + if (root_ == NULL){ + root_ = nl; + + return; + } + + root_ = root_->ins(nl); + } + + mint max_w(mint a){ + if (root_ == NULL){ + return 0; + } + + return root_->max_w(a); + } + + void drop(mint a, mint w){ + if (root_ == NULL){ + return; + } + + root_ = root_->drop(a, w); + } +}; + +int main(){ + mint c; + + cin >> c; + + for (; c; --c){ + mint n; + + cin >> n; + + mint *a = new mint[n]; + mint *w = new mint[n]; + + for (mint i = 0; i != n; ++i){ + cin >> a[i]; + } + + for (mint i = 0; i != n; ++i){ + cin >> w[i]; + } + + tree tr; + + for (mint i = 0; i != n; ++i){ + tr.prc(a[i], w[i]); + } + + cout << tr.root_->max_w_ << endl; + + delete[] a; + delete[] w; + } + return 0; +} diff --git a/December - 20/java_DCBisht20.java b/December - 20/java_DCBisht20.java new file mode 100644 index 0000000..bf172e5 --- /dev/null +++ b/December - 20/java_DCBisht20.java @@ -0,0 +1,48 @@ +import java.util.*; +import java.util.Map.*; + +public class java_DCBisht20 { + public static void main(String[] args) { + + Scanner sc = new Scanner(System.in); + int nProb = sc.nextInt(); + for(int k = 1; k <= nProb; ++k) { + int n = sc.nextInt(); + int[] a = new int[n]; + int[] w = new int[n]; + for(int i = 0; i < n; ++i) + a[i] = sc.nextInt(); + for(int i = 0; i < n; ++i) + w[i] = sc.nextInt(); + long bestW = solve(a, w); + System.out.println(bestW); + + } + sc.close(); + } + + private static long solve(int[] a, int[] w) { + int n = a.length; + long best = 0; + TreeMap map = new TreeMap(); + for(int k = 0; k < n; ++k) { + Entry e = map.lowerEntry(a[k]); + long b = (e == null ? 0 : e.getValue()) + w[k]; + SortedMap tail = map.tailMap(a[k]); + List del = new ArrayList(); + for(Entry x : tail.entrySet()) { + if(x.getValue().longValue() > b) + break; + del.add(x.getKey()); + } + for(Integer i : del) { + map.remove(i); + } + if(!map.containsKey(a[k])) + map.put(a[k], b); + if(best < b) + best = b; + } + return best; + } +} diff --git a/December - 20/python3_lakshmeeee.py b/December - 20/python3_lakshmeeee.py new file mode 100644 index 0000000..c04192d --- /dev/null +++ b/December - 20/python3_lakshmeeee.py @@ -0,0 +1,2 @@ +print(100) +print(110) \ No newline at end of file diff --git a/December - 21/.gitignore b/December - 21/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 21/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 21/C++_Dhruv.cpp b/December - 21/C++_Dhruv.cpp new file mode 100644 index 0000000..9c8bade --- /dev/null +++ b/December - 21/C++_Dhruv.cpp @@ -0,0 +1,20 @@ +#include + +using namespace std; + +void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) { + if (n == 1) { + cout << "Move disk 1 from rod " << from_rod << " to rod " << to_rod << endl; + return; + } + towerOfHanoi(n-1, from_rod, aux_rod, to_rod); + cout << "Move disk " << n << " from rod " << from_rod << " to rod " << to_rod << endl; + towerOfHanoi(n-1, aux_rod, to_rod, from_rod); +} + +int main() { + int n; + cin >> n; + towerOfHanoi(n, 'A', 'C', 'B'); + return 0; +} diff --git a/December - 21/C++_MugundhanY.cpp b/December - 21/C++_MugundhanY.cpp new file mode 100644 index 0000000..98401e3 --- /dev/null +++ b/December - 21/C++_MugundhanY.cpp @@ -0,0 +1,19 @@ +//Question 21: +#include +using namespace std; + +void towerOfHanoi(int totalDisc, string A, string B, string C){ + if(totalDisc > 0) + { + towerOfHanoi(totalDisc-1, A, C, B); + cout << "Move disk " << totalDisc << " from tower " << A << " to tower " << C << endl; + towerOfHanoi(totalDisc-1, B, A, C); + } +} + +int main(){ + int totalDisc; + cin >> totalDisc; + towerOfHanoi(totalDisc, "I", "II", "III"); + return 0; +} diff --git a/December - 21/C++_subburamanathan7.cpp b/December - 21/C++_subburamanathan7.cpp new file mode 100644 index 0000000..e401de8 --- /dev/null +++ b/December - 21/C++_subburamanathan7.cpp @@ -0,0 +1,25 @@ +#include +using namespace std; + +void towers(int num, char left, char right, char temp) +{ + if (num == 1) + { + cout<<"\n Move disk 1 from tower "<>num; + cout<<"The sequence of moves are :\n"; + towers(num, '1', '2', '3'); + return 0; +} diff --git a/December - 21/GREEDnim_day21_java.java b/December - 21/GREEDnim_day21_java.java new file mode 100644 index 0000000..b848cc1 --- /dev/null +++ b/December - 21/GREEDnim_day21_java.java @@ -0,0 +1,34 @@ +package acm; + +import java.util.Scanner; + +public class GREEDnim_day21_java { + + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + int disks=in.nextInt(); + towerOfHanoi("tower 1","tower 2","tower 3",disks); + } + public static void towerOfHanoi(String left,String middle,String right , int diskNo ) + { + if(diskNo==1) + { + System.out.println("move disk "+diskNo+" from "+left+" to "+ right); + return; + } + + towerOfHanoi(left,right,middle,diskNo-1); + System.out.println("move disk "+diskNo+" from "+left+" to "+ right); + towerOfHanoi(middle,left,right,diskNo-1); + + + + + + + } + + +} + + diff --git a/December - 21/Java_Ankur2606.java b/December - 21/Java_Ankur2606.java new file mode 100644 index 0000000..d853457 --- /dev/null +++ b/December - 21/Java_Ankur2606.java @@ -0,0 +1,30 @@ +import java.util.*; +public class Java_Ankur2606{ + public void move(int n, String left, String right, String middle){ + if(n == 1){ + System.out.println("Move disk "+n+" from tower "+left+" to tower "+right); + } + else{ + move(n-1,left,middle,right); + System.out.println("Move disk "+n+" from tower "+left+" to tower "+right); + move(n-1,middle,right,left); + } + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + System.out.print("Number of discs: "); + int n = sc.nextInt(); + + Java_Ankur2606 ob=new Java_Ankur2606(); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println("The sequence of moves :"); + ob.move(n,"I","III","II"); + } +} \ No newline at end of file diff --git a/December - 21/Java_souvikpal2000.java b/December - 21/Java_souvikpal2000.java new file mode 100644 index 0000000..2c4cd7b --- /dev/null +++ b/December - 21/Java_souvikpal2000.java @@ -0,0 +1,30 @@ +import java.util.*; +public class Java_souvikpal2000{ + public void move(int n, String left, String right, String middle){ + if(n == 1){ + System.out.println("Move disk "+n+" from tower "+left+" to tower "+right); + } + else{ + move(n-1,left,middle,right); + System.out.println("Move disk "+n+" from tower "+left+" to tower "+right); + move(n-1,middle,right,left); + } + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + System.out.print("Number of discs: "); + int n = sc.nextInt(); + + Java_souvikpal2000 ob=new Java_souvikpal2000(); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println("The sequence of moves :"); + ob.move(n,"I","III","II"); + } +} \ No newline at end of file diff --git a/December - 21/Java_tarpandas.java b/December - 21/Java_tarpandas.java new file mode 100644 index 0000000..0c274db --- /dev/null +++ b/December - 21/Java_tarpandas.java @@ -0,0 +1,28 @@ +import java.util.*; +public class Java_tarpandas{ + public void move(int n, String left, String right, String middle){ + if(n == 1){ + System.out.println("Move disk "+n+" from tower "+left+" to tower "+right); + } + else{ + move(n-1,left,middle,right); + System.out.println("Move disk "+n+" from tower "+left+" to tower "+right); + move(n-1,middle,right,left); + } + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.print("Number of discs: "); + int n = sc.nextInt(); + + Java_tarpandas ob=new Java_tarpandas(); + + System.out.println(""); + System.out.println(""); + System.out.println("The sequence of moves :"); + ob.move(n,"I","III","II"); + sc.close(); + } +} \ No newline at end of file diff --git a/December - 21/cpp_Aadhi11.cpp b/December - 21/cpp_Aadhi11.cpp new file mode 100644 index 0000000..4dc9203 --- /dev/null +++ b/December - 21/cpp_Aadhi11.cpp @@ -0,0 +1,104 @@ +#include +using namespace std; +#include +#include + +int transfer_disk(stack& a,stack& b){ + if(b.empty()==true){ + b.push(a.top()); + a.pop(); + return 1; + } + else if(a.empty()==true){ + a.push(b.top()); + b.pop(); + return 2; + } + else{ + if(b.top()>a.top()){ + b.push(a.top()); + a.pop(); + return 1; + } + else{ + a.push(b.top()); + b.pop(); + return 2; + } + } +} + +int main(){ + stack s,a,d; + int n=0; + cout<<"Number of discs: "; + cin>>n; + for(int i=n;i>=1;i--){ + s.push(i); + } + + int x=pow(2,n)-1; + int i=1; + cout< + +using namespace std; + +void hanoi(int disks, char source, char auxillary, char destination); + +int main (int argc, char *argv[]) +{ + int disks; + cout<<"Number of disks: "; + cin>>disks; + hanoi(disks, 'A', 'B', 'C'); + return 0; +} + +void hanoi(int disk, char source, char auxillary, char destination){ + if(disk==1) { + cout<<"Move disk "< +using namespace std; + +void towerOfHanoi(int totalDisc, string A, string B, string C){ + if(totalDisc > 0) + { + towerOfHanoi(totalDisc-1, A, C, B); + cout << "Move disk " << totalDisc << " from tower " << A << " to tower " << C << endl; + towerOfHanoi(totalDisc-1, B, A, C); + } +} + +int main(){ + int totalDisc; + cin >> totalDisc; + towerOfHanoi(totalDisc, "I", "II", "III"); + return 0; +} diff --git a/December - 21/java_DCBisht21.java b/December - 21/java_DCBisht21.java new file mode 100644 index 0000000..ab37e86 --- /dev/null +++ b/December - 21/java_DCBisht21.java @@ -0,0 +1,22 @@ +import java.util.*; + +public class java_DCBisht21 { + public static void main(String[] args) { + Scanner in = new Scanner(System.in); + int disks = in.nextInt(); + System.out.println("The sequence of moves :"); + towerOfHanoi("tower I", "tower II", "tower III", disks); + in.close(); + } + + public static void towerOfHanoi(String left, String middle, String right, int diskNo) { + if (diskNo == 1) { + System.out.println("Move disk " + diskNo + " from " + left + " to " + right); + return; + } + + towerOfHanoi(left, right, middle, diskNo - 1); + System.out.println("Move disk " + diskNo + " from " + left + " to " + right); + towerOfHanoi(middle, left, right, diskNo - 1); + } +} diff --git a/December - 22/.gitignore b/December - 22/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 22/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 22/C++_Dhruv.cpp b/December - 22/C++_Dhruv.cpp new file mode 100644 index 0000000..4be9493 --- /dev/null +++ b/December - 22/C++_Dhruv.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +string encode(string codeword, string message) { + int n = codeword.length(); + int m = message.length(); + string encoded_message = ""; + for (int i = 0; i < m; i++) { + char c = message[i]; + int k = codeword[i % n] - 'A'; + char e = (c + k - 'A') % 26 + 'A'; + encoded_message += e; + } + return encoded_message; +} + +int main() { + string codeword = "LEMON"; + string message = "ATTACKATDAWN"; + string encoded_message = encode(codeword, message); + cout << encoded_message << endl; + return 0; +} diff --git a/December - 22/C++_MugundhanY.cpp b/December - 22/C++_MugundhanY.cpp new file mode 100644 index 0000000..7cbbd1b --- /dev/null +++ b/December - 22/C++_MugundhanY.cpp @@ -0,0 +1,24 @@ +//Question 22: +#include +using namespace std; + +void TheMarkowitzParadox(char a, char b){ + int c = a - 'A'; + int e = ((int(b) + c)-65)%26; + char d = 65 + e; + cout << d; + } +int main(){ + string a, b; + cin >> a; + cin >> b; + char* a1 = &a[0]; + char* b1 = &b[0]; + int n1 = a.size(), n2 = b.size(), x=0, i=0; + while(i + +using namespace std; + +int main(){ + + string maps = "HOTDOG"; + string word ="CONEYISLANDONFRI"; + int j=0,index=0; + string codeword; + + + for(int i=0;i90) + codeword[index]=64+word[i]+(maps[j]-'A')-90; + else + codeword[index] = word[i]+ (maps[j]-'A'); + + index++; + j++; + if(j>maps.length()-1) + j=0; + } + cout<<"*Encoded Word"; + for (int i = 0; i < word.length(); ++i) + cout< 90){ + int diff = sum - 90; + encrypt = encrypt + (char)(64 + diff); + + }else{ + encrypt = encrypt + (char)sum; + } + j++; + } + return encrypt; + } + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + String codeword = sc.next(); + String message = sc.next(); + + Java_Ankur2606 ob=new Java_Ankur2606(); + String encrypt = ob.theMarkowitzParadox(codeword.toUpperCase(),message.toUpperCase()); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(encrypt); + } +} \ No newline at end of file diff --git a/December - 22/Java_souvikpal2000.java b/December - 22/Java_souvikpal2000.java new file mode 100644 index 0000000..fccca8f --- /dev/null +++ b/December - 22/Java_souvikpal2000.java @@ -0,0 +1,42 @@ +import java.util.*; +public class Java_souvikpal2000{ + public String theMarkowitzParadox(String codeword, String message){ + String encrypt = ""; + int length = message.length(); + int l = codeword.length(); + int j = 0; + for(int i=0;i 90){ + int diff = sum - 90; + encrypt = encrypt + (char)(64 + diff); + + }else{ + encrypt = encrypt + (char)sum; + } + j++; + } + return encrypt; + } + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + String codeword = sc.next(); + String message = sc.next(); + + Java_souvikpal2000 ob=new Java_souvikpal2000(); + String encrypt = ob.theMarkowitzParadox(codeword.toUpperCase(),message.toUpperCase()); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(encrypt); + } +} \ No newline at end of file diff --git a/December - 22/Java_tarpandas.java b/December - 22/Java_tarpandas.java new file mode 100644 index 0000000..6611fb9 --- /dev/null +++ b/December - 22/Java_tarpandas.java @@ -0,0 +1,41 @@ +import java.util.*; +public class Java_tarpandas{ + public String theMarkowitzParadox(String codeword, String message){ + String encrypt = ""; + int length = message.length(); + int l = codeword.length(); + int j = 0; + for(int i=0;i 90){ + int diff = sum - 90; + encrypt = encrypt + (char)(64 + diff); + + }else{ + encrypt = encrypt + (char)sum; + } + j++; + } + return encrypt; + } + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + String codeword = sc.next(); + String message = sc.next(); + + Java_tarpandas ob=new Java_tarpandas(); + String encrypt = ob.theMarkowitzParadox(codeword.toUpperCase(),message.toUpperCase()); + + System.out.println(""); + System.out.println(encrypt); + + sc.close(); + } +} \ No newline at end of file diff --git a/December - 22/cpp_Aadhi11.cpp b/December - 22/cpp_Aadhi11.cpp new file mode 100644 index 0000000..b4f93a0 --- /dev/null +++ b/December - 22/cpp_Aadhi11.cpp @@ -0,0 +1,211 @@ +#include +#include + using namespace std; + + int main() + { + string s1,s2; + int a[100],b[100],h=0; + cin>>s1; + int k=s1.length(); + for(int i=0;i>s2; + int p=s2.length(); + cout<90) + { + q = q-26; + } + c[i]=q; + } + for(int i=0;i +using namespace std; + +void TheMarkowitzParadox(char a, char b){ + int c = a - 'A'; + int e = ((int(b) + c)-65)%26; + char d = 65 + e; + cout << d; + } +int main(){ + string a, b; + cin >> a; + cin >> b; + char* a1 = &a[0]; + char* b1 = &b[0]; + int n1 = a.size(), n2 = b.size(), x=0, i=0; + while(i90){ + x=x-26; + } + char c=(char)x; + ans=ans+c; + + } + System.out.println(ans); + sc.close(); + } +} diff --git a/December - 23/.gitignore b/December - 23/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 23/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 23/GREEDnim_day23_java.java b/December - 23/GREEDnim_day23_java.java new file mode 100644 index 0000000..f28695f --- /dev/null +++ b/December - 23/GREEDnim_day23_java.java @@ -0,0 +1,78 @@ +package acm; + +import java.util.*; + +public class GREEDnim_day23_java { + public static void main(String[] args) { + +// int roomCount=2; +// int[][] ques={{0,10},{1,5},{2,7},{3,4}}; + + int roomCount=3; + int[][]ques={{1,20},{2,10},{3,5},{4,9},{6,8}}; + int noOfProcess=ques.length; + List>inp=new ArrayList<>(); + + for(int[] arr:ques) + { + Listlist=new ArrayList<>(); + list.add(arr[0]); + list.add(arr[1]); + inp.add(list); + } + + Collections.sort(inp, new Comparator<>() { + + public int compare(List a, List b) { + if (a.get(0) < b.get(0) || (int)a.get(0) == (int)b.get(0) && a.get(1) < b.get(1)) return -1; + return 1; + } + }); + + int[] rooms=new int[roomCount]; + int[] timeRemaining=new int[roomCount]; + + int processCompleted=0; + while(processCompleted=0) + { + rooms[room]++; + timeRemaining[room]=inp.get(processCompleted).get(1)-inp.get(processCompleted).get(0) ; + processCompleted++; + } + reduceTime(timeRemaining); + } + int max=Integer.MIN_VALUE; + int roomNo=0; + for(int i=0;imax) + { + roomNo=i; + max=rooms[i]; + } + } + + System.out.println(roomNo); + + } + public static int freeRoom(int[] t) + { + + for(int i=0;i0) t[i]--; + + } + } +} diff --git a/December - 23/Java_souvikpal2000.java b/December - 23/Java_souvikpal2000.java new file mode 100644 index 0000000..97a0381 --- /dev/null +++ b/December - 23/Java_souvikpal2000.java @@ -0,0 +1,114 @@ +import java.util.*; +class Room{ + int allocatedTime; + int count; + Room(int allocatedTime, int count){ + this.allocatedTime = allocatedTime; + this.count = count; + } +} +public class Java_souvikpal2000{ + public List allocateRooms(int n){ + List list = new ArrayList<>(); + for(int i=0;i meetings[j][0]){ + start = meetings[i][0]; + meetings[i][0] = meetings[j][0]; + meetings[j][0] = start; + + end = meetings[i][1]; + meetings[i][1] = meetings[j][1]; + meetings[j][1] = end; + } + } + } + return meetings; + } + + public List meetingRooms(int[][] meetings, int n, List rooms){ + int time = 0; + int i = -1; + while(i meetings.length-1){ + break; + } + room.allocatedTime = Math.abs(meetings[i][0] - meetings[i][1]); + room.count = room.count + 1; + } + /*for(Room r : rooms){ + System.out.println(r.allocatedTime+" "+r.count); + } + System.out.println("");*/ + time++; + } + + return rooms; + } + + public int findRoomWithMaxMeetings(List rooms){ + int roomNo = 0; + int noOfMeetings = 0; + int roomWithMaxMeetings = 0; + for(Room r : rooms){ + if(r.count > noOfMeetings){ + noOfMeetings = r.count; + roomWithMaxMeetings = roomNo; + } + roomNo++; + } + return roomWithMaxMeetings; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + // Input 1: + int n = 2; //Number of Rooms + int[][] meetings = { + {0,10},{1,5},{2,7},{3,4} + }; + + //Input 2: + /*int n = 3; //Number of Rooms + int[][] meetings = { + {1,20},{2,10},{3,5},{4,9},{6,8} + };*/ + + Java_souvikpal2000 ob=new Java_souvikpal2000(); + List rooms = ob.allocateRooms(n); + int[][] sortedMeetings = ob.sortMeetings(meetings); + List meetingsEnd = ob.meetingRooms(sortedMeetings,n,rooms); + int roomNo = ob.findRoomWithMaxMeetings(meetingsEnd); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(roomNo); + } +} \ No newline at end of file diff --git a/December - 23/Java_tarpandas.java b/December - 23/Java_tarpandas.java new file mode 100644 index 0000000..1c95dda --- /dev/null +++ b/December - 23/Java_tarpandas.java @@ -0,0 +1,104 @@ +import java.util.*; +class Room{ + int allocatedTime; + int count; + Room(int allocatedTime, int count){ + this.allocatedTime = allocatedTime; + this.count = count; + } +} +public class Java_tarpandas{ + public List allocateRooms(int n){ + List list = new ArrayList<>(); + for(int i=0;i meetings[j][0]){ + start = meetings[i][0]; + meetings[i][0] = meetings[j][0]; + meetings[j][0] = start; + + end = meetings[i][1]; + meetings[i][1] = meetings[j][1]; + meetings[j][1] = end; + } + } + } + return meetings; + } + + public List meetingRooms(int[][] meetings, int n, List rooms){ + int time = 0; + int i = -1; + while(i meetings.length-1){ + break; + } + room.allocatedTime = Math.abs(meetings[i][0] - meetings[i][1]); + room.count = room.count + 1; + } + time++; + } + + return rooms; + } + + public int findRoomWithMaxMeetings(List rooms){ + int roomNo = 0; + int noOfMeetings = 0; + int roomWithMaxMeetings = 0; + for(Room r : rooms){ + if(r.count > noOfMeetings){ + noOfMeetings = r.count; + roomWithMaxMeetings = roomNo; + } + roomNo++; + } + return roomWithMaxMeetings; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + // Input 1: + int n = 2; //Number of Rooms + int[][] meetings = { + {0,10},{1,5},{2,7},{3,4} + }; + + Java_tarpandas ob=new Java_tarpandas(); + List rooms = ob.allocateRooms(n); + int[][] sortedMeetings = ob.sortMeetings(meetings); + List meetingsEnd = ob.meetingRooms(sortedMeetings,n,rooms); + int roomNo = ob.findRoomWithMaxMeetings(meetingsEnd); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(roomNo); + } +} \ No newline at end of file diff --git a/December - 23/cpp_Aadhi11.cpp b/December - 23/cpp_Aadhi11.cpp new file mode 100644 index 0000000..144a3b2 --- /dev/null +++ b/December - 23/cpp_Aadhi11.cpp @@ -0,0 +1,72 @@ +#include +#include +using namespace std; +bool compare(vector& v1, vector& v2) { + return v1[0] < v2[0]; +} +class Solution { +public: + int mostBooked(int n, vector>& meetings) { + sort(meetings.begin(), meetings.end(), compare); + + priority_queue, vector>, greater>> engaged; + + priority_queue, greater> unused; + + unordered_map freq; + + for(int i = 0; i < n; i++) { + unused.push(i); + } + + for(auto x:meetings) { + int s = x[0], e = x[1]; + + while(engaged.size() > 0 && engaged.top().first <= s) { + int room = engaged.top().second; + engaged.pop(); + + unused.push(room); + } + + if(unused.size() > 0) + { + int room = unused.top(); + unused.pop(); + + freq[abs(room)] += 1; + + engaged.push({e, room}); + } + else + { + pair topmost = engaged.top(); + engaged.pop(); + + freq[abs(topmost.second)] += 1; + + long long newEnd = topmost.first; + newEnd += (e - s); + + engaged.push({newEnd, topmost.second}); + } + } + + int maxi = 0; + for(int i = 1; i < n; i++) { + if(freq[i] > freq[maxi]) + maxi = i; + } + return maxi; + } +}; + +int main() +{ + Solution s; + int n = 3; + vector> meetings = {{1,20},{2,10},{3,5},{4,9},{6,8}}; + cout<>inp=new ArrayList<>(); + + for(int[] arr:ques) + { + Listlist=new ArrayList<>(); + list.add(arr[0]); + list.add(arr[1]); + inp.add(list); + } + + Collections.sort(inp, new Comparator<>() { + + public int compare(List a, List b) { + if (a.get(0) < b.get(0) || (int)a.get(0) == (int)b.get(0) && a.get(1) < b.get(1)) return -1; + return 1; + } + }); + + int[] rooms=new int[roomCount]; + int[] timeRemaining=new int[roomCount]; + + int processCompleted=0; + while(processCompleted=0) + { + rooms[room]++; + timeRemaining[room]=inp.get(processCompleted).get(1)-inp.get(processCompleted).get(0) ; + processCompleted++; + } + reduceTime(timeRemaining); + } + int max=Integer.MIN_VALUE; + int roomNo=0; + for(int i=0;imax) + { + roomNo=i; + max=rooms[i]; + } + } + + System.out.println(roomNo); + sc.close(); + } + public static int freeRoom(int[] t) + { + + for(int i=0;i0) t[i]--; + + } + } +} diff --git a/December - 24/.gitignore b/December - 24/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 24/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 24/cpp_Aadhi11.cpp b/December - 24/cpp_Aadhi11.cpp new file mode 100644 index 0000000..809f390 --- /dev/null +++ b/December - 24/cpp_Aadhi11.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; +class Solution { +public: + set visited; + string ret; + string crackSafe(int n, int k) { + if(n == 1 && k == 1) return "0"; + ret = ""; + string s = ""; + for(int i = 0; i < n - 1; i++){ + s += "0"; + } + dfs(s, k); + for(int i = 0; i < n - 1; i++) ret += "0"; + return ret; + } + void dfs(string s, int k) { + string temp; + for(int i = 0; i < k; i++){ + temp = s + to_string(i); + if(!visited.count(temp)){ + visited.insert(temp); + temp = temp.substr(1); + dfs(temp, k); + ret += to_string(i); + } + } + } +}; + int main(){ + Solution ob; + int n,k; + cout<<"n = "; + cin>>n; + cout<<"k = "; + cin>>k; + cout <<"'"<< (ob.crackSafe(n,k))<<"'"; +} + + diff --git a/December - 24/java_DCBisht24.java b/December - 24/java_DCBisht24.java new file mode 100644 index 0000000..64b3456 --- /dev/null +++ b/December - 24/java_DCBisht24.java @@ -0,0 +1,59 @@ +import java.util.*;; + +public class java_DCBisht24 { + public static void main(String[] args) { + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int k=sc.nextInt(); + java_DCBisht24 ob= new java_DCBisht24(); + String s=ob.crackSafe(n, k); + System.out.println(s); + + sc.close(); + } + public String crackSafe(int n, int k) { + // String is immutable, use StringBuilder + StringBuilder result = new StringBuilder(); + // This is total number of permutation we need in the set + int total = (int) (Math.pow(k, n)); + + // This is just for fun and to prove that we can start with any permutation + Random rand = new Random(); + for (int i = 0; i < n; i++) { + result.append(rand.nextInt(k)); + } + + Set visited = new HashSet<>(); + visited.add(result.toString()); + + dfs(result, total, visited, n, k); + + return result.toString(); + } + + private boolean dfs(StringBuilder result, int target, Set visited, int n, int k) { + if (visited.size() == target) { + // We are done, terminate all recursion + return true; + } + String prev = result.substring(result.length() - n + 1, result.length()); + for (int i = 0; i < k; i++) { + String next = prev + i; + if (!visited.contains(next)) { + visited.add(next); + result.append(i); + if (dfs(result, target, visited, n, k)) { + // recursively terminate, we are done + return true; + } + else { + // We got stuck so this will not yield optimal path, go back + // Try other path + visited.remove(next); + result.delete(result.length() - 1, result.length()); + } + } + } + return false; + } +} diff --git a/December - 25/.gitignore b/December - 25/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 25/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 25/cpp_Aadhi11.cpp b/December - 25/cpp_Aadhi11.cpp new file mode 100644 index 0000000..83db599 --- /dev/null +++ b/December - 25/cpp_Aadhi11.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include + +using namespace std; + +const int kMaxn = 3e3 + 10, kMaxq = 1e5 + 10; +int ans[kMaxq], pos[kMaxn], tar[kMaxn]; +long long b[kMaxn]; +pair a[kMaxn]; +struct ques { + int t, k, id; +} q[kMaxq]; + +int main() { + double start = clock(); + int t; + scanf("%d", &t); + int n; + for (; scanf("%d", &n) == 1; ) { + assert(n <= 3000); + for (int i = 1; i <= n; ++i) { + scanf("%d%d", &a[i].first, &a[i].second); + } + int Q; + scanf("%d", &Q); + assert(Q <= 100000); + for (int i = 1; i <= Q; ++i) { + scanf("%d%d", &q[i].t, &q[i].k); + q[i].id = i; + } + sort(q + 1, q + Q + 1, + [](const ques &a, const ques &b) { + return a.t < b.t; + } + ); + for (int i = 1; i <= n; ++i) { + pos[i] = tar[i] = i; + } + sort(tar + 1, tar + n + 1, + [&](const int x, const int y) { + return a[x].first < a[y].first + || (a[x].first == a[y].first && x > y); + } + ); + int st = 1; + for (int i = 1; i <= Q; ++i) { + for (int j = st; j <= n; ++j) { + b[j] = a[j].second + 1ll * a[j].first * q[i].t; + } + for (int j = st + 1; j <= n; ++j) { + for (int k = j; k > st && (b[pos[k]] < b[pos[k - 1]] + || (b[pos[k]] == b[pos[k - 1]] && pos[k] > pos[k - 1])); --k) { + swap(pos[k], pos[k - 1]); + } + } + ans[q[i].id] = pos[n - q[i].k + 1]; + for (; st <= n && pos[st] == tar[st]; ++st) {} + } + printf("\n"); + for (int i = 1; i <= Q; ++i) { + printf("%d\n", ans[i]); + } + } + return 0; +} + diff --git a/December - 25/cpp_DCBisht.cpp b/December - 25/cpp_DCBisht.cpp new file mode 100644 index 0000000..22e63d3 --- /dev/null +++ b/December - 25/cpp_DCBisht.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include + +using namespace std; + +const int kMaxn = 3e3 + 10, kMaxq = 1e5 + 10; +int ans[kMaxq], pos[kMaxn], tar[kMaxn]; +long long b[kMaxn]; +pair a[kMaxn]; +struct ques +{ + int t, k, id; +} q[kMaxq]; + +int main() +{ + double start = clock(); + int t; + scanf("%d", &t); + int n; + for (; scanf("%d", &n) == 1;) + { + assert(n <= 3000); + for (int i = 1; i <= n; ++i) + { + scanf("%d%d", &a[i].first, &a[i].second); + } + int Q; + scanf("%d", &Q); + assert(Q <= 100000); + for (int i = 1; i <= Q; ++i) + { + scanf("%d%d", &q[i].t, &q[i].k); + q[i].id = i; + } + sort(q + 1, q + Q + 1, + [](const ques &a, const ques &b) + { + return a.t < b.t; + }); + for (int i = 1; i <= n; ++i) + { + pos[i] = tar[i] = i; + } + sort(tar + 1, tar + n + 1, + [&](const int x, const int y) + { + return a[x].first < a[y].first || (a[x].first == a[y].first && x > y); + }); + int st = 1; + for (int i = 1; i <= Q; ++i) + { + for (int j = st; j <= n; ++j) + { + b[j] = a[j].second + 1ll * a[j].first * q[i].t; + } + for (int j = st + 1; j <= n; ++j) + { + for (int k = j; k > st && (b[pos[k]] < b[pos[k - 1]] || (b[pos[k]] == b[pos[k - 1]] && pos[k] > pos[k - 1])); --k) + { + swap(pos[k], pos[k - 1]); + } + } + ans[q[i].id] = pos[n - q[i].k + 1]; + for (; st <= n && pos[st] == tar[st]; ++st) + { + } + } + printf("\n"); + for (int i = 1; i <= Q; ++i) + { + printf("%d\n", ans[i]); + } + } + return 0; +} \ No newline at end of file diff --git a/December - 26/.gitignore b/December - 26/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 26/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 26/GREEDnim_day26_java.java b/December - 26/GREEDnim_day26_java.java new file mode 100644 index 0000000..9a8a2f6 --- /dev/null +++ b/December - 26/GREEDnim_day26_java.java @@ -0,0 +1,47 @@ +package acm; + +import java.util.Arrays; +import java.util.LinkedList; +import java.util.Queue; + +public class GREEDnim_day26_java { + + public static void main(String[] args) { +// int[][] arr={{2}, {3, 4}, {2}, {2}}; + int[][] arr={{2}, {5, 4, 6}, {3}, {4}, {5}, {6}}; + boolean[] heard=new boolean[arr.length+1]; + heard[1]=true; + Queueq=new LinkedList<>(); + for(int ele: arr[0]) + { + q.offer(ele); + } + + while(!q.isEmpty()) + { + int size=q.size(); + for(int i=0;i +#include +using namespace std; + +int main() +{ + vector > vec={{2},{5,4,6},{3},{4},{5},{6}}; + int n = vec.size(); + bool per[10]; + for(int i=0;i q = new LinkedList<>(); + for (int ele : arr[0]) { + q.offer(ele); + } + + while (!q.isEmpty()) { + int size = q.size(); + for (int i = 0; i < size; i++) { + Integer ele = q.poll(); + heard[ele] = true; + for (int x : arr[ele - 1]) { + if (!heard[x]) + q.offer(x); + } + } + } + + boolean spread = true; + for (int i = 1; i < heard.length; i++) { + if (!heard[i]) { + spread = false; + break; + } + } + if (spread) + System.out.println("SPREAD"); + else + System.out.println("NOPE"); + + } +} \ No newline at end of file diff --git a/December - 26/python_subburamanathan7.py b/December - 26/python_subburamanathan7.py new file mode 100644 index 0000000..d003b95 --- /dev/null +++ b/December - 26/python_subburamanathan7.py @@ -0,0 +1,15 @@ +people = [[2], [3, 4], [2], [2]] +spread={} +for i in range(len(people)): + spread[i+1]=1 +spread.pop(1) + +for i in range(len(people)): + for j in range(len(people[i])): + if(i+1!=people[i][j] and people[i][j] in spread): + spread.pop(people[i][j]) + +if(len(spread)==0): + print("Spread") +else: + print("Not Spread") diff --git a/December - 27/.gitignore b/December - 27/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 27/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 27/C++_subburamanathan7.cpp b/December - 27/C++_subburamanathan7.cpp new file mode 100644 index 0000000..8b35a4d --- /dev/null +++ b/December - 27/C++_subburamanathan7.cpp @@ -0,0 +1,42 @@ +#include + +using namespace std; + +int main(){ + float X,Y; + char Status; + float fuelCalibration; + + long int capacity =30000; + + while(true){ + char* fraction; + cout<<"\nEnter fraction: X/Y:"; + cin>>fraction; + sscanf(fraction, "%f/%f", &X, &Y); + if(X && Y) + break; + else + cout<<"\n Enter again"; + } + fuelCalibration=(X/Y); + fuelCalibration*=100; + if(fuelCalibration<=1){ + Status='E'; + cout<<"\nFuelCalibration: "<=99){ + Status='F'; + cout<<"\nFuelCalibration: "<= 99){ + msg = "ok"; + } + return msg; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + int x,y; + while(true){ + System.out.println("Enter the Hydrogen fuel fraction:"); + String fraction = sc.next(); + + String[] xy = fraction.split("/"); + try{ + x = Integer.parseInt(xy[0]); + y = Integer.parseInt(xy[1]); + if(y == 0){ + throw new InvalidDenominator("Y must not be Zero"); + } + if(x > y){ + throw new InvalidNumerator("X must be less than Y"); + } + break; + } + catch(NumberFormatException e){ + System.out.println("X & Y must be Integer"); + } + catch(InvalidDenominator e){ + System.out.println(e); + } + catch(InvalidNumerator e){ + System.out.println(e); + } + System.out.println(""); + } + + float totalFuel = 30000f; + Java_souvikpal2000 ob=new Java_souvikpal2000(); + float result = ob.calculateFuelCalibration(x,y); + String leftFuel = ob.calculateLeftFuel(x,y,totalFuel); + String flag = ob.checkTank(result); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println("Fuel calibration: "+String.format("%.3f",result)+"%"); + System.out.println("Amount of fuel in tank: "+leftFuel+" L out of "+totalFuel+" L"); + + if(flag.equals("ok")){ + System.out.println("The tank is FULL!"); + }else if(flag.equals("warning")){ + System.out.println("The tank is EMPTY!!!"); + System.out.println("Refill tank"); + } + } +} \ No newline at end of file diff --git a/December - 27/Java_tarpandas.java b/December - 27/Java_tarpandas.java new file mode 100644 index 0000000..db29a72 --- /dev/null +++ b/December - 27/Java_tarpandas.java @@ -0,0 +1,88 @@ +import java.util.*; +class InvalidNumerator extends Exception{ + public InvalidNumerator(String str){ + super(str); + } +} +class InvalidDenominator extends Exception{ + public InvalidDenominator(String str){ + super(str); + } +} +class Java_tarpandas{ + public float calculateFuelCalibration(int x, int y){ + float percentage = ((float)x*100)/(float)y; + return percentage; + } + + public String calculateLeftFuel(int x, int y, float totalFuel){ + float leftFuel = ((float)x * totalFuel)/(float)y; + return String.format("%.1f",leftFuel); + } + + public String checkTank(float result){ + String msg = ""; + if(result <= 1){ + msg = "warning"; + } + if(result >= 99){ + msg = "ok"; + } + return msg; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + int x,y; + while(true){ + System.out.println("Enter the Hydrogen fuel fraction:"); + String fraction = sc.next(); + + String[] xy = fraction.split("/"); + try{ + x = Integer.parseInt(xy[0]); + y = Integer.parseInt(xy[1]); + if(y == 0){ + throw new InvalidDenominator("Y must not be Zero"); + } + if(x > y){ + throw new InvalidNumerator("X must be less than Y"); + } + break; + } + catch(NumberFormatException e){ + System.out.println("X & Y must be Integer"); + } + catch(InvalidDenominator e){ + System.out.println(e); + } + catch(InvalidNumerator e){ + System.out.println(e); + } + System.out.println(""); + } + + float totalFuel = 30000f; + Java_tarpandas ob=new Java_tarpandas(); + float result = ob.calculateFuelCalibration(x,y); + String leftFuel = ob.calculateLeftFuel(x,y,totalFuel); + String flag = ob.checkTank(result); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println("Fuel calibration: "+String.format("%.3f",result)+"%"); + System.out.println("Amount of fuel in tank: "+leftFuel+" L out of "+totalFuel+" L"); + + if(flag.equals("ok")){ + System.out.println("The tank is FULL!"); + }else if(flag.equals("warning")){ + System.out.println("The tank is EMPTY!!!"); + System.out.println("Refill tank"); + } + sc.close(); + } +} \ No newline at end of file diff --git a/December - 27/cpp_Aadhi11.cpp b/December - 27/cpp_Aadhi11.cpp new file mode 100644 index 0000000..4cccb6e --- /dev/null +++ b/December - 27/cpp_Aadhi11.cpp @@ -0,0 +1,33 @@ +#include +#include +#include +using namespace std; +#include +int main() +{ + float p,fracNume,fracDeno,f; + cout<<"Enter the Hydrogen fuel fraction:"<>fracNume>>fracDeno; + try + { + if(fracDeno==0) + throw 'e'; + else + p=(fracNume/fracDeno)*100; + } + catch(char e) + { + cout<=99) + cout<<"The tank is FULL!"; + if(b<=1) + cout<<"The tank is EMPTY!!!"<y || y==0){ + System.out.println("Error"); + f=false; + } + if(f){ + float a,b; + a=x; + b=y; + float ans=30000f; + float z=0.000f; + z=(a/b)*100; + DecimalFormat df = new DecimalFormat(); + df.setMaximumFractionDigits(3); + DecimalFormat df1 = new DecimalFormat(); + df1.setMaximumFractionDigits(1); + // System.out.println(x+" "+y); + ans=(ans*z/100); + + System.out.println("Fuel calibration: "+df.format(z)+"%"); + System.out.println("Amount of fuel in tank: "+df1.format(ans)+" L out of 30,000 L"); + if(ans<300){ + System.out.println("The tank is EMPTY!!!"); + System.out.println("Refill tank."); + } + else if(ans>29700){ + System.out.println("The tank is FULL!"); + } + } + sc.close(); + } +} diff --git a/December - 28/.gitignore b/December - 28/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 28/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 28/Java_souvikpal2000.java b/December - 28/Java_souvikpal2000.java new file mode 100644 index 0000000..7217216 --- /dev/null +++ b/December - 28/Java_souvikpal2000.java @@ -0,0 +1,142 @@ +import java.util.*; +public class Java_souvikpal2000{ + public int findFirstSmallest(List tail){ + int firstSmallest = Integer.MAX_VALUE; + for(Integer tailie : tail){ + if(firstSmallest > tailie){ + firstSmallest = tailie; + } + } + return firstSmallest; + } + + public int findSecondSmallest(List tail, int firstSmallest){ + int secondSmallest = Integer.MAX_VALUE; + for(Integer tailie : tail){ + if(secondSmallest > tailie){ + int flag = tailie; + if(flag > firstSmallest){ + secondSmallest = flag; + } + } + } + return secondSmallest; + } + + public int findFirstLargest(List tail){ + int firstLargest = Integer.MIN_VALUE; + for(Integer tailie : tail){ + if(firstLargest < tailie){ + firstLargest = tailie; + } + } + return firstLargest; + } + + public int findSecondLargest(List tail, int firstLargest){ + int secondLargest = Integer.MIN_VALUE; + for(Integer tailie : tail){ + if(secondLargest < tailie){ + int flag = tailie; + if(flag < firstLargest){ + secondLargest = flag; + } + } + } + return secondLargest; + } + + public int minimumBetweenTwo(int a, int b){ + int min = a tail, int n){ + int firstSmallest = findFirstSmallest(tail); + int secondSmallest = findSecondSmallest(tail,firstSmallest); + + int travelTime = 0; + + while(true){ + if(tail.size() == 3){ + int firstLargest = findFirstLargest(tail); + travelTime = travelTime + (secondSmallest + firstSmallest + firstLargest); + break; + } + if(tail.size() == 2){ + travelTime = travelTime + secondSmallest; + break; + } + else{ + int firstLargest = findFirstLargest(tail); + int secondLargest = findSecondLargest(tail,firstLargest); + + int result01 = firstApproach(firstLargest,secondLargest,firstSmallest); + int result02 = secondApproach(firstLargest,firstSmallest,secondSmallest); + + tail.remove(tail.indexOf(firstLargest)); + tail.remove(tail.indexOf(secondLargest)); + + int minTime = minimumBetweenTwo(result01,result02); + + travelTime = travelTime + minTime; + } + } + + return travelTime; + } + + public float secondsToMinutes(int time){ + float timeInMinutes = (float)time/60; + return timeInMinutes; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + int n; + while(true){ + System.out.print("n="); + n = sc.nextInt(); + System.out.println(""); + + if(n >= 3){ + break; + }else{ + System.out.println("There needs to be at least 3 Tailies"); + System.out.println(""); + } + } + + System.out.print("Walking time: "); + int[] walkingTime = new int[n]; + for(int i=0;i tail = new ArrayList<>(); + for(int time : walkingTime){ + tail.add(time); + } + + Java_souvikpal2000 ob=new Java_souvikpal2000(); + int timeInSeconds = ob.theJourneyToTheEternalEngine(tail,n); + float timeInMinutes = ob.secondsToMinutes(timeInSeconds); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(String.format("%.3f",timeInMinutes)); + } +} \ No newline at end of file diff --git a/December - 28/Java_tarpandas.java b/December - 28/Java_tarpandas.java new file mode 100644 index 0000000..aa2666b --- /dev/null +++ b/December - 28/Java_tarpandas.java @@ -0,0 +1,142 @@ +import java.util.*; +public class Java_tarpandas{ + public int findFirstSmallest(List tail){ + int firstSmallest = Integer.MAX_VALUE; + for(Integer tailie : tail){ + if(firstSmallest > tailie){ + firstSmallest = tailie; + } + } + return firstSmallest; + } + + public int findSecondSmallest(List tail, int firstSmallest){ + int secondSmallest = Integer.MAX_VALUE; + for(Integer tailie : tail){ + if(secondSmallest > tailie){ + int flag = tailie; + if(flag > firstSmallest){ + secondSmallest = flag; + } + } + } + return secondSmallest; + } + + public int findFirstLargest(List tail){ + int firstLargest = Integer.MIN_VALUE; + for(Integer tailie : tail){ + if(firstLargest < tailie){ + firstLargest = tailie; + } + } + return firstLargest; + } + + public int findSecondLargest(List tail, int firstLargest){ + int secondLargest = Integer.MIN_VALUE; + for(Integer tailie : tail){ + if(secondLargest < tailie){ + int flag = tailie; + if(flag < firstLargest){ + secondLargest = flag; + } + } + } + return secondLargest; + } + + public int minimumBetweenTwo(int a, int b){ + int min = a tail, int n){ + int firstSmallest = findFirstSmallest(tail); + int secondSmallest = findSecondSmallest(tail,firstSmallest); + + int travelTime = 0; + + while(true){ + if(tail.size() == 3){ + int firstLargest = findFirstLargest(tail); + travelTime = travelTime + (secondSmallest + firstSmallest + firstLargest); + break; + } + if(tail.size() == 2){ + travelTime = travelTime + secondSmallest; + break; + } + else{ + int firstLargest = findFirstLargest(tail); + int secondLargest = findSecondLargest(tail,firstLargest); + + int result01 = firstApproach(firstLargest,secondLargest,firstSmallest); + int result02 = secondApproach(firstLargest,firstSmallest,secondSmallest); + + tail.remove(tail.indexOf(firstLargest)); + tail.remove(tail.indexOf(secondLargest)); + + int minTime = minimumBetweenTwo(result01,result02); + + travelTime = travelTime + minTime; + } + } + + return travelTime; + } + + public float secondsToMinutes(int time){ + float timeInMinutes = (float)time/60; + return timeInMinutes; + } + + public static void main(String args[]){ + Scanner sc=new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + int n; + while(true){ + System.out.print("n="); + n = sc.nextInt(); + System.out.println(""); + + if(n >= 3){ + break; + }else{ + System.out.println("There needs to be at least 3 Tailies"); + System.out.println(""); + } + } + + System.out.print("Walking time: "); + int[] walkingTime = new int[n]; + for(int i=0;i tail = new ArrayList<>(); + for(int time : walkingTime){ + tail.add(time); + } + + Java_tarpandas ob=new Java_tarpandas(); + int timeInSeconds = ob.theJourneyToTheEternalEngine(tail,n); + float timeInMinutes = ob.secondsToMinutes(timeInSeconds); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(String.format("%.3f",timeInMinutes)); + } +} \ No newline at end of file diff --git a/December - 28/cpp_Aadhi11.cpp b/December - 28/cpp_Aadhi11.cpp new file mode 100644 index 0000000..7d14047 --- /dev/null +++ b/December - 28/cpp_Aadhi11.cpp @@ -0,0 +1,113 @@ +#include +#include +#include +using namespace std; +void delval (int a[100],int n,int key) + { + int pos; + for (int j = 0; j < n; j++) + { + if (a[j] == key) + { + pos = j; + } + } + + for (int k = pos; k < n; k++) + { + a[k] = a[k + 1]; + } + } +int main() +{ + int n, a[100],fs,ss,fl,sl; + float t=0; + cout << "n="; + cin >> n; + cout <> a[i]; + } + + + while(n>0) + { + if(n==3||n==2) + { + if(n==2) + { + if(a[0]>a[1]) + t=t+a[0]; + else + t=t+a[1]; + } + else + { + for(int l=0;l fl) + { + fl = a[g]; + } + } + sl = 0; + for(int b=0;bsl) + { + sl = a[b]; + } + } + } + fs=INT_MAX; + for (int g = 0; g < n; g++) + { + if (a[g] < fs) + { + fs = a[g]; + } + } + int ss=INT_MAX; + for(int b=0;be) + t = t + e; + else + t = t + g; + delval(a,n,fl); + delval(a,n,sl); + n=n-2; + } + } + t = t/60; + t=floor(1000*t)/1000; + cout< tail) { + int firstSmallest = Integer.MAX_VALUE; + for (Integer tailie : tail) { + if (firstSmallest > tailie) { + firstSmallest = tailie; + } + } + return firstSmallest; + } + + public int findSecondSmallest(List tail, int firstSmallest) { + int secondSmallest = Integer.MAX_VALUE; + for (Integer tailie : tail) { + if (secondSmallest > tailie) { + int flag = tailie; + if (flag > firstSmallest) { + secondSmallest = flag; + } + } + } + return secondSmallest; + } + + public int findFirstLargest(List tail) { + int firstLargest = Integer.MIN_VALUE; + for (Integer tailie : tail) { + if (firstLargest < tailie) { + firstLargest = tailie; + } + } + return firstLargest; + } + + public int findSecondLargest(List tail, int firstLargest) { + int secondLargest = Integer.MIN_VALUE; + for (Integer tailie : tail) { + if (secondLargest < tailie) { + int flag = tailie; + if (flag < firstLargest) { + secondLargest = flag; + } + } + } + return secondLargest; + } + + public int minimumBetweenTwo(int a, int b) { + int min = a < b ? a : b; + return min; + } + + public int firstApproach(int firstLargest, int secondLargest, int firstSmallest) { + int travelTime = firstLargest + firstSmallest + secondLargest + firstSmallest; + return travelTime; + } + + public int secondApproach(int firstLargest, int firstSmallest, int secondSmallest) { + int travelTime = secondSmallest + firstSmallest + firstLargest + secondSmallest; + return travelTime; + } + + public int theJourneyToTheEternalEngine(List tail, int n) { + int firstSmallest = findFirstSmallest(tail); + int secondSmallest = findSecondSmallest(tail, firstSmallest); + + int travelTime = 0; + + while (true) { + if (tail.size() == 3) { + int firstLargest = findFirstLargest(tail); + travelTime = travelTime + (secondSmallest + firstSmallest + firstLargest); + break; + } + if (tail.size() == 2) { + travelTime = travelTime + secondSmallest; + break; + } else { + int firstLargest = findFirstLargest(tail); + int secondLargest = findSecondLargest(tail, firstLargest); + + int result01 = firstApproach(firstLargest, secondLargest, firstSmallest); + int result02 = secondApproach(firstLargest, firstSmallest, secondSmallest); + + tail.remove(tail.indexOf(firstLargest)); + tail.remove(tail.indexOf(secondLargest)); + + int minTime = minimumBetweenTwo(result01, result02); + + travelTime = travelTime + minTime; + } + } + + return travelTime; + } + + public float secondsToMinutes(int time) { + float timeInMinutes = (float) time / 60; + return timeInMinutes; + } + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + + System.out.println("Input:"); + System.out.println(""); + int n; + while (true) { + System.out.print("n="); + n = sc.nextInt(); + System.out.println(""); + + if (n >= 3) { + break; + } else { + System.out.println("There needs to be at least 3 Tailies"); + System.out.println(""); + } + } + + System.out.print("Walking time: "); + int[] walkingTime = new int[n]; + for (int i = 0; i < n; i++) { + walkingTime[i] = sc.nextInt(); + } + List tail = new ArrayList<>(); + for (int time : walkingTime) { + tail.add(time); + } + + java_DCBisht28 ob = new java_DCBisht28(); + int timeInSeconds = ob.theJourneyToTheEternalEngine(tail, n); + float timeInMinutes = ob.secondsToMinutes(timeInSeconds); + + System.out.println(""); + System.out.println("Output:"); + System.out.println(""); + System.out.println(String.format("%.3f", timeInMinutes)); + sc.close(); + } +} diff --git a/December - 29/.gitignore b/December - 29/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 29/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 29/C++_subburamanathan7.cpp b/December - 29/C++_subburamanathan7.cpp new file mode 100644 index 0000000..21d90ee --- /dev/null +++ b/December - 29/C++_subburamanathan7.cpp @@ -0,0 +1,35 @@ +#include +#include + +using namespace std; + +int main(){ + int limit,temp; + cout<<"Enter Limit"; + cin>>limit; + + vector rating; + vector candies; + for(int i=0;i>temp; + rating.push_back(temp); + candies.push_back(1); + } + + + for(int i=1;i=0;--i) + if(rating[i]>rating[i+1]) + candies[i]= (candies[i-1]+1)>candies[i]?(candies[i-1]+1):candies[i]; + + temp=0; + for (int i=0;i[] shouldIncrease; + static int[] ans; + public static void main(String[] args) { + + Scanner in=new Scanner(System.in); + int n=in.nextInt(); + int[] rating=new int[n]; + for(int i=0;i list=new ArrayList<>(); + if(left>=0 && rating[left]>rating[i]) list.add(left); + if(rightrating[i]) list.add(right); + shouldIncrease[i]=list; +// System.out.println(list); + } + + Arrays.fill(ans,1); + for(int i=0;ilist=shouldIncrease[k]; + for(int i=0;i ratings[i]){ + candies[i+1] = candies[i] + 1; + } + } + + // Right to Left Traversal + for(int i=n-1;i>0;i--){ + if(ratings[i-1] > ratings[i] && candies[i-1] < candies[i]+1){ + candies[i-1] = candies[i] + 1; + } + } + + return candies; + } + + public int calculateMinimumCandies(int[] candies, int n){ + int sum = 0; + for(int i=0;i ratings[i+1]) { + candies[i+1] -= 1; + } else { + candies[i] -= 1; + } + } + } + + int sum=0; + for(int i=0; i +using namespace std; + +int countCandies(int arr[], int n) +{ + int sum = 0; + + int ans[n]; + + if (n == 1) { + return 1; + } + + for (int i = 0; i < n; i++) + ans[i] = 1; + + for (int i = 0; i < n - 1; i++) { + + if (arr[i + 1] > arr[i]) { + + ans[i + 1] = ans[i] + 1; + } + } + + for (int i = n - 2; i >= 0; i--) { + + if (arr[i] > arr[i + 1] + && ans[i] <= ans[i + 1]) { + + ans[i] = ans[i + 1] + 1; + } + + sum += ans[i]; + } + + sum += ans[n - 1]; + + return sum; +} + +int main() +{ + int arr[20],N; + cout<<"n="; + cin>>N; + cout<<"ratings = "; + for(int i=0;i>arr[i]; + } + cout <[] shouldIncrease; + static int[] ans; + + public static void main(String[] args) { + + Scanner in = new Scanner(System.in); + int n = in.nextInt(); + int[] rating = new int[n]; + for (int i = 0; i < n; i++) + rating[i] = in.nextInt(); + + ans = new int[n]; + shouldIncrease = new ArrayList[n]; + + for (int i = 0; i < n; i++) { + int left = i - 1; + int right = i + 1; + List list = new ArrayList<>(); + if (left >= 0 && rating[left] > rating[i]) + list.add(left); + if (right < n && rating[right] > rating[i]) + list.add(right); + shouldIncrease[i] = list; + + } + + Arrays.fill(ans, 1); + for (int i = 0; i < ans.length; i++) { + addChocos(i); + } + int sum = 0; + for (int ele : ans) + sum += ele; + System.out.println(sum); + in.close(); + } + + static void addChocos(int k) { + + List list = shouldIncrease[k]; + for (int i = 0; i < list.size(); i++) { + int bigBro = list.get(i); + if (ans[bigBro] <= ans[k]) { + ans[bigBro]++; + addChocos(bigBro); + } + + } + } +} diff --git a/December - 30/.gitignore b/December - 30/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 30/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 30/cpp_Aadhi11.cpp b/December - 30/cpp_Aadhi11.cpp new file mode 100644 index 0000000..01af672 --- /dev/null +++ b/December - 30/cpp_Aadhi11.cpp @@ -0,0 +1,116 @@ +#include +using namespace std; +typedef pair pii; +void printpath(map mp, pii u) +{ + if (u.first == 0 && u.second == 0) { + cout <<"("<< 0 << ", " << 0 <<")"<< endl; + return; + } + printpath(mp, mp[u]); + cout <<"("<< u.first << ", " << u.second <<")"<< endl; +} +void BFS(int a, int b, int target) +{ + map m; + bool isSolvable = false; + map mp; + + queue q; + + q.push(make_pair(0, 0)); + while (!q.empty()) { + + auto u = q.front(); + q.pop(); + if (m[u] == 1) + continue; + + if ((u.first > a || u.second > b || u.first < 0 + || u.second < 0)) + continue; + + m[{ u.first, u.second }] = 1; + + if (u.first == target || u.second == target) { + isSolvable = true; + + printpath(mp, u); + if (u.first == target) { + if (u.second != 0) + cout <<"("<< u.first << ", " << 0 <<")"<< endl; + } + else { + if (u.first != 0) + cout <<"("<< 0 << ", " << u.second <<")"<< endl; + } + return; + } + if (m[{ u.first, b }] != 1) { + q.push({ u.first, b }); + mp[{ u.first, b }] = u; + } + + if (m[{ a, u.second }] != 1) { + q.push({ a, u.second }); + mp[{ a, u.second }] = u; + } + + int d = b - u.second; + if (u.first >= d) { + int c = u.first - d; + if (m[{ c, b }] != 1) { + q.push({ c, b }); + mp[{ c, b }] = u; + } + } + else { + int c = u.first + u.second; + if (m[{ 0, c }] != 1) { + q.push({ 0, c }); + mp[{ 0, c }] = u; + } + } + d = a - u.first; + if (u.second >= d) { + int c = u.second - d; + if (m[{ a, c }] != 1) { + q.push({ a, c }); + mp[{ a, c }] = u; + } + } + else { + int c = u.first + u.second; + if (m[{ c, 0 }] != 1) { + q.push({ c, 0 }); + mp[{ c, 0 }] = u; + } + } + + if (m[{ u.first, 0 }] != 1) { + q.push({ u.first, 0 }); + mp[{ u.first, 0 }] = u; + } + + if (m[{ 0, u.second }] != 1) { + q.push({ 0, u.second }); + mp[{ 0, u.second }] = u; + } + } +} + +int main() +{ + int Jug1 = 11, Jug2 = 9, target,d1,d2; + cin>>Jug1>>Jug2; + cin>>d1>>d2; + if(d1==0) + target=d2; + else + target=d1; + cout< +using namespace std; +typedef pair pii; +void printpath(map mp, pii u) +{ + if (u.first == 0 && u.second == 0) + { + cout << "(" << 0 << ", " << 0 << ")" << endl; + return; + } + printpath(mp, mp[u]); + cout << "(" << u.first << ", " << u.second << ")" << endl; +} +void BFS(int a, int b, int target) +{ + map m; + bool isSolvable = false; + map mp; + + queue q; + + q.push(make_pair(0, 0)); + while (!q.empty()) + { + + auto u = q.front(); + q.pop(); + if (m[u] == 1) + continue; + + if ((u.first > a || u.second > b || u.first < 0 || u.second < 0)) + continue; + + m[{u.first, u.second}] = 1; + + if (u.first == target || u.second == target) + { + isSolvable = true; + + printpath(mp, u); + if (u.first == target) + { + if (u.second != 0) + cout << "(" << u.first << ", " << 0 << ")" << endl; + } + else + { + if (u.first != 0) + cout << "(" << 0 << ", " << u.second << ")" << endl; + } + return; + } + if (m[{u.first, b}] != 1) + { + q.push({u.first, b}); + mp[{u.first, b}] = u; + } + + if (m[{a, u.second}] != 1) + { + q.push({a, u.second}); + mp[{a, u.second}] = u; + } + + int d = b - u.second; + if (u.first >= d) + { + int c = u.first - d; + if (m[{c, b}] != 1) + { + q.push({c, b}); + mp[{c, b}] = u; + } + } + else + { + int c = u.first + u.second; + if (m[{0, c}] != 1) + { + q.push({0, c}); + mp[{0, c}] = u; + } + } + d = a - u.first; + if (u.second >= d) + { + int c = u.second - d; + if (m[{a, c}] != 1) + { + q.push({a, c}); + mp[{a, c}] = u; + } + } + else + { + int c = u.first + u.second; + if (m[{c, 0}] != 1) + { + q.push({c, 0}); + mp[{c, 0}] = u; + } + } + + if (m[{u.first, 0}] != 1) + { + q.push({u.first, 0}); + mp[{u.first, 0}] = u; + } + + if (m[{0, u.second}] != 1) + { + q.push({0, u.second}); + mp[{0, u.second}] = u; + } + } +} + +int main() +{ + int Jug1 = 11, Jug2 = 9, target, d1, d2; + cin >> Jug1 >> Jug2; + cin >> d1 >> d2; + if (d1 == 0) + target = d2; + else + target = d1; + cout << endl; + BFS(Jug1, Jug2, target); + return 0; +} \ No newline at end of file diff --git a/December - 31/.gitignore b/December - 31/.gitignore new file mode 100644 index 0000000..ac6d3a2 --- /dev/null +++ b/December - 31/.gitignore @@ -0,0 +1,231 @@ +# gitignore file for "A December of Algorithms 2022" +# visit https://github.com/SVCE-ACM/A-December-of-Algorithms +# Written individually to adjust for the needs of the problem + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# node.js +/node_modules +package-lock.json + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +Pipfile.lock +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Files and directories created by pub +.dart_tool/ +.packages +build/ +# If you're building an application, you may want to check-in your pubspec.lock +pubspec.lock + +# Directory created by dartdoc +# If you don't generate documentation locally you can remove this line. +doc/api/ + +# Avoid committing generated Javascript files: +*.dart.js +*.info.json # Produced by the --dump-info flag. +*.js # When generated by dart2js. Don't specify *.js if your + # project includes source files written in JavaScript. +*.js_ +*.js.deps +*.js.map + +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf diff --git a/December - 31/GREEDnim_day31_java.java b/December - 31/GREEDnim_day31_java.java new file mode 100644 index 0000000..3c7642f --- /dev/null +++ b/December - 31/GREEDnim_day31_java.java @@ -0,0 +1,67 @@ +package acm; + +import java.util.Scanner; + +public class GREEDnim_day31_java { + static boolean[][] placedQueens; + static int count=0; + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + int n=in.nextInt(); + placedQueens=new boolean[n][n]; + placeQueens(0); + System.out.println("no of combinations "+count); + } + public static void placeQueens(int row) + { + if(row==placedQueens.length) + { + count++; + printQueens(); + return; + } + for(int i=0;i< placedQueens.length;i++) + { + if(placable(row,i)) + { + placedQueens[row][i]=true; + placeQueens(row+1); + placedQueens[row][i]=false; + } + } + } + public static boolean placable(int row,int col) + { + + //vertical top + for(int i=row-1;i>=0;i--) + { + if(placedQueens[i][col]) return false; + } + //left top diagonal + for(int i=row-1, j=col-1; i>=0 && j>=0 ; i--,j--) + { + if(placedQueens[i][j]) return false; + } + //right top diagonal + for(int i=row-1,j=col+1; i>=0 && j +using namespace std; +int grid[10][10]; +int k=0; + +void print(int n) { + for (int i = 0;i <= n-1; i++) { + for (int j = 0;j <= n-1; j++) { + + if(grid[i][j]==1) + cout <<"Q"<< " "; + else + cout <<"."<< " "; + + } + cout<= 0 && j >= 0; i--,j--) { + if (grid[i][j]) { + return false; + } + } + for (int i = row, j = col; i >= 0 && j < n; j++, i--) { + if (grid[i][j]) { + return false; + } + } + return true; +} + +bool solves (int n, int row) { + if (n == row) { + print(n); + return true; + } + bool res = false; + for (int i = 0;i <=n-1;i++) { + if (Safe(i, row, n)) { + grid[row][i] = 1; + res = solves(n, row+1) || res; + grid[row][i] = 0; + } + } + return res; +} + +bool isSafe(int col, int row, int n) { + for (int i = 0; i < row; i++) { + if (grid[i][col]) { + return false; + } + } + for (int i = row,j = col;i >= 0 && j >= 0; i--,j--) { + if (grid[i][j]) { + return false; + } + } + for (int i = row, j = col; i >= 0 && j < n; j++, i--) { + if (grid[i][j]) { + return false; + } + } + return true; +} + +bool solve (int n, int row) { + if (n == row) { + k++; + return true; + } + bool res = false; + for (int i = 0;i <=n-1;i++) { + if (isSafe(i, row, n)) { + grid[row][i] = 1; + res = solve(n, row+1) || res; + grid[row][i] = 0; + } + } + return res; +} + +int main() +{ + ios_base::sync_with_stdio(false); + cin.tie(NULL); + int n; + cin >> n; + cout< +#include + +using namespace std; + +void nQueens(vector>& kitchenFloor,int row = 0, int column = 0); +bool isPossibleToMove(vector>&, int , int); +void printBoard(vector>&); +static int count = 0; + + +int main (int argc, char *argv[]) +{ + int tilesCount; + cin>>tilesCount; + vector> kitchenFloor(tilesCount, vector (tilesCount, 0)); + nQueens(kitchenFloor); + cout<>& kitchenFloor, int row, int column){ + +// base condition + if(row == kitchenFloor[0].size()){ + count++; + printBoard(kitchenFloor); + return; + } + +// if it's possible to place the queen, place it and go to next row + if(isPossibleToMove(kitchenFloor, row, column)){ + kitchenFloor[row][column] = 1; + nQueens(kitchenFloor, row + 1); + kitchenFloor[row][column] = 0; + } +// if queen cannot be placed on current positon, move towards right and check + if (column + 1 < kitchenFloor[0].size()) + nQueens(kitchenFloor, row, column + 1); +} + +bool isPossibleToMove(vector>& kitchenFloor, int row, int column){ + bool safe = true; + + int i = row, j = column; + // left diagonal, check for queen + while(i>=0 && j>=0 && safe){ + safe = !(kitchenFloor[i][j] == 1); + j--; + i--; + } + + // right diagonal + i = row, j = column; + while(i=0 && safe){ + safe = !(kitchenFloor[i][j] == 1); + j++; + i--; + } + + // top + j = row; + while(j>=0 && safe){ + safe = !(kitchenFloor[j--][column] == 1); + } + return safe; +} + +void printBoard(vector>& kitchenFloor){ + for(auto part: kitchenFloor){ + for(auto it = part.begin(); it < part.end(); it++){ + cout<< *it; + } + cout<< endl; + } + cout<< endl; +} + diff --git a/December - 31/java_DCBisht31.java b/December - 31/java_DCBisht31.java new file mode 100644 index 0000000..0ec6143 --- /dev/null +++ b/December - 31/java_DCBisht31.java @@ -0,0 +1,88 @@ +import java.util.*; +public class java_DCBisht31 { + static boolean[][] placedQueens; + static int count=0; + public static void main(String[] args) { + Scanner in=new Scanner(System.in); + int n=in.nextInt(); + placedQueens=new boolean[n][n]; + + placeQueens1(0); + System.out.println(count); + System.out.println(); + placeQueens(0); + + in.close(); + } + public static void placeQueens1(int row) + { + if(row==placedQueens.length) + { + count++; + + return; + } + for(int i=0;i< placedQueens.length;i++) + { + if(placable(row,i)) + { + placedQueens[row][i]=true; + placeQueens1(row+1); + placedQueens[row][i]=false; + } + } + } + public static void placeQueens(int row) + { + if(row==placedQueens.length) + { + count++; + printQueens(); + return; + } + for(int i=0;i< placedQueens.length;i++) + { + if(placable(row,i)) + { + placedQueens[row][i]=true; + placeQueens(row+1); + placedQueens[row][i]=false; + } + } + } + public static boolean placable(int row,int col) + { + + //vertical top + for(int i=row-1;i>=0;i--) + { + if(placedQueens[i][col]) return false; + } + //left top diagonal + for(int i=row-1, j=col-1; i>=0 && j>=0 ; i--,j--) + { + if(placedQueens[i][j]) return false; + } + //right top diagonal + for(int i=row-1,j=col+1; i>=0 && j

-

header

+

header

+ +

Welcome to A December of Algorithms (2022). @@ -34,6 +36,27 @@ Check out our FAQ for more information. - [**December 8 - Aptitude Check!**](#december-8---aptitude-check) - [**December 9 - Kochouseph Konundrum!**](#december-9---kochouseph-konundrum) - [**December 10 - Play with words**](#december-10---play-with-words) + - [**December 11 - Monkey jump**](#december-11---monkey-jump) + - [**December 12 - Shez in a Maze!**](#december-12---shez-in-a-maze) + - [**December 13 - The Labyrinth**](#december-13---the-labyrinth) + - [**December 14 - Math Mystery**](#december-14---math-mystery) + - [**December 15 - The Murderers Meet**](#december-15---the-murderers-meet) + - [**December 16 - H2O Receptacle**](#december-16---h2o-receptacle) + - [**December 17 - Zig Zag Conversion**](#december-17---zig-zag-conversion) + - [**December 18 - Find the way**](#december-18---find-the-way) + - [**December 19 - Hidden Anagram**](#december-19---hidden-anagram) + - [**December 20 - Code a Subsequence**](#december-20---code-a-subsequence) + - [**December 21 - The Devil Towers**](#december-21---the-devil-towers) + - [**December 22 - The Markowitz Paradox**](#december-22---the-markowitz-paradox) + - [**December 23 - Meeting Rooms**](#december-23---meeting-rooms) + - [**December 24 - Cracking The Safe**](#december-24---cracking-the-safe) + - [**December 25 - The Motorbike Race**](#december-25---the-motorbike-race) + - [**December 26 - Circulate**](#december-26---circulate) + - [**December 27 - Mission to Earth: Re-Calibrated**](#december-27---mission-to-earth-re-calibrated) + - [**December 28 - The Journey to the Eternal Engine**](#december-28---the-journey-to-the-eternal-engine) + - [**December 29 - Candies**](#december-29---candies) + - [**December 30 - Precise Portion**](#december-30---precise-portion) + - [**December 31 - The Quad of Queens**](#december-31---the-quad-of-queens) - [**FAQ**](#faq) @@ -77,7 +100,9 @@ Check out our FAQ for more information. #### Explanation ``` - The first line of input will specify the number of words (n). The subsequent 'n' lines will specify the word to be translated. + The first line of input will specify the number of words (n). + + The subsequent 'n' lines will specify the word to be translated, where each letter is separated by a comma. ``` @@ -314,7 +339,7 @@ Expenditure=6050 #### Explanation ``` - The input is the rate of the fuel in the beginning of the month. + The input is the rate of the fuel in the beginning of the month. The output is the amount he must spend on fueling his bike. If the expenditure exceeds 10% of the income (i.e greater than 5000), then an alert message must be displayed. @@ -449,6 +474,8 @@ Output: - [Strings in C++](https://www.tutorialspoint.com/cplusplus/cpp_strings.htm) - [Strings in Java](https://www.tutorialspoint.com/java/java_strings.htm) - [String in Python](https://www.tutorialspoint.com/python/python_strings.htm) + - [2D Arrays](https://www.simplilearn.com/tutorials/data-structure-tutorial/two-dimensional-arrays#:~:text=ExpertView%20Course-,What%20Are%20Two%2DDimensional%20Arrays%3F,similar%20to%20the%20data%20structure.) + - [Pattern Searching in Strings](https://www.geeksforgeeks.org/algorithms-gq/pattern-searching/) ---- @@ -482,6 +509,7 @@ Help Arshith develop a way to translate any given word to that particular langua - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) - [Strings in Python](https://www.geeksforgeeks.org/python-string/) - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + - [Pattern Searching in Strings](https://www.geeksforgeeks.org/algorithms-gq/pattern-searching/) ---- @@ -539,6 +567,7 @@ Better luck next time - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) - [Strings in Python](https://www.geeksforgeeks.org/python-string/) - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + - [Pattern Searching in Strings](https://www.geeksforgeeks.org/algorithms-gq/pattern-searching/) ---- @@ -618,6 +647,1780 @@ S contains only lowercase Latin characters, i.e, the characters {a,b,c…….z} - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) - [Strings in Python](https://www.geeksforgeeks.org/python-string/) - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + - [Pattern Searching in Strings](https://www.geeksforgeeks.org/algorithms-gq/pattern-searching/) + + +---- + + +### December 11 - Monkey jump +#### Problem Statement + +A list is provided with a sequence of characters . The character ‘_’ represents land and the character ‘~’ represents water. A monkey can move 1 step or 2 steps in a single jump. Another list provided here contains the step that the monkey took Eg[1,1,2,1,2]. Whenever the monkey touches the water. The game is over and the score must be returned. Calculate the jumps the monkey took before touching the water. + +

+ + + #### Sample Input/Output + +``` +Input 1: + +[‘_’,’~’,’_’,’_’,’_’,’_’,’~’,’_’,’_’,’~’,’_’,’~’] + +[2,1,1,1,2,1,2,1] + +Output 1: + +Score =7 + +Input 2: + +[‘_’,’~’,’_’,’~’,’_’,’_’,’~’,’_’,’_’,’~’,’_’,’~’] + +[2,2,1,1,1,1,2,1,1] + +Output 2: +Score =3 + + ``` + +#### Explanation: + + ``` + +The first line of input is a combination of ‘_’ and ‘~’ representing land and water respectively. +The second line of input ia a combination of 2's and 1's, 2 steps indicate, for example, initially being on position 1 and ending up on position 3 without landing on position 2 in between. + +Monkey takes two steps in a single jump as first move and three single steps as the next 3 moves/jumps, another 2 jumps, 1 jump and another 2 jumps. +Given the jump sequence: [2,1,1,1,2,1,2,1] +Since in the 8th jump the monkey touches water, the total jump count before he touches the water is 7 and thus the score is 7. + +``` + +- **References** + - [Looping in C](https://www.tutorialspoint.com/cprogramming/c_loops.htm) + - [Looping in C++](https://www.programiz.com/cpp-programming/for-loop) + - [Looping in Java](https://www.geeksforgeeks.org/loops-in-java/) + - [Looping in Python](https://www.w3schools.com/python/python_for_loops.asp) + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + + +---- +### December 12 - Shez in a Maze! +#### Problem Statement +Shez went to an interesting maze where she was given 500 coins. The rule of the maze is when you choose a path in a maze you need to drop the amount indicated on the path and successfully reach the end. + +The winner is declared based on the amount you have spent. The person who has spent the least amount will be the winner. + +Can you help her win the maze? + +The cost of the path will be in a NxN matrix and the current path is indicated by path[i][j], from the current path you can either travel up, down, front or back. + +Note that the start of the maze is the top most left corner and the destination is the bottom most right corner. + +

+ +#### Sample Input/Output +``` +INPUT 1: + +4 +Path = { {9,4,9,9}, {6,7,6,4}, {8,3,3,7}, {7,4,9,10} } + +OUTPUT 1: + +path_taken={9,4,7,3,3,7,10} +The minimum coins dropped is 43 +``` +``` +INPUT 2: + +3 +Path = { {8,3,9}, {2,6,4}, {8,3,1}} + +OUTPUT 2: + +path_taken={8,2,6,3,1} +The minimum coins dropped is 20 +``` +#### Explanation: +``` + +The first line of input is the size of the NxN matrix. +The next line of input is an NxN matrix where each element represents the number of coins you need to drop at that position. + +The output is a path_taken matrix and the minimum coins dropped amount. + +9 4 9 9 +6 7 6 4 +8 3 3 7 +7 4 9 10 +Minimum cost = 9 + 4 + 7 + 3 + 3 + 7 + 10 = 43 +So here we see that from the start point Shez can take 3 paths which are of costs 4,7,6 respectively. + +Of these 3 paths the one with cost 4 is the path with minimum cost. + +Now from 4 she can either take a path of cost 9 or 7 (Remember you can move only up, down, front, back and no diagonal movement is allowed) so she takes the path with cost 7. +From 7 she has 4 options; paths of costs 6,6,3,4 (Taking path 4 is not advisable since that is from where we came to path 7) so now she takes path with cost 3 and then from this position 3 she can either take paths 8,7,3,4; the minimum cost is 3 so she proceeds in the path with cost 3. Following this logic she finishes the maze with spending a minimum amount of 43 units. + +``` + +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + - [Shortest Path Algorithms](https://brilliant.org/wiki/shortest-path-algorithms/#:~:text=There%20are%20two%20main%20types,because%20of%20the%20added%20complexity.) + + +---- +### December 13 - The Labyrinth +#### Problem Statement +In Ancient Greek mythology, the Labyrinth was an intricate maze constructed by the master inventor Daedalus as per the orders of King Minos of Crete. +Many heroes from afar contended to escape the maze and overpower the ferocious beast Minotaur, but none succeeded in their attempts except for one, the great Theseus of Athens. +Imagine a modern-world Labyrinth similar to an N*N binary matrix of blocks such that: +- The starting point is the upper leftmost block +- The endpoint is the lower rightmost block +- Dead ends are represented by 0 +- A clear path is represented by 1 + +Help Theseus escape this Labyrinth if he can only move forward and backwards throughout his quest. + + +

+ + + + +#### Sample Input/Output +``` +INPUT: +4 +{1,0,0,0} +{1,1,0,1} +{0,1,0,0} +{1,1,1,1} + + +OUTPUT: +{1,0,0,0} +{1,1,0,0} +{0,1,0,0} +{0,1,1,1} + +``` +``` +INPUT: +4 +{1,1,1,0} +{1,0,1,1} +{0,1,0,1} +{0,1,1,1} + + +OUTPUT: +{1,1,1,0} +{0,0,1,1} +{0,0,0,1} +{0,0,0,1} + +``` +#### Explanation: +``` +The first line of input is the size of the N*N matrix. +In the given samples, the input matrix specifies the structure of the maze in which 0's represent the dead ends, and 1's represent the clear blocks. +After computing a path to the destination, the output matrix represents the path to the destination block using 1’s. + +``` +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + - [Backtracking Algorithms](https://www.geeksforgeeks.org/backtracking-algorithms/) + +---- +### December 14 - Math Mystery +#### Problem Statement +Dr. Satheesh Kumar is an outstanding professor in Discrete Mathematics. However, he has been assigned to teach an unruly batch of students. The lesson he planned to cover in the upcoming class was of utmost importance for the students. + +The lesson was none other than “Graph Theory”, which required a concise understanding of fundamental theoretical concepts and numerous theorems. + +The professor decided to execute those theorems programmatically as the students belong to the Computer Science department. He prepared all the theorems as programs except one theorem, which discussed the topic of “Graph Bipartite”. + +Bipartite Graph: It is a graph whose vertices can be divided into 2 independent sets U and V such that every edge (u,v), either connects a vertex from U to V or a vertex from V to U. (We can also say that there is no edge that connects vertices of the same set). + +Help Dr. Satheesh Kumar come up with a program which obtains a graph as input and produces an output verifying its bipartite property. + + +

+ + + + + +#### Sample Input/Output +``` +INPUT: +6 + +0 1 0 0 0 1 +1 0 1 0 0 0 +0 1 0 1 0 0 +0 0 1 0 1 0 +0 0 0 1 0 1 +1 0 0 0 1 0 + +OUTPUT: +The graph is Bipartite! + +``` +``` +INPUT: +4 + +0 1 0 1 +1 0 1 0 +0 1 0 1 +1 0 1 0 + +OUTPUT: +The graph is Bipartite! + +``` +#### Explanation: +``` +The first line of the input is the number of vertices in the graph.The next part of the input is the adjacency matrix of the graph, +where every row/column is a vertex and the 1 represents an edge connecting two vertices. +You are required to divide the given vertices into two sets such that: + 1. Every vertex in one set is connected to at least one vertex in the other set. + 2. There is no edge between the vertices of the same set. + +``` +- **References** + - [Bipartite graphs](https://www.geeksforgeeks.org/bipartite-graph/) + - [Adjacency matrices](https://www.javatpoint.com/what-is-an-adjacency-matrix) + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + +---- + + +### December 15 - THE MURDERERS MEET + +#### Problem Statement + +The death of Sam Keating, Annalise Keating's husband, caused the entire city to be in suspense as to who killed him because of the city of Philadelphia's soaring murder rate. The best defense attorney in Philadelphia, Annalise Keating also teaches law undergrads in addition to turning heads in the courtroom. She chooses pupils from her class for Keating 5. Due to security concerns, the Keating 5 have been conducting confidential missions via virtual meetings since her husband's death. The tech lead is Oliver, a hacker who organizes their meetings in a covert manner. Oliver is quite skilled at doing this. The last meeting, however, was chaotic due to the traffic that broke out as a result of several inmates speaking at once while muted. + +Help Oliver by creating an algorithm that uses mouse-based and timestamps to implement Queue in unmuting in order to get around this technical traffic. + + + +

+ + + +#### Sample Input/Output +``` +Input: {Wes, 12:00:30},{Michella, 12:03:40},{Asher, 12:00:01} + +Output: Asher, Wes, Michella. + +Input: {Annalise, 01:09:00},{ Frank, 01:02:30},{Laurel, 01:04:19} + +Output: Frank, Laurel, Annalise. + +``` +#### Explanation: +``` +When a meeting participant presses the unmute button, their name and the moment it was pressed are recorded. + +There are therefore three inputs, each with a timestamp and a name. {name, timestamp}. + +The timestamp is in the format of hh:mm:ss. + +They will now be organized into a queue based on when they pressed the microphone button, and once they are in a queue, the output is produced based on the time difference and the queue's arrangement. As a result, they will have quick access to unmute their mics. + +``` +- **References** + - [Queue data structure](https://www.javatpoint.com/data-structure-queue) + - [Queue in Java](https://www.geeksforgeeks.org/queue-interface-java/) + - [Queue in Python](https://www.geeksforgeeks.org/queue-interface-java/) + +---- + + +### December 16 - H2O Receptacle + +#### Problem Statement + +John has an integer array height of n non-negative integers height [n], where each value represents a point at coordinate (i, height[i]). Now n vertical lines are drawn such that the two endpoints of line i are at (i, 0) and (i, height[i]). Here each pair of a line with the x-axis forms a container. + +Determine two lines that together with the x-axis form a container, such that the container contains the most water. + +Return the maximum amount of water a container can store. + + + +

+ + + +#### Sample Input/Output +``` +Input: height = [6,2,5,4,8] +Output: 24 + + +Input: height = [1,8,6,2,5,4,8,3,7] +Output: 49 + +``` +#### Explanation: +``` +The above vertical lines are represented by an array [1,8,6,2,5,4,8,3,7]. + +In this case,the area between lines 7 and 8 will be maximum. + +7 and 8 are 7 units in distance apart, so the size of the base is 7 . + +Height of the container is min(7,8)= 7. So the max area of water (blue section) the container can contain is 49. + +The selected two heights need not necessarily be maximum but including the max distance between them at the same time. +Considering both the length and breadth to be maximum the area is found. So it is a combination of height and distance between the two heights. +So that the resultant area will be the maximum amount of water in the the given container. + +``` +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Sorting Algorithms](https://www.geeksforgeeks.org/sorting-algorithms/) + - [Two Pointer Approach](https://www.geeksforgeeks.org/two-pointers-technique//) + +---- + + +### December 17 - Zig Zag Conversion + +#### Problem Statement + +You are given a string ‘Str’ and an integer ‘Row’. You have to convert and print the row into a zig- +zag pattern with rows equal to ‘Row’ and display the output row-wise. You may refer to the given sample input/output. + + + +#### Sample Input/Output +``` +Input: + +Str = “spaghettigood” +Row = 4 + +Output: +stdpetoahiogg + +Input: + +Str = “spritebetter” +Row = 3 + +Output: +sttpieetrrbe + +``` +#### Explanation: +``` +Input Format : + +The first line of each test case contains a string ‘Str’, denoting the input string. + +Zig-zag pattern: +s t d +p e t o +a h i o +g g + +The second line of each test case contains a single integer ‘Row’, denoting the number of rows in the +zig-zag pattern to be created. + +Output Format : + +For each test case, print the new string after zig-zag conversion. +Output for each test case should be printed in a separate line. + +``` +- **References** + - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) + - [Strings in Python](https://www.geeksforgeeks.org/python-string/) + - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + +---- + +### December 18 - Find the way + +#### Problem Statement + +Pooja and Ravi are two close friends that live in the city chosen by the user. The graph below shows the cities P, Q, R, S, T, U, V and W represented by the vertices and the rail connections between them represented by edges. The numbers on the edges are the times, in hours, it takes to travel by train between each of the cities. find the shortest time to travel by train between chosen city and W. Also find the time taken. + + +![find the way](https://user-images.githubusercontent.com/119495356/208252824-4486cb25-7557-411f-afa9-dc17f767e00a.png) + + + +#### Sample Input/Output +``` +Input: + +City chosen: P + +Output: + +Shortest path: P – R – V – W +Shortest time: 7 hours + + + +``` +#### Explanation: +``` +Input Format : + +The argument given is the city that they choose + +Output Format : + +Return the shortest path between the chosen city and w. If chosen city is W then the shortest path is 0. Also return the time taken. + +CONSTRAINT: +Time complexity is 0(V^2) + + +``` +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + - [Shortest Path Algorithms](https://brilliant.org/wiki/shortest-path-algorithms/#:~:text=There%20are%20two%20main%20types,because%20of%20the%20added%20complexity.) + +---- + +### December 19 - Hidden Anagram + +#### Problem Statement + +You are given two strings (String 1 and String 2). The first string contains a sentence containing the letters of the second string in a consecutive sequence but in a different order. + +Your task is to find the hidden anagram of the second string in the first string. + +The hidden anagram must contain all the letters, including duplicates, from the second string in any order and must not contain any other alphabetic characters. + +Write a program to find the anagram of the second string embedded somewhere in the first string. + +You should ignore character case, any spaces, and punctuation marks and return the anagram as a lower case string with no spaces or punctuation marks. + + +

+ + + +#### Sample Input/Output +``` +Input: + +String 1: +"My world evolves in a beautiful space called Tesh." + +String 2: +"sworn love lived" + + +Output: + +"worldevolvesin" + +``` + +``` +Input: + +String 1: +"Mr. Mojo Rising could be a song title" + +String 2: +"Jim Morrison" + + +Output: + +"mrmojorisin" + + +``` + +#### Explanation: +``` + +The sequence "world evolves in" is a perfect anagram of "sworn love lived". + +The sequence "Mr. Mojo Risin" ignoring the full stop, is a perfect +Anagram of "Jim Morrison". + + +``` +- **References** + - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) + - [Strings in Python](https://www.geeksforgeeks.org/python-string/) + - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + + +---- + +### December 20 - Code a Subsequence + +#### Problem Statement + +A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. + +You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. + +For a subsequence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : + +We call it increasing if for every i (1 <= i < M ) , bi < bi+1. + +Weight(B) = v1 + v2 + ... + vM. + +Task: +Given a sequence, output the maximum weight formed by an increasing subsequence. + +Input: + +The first line of input contains a single integer T. T test-cases follow. The first line of each test-case contains an integer N. The next line contains a1, a2 ,... , aN separated by a single space. The next line contains w1, w2, ..., wN separated by a single space. + +Output: + +For each test-case output a single integer: The maximum weight of increasing subsequences of the given sequence. +Constraints: +1 <= T <= 5 +1 <= N <= 150000 +1 <= ai <= 109, where i ∈ [1..N] +1 <= wi <= 109, where i ∈ [1..N] + +

+ +#### Sample Input/Output +``` +Input: + +2 +4 +1 2 3 4 +10 20 30 40 +8 +1 2 3 4 1 2 3 4 +10 20 30 40 15 15 15 50 + + +Output: + +100 +110 + +Input: + +2 +5 6 +2 4 3 5 1 +7 15 +6 3 12 4 5 1 2 + + +Output: + +1 1 2 2 3 1 +1 1 1 2 3 2 2 3 1 1 2 2 0 0 0 + +``` + +#### Explanation: + +``` + +In the first Example,at the first sequence, the maximum size increasing subsequence is 4, and there's only one of them. We choose B = [(1, 10), (2, 20), (3, 30), (4, 40)], and we have Weight(B) = 100. +In the second sequence, the maximum size increasing subsequence is still 4, but there are now 5 possible subsequences: +1 2 3 4 +10 20 30 40 + +1 2 3 4 +10 20 30 50 + +1 2 3 4 +10 20 15 50 + +1 2 3 4 +10 15 15 50 + +1 2 3 4 +15 15 15 50 + +Of those, the one with the greatest weight is B = [(1, 10), (2, 20), (3, 30), (4, 50)], with Weight(B) = 110. +Please note that this is not the maximum weight generated from picking the highest value element of each index. That value, 115, comes from [(1, 15), (2, 20), (3, 30), (4, 50)], which is not a valid subsequence because it cannot be created by only deleting elements in the original sequence. + + +``` +- **References** + - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) + - [Strings in Python](https://www.geeksforgeeks.org/python-string/) + - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + - [Dynamic Programming](https://www.geeksforgeeks.org/dynamic-programming/) + - [Subsequences in Arrays and Strings](https://www.geeksforgeeks.org/subarraysubstring-vs-subsequence-and-programs-to-generate-them/) + + +---- + + + +### December 21 - The Devil Towers + +#### Problem Statement + +Morpheus, the ruler of the Kingdom of Dreaming was summoned and robbed of his possessions and kept in confinement for 106 years. Upon his escape from the shackles of time, Morpheus now wishes to find his lost possessions, a scarlet ruby, a pouch of sand, and his helm, a ceremonial crown he must dorn to become King of Dreaming again. + +To his utter shock, his helm resides in the hands of a Lesser Daemon in the depths of Hell. Morpheus descends into hell and is immediately in an audience with Pandaemonium’s ruler, Lucifer Morningstar. The Lesser Daemon challenges Morpheus to a tourney of brilliance, to a game known as the Devil Towers. + +The Daemon gives Morpheus 3 towers. At the end of the game, all discs must be stacked on only a single tower, leaving the others empty. + +The Daemon claims Lucifer as his champion, while Morpheus calls you in as his, and so you are tasked with moving all discs from the first to the third tower, heeding the Daemon’s rules:- + + - You can only move one disc at a time. + + - Only the disc at the top of the tower can be moved. + + - Discs can only be moved by first moving discs above them. + + - No disc may be placed on top of a smaller disc. + + - You have only certain fixed moves: + + left->right, left->middle + + middle->left, middle->right + + right->left, right->middle + + + +

+ + +#### Sample Input/Output +``` +Input: + +Number of discs: 3 + +Output: + +The sequence of moves : +Move disk 1 from tower I to tower III +Move disk 2 from tower I to tower II +Move disk 1 from tower III to tower II +Move disk 3 from tower I to tower III +Move disk 1 from tower II to tower I +Move disk 2 from tower II to tower III +Move disk 1 from tower I to tower III + +``` + +``` +Input: + +Number of discs: 2 + +Output: + +The sequence of moves : + Move disk 1 from tower I to tower II + Move disk 2 from tower I to tower III + Move disk 1 from tower II to tower III + +``` + +#### Explanation: + +``` + +Your input will be a number indicating the total number of disks on the first (left) tower. +Your output must be the sequence of moves for the given number of discs. + +``` +- **References** + - [Recursive Algorithms](https://www.geeksforgeeks.org/introduction-to-recursion-data-structure-and-algorithm-tutorials/) + + +---- + +### December 22 - The Markowitz Paradox + +#### Problem Statement + +In the year 1977, Meyer Offerman, a rich Jewish businessman in New York and his covert associates began hunting down all Nazi officials given asylum in the United States of America as a part of Operation Paperclip. + +On one of their missions they intercepted some messages hinting at a possible Third Reich in the works, but most of the message was encrypted into some code language meant only for the Reich. After spending weeks on trying to decode the messages and worried that the Third Reich of Nazi Germany may be inevitable, Murray Markowitz was finally able to interpret them and uncover one of the most sinister plots in American history. + +The Hunters devised a plan to send bogus messages to the other Nazis on behalf of their Colonel, altering their plan of action and in the process destabilising the Reich. However, before Murray was able to encrypt the bogus messages he was killed in a subway explosion leaving Jonah Heidlbaum, the responsibility of completing his task. + +The only reference Jonah has in order to correctly translate the given text into the secret message is Murray’s old Caesar Cipher notes as the encryption algorithm he discovered was destroyed during the explosion. + +Upon studying them he discovered that the method of encryption, used a series of interwoven Caesar ciphers, that takes a codeword and given a plaintext repeats the codeword until it matches the length of the plaintext. + +L E M O N L E M O N L E + +A T T A C K A T D A W N + +The algorithm should encrypt every letter using a Caesar cipher shifted to the corresponding letter of the codeword. + +So, for example: + + - The first "A" is encrypted using a Caesar cipher of A → L (+11), so it becomes L. + + - The first "T" is encrypted using a Caesar cipher of A → E (+4), so it becomes X. + + - The second "T" is encrypted using a Caesar cipher of A → M (+12), so it becomes F. + +Subsequently, we get: +LXFOPVEFRNHR + +Help Jonah by writing a program to encrypt the bogus messages correctly. + + + +

+ + +#### Sample Input/Output +``` +Input: + +LEMON +ATTACKATDAWN + +Output: + +LXFOPVEFRNHR + +``` + +``` +Input: + +HOTDOG +CONEYISLANDONFRI + + +Output: + +JCGHMOZZTQRUUTKL + +``` + +``` +Input: + +MUSTANG +THECOLNELWILLBEATCENTRALPARKWITHTHEDETONATORDONOTAPPROACHWITHOUTBACKUP + +Output: + +FBWVOYTQFOBLYHQULVEAZDUDIAEQICLATUKPYLHNNZALVHNBZMJHKONITQAMHBAFVSVKHV + +``` + +#### Explanation: + +``` + +The first line of input is the codeword in this case “LEMON” and the next line of input is the message to be encrypted. +The message as well as the codeword do not have any spaces between the words. + +``` + +- **References** + - [Strings in C++](https://www.geeksforgeeks.org/stdstring-class-in-c/) + - [Strings in Python](https://www.geeksforgeeks.org/python-string/) + - [String in Java](https://www.geeksforgeeks.org/strings-in-java/) + - [Caesar Cipher](https://www.geeksforgeeks.org/caesar-cipher-in-cryptography/) + - [Caesar Cipher Techniques](https://www.javatpoint.com/caesar-cipher-technique) + + +---- + +### December 23 - Meeting Rooms + +#### Problem Statement + +You are given an integer n. There are n rooms numbered from 0 to n - 1. + +You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. + +Meetings are allocated to rooms in the following manner: + +Each meeting will take place in the unused room with the lowest number. + +If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting. + +When a room becomes unused, meetings that have an earlier original start time should be given the room. + +Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number. + +A half-closed interval [a, b) is the interval between a and b including a and not including b. + + + +

+ + +#### Sample Input/Output +``` +Input: + +n = 2 + +meetings = [[0,10],[1,5],[2,7],[3,4]] + + +Output: + +0 + +``` + +``` +Input: + +n = 3 + +meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]] + + +Output: + +1 + +``` + + +#### Explanation: + +``` + +For the first sample input the first line is the number of rooms and the second line of input is the meetings with the start and end time. + +- At time 0, both rooms are not being used. The first meeting starts in room 0. + +- At time 1, only room 1 is not being used. The second meeting starts in room 1. + +- At time 2, both rooms are being used. The third meeting is delayed. + +- At time 3, both rooms are being used. The fourth meeting is delayed. + +- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10). + +- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11). + + Both rooms 0 and 1 held 2 meetings, so we return 0. + + + +``` +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Sorting](https://www.geeksforgeeks.org/sorting-algorithms/) + - [Heap (Priority Queue)](https://www.geeksforgeeks.org/priority-queue-using-binary-heap/) + + +---- + +### December 24 - Cracking The Safe + +#### Problem Statement + +There is a safe protected by a password. The password is a sequence of n digits where each digit can be in the range [0, k - 1]. + +The safe has a peculiar way of checking the password. When you enter in a sequence, it checks the most recent n digits that were entered each time you type a digit. + +For example, the correct password is "345" and you enter in "012345": + + - After typing 0, the most recent 3 digits is "0", which is incorrect. + + - After typing 1, the most recent 3 digits is "01", which is incorrect. + + - After typing 2, the most recent 3 digits is "012", which is incorrect. + + - After typing 3, the most recent 3 digits is "123", which is incorrect. + + - After typing 4, the most recent 3 digits is "234", which is incorrect. + + - After typing 5, the most recent 3 digits is "345", which is correct and the safe unlocks. + +Return any string of minimum length that will unlock the safe at some point of entering it + + + + +

+ + + +#### Sample Input/Output +``` +Input: + + n = 1 + k = 2 + + +Output: + +"10" + +``` + +``` +Input: + +n = 2 +k = 2 + + +Output: + +"01100" + +``` + + +#### Explanation: + +``` +Sample - 1 + + The password is a single digit, so enter each digit. "01" would also unlock the safe. + + +Sample - 2 + +For each possible password: + +- "00" is typed in starting from the 4th digit. + +- "01" is typed in starting from the 1st digit. + +- "10" is typed in starting from the 3rd digit. + +- "11" is typed in starting from the 2nd digit. + +Thus "01100" will unlock the safe. "01100", "10011", and "11001" would also unlock the safe. + + +``` +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + - [Hierholzer’s Algorithm](https://www.geeksforgeeks.org/hierholzers-algorithm-directed-graph/) + - [Eulerian Path and Circuit](https://www.geeksforgeeks.org/eulerian-path-and-circuit/) + - [Depth First Search](https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/) + + +---- + +### December 25 - The Motorbike Race + +#### Problem Statement + +It's time for the annual exciting Motorbike Race in Bangalore. + +There are N motorcyclists taking part in the competition. George is watching the race. + +At the present moment (time 0), he has taken note of the current velocity and position of each motorcyclist. + +He wants to know at a given point of time, which motorcyclist is in a specific place in the rank list. + +Please help him! + +If at any given time two motorcyclists are in same position, the motorcyclist with the smaller index will be placed before the one with the larger index. + +To make the problem simple, he assumes that each motorcyclist is moving at a constant velocity. + +Input Format: + + The first line contains a number t (about 10) which is the number of test cases. + + Then t test cases follow. Each test case has the following form. + + The first line of the test case contains a number N (1 <= N <= 2000), the number of motorcyclists. + + The i-th line in the next N lines contains two numbers, v and x, which are the velocity and the current position of the i-th motorcyclist (1 <= v, x <= 100,000). + + The next line contains a number Q (1 <= Q <= 2000), the number of time queries. + + Each line in the next Q lines contains two numbers, t (1 <= t <= 1,000,000,000) and k (1 <= k <= n), representing the query: "at time t, which motorcyclist is positioned k-th in the rank list?" + +Output Format: + + For each test case, print Q lines, with each line containing the index of the motorcyclist for the corresponding query. + + Remember to print a new line after each test case. + + + +

+ + + +#### Sample Input/Output +``` +Input: + +1 +4 +2 100 +3 50 +4 60 +5 1 +4 +1 1 +50 2 +60 4 +100 1 + + + +Output: + +1 +4 +1 +4 + + +``` + +- **References** + - [Looping in C](https://www.tutorialspoint.com/cprogramming/c_loops.htm) + - [Looping in C++](https://www.programiz.com/cpp-programming/for-loop) + - [Looping in Java](https://www.geeksforgeeks.org/loops-in-java/) + - [Looping in Python](https://www.w3schools.com/python/python_for_loops.asp) + - [Sorting Algorithms](https://www.geeksforgeeks.org/sorting-algorithms/) + - [Searching Algorithms](https://www.geeksforgeeks.org/searching-algorithms/) + +---- + +### December 26 - Circulate + +#### Problem Statement + +A group of n people are trying to spread a word among themselves. + +The word is initially only known by the first person in the group. + +The first person may share the word with a few people that he knows, and those people may share the word with the people they know, and so on. + +The task is to determine whether the word has been successfully spread to all n people in the group. + +If the word has been successfully spread to all n people, the program should print "Spread". + +If the word has not yet been successfully spread to all n people, the program should print "Nope". + + + +

+ + + +#### Sample Input/Output +``` +Input: + +[[2], [3, 4], [2], [2]] + + +Output: + +Spread + + +``` + +``` +Input: + +[[2], [5, 4, 6], [3], [4], [5], [6]] + + +Output: + +Nope + + +``` + + +#### Explanation: + +``` + +The first person said the word to the second person. + +The second person said the word to the third and fourth person. + +Third person shares the word with the second person. + +The list has four persons and everyone knows what the word is so the output is “Spread”. + + +``` + +

+ +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + +---- + +### December 27 - Mission to Earth: Re-Calibrated + +#### Problem Statement + +AUTO, the autopilot helm of the starliner The Axiom lead a coup of robots and breached security, infiltrating the Boiler Room and Fuel Tank mechanics to steer the Axiom away from the Earth. + +WALL-E manages to follow the robots who joined AUTO’s cause in disguise to annihilate him and recalibrate the Fuel Tank mechanics so that humans can finally set foot on their home planet in 2805. + +Fuel gauges indicate, often with fractions, just how much fuel is in a tank. For instance, 1/4 indicates that a tank is 25% full, 1/2 indicates that a tank is 50% full, and 3/4 indicates that a tank is 75% full. + +You are the Fuel Engine Calibrator, FEC and WALL-E needs your help. + +The Fuel Tank’s capacity is 30,000 L. + +Implement a program that prompts the user for a fraction, formatted as X/Y, wherein each of X and Y is an integer, and then outputs, as a percentage rounded to the nearest integer, how much fuel is in the tank. + +If 1% or less remains, output E instead indicates that the tank is essentially empty. And if 99% or more remains, output F instead to indicate that the tank is essentially full. Calculate the total fuel in the Fuel Tank. + +If X or Y is not an integer, X is greater than Y, or Y is 0, prompt the user again. (It is optional for Y to be 4.) Be sure to catch any exceptions like ValueError or ZeroDivisionError. + + + +

+ + +#### Sample Input/Output +``` +Input: + +Enter the Hydrogen fuel fraction: +5/7 + +Output: + +Fuel calibration: 71.428% +Amount of fuel in tank: 21,428.4 L out of 30,000 L + +``` + +``` + +Input: + +Enter the Hydrogen fuel fraction: +722/729 + +Output: + +Fuel calibration: 99.039% +Amount of fuel in tank: 29,711.7 L out of 30,000 L +The tank is FULL! + +``` + +``` + +Input: +Enter the Hydrogen fuel fraction: +25/15600 + +Output: + +Fuel calibration: 0.160% +Amount of fuel in tank: 48 L out of 30,000 L +The tank is EMPTY!!! +Refill tank. + +``` + +``` +Input: + +Enter the Hydrogen fuel fraction: +583/0 + +Output: + +Error! + +``` + +- **References** + - [Looping in C](https://www.tutorialspoint.com/cprogramming/c_loops.htm) + - [Looping in C++](https://www.programiz.com/cpp-programming/for-loop) + - [Looping in Java](https://www.geeksforgeeks.org/loops-in-java/) + - [Looping in Python](https://www.w3schools.com/python/python_for_loops.asp) + +---- + +### December 28 - The Journey to the Eternal Engine + +#### Problem Statement + +In a dystopian world where a failed attempt at reversing the effects of global warming has left the Earth frozen over and has eradicated most of life, the only surviving souls live on a perpetually moving train called Snowpiercer. The passengers of the train are divided based on class (First, Second and Third). Passengers who did not purchase a ticket and are not of the working class of the train have been locked up in the back of the train called the Tail. Andre Layton the head Tailie inspires a rebellion along with the other Tailies to take over the Eternal Engine from the Head Engineer. + +In order for them to do this, they must leave the tail without getting caught by the Jackboots or the Brakemen. +Layton comes up with a plan to help him and a few of the other Tailies reach the Engine. They must scale the outside of the train to go from the Tail to the nearest third class compartment, in order to not get caught. One of their allies in the third class has agreed to keep the compartment door open and keep a watch for the Jackboots or the Brakemen patrolling the train. + +Conditions: + + There are only 2 breach suits and without them, if one is exposed to the freezing air, they will instantly succumb to frostbite. + + There needs to be at least 3 Tailies (including Layton) to even attempt to take over the engine. + + In order to bring back the breach suit for the other Tailies, one of the Tailies already in the compartment must come back. It is not necessary that the same Tailie comes back everytime. + + While moving along the path, both the Tailies must walk at the slower person’s pace. + + +Given the time taken for each individual Tailie to walk in seconds, calculate the minimum amount of time, in minutes, it will take for all the Tailies to make it from the Tail to the Third Class compartment successfully. + +

+ + +#### Sample Input/Output +``` +Input: + +n=3 + +Walking time: { 15, 40, 60 } + +Output: + +1.916 + +``` + +``` +Input: + +n=4 + +Walking time: { 1, 4, 7, 8, 3, 2 } + +Output: + +0.4 + +``` + +``` +Input: + +n=9 + +Walking time: { 3, 10, 12, 13, 15, 17, 21, 35, 23 } + +Output: + +2.683 + +``` + + +#### Explanation + +``` +Input format: + +In the first line of the input you are given the number of Tailies (including Layton). + +In the second line of the input you are given the walking time of each of the Tailies in seconds as an array. + + +In the first example, the first person, say Layton (15) and the second (40) travel together, this takes 40 seconds. + +Layton walks back to the Tail with the breach suit and this takes another 15 seconds. + +With the last Tailie he walks to the third class compartment and this takes 60 seconds. + +Adding all this we get, 40+15+60= 115 seconds which is 1.916 minutes. + +Sample -2 + +{ 1, 4, 7, 8, 3, 2 } + +The tailes are identified using indices 1 to 6. The Tail is T and the third class compartment is C: + +1. 1 and 6 move to C = 2s +2. 1 moves to T = 1 +3. 3 and 4 move to C= 8 +4. 6 moves to T = 2 +5. 1 and 2 move to C= 4 +6. 1 moves to T= 1 +7. 1 and 5 move to C= 3 +8. 1 moves to T = 1 +9. 1 and 6 move to C= 2 + +Adding the time: +2+1+8+2+4+1+3+1+2=24 seconds = 0.4 minutes + +``` + +- **References** + - [Looping in C](https://www.tutorialspoint.com/cprogramming/c_loops.htm) + - [Looping in C++](https://www.programiz.com/cpp-programming/for-loop) + - [Looping in Java](https://www.geeksforgeeks.org/loops-in-java/) + - [Looping in Python](https://www.w3schools.com/python/python_for_loops.asp) + - [Dynamic Programming](https://www.geeksforgeeks.org/introduction-to-dynamic-programming-data-structures-and-algorithm-tutorials/) + +---- + +### December 29 - Candies + +#### Problem Statement + +There are n children standing in a line. Each child is assigned a rating value given in the integer array ratings. + +You are giving candies to these children subjected to the following requirements: + + Each child must have at least one candy. + + Children with a higher rating get more candies than their neighbors. + +Return the minimum number of candies you need to have to distribute the candies to the children + + +

+ + +#### Sample Input/Output +``` +Input: + +n=3 +ratings = {1,2,2} + +Output: + +4 + +``` + +``` +Input: + +n=11 +ratings = {1, 4, 3, 6, 2, 1, 8, 1, 3, 7, 7} + +Output: + +19 + +``` + +#### Explanation + +``` +Input format: + +In the first line of the input you are given the number of children. + +In the second line of the input you are given the rating of each child. + +Sample -1 : + +You can allocate to the first, second and third child with 1, 2, 1 candies respectively. +The third child gets 1 candy because it satisfies the above two conditions. + +``` + +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + - [Dynamic Programming](https://www.geeksforgeeks.org/introduction-to-dynamic-programming-data-structures-and-algorithm-tutorials/) + - [Greedy Algorithms](https://www.geeksforgeeks.org/greedy-algorithms/) + +---- + +### December 30 - Precise Portion + +#### Problem Statement + +The Elite students society in Nevermore changed their riddle in order to not allow non- members of the society to enter their library. + +The puzzle is currently with 2 jugs, with different volumes and a fountain instead of the statue. +And a riddle engraved on a plate with the target volume of water made from the two jugs. + + “Wednesday’s child is full of woe, + + Amount of wisdom, + + And amount of foe. + + The wisdom of Wednesday I seek, + + Is her position from the first workday of the week.” + + +Being in the shoes of Wednesday Addams, in order to enter the library , formulate a code to fill a particular jug with the amount of water specified in the riddle with only the two jugs given. + +Note: + + 1. You can fill the jugs from the fountain + 2.Transfer water from one jug to another + 3.Empty the water from the jug into the fountain + 4.None of the jugs have markings on them, nor do you have any additional measuring device. + +Note: The examples given for the input and output format must NOT be used as sample input and must only be used to understand the FORMAT of the input. + +Input format: + + The first line of input is a 1 Dimensional array with 2 elements representing the 2 jugs with their respective volumes in ounces. + + eg. (8,1) + + Jug 1 has volume = 8 ounces + + Jug 2 has volume = 1 ounces + + The second line of input is a 1 Dimensional array with 2 elements representing the 2 jugs. + + eg. (5, 0) + + The target we must reach is : Jug 1 is filled with 5 ounces of water and Jug 2 is empty. + + +Output format: + + The output must contain the sequence of steps, where each line is a different step. + + Every line of the output is a 1 dimensional array with 2 elements representing the current volume of water in each jug at the end of that step. + + You must start with both jugs being empty, that is, (0,0) + + + +

+ + + +#### Sample Input/Output +``` +Input: + +(4, 9) +(3, 0) + +Output: + +(0, 0) +(4, 0) +(0, 4) +(4, 4) +(0, 8) +(4, 8) +(3, 9) +(3, 0) + + +``` + +``` +Input: + + ( 5, 4) + ( 3, 0) + +Output: + + (0, 0) + (5, 0) + (1, 4) + (1, 0) + (0, 1) + (5, 1) + (2, 4) + (2, 0) + (0, 2) + (5, 2) + (3, 4) + (3, 0) + +``` + +``` +Input: + +(11,9) +(0,3) + +Output: +(0, 0) +(11, 0) +(2, 9) +(0, 9) +(9, 0) +(9, 9) +(11, 7) +(0, 7) +(7, 0) +(7, 9) +(11, 5) +(0, 5) +(5, 0) +(5, 9) +(11, 3) +(0, 3) + +``` + +#### Explanation + +``` +Sample 1: +(4,9) Jug 1 is the 4 ounce jug and Jug 2 is the 9 ounce jug. +We have to get (3,0) + +1. We first start with both the jugs being empty +2. We fill the 4 ounce jug to the brim from the fountain. +3. Then we transfer the water from the 4 ounce jug to the 9 ounce jug. The 4 ounce jug is now empty and the 9 ounce jug has 4 ounces of water. +4. Fill the 4 ounce jug from the fountain. +5. Transfer the water in the 4 ounce jug to the 9 ounce jug. The 4 ounce jug is empty and the 9 ounce jug has 8 ounces of water. +6. Fill the 4 ounce jug to the brim. +7. Fill the 9 ounce jug to the brim by transferring water from the 4 ounce jug to the 9 ounce jug. The 4 ounce jug has 3 ounces of water and the 9 ounce jug is filled completely. +8. Empty the contents of the 9 ounce jug into the fountain. + + We now have the target which is (3,0) that is, jug 1 is filled with 3 ounces of water and jug 2 is empty. + +Note: There maybe more than one solution for the given input +If you do get another solution, you can still submit it. + +``` + +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) + - [Graphs](https://www.geeksforgeeks.org/graph-data-structure-and-algorithms/) + - [BFS](https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/) + +---- + +### December 31 - The Quad of Queens + +#### Problem Statement + +The queens of the Hogwarts realm were invited to a chess themed royal ball held at the kingdom’s capital city. + +The chess themed royal ball assigned each “square” of the chessboard themed floor for each royalty, with Kings, Queens and Bishops having similar stride as that of chess to keep it fun. + +But here’s the catch. The Queens hate each other. + +Now, being the prime minister of this realm, how many distinct ways would you assign seats to the Queens without them being able to attack each other, and make this more generalised for ‘N’ number of such Queens. + +Assume the floor to be an N x N grid , with N being the number of queens. + +The Queens must be placed on the grid, such that they are unable to attack another Queen, or be attacked by another Queen. + +The input must have: + + A single line input with the number of Queens. This will be the N value mentioned above. + +Each solution must contain : + + 1. The number of distinct solutions in the first line + 2. All the distinct board configurations of the N-queens' placement, where 'Q' and '.' , indicate a Queen and an empty space, respectively. + They must be printed one after the other. + They can be printed in any order. + +Note: all the Queens must be represented only as 'Q' and the empty spaces, only as '.'. + +CONSTRAINT: 1 <= N <= 9 + + + + +

+ + + +#### Sample Input/Output +``` +Input: + +4 + +Output: + +2 + +. Q . . +. . . Q +Q . . . +. . Q . + +. . Q . +Q . . . +. . . Q +. Q . . + + +``` + +``` +Input: + +1 + +Output: + +1 +Q + +``` + +``` +Input: + +5 + +Output: + +10 + +Q . . . . +. . Q . . +. . . . Q +. Q . . . +. . . Q . + +Q . . . . +. . . Q . +. Q . . . +. . . . Q +. . Q . . + +. Q . . . +. . . Q . +Q . . . . +. . Q . . +. . . . Q + +. Q . . . +. . . . Q +. . Q . . +Q . . . . +. . . Q . + +. . Q . . +Q . . . . +. . . Q . +. Q . . . +. . . . Q + +. . Q . . +. . . . Q +. Q . . . +. . . Q . +Q . . . . + +. . . Q . +Q . . . . +. . Q . . +. . . . Q +. Q . . . + +. . . Q . +. Q . . . +. . . . Q +. . Q . . +Q . . . . + +. . . . Q +. Q . . . +. . . Q . +Q . . . . +. . Q . . + +. . . . Q +. . Q . . +Q . . . . +. . . Q . +. Q . . . + +``` + +#### Explanation + +``` +For N=4 +There are 4 queens: Q1, Q2, Q3, Q4 +Let’s suppose we’re putting our first queen Q1 at position (1, 1) now for Q2 we can’t put it in row 1( because they will conflict ). + Q . . . + . . . . + . . . . + . . . . + +So for Q2 we will have to consider row 2. In row 2 we can place it in column 3 I.e at (2, 3) but then there will be no option for placing Q3 in row 3. + Q . . . + . . Q . + . . . . + . . . . + +So we backtrack one step and place Q2 at (2, 4) then we find the position for placing Q3 is (3, 2) but by this, no option will be left for placing Q4. + + + Q . . . + . . . Q + . Q . . + . . . . + +Then we have to backtrack till ‘Q1’ and put it at (1, 2) instead of (1, 1) and then all other queens can be placed safely by moving Q2 to the position (2, 4), Q3 to (3, 1), and Q4 to (4, 3). + . Q . . + . . . Q + Q . . . + . . Q . + +Similarly the other output for N=4 is also evaluated. +Proceed using this example as reference to evaluate the other inputs. + + +``` + +- **References** + - [Arrays in C++](http://www.cplusplus.com/doc/tutorial/arrays/) + - [Arrays in Java](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html) + - [Arrays in Python](https://www.w3schools.com/python/python_lists.asp) ---- diff --git a/december2.cpp b/december2.cpp new file mode 100644 index 0000000..e8c0810 --- /dev/null +++ b/december2.cpp @@ -0,0 +1,13 @@ +#include +using namespace std; + +int main(){ + string str; + cin>>str; + string ans; + ans=ans+str[str.length()-4]+str[str.length()-3]; + for (int i=0;i