diff --git a/.gitmodules b/.gitmodules index 6c4191d551..7468d2afdb 100644 --- a/.gitmodules +++ b/.gitmodules @@ -2,3 +2,6 @@ path = third_party/uncrustify url = https://github.com/uncrustify/uncrustify.git branch = uncrustify-0.66.1 +[submodule "third_party/namanager"] + path = third_party/namanager + url = https://github.com/iattempt/namanager.git diff --git a/.travis.yml b/.travis.yml index 9b6574f6c4..78746be3b2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -54,6 +54,15 @@ matrix: env: - MATRIX_EVAL="CXX=g++-7" + # Verify file name + - os: linux + language: python + python: + - "3.6" + script: + - pip install namanager + - namanager -s third_party/namanager_settings.json --required + # Check formatting of Python code - os: linux language: python diff --git a/code/artificial_intelligence/src/DBSCAN_Clustering/dbscan.py b/code/artificial_intelligence/src/dbscan_clustering/dbscan.py similarity index 100% rename from code/artificial_intelligence/src/DBSCAN_Clustering/dbscan.py rename to code/artificial_intelligence/src/dbscan_clustering/dbscan.py diff --git a/code/artificial_intelligence/src/DBSCAN_Clustering/readme.md b/code/artificial_intelligence/src/dbscan_clustering/readme.md similarity index 100% rename from code/artificial_intelligence/src/DBSCAN_Clustering/readme.md rename to code/artificial_intelligence/src/dbscan_clustering/readme.md diff --git a/code/artificial_intelligence/src/decision_tree/Decision_Trees_Information_Gain.py b/code/artificial_intelligence/src/decision_tree/decision_trees_information_gain.py similarity index 100% rename from code/artificial_intelligence/src/decision_tree/Decision_Trees_Information_Gain.py rename to code/artificial_intelligence/src/decision_tree/decision_trees_information_gain.py diff --git a/code/artificial_intelligence/src/hierachical-clustering/README.md b/code/artificial_intelligence/src/hierachical_clustering/README.md similarity index 100% rename from code/artificial_intelligence/src/hierachical-clustering/README.md rename to code/artificial_intelligence/src/hierachical_clustering/README.md diff --git a/code/artificial_intelligence/src/hierachical-clustering/hierachical_clustering.cpp b/code/artificial_intelligence/src/hierachical_clustering/hierachical_clustering.cpp similarity index 100% rename from code/artificial_intelligence/src/hierachical-clustering/hierachical_clustering.cpp rename to code/artificial_intelligence/src/hierachical_clustering/hierachical_clustering.cpp diff --git a/code/artificial_intelligence/src/hierachical-clustering/Hierarchical_Clustering.ipynb b/code/artificial_intelligence/src/hierachical_clustering/hierachical_clustering/hierarchical_clustering.ipynb similarity index 100% rename from code/artificial_intelligence/src/hierachical-clustering/Hierarchical_Clustering.ipynb rename to code/artificial_intelligence/src/hierachical_clustering/hierachical_clustering/hierarchical_clustering.ipynb diff --git a/code/artificial_intelligence/src/image_processing/Canny/canny.cpp b/code/artificial_intelligence/src/image_processing/Canny/canny.cpp deleted file mode 100644 index 7e4d668611..0000000000 --- a/code/artificial_intelligence/src/image_processing/Canny/canny.cpp +++ /dev/null @@ -1,312 +0,0 @@ -// -// canny.cpp -// Canny Edge Detector -// - -#include -#define _USE_MATH_DEFINES -#include -#include -#include "canny.h" -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/highgui/highgui.hpp" - - - -canny::canny(std::string filename) -{ - img = cv::imread(filename); - - if (!img.data) // Check for invalid input - { - cout << "Could not open or find the image" << std::endl; - - } - else - { - - std::vector> filter = createFilter(3, 3, 1); - - //Print filter - for (int i = 0; i(i, j)[0]; - int g = img.at(i, j)[1]; - int r = img.at(i, j)[2]; - - double newValue = (r * 0.2126 + g * 0.7152 + b * 0.0722); - grayscaled.at(i, j) = newValue; - - } - return grayscaled; -} - -std::vector> canny::createFilter(int row, int column, double sigmaIn) -{ - std::vector> filter; - - for (int i = 0; i < row; i++) - { - std::vector col; - for (int j = 0; j < column; j++) - { - col.push_back(-1); - } - filter.push_back(col); - } - - float coordSum = 0; - float constant = 2.0 * sigmaIn * sigmaIn; - - // Sum is for normalization - float sum = 0.0; - - for (int x = - row/2; x <= row/2; x++) - { - for (int y = -column/2; y <= column/2; y++) - { - coordSum = (x*x + y*y); - filter[x + row/2][y + column/2] = (exp(-(coordSum) / constant)) / (M_PI * constant); - sum += filter[x + row/2][y + column/2]; - } - } - - // Normalize the Filter - for (int i = 0; i < row; i++) - for (int j = 0; j < column; j++) - filter[i][j] /= sum; - - return filter; - -} - -cv::Mat canny::useFilter(cv::Mat img_in, std::vector> filterIn) -{ - int size = (int)filterIn.size()/2; - cv::Mat filteredImg = cv::Mat(img_in.rows - 2*size, img_in.cols - 2*size, CV_8UC1); - for (int i = size; i < img_in.rows - size; i++) - { - for (int j = size; j < img_in.cols - size; j++) - { - double sum = 0; - - for (int x = 0; x < filterIn.size(); x++) - for (int y = 0; y < filterIn.size(); y++) - { - sum += filterIn[x][y] * (double)(img_in.at(i + x - size, j + y - size)); - } - - filteredImg.at(i-size, j-size) = sum; - } - - } - return filteredImg; -} - -cv::Mat canny::sobel() -{ - - //Sobel X Filter - double x1[] = {-1.0, 0, 1.0}; - double x2[] = {-2.0, 0, 2.0}; - double x3[] = {-1.0, 0, 1.0}; - - std::vector> xFilter(3); - xFilter[0].assign(x1, x1+3); - xFilter[1].assign(x2, x2+3); - xFilter[2].assign(x3, x3+3); - - //Sobel Y Filter - double y1[] = {1.0, 2.0, 1.0}; - double y2[] = {0, 0, 0}; - double y3[] = {-1.0, -2.0, -1.0}; - - std::vector> yFilter(3); - yFilter[0].assign(y1, y1+3); - yFilter[1].assign(y2, y2+3); - yFilter[2].assign(y3, y3+3); - - //Limit Size - int size = (int)xFilter.size()/2; - - cv::Mat filteredImg = cv::Mat(gFiltered.rows - 2*size, gFiltered.cols - 2*size, CV_8UC1); - - angles = cv::Mat(gFiltered.rows - 2*size, gFiltered.cols - 2*size, CV_32FC1); //AngleMap - - for (int i = size; i < gFiltered.rows - size; i++) - { - for (int j = size; j < gFiltered.cols - size; j++) - { - double sumx = 0; - double sumy = 0; - - for (int x = 0; x < xFilter.size(); x++) - for (int y = 0; y < xFilter.size(); y++) - { - sumx += xFilter[x][y] * (double)(gFiltered.at(i + x - size, j + y - size)); //Sobel_X Filter Value - sumy += yFilter[x][y] * (double)(gFiltered.at(i + x - size, j + y - size)); //Sobel_Y Filter Value - } - double sumxsq = sumx*sumx; - double sumysq = sumy*sumy; - - double sq2 = sqrt(sumxsq + sumysq); - - if(sq2 > 255) //Unsigned Char Fix - sq2 =255; - filteredImg.at(i-size, j-size) = sq2; - - if(sumx==0) //Arctan Fix - angles.at(i-size, j-size) = 90; - else - angles.at(i-size, j-size) = atan(sumy/sumx); - } - } - - return filteredImg; -} - - -cv::Mat canny::nonMaxSupp() -{ - cv::Mat nonMaxSupped = cv::Mat(sFiltered.rows-2, sFiltered.cols-2, CV_8UC1); - for (int i=1; i< sFiltered.rows - 1; i++) { - for (int j=1; j(i,j); - - nonMaxSupped.at(i-1, j-1) = sFiltered.at(i,j); - //Horizontal Edge - if (((-22.5 < Tangent) && (Tangent <= 22.5)) || ((157.5 < Tangent) && (Tangent <= -157.5))) - { - if ((sFiltered.at(i,j) < sFiltered.at(i,j+1)) || (sFiltered.at(i,j) < sFiltered.at(i,j-1))) - nonMaxSupped.at(i-1, j-1) = 0; - } - //Vertical Edge - if (((-112.5 < Tangent) && (Tangent <= -67.5)) || ((67.5 < Tangent) && (Tangent <= 112.5))) - { - if ((sFiltered.at(i,j) < sFiltered.at(i+1,j)) || (sFiltered.at(i,j) < sFiltered.at(i-1,j))) - nonMaxSupped.at(i-1, j-1) = 0; - } - - //-45 Degree Edge - if (((-67.5 < Tangent) && (Tangent <= -22.5)) || ((112.5 < Tangent) && (Tangent <= 157.5))) - { - if ((sFiltered.at(i,j) < sFiltered.at(i-1,j+1)) || (sFiltered.at(i,j) < sFiltered.at(i+1,j-1))) - nonMaxSupped.at(i-1, j-1) = 0; - } - - //45 Degree Edge - if (((-157.5 < Tangent) && (Tangent <= -112.5)) || ((22.5 < Tangent) && (Tangent <= 67.5))) - { - if ((sFiltered.at(i,j) < sFiltered.at(i+1,j+1)) || (sFiltered.at(i,j) < sFiltered.at(i-1,j-1))) - nonMaxSupped.at(i-1, j-1) = 0; - } - } - } - return nonMaxSupped; -} - -cv::Mat canny::threshold(cv::Mat imgin,int low, int high) -{ - if(low > 255) - low = 255; - if(high > 255) - high = 255; - - cv::Mat EdgeMat = cv::Mat(imgin.rows, imgin.cols, imgin.type()); - - for (int i=0; i(i,j) = imgin.at(i,j); - if(EdgeMat.at(i,j) > high) - EdgeMat.at(i,j) = 255; - else if(EdgeMat.at(i,j) < low) - EdgeMat.at(i,j) = 0; - else - { - bool anyHigh = false; - bool anyBetween = false; - for (int x=i-1; x < i+2; x++) - { - for (int y = j-1; y EdgeMat.cols) //Out of bounds - continue; - else - { - if(EdgeMat.at(x,y) > high) - { - EdgeMat.at(i,j) = 255; - anyHigh = true; - break; - } - else if(EdgeMat.at(x,y) <= high && EdgeMat.at(x,y) >= low) - anyBetween = true; - } - } - if(anyHigh) - break; - } - if(!anyHigh && anyBetween) - for (int x=i-2; x < i+3; x++) - { - for (int y = j-1; y EdgeMat.rows || y > EdgeMat.cols) //Out of bounds - continue; - else - { - if(EdgeMat.at(x,y) > high) - { - EdgeMat.at(i,j) = 255; - anyHigh = true; - break; - } - } - } - if(anyHigh) - break; - } - if(!anyHigh) - EdgeMat.at(i,j) = 0; - } - } - } - return EdgeMat; -} diff --git a/code/artificial_intelligence/src/image_processing/Erode_dilate/main.cpp b/code/artificial_intelligence/src/image_processing/Erode_dilate/main.cpp deleted file mode 100644 index d2b9116ed3..0000000000 --- a/code/artificial_intelligence/src/image_processing/Erode_dilate/main.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "opencv2/imgproc/imgproc.hpp" -#include "opencv2/highgui/highgui.hpp" -#include "highgui.h" -#include -#include - -/// Global variables -cv::Mat src, erosion_dst, dilation_dst; - -int erosion_elem = 0; -int erosion_size = 0; -int dilation_elem = 0; -int dilation_size = 0; -int const max_elem = 2; -int const max_kernel_size = 21; - -/** Function Headers */ -void Erosion( int, void* ); -void Dilation( int, void* ); - -/** @function main */ -int main( int argc, char** argv ) -{ - /// Load an image - src = cv::imread( argv[1] ); - - if( !src.data ) - { return -1; } - - /// Create windows - cv::namedWindow( "Erosion Demo", CV_WINDOW_AUTOSIZE ); - cv::namedWindow( "Dilation Demo", CV_WINDOW_AUTOSIZE ); - cvMoveWindow( "Dilation Demo", src.cols, 0 ); - - /// Create Erosion Trackbar - cv::createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Erosion Demo", - &erosion_elem, max_elem, - Erosion ); - - cv::createTrackbar( "Kernel size:\n 2n +1", "Erosion Demo", - &erosion_size, max_kernel_size, - Erosion ); - - /// Create Dilation Trackbar - cv::createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Dilation Demo", - &dilation_elem, max_elem, - Dilation ); - - cv::createTrackbar( "Kernel size:\n 2n +1", "Dilation Demo", - &dilation_size, max_kernel_size, - Dilation ); - - /// Default start - Erosion( 0, 0 ); - Dilation( 0, 0 ); - - cv::waitKey(0); - return 0; -} - -/** @function Erosion */ -void Erosion( int, void* ) -{ - int erosion_type; - if( erosion_elem == 0 ){ erosion_type = cv::MORPH_RECT; } - else if( erosion_elem == 1 ){ erosion_type = cv::MORPH_CROSS; } - else if( erosion_elem == 2) { erosion_type = cv::MORPH_ELLIPSE; } - - cv::Mat element = cv::getStructuringElement( erosion_type, - cv::Size( 2*erosion_size + 1, 2*erosion_size+1 ), - cv::Point( erosion_size, erosion_size ) ); - - /// Apply the erosion operation - cv::erode( src, erosion_dst, element ); - cv::imshow( "Erosion Demo", erosion_dst ); -} - -/** @function Dilation */ -void Dilation( int, void* ) -{ - int dilation_type; - if( dilation_elem == 0 ){ dilation_type = cv::MORPH_RECT; } - else if( dilation_elem == 1 ){ dilation_type = cv::MORPH_CROSS; } - else if( dilation_elem == 2) { dilation_type = cv::MORPH_ELLIPSE; } - - cv::Mat element = cv::getStructuringElement( dilation_type, - cv::Size( 2*dilation_size + 1, 2*dilation_size+1 ), - cv::Point( dilation_size, dilation_size ) ); - /// Apply the dilation operation - cv::dilate( src, dilation_dst, element ); - cv::imshow( "Dilation Demo", dilation_dst ); -} diff --git a/code/artificial_intelligence/src/image_processing/Image_Stitching/ImageStitching.cpp b/code/artificial_intelligence/src/image_processing/Image_Stitching/ImageStitching.cpp deleted file mode 100644 index 5701d30d54..0000000000 --- a/code/artificial_intelligence/src/image_processing/Image_Stitching/ImageStitching.cpp +++ /dev/null @@ -1,309 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -int main(int argc, char* argv[]) -{ -// Default parameters - std::vector img_names; - double scale = 1; - std::string features_type = "orb";//"surf" or "orb" features type - float match_conf = 0.3f; - float conf_thresh = 1.f; - std::string adjuster_method = "ray";//"reproj" or "ray" adjuster method - bool do_wave_correct = true; - cv::detail::WaveCorrectKind wave_correct_type = cv::detail::WAVE_CORRECT_HORIZ; - std::string warp_type = "spherical"; - int expos_comp_type = cv::detail::ExposureCompensator::GAIN_BLOCKS; - std::string seam_find_type = "gc_color"; - - float blend_strength = 5; - int blend_type = cv::detail::Blender::MULTI_BAND; - std::string result_name = "img/panorama_result.jpg"; - double start_time = cv::getTickCount(); - // 1-Input images - if(argc > 1) - { - for(int i=1; i < argc; i++) - img_names.push_back(argv[i]); - } - else - { - img_names.push_back("./panorama1.jpg"); - img_names.push_back("./panorama2.jpg"); - } - // Check if have enough images - int num_images = static_cast(img_names.size()); - if (num_images < 2) {std::cout << "Need more images" << std::endl; return -1; } - // 2- Resize images and find features steps - std::cout << "Finding features..." << std::endl; - double t = cv::getTickCount(); - cv::Ptr finder; - if (features_type == "surf") - finder = cv::makePtr(); - else if (features_type == "orb") - finder = cv::makePtr(); - else - {std::cout << "Unknown 2D features type: '" << features_type << std::endl; return -1; } - - cv::Mat full_img, img; - std::vector features(num_images); - std::vector images(num_images); - - std::vector full_img_sizes(num_images); - for (int i = 0; i < num_images; ++i) - { - full_img = cv::imread(img_names[i]); - full_img_sizes[i] = full_img.size(); - if (full_img.empty()) - {std::cout << "Can't open image " << img_names[i] << std::endl; return -1; } - resize(full_img, img, cv::Size(), scale, scale); - images[i] = img.clone(); - (*finder)(img, features[i]); - features[i].img_idx = i; - std::cout << "Features in image #" << i+1 << " are : " <collectGarbage(); - full_img.release(); - img.release(); - std::cout << "Finding features, time: " << ((cv::getTickCount() - t) /cv::getTickFrequency()) << " sec" << std::endl; - // 3- cv::Match features - std::cout << "Pairwise matching" << std::endl; - t = cv::getTickCount(); - std::vector pairwise_matches; - BestOf2Nearestcv::Matcher matcher(false, match_conf); - matcher(features, pairwise_matches); - matcher.collectGarbage(); - std::cout << "Pairwise matching, time: " << ((cv::getTickCount() - t) /cv::getTickFrequency()) << " sec" << std::endl; - // 4- Select images and matches subset to build panorama - std::vector indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh); - std::vector img_subset; - std::vector img_names_subset; - std::vector full_img_sizes_subset; - - for (size_t i = 0; i < indices.size(); ++i) - { - img_names_subset.push_back(img_names[indices[i]]); - img_subset.push_back(images[indices[i]]); - full_img_sizes_subset.push_back(full_img_sizes[indices[i]]); - } - - images = img_subset; - img_names = img_names_subset; - full_img_sizes = full_img_sizes_subset; - // Estimate camera parameters rough - HomographyBasedEstimator estimator; - std::cout<<"0\n"; - std::vector cameras; - estimator(features, pairwise_matches, cameras); - // // if (!estimator(features, pairwise_matches, cameras)) - // // {std::cout <<"Homography estimation failed." << std::endl; return -1; } - std::cout<<"1\n"; - for (size_t i = 0; i < cameras.size(); ++i) - { - cv::Mat R; - std::cout<<"2\n"; - cameras[i].R.convertTo(R, CV_32F); - cameras[i].R = R; - std::cout << "Initial intrinsic #" << indices[i]+1 << ":\n" < adjuster; - if (adjuster_method == "reproj") - // "reproj" method - adjuster = cv::makePtr(); - else // "ray" method - adjuster = cv::makePtr(); - adjuster->setConfThresh(conf_thresh); - if (!(*adjuster)(features, pairwise_matches, cameras)) - {std::cout <<"Camera parameters adjusting failed." << std::endl; return -1; } - // Find median focal length - std::vector focals; - - - for (size_t i = 0; i < cameras.size(); ++i) - { - std::cout << "Camera #" << indices[i]+1 << ":\n" << cameras[i].K()<< std::endl; - focals.push_back(cameras[i].focal); - } - sort(focals.begin(), focals.end()); - float warped_image_scale; - if (focals.size() % 2 == 1) - warped_image_scale = static_cast(focals[focals.size() /2]); - else - warped_image_scale = static_cast(focals[focals.size() /2 - 1] + focals[focals.size() / 2]) * 0.5f; - // 6- Wave correlation (optional) - if (do_wave_correct) - { - std::vector rmats; - for (size_t i = 0; i < cameras.size(); ++i) - rmats.push_back(cameras[i].R.clone()); - waveCorrect(rmats, wave_correct_type); - for (size_t i = 0; i < cameras.size(); ++i) - cameras[i].R = rmats[i]; - } - // 7- Warp images - std::cout << "Warping images (auxiliary)... " << std::endl; - t = cv::getTickCount(); - std::vector corners(num_images); - std::vector masks_warped(num_images); - std::vector images_warped(num_images); - std::vector sizes(num_images); - std::vector masks(num_images); - // Prepare images masks - for (int i = 0; i < num_images; ++i) - { - masks[i].create(images[i].size(), CV_8U); - masks[i].setTo(cv::Scalar::all(255)); - } - // Map projections - cv::Ptr warper_creator; - if (warp_type == "rectilinear") - warper_creator = cv::makePtr(2.0f, 1.0f); - else if (warp_type == "cylindrical") - warper_creator = cv::makePtr(); - else if (warp_type == "spherical") - warper_creator = cv::makePtr(); - else if (warp_type == "stereographic") - warper_creator = cv::makePtr(); - else if (warp_type == "panini") - warper_creator = cv::makePtr(2.0f, 1.0f); - - if (!warper_creator) - { - std::cout << "Can't create the following warper" << warp_type << std::endl; return 1; - } - cv::Ptr warper = warper_creator->create(static_cast(warped_image_scale * scale)); - - for (int i = 0; i < num_images; ++i) - { - cv::Mat_ K; - cameras[i].K().convertTo(K, CV_32F); - float swa = (float)scale; - K(0,0) *= swa; K(0,2) *= swa; - K(1,1) *= swa; K(1,2) *= swa; - corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, images_warped[i]); - - sizes[i] = images_warped[i].size(); - warper->warp(masks[i], K, cameras[i].R, cv::INTER_NEAREST, cv::BORDER_CONSTANT, masks_warped[i]); - } - std::vector images_warped_f(num_images); - - for (int i = 0; i < num_images; ++i) - images_warped[i].convertTo(images_warped_f[i], CV_32F); - - std::cout << "Warping images, time: " << ((cv::getTickCount() - t) /cv::getTickFrequency()) << " sec" << std::endl; - // 8- Compensate exposure errors - cv::Ptr compensatcv::detail::or = ExposureCompensator::createDefault(expos_comp_type); - compensator->feed(corners, images_warped, masks_warped); - // 9- Find seam masks - cv::Ptr seam_finder; - if (seam_find_type == "no") - seam_finder = cv::makePtr(); - else if (seam_find_type == "voronoi") - seam_finder = cv::makePtr(); - else if (seam_find_type == "gc_color") - seam_finder = cv::makePtr(GraphCutSeamFinderBase::COST_COLOR); - else if (seam_find_type == "gc_colorgrad") - seam_finder = cv::makePtr(GraphCutSeamFinderBase::COST_COLOR_GRAD); - else if (seam_find_type == "dp_color") - seam_finder = cv::makePtr(DpSeamFinder::COLOR); - else if (seam_find_type == "dp_colorgrad") - seam_finder = cv::makePtr(DpSeamFinder::COLOR_GRAD); - if (!seam_finder) - { - std::cout << "Can't create the following seam finder" << seam_find_type << std::endl; - return 1; - } - - - seam_finder->find(images_warped_f, corners, masks_warped); - // Release unused memory - images.clear(); - images_warped.clear(); - images_warped_f.clear(); - masks.clear(); - // 10- Create a blender - cv::Ptr blender = cv::detail::Blender::createDefault(blend_type, false); - cv::Size dst_sz = resultRoi(corners, sizes).size(); - float blend_width = sqrt(static_cast(dst_sz.area())) *blend_strength / 100.f; - - if (blend_width < 1.f) - blender = cv::detail::Blender::createDefault(cv::detail::Blender::NO, false); - else if (blend_type == cv::detail::Blender::MULTI_BAND) - { - MultiBandcv::detail::Blender* mb = dynamic_cast(blender.get()); - mb->setNumBands(static_cast(ceil(log(blend_width)/ log(2.)) - 1.)); - std::cout << "Multi-band blender, number of bands: " << mb->numBands() << std::endl; - } - else if (blend_type == cv::detail::Blender::FEATHER) - { - Feathercv::detail::Blender* fb = dynamic_cast(blender.get()); - fb->setSharpness(1.f/blend_width); - std::cout << "Feather blender, sharpness: " << fb->sharpness() << std::endl; - } - blender->prepare(corners, sizes); - // 11- Compositing step - std::cout << "Compositing..." << std::endl; - t = cv::getTickCount(); - cv::Mat img_warped, img_warped_s; - - - - cv::Mat dilated_mask, seam_mask, mask, mask_warped; - for (int img_idx = 0; img_idx < num_images; ++img_idx) - { - std::cout << "Compositing image #" << indices[img_idx]+1 << std::endl; - // 11.1- Read image and resize it if necessary - full_img = cv::imread(img_names[img_idx]); - if (abs(scale - 1) > 1e-1) - resize(full_img, img, cv::Size(), scale, scale); - else - img = full_img; - full_img.release(); - cv::Size img_size = img.size(); - cv::Mat K; - cameras[img_idx].K().convertTo(K, CV_32F); - // 11.2- Warp the current image - warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT,img_warped); - // Warp the current image mask - mask.create(img_size, CV_8U); - mask.setTo(cv::Scalar::all(255)); - warper->warp(mask, K, cameras[img_idx].R, cv::INTER_NEAREST,cv::BORDER_CONSTANT, mask_warped); - // 11.3- Compensate exposure error step - compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped); - img_warped.convertTo(img_warped_s, CV_16S); - img_warped.release(); - img.release(); - mask.release(); - dilate(masks_warped[img_idx], dilated_mask, cv::Mat()); - resize(dilated_mask, seam_mask, mask_warped.size()); - - - mask_warped = seam_mask & mask_warped; - // 11.4- Blending images step - blender->feed(img_warped_s, mask_warped, corners[img_idx]); - } - cv::Mat result, result_mask; - blender->blend(result, result_mask); - std::cout << "Compositing, time: " << ((cv::getTickCount() - t) /cv::getTickFrequency()) << " sec" << std::endl; - imwrite(result_name, result); - // imshow(result_name,result); - // waitKey(8000); - std::cout << "Finished, total time: " << ((cv::getTickCount() - start_time)/ cv::getTickFrequency()) << " sec" << std::endl; - return 0; -} \ No newline at end of file diff --git a/code/artificial_intelligence/src/image_processing/PrewittFilter/prewitt.cpp b/code/artificial_intelligence/src/image_processing/PrewittFilter/prewitt.cpp deleted file mode 100644 index 9b0cb40f8b..0000000000 --- a/code/artificial_intelligence/src/image_processing/PrewittFilter/prewitt.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include -#include -#include - - - - -// Computes the x component of the gradient vector -// at a given point in a image. -// returns gradient in the x direction -int xGradient(cv::Mat image, int x, int y) -{ - return image.at(y-1, x-1) - +image.at(y, x-1) - +image.at(y+1, x-1) - -image.at(y-1, x+1) - -image.at(y, x+1) - -image.at(y+1, x+1); -} - -// Computes the y component of the gradient vector -// at a given point in a image -// returns gradient in the y direction - -int yGradient(cv::Mat image, int x, int y) -{ - return image.at(y-1, x-1) - +image.at(y-1, x) - +image.at(y-1, x+1) - -image.at(y+1, x-1) - -image.at(y+1, x) - -image.at(y+1, x+1); -} - -int main() -{ - - cv::Mat src, dst; - int gx, gy, sum; - - // Load an image - src = cv::imread("lena.jpg", CV_LOAD_IMAGE_GRAYSCALE); - dst = src.clone(); - if( !src.data ) - { return -1; } - - - for(int y = 0; y < src.rows; y++) - for(int x = 0; x < src.cols; x++) - dst.at(y,x) = 0.0; - - for(int y = 1; y < src.rows - 1; y++){ - for(int x = 1; x < src.cols - 1; x++){ - gx = xGradient(src, x, y); - gy = yGradient(src, x, y); - sum = abs(gx) + abs(gy); - sum = sum > 255 ? 255:sum; - sum = sum < 0 ? 0 : sum; - dst.at(y,x) = sum; - } - } - - cv::namedWindow("final"); - cv::imshow("final", dst); - - cv::namedWindow("initial"); - cv::imshow("initial", src); - - cv::waitKey(); - - - return 0; -} diff --git a/code/artificial_intelligence/src/image_processing/SobelFilter/sobel.cpp b/code/artificial_intelligence/src/image_processing/SobelFilter/sobel.cpp deleted file mode 100644 index 4bc4dd5ce6..0000000000 --- a/code/artificial_intelligence/src/image_processing/SobelFilter/sobel.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include - - - -// Computes the x component of the gradient vector -// at a given point in a image. -// returns gradient in the x direction -int xGradient(cv::Mat image, int x, int y) -{ - return image.at(y-1, x-1) - +2*image.at(y, x-1) - +image.at(y+1, x-1) - -image.at(y-1, x+1) - -2*image.at(y, x+1) - -image.at(y+1, x+1); -} - -// Computes the y component of the gradient vector -// at a given point in a image -// returns gradient in the y direction - -int yGradient(cv::Mat image, int x, int y) -{ - return image.at(y-1, x-1) - +2*image.at(y-1, x) - +image.at(y-1, x+1) - -image.at(y+1, x-1) - -2*image.at(y+1, x) - -image.at(y+1, x+1); -} - -int main() -{ - - cv::Mat src, dst; - int gx, gy, sum; - - // Load an image - src = cv::imread("lena.jpg", CV_LOAD_IMAGE_GRAYSCALE); - dst = src.clone(); - if( !src.data ) - { return -1; } - - - for(int y = 0; y < src.rows; y++) - for(int x = 0; x < src.cols; x++) - dst.at(y,x) = 0.0; - - for(int y = 1; y < src.rows - 1; y++){ - for(int x = 1; x < src.cols - 1; x++){ - gx = xGradient(src, x, y); - gy = yGradient(src, x, y); - sum = abs(gx) + abs(gy); - sum = sum > 255 ? 255:sum; - sum = sum < 0 ? 0 : sum; - dst.at(y,x) = sum; - } - } - - cv::namedWindow("final"); - cv::imshow("final", dst); - - cv::namedWindow("initial"); - cv::imshow("initial", src); - - cv::waitKey(); - - - return 0; -} diff --git a/code/artificial_intelligence/src/image_processing/canny/canny.cpp b/code/artificial_intelligence/src/image_processing/canny/canny.cpp new file mode 100644 index 0000000000..3e689e6c72 --- /dev/null +++ b/code/artificial_intelligence/src/image_processing/canny/canny.cpp @@ -0,0 +1,308 @@ +// +// canny.cpp +// Canny Edge Detector +// + +#include +#define _USE_MATH_DEFINES +#include +#include +#include "canny.h" +#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui/highgui.hpp" + + + +canny::canny(std::string filename) +{ + img = cv::imread(filename); + + if (!img.data) // Check for invalid input + cout << "Could not open or find the image" << std::endl; + + else + { + + std::vector> filter = createFilter(3, 3, 1); + + //Print filter + for (int i = 0; i < filter.size(); i++) + for (int j = 0; j < filter[i].size(); j++) + cout << filter[i][j] << " "; + + grayscaled = cv::Mat(img.toGrayScale()); //Grayscale the image + gFiltered = cv::Mat(useFilter(grayscaled, filter)); //Gaussian Filter + sFiltered = cv::Mat(sobel()); //Sobel Filter + + non = cv::Mat(nonMaxSupp()); //Non-Maxima Suppression + thres = cv::Mat(threshold(non, 20, 40)); //Double Threshold and Finalize + + cv::namedWindow("Original"); + cv::namedWindow("GrayScaled"); + cv::namedWindow("Gaussian Blur"); + cv::namedWindow("Sobel Filtered"); + cv::namedWindow("Non-Maxima Supp."); + cv::namedWindow("Final"); + + cv::imshow("Original", img); + cv::imshow("GrayScaled", grayscaled); + cv::imshow("Gaussian Blur", gFiltered); + cv::imshow("Sobel Filtered", sFiltered); + cv::imshow("Non-Maxima Supp.", non); + cv::imshow("Final", thres); + + } +} + +Mat canny::toGrayScale() +{ + grayscaled = Mat(img.rows, img.cols, CV_8UC1); //To one channel + for (int i = 0; i < img.rows; i++) + for (int j = 0; j < img.cols; j++) + { + int b = img.at(i, j)[0]; + int g = img.at(i, j)[1]; + int r = img.at(i, j)[2]; + + double newValue = (r * 0.2126 + g * 0.7152 + b * 0.0722); + grayscaled.at(i, j) = newValue; + + } + return grayscaled; +} + +std::vector> canny::createFilter(int row, int column, double sigmaIn) +{ + std::vector> filter; + + for (int i = 0; i < row; i++) + { + std::vector col; + for (int j = 0; j < column; j++) + col.push_back(-1); + filter.push_back(col); + } + + float coordSum = 0; + float constant = 2.0 * sigmaIn * sigmaIn; + + // Sum is for normalization + float sum = 0.0; + + for (int x = -row / 2; x <= row / 2; x++) + for (int y = -column / 2; y <= column / 2; y++) + { + coordSum = (x * x + y * y); + filter[x + row / 2][y + column / 2] = (exp(-(coordSum) / constant)) / (M_PI * constant); + sum += filter[x + row / 2][y + column / 2]; + } + + // Normalize the Filter + for (int i = 0; i < row; i++) + for (int j = 0; j < column; j++) + filter[i][j] /= sum; + + return filter; + +} + +cv::Mat canny::useFilter(cv::Mat img_in, std::vector> filterIn) +{ + int size = (int)filterIn.size() / 2; + cv::Mat filteredImg = cv::Mat(img_in.rows - 2 * size, img_in.cols - 2 * size, CV_8UC1); + for (int i = size; i < img_in.rows - size; i++) + for (int j = size; j < img_in.cols - size; j++) + { + double sum = 0; + + for (int x = 0; x < filterIn.size(); x++) + for (int y = 0; y < filterIn.size(); y++) + sum += filterIn[x][y] * (double)(img_in.at(i + x - size, j + y - size)); + + + filteredImg.at(i - size, j - size) = sum; + } + + return filteredImg; +} + +cv::Mat canny::sobel() +{ + + //Sobel X Filter + double x1[] = {-1.0, 0, 1.0}; + double x2[] = {-2.0, 0, 2.0}; + double x3[] = {-1.0, 0, 1.0}; + + std::vector> xFilter(3); + xFilter[0].assign(x1, x1 + 3); + xFilter[1].assign(x2, x2 + 3); + xFilter[2].assign(x3, x3 + 3); + + //Sobel Y Filter + double y1[] = {1.0, 2.0, 1.0}; + double y2[] = {0, 0, 0}; + double y3[] = {-1.0, -2.0, -1.0}; + + std::vector> yFilter(3); + yFilter[0].assign(y1, y1 + 3); + yFilter[1].assign(y2, y2 + 3); + yFilter[2].assign(y3, y3 + 3); + + //Limit Size + int size = (int)xFilter.size() / 2; + + cv::Mat filteredImg = cv::Mat(gFiltered.rows - 2 * size, gFiltered.cols - 2 * size, CV_8UC1); + + angles = cv::Mat(gFiltered.rows - 2 * size, gFiltered.cols - 2 * size, CV_32FC1); //AngleMap + + for (int i = size; i < gFiltered.rows - size; i++) + for (int j = size; j < gFiltered.cols - size; j++) + { + double sumx = 0; + double sumy = 0; + + for (int x = 0; x < xFilter.size(); x++) + for (int y = 0; y < xFilter.size(); y++) + { + sumx += xFilter[x][y] * + (double)(gFiltered.at(i + x - size, j + y - size)); //Sobel_X Filter Value + sumy += yFilter[x][y] * + (double)(gFiltered.at(i + x - size, j + y - size)); //Sobel_Y Filter Value + } + double sumxsq = sumx * sumx; + double sumysq = sumy * sumy; + + double sq2 = sqrt(sumxsq + sumysq); + + if (sq2 > 255) //Unsigned Char Fix + sq2 = 255; + filteredImg.at(i - size, j - size) = sq2; + + if (sumx == 0) //Arctan Fix + angles.at(i - size, j - size) = 90; + else + angles.at(i - size, j - size) = atan(sumy / sumx); + } + + return filteredImg; +} + + +cv::Mat canny::nonMaxSupp() +{ + cv::Mat nonMaxSupped = cv::Mat(sFiltered.rows - 2, sFiltered.cols - 2, CV_8UC1); + for (int i = 1; i < sFiltered.rows - 1; i++) + for (int j = 1; j < sFiltered.cols - 1; j++) + { + float Tangent = angles.at(i, j); + + nonMaxSupped.at(i - 1, j - 1) = sFiltered.at(i, j); + //Horizontal Edge + if (((-22.5 < Tangent) && (Tangent <= 22.5)) || + ((157.5 < Tangent) && (Tangent <= -157.5))) + if ((sFiltered.at(i, + j) < + sFiltered.at(i, + j + 1)) || + (sFiltered.at(i, j) < sFiltered.at(i, j - 1))) + nonMaxSupped.at(i - 1, j - 1) = 0; + //Vertical Edge + if (((-112.5 < Tangent) && (Tangent <= -67.5)) || + ((67.5 < Tangent) && (Tangent <= 112.5))) + if ((sFiltered.at(i, + j) < + sFiltered.at(i + 1, + j)) || + (sFiltered.at(i, j) < sFiltered.at(i - 1, j))) + nonMaxSupped.at(i - 1, j - 1) = 0; + + //-45 Degree Edge + if (((-67.5 < Tangent) && (Tangent <= -22.5)) || + ((112.5 < Tangent) && (Tangent <= 157.5))) + if ((sFiltered.at(i, + j) < + sFiltered.at(i - 1, + j + 1)) || + (sFiltered.at(i, j) < sFiltered.at(i + 1, j - 1))) + nonMaxSupped.at(i - 1, j - 1) = 0; + + //45 Degree Edge + if (((-157.5 < Tangent) && (Tangent <= -112.5)) || + ((22.5 < Tangent) && (Tangent <= 67.5))) + if ((sFiltered.at(i, + j) < + sFiltered.at(i + 1, + j + 1)) || + (sFiltered.at(i, j) < sFiltered.at(i - 1, j - 1))) + nonMaxSupped.at(i - 1, j - 1) = 0; + } + return nonMaxSupped; +} + +cv::Mat canny::threshold(cv::Mat imgin, int low, int high) +{ + if (low > 255) + low = 255; + if (high > 255) + high = 255; + + cv::Mat EdgeMat = cv::Mat(imgin.rows, imgin.cols, imgin.type()); + + for (int i = 0; i < imgin.rows; i++) + for (int j = 0; j < imgin.cols; j++) + { + EdgeMat.at(i, j) = imgin.at(i, j); + if (EdgeMat.at(i, j) > high) + EdgeMat.at(i, j) = 255; + else if (EdgeMat.at(i, j) < low) + EdgeMat.at(i, j) = 0; + else + { + bool anyHigh = false; + bool anyBetween = false; + for (int x = i - 1; x < i + 2; x++) + { + for (int y = j - 1; y < j + 2; y++) + { + if (x <= 0 || y <= 0 || EdgeMat.rows || y > EdgeMat.cols) //Out of bounds + continue; + else + { + if (EdgeMat.at(x, y) > high) + { + EdgeMat.at(i, j) = 255; + anyHigh = true; + break; + } + else if (EdgeMat.at(x, + y) <= high && EdgeMat.at(x, y) >= low) + anyBetween = true; + } + } + if (anyHigh) + break; + } + if (!anyHigh && anyBetween) + for (int x = i - 2; x < i + 3; x++) + { + for (int y = j - 1; y < j + 3; y++) + { + if (x < 0 || y < 0 || x > EdgeMat.rows || y > EdgeMat.cols) //Out of bounds + continue; + else if (EdgeMat.at(x, y) > high) + { + EdgeMat.at(i, j) = 255; + anyHigh = true; + break; + } + } + if (anyHigh) + break; + } + if (!anyHigh) + EdgeMat.at(i, j) = 0; + } + } + return EdgeMat; +} diff --git a/code/artificial_intelligence/src/image_processing/Canny/canny.h b/code/artificial_intelligence/src/image_processing/canny/canny.h similarity index 100% rename from code/artificial_intelligence/src/image_processing/Canny/canny.h rename to code/artificial_intelligence/src/image_processing/canny/canny.h diff --git a/code/artificial_intelligence/src/image_processing/Canny/main.cpp b/code/artificial_intelligence/src/image_processing/canny/main.cpp similarity index 97% rename from code/artificial_intelligence/src/image_processing/Canny/main.cpp rename to code/artificial_intelligence/src/image_processing/canny/main.cpp index 17e75d8a4c..fb91b19396 100644 --- a/code/artificial_intelligence/src/image_processing/Canny/main.cpp +++ b/code/artificial_intelligence/src/image_processing/canny/main.cpp @@ -17,7 +17,6 @@ int main() { std::string filePath = "lena.jpg"; //Filepath of input image canny cny(filePath); - + return 0; } - diff --git a/code/artificial_intelligence/src/image_processing/erode_dilate/main.cpp b/code/artificial_intelligence/src/image_processing/erode_dilate/main.cpp new file mode 100644 index 0000000000..6118c74aa4 --- /dev/null +++ b/code/artificial_intelligence/src/image_processing/erode_dilate/main.cpp @@ -0,0 +1,97 @@ +#include "opencv2/imgproc/imgproc.hpp" +#include "opencv2/highgui/highgui.hpp" +#include "highgui.h" +#include +#include + +/// Global variables +cv::Mat src, erosion_dst, dilation_dst; + +int erosion_elem = 0; +int erosion_size = 0; +int dilation_elem = 0; +int dilation_size = 0; +int const max_elem = 2; +int const max_kernel_size = 21; + +/** Function Headers */ +void Erosion( int, void* ); +void Dilation( int, void* ); + +/** @function main */ +int main( int argc, char** argv ) +{ + /// Load an image + src = cv::imread( argv[1] ); + + if (!src.data) + return -1; + /// Create windows + cv::namedWindow( "Erosion Demo", CV_WINDOW_AUTOSIZE ); + cv::namedWindow( "Dilation Demo", CV_WINDOW_AUTOSIZE ); + cvMoveWindow( "Dilation Demo", src.cols, 0 ); + + /// Create Erosion Trackbar + cv::createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Erosion Demo", + &erosion_elem, max_elem, + Erosion ); + + cv::createTrackbar( "Kernel size:\n 2n +1", "Erosion Demo", + &erosion_size, max_kernel_size, + Erosion ); + + /// Create Dilation Trackbar + cv::createTrackbar( "Element:\n 0: Rect \n 1: Cross \n 2: Ellipse", "Dilation Demo", + &dilation_elem, max_elem, + Dilation ); + + cv::createTrackbar( "Kernel size:\n 2n +1", "Dilation Demo", + &dilation_size, max_kernel_size, + Dilation ); + + /// Default start + Erosion( 0, 0 ); + Dilation( 0, 0 ); + + cv::waitKey(0); + return 0; +} + +/** @function Erosion */ +void Erosion( int, void* ) +{ + int erosion_type; + if (erosion_elem == 0) + erosion_type = cv::MORPH_RECT; + else if (erosion_elem == 1) + erosion_type = cv::MORPH_CROSS; + else if (erosion_elem == 2) + erosion_type = cv::MORPH_ELLIPSE; + cv::Mat element = cv::getStructuringElement( erosion_type, + cv::Size( 2 * erosion_size + 1, + 2 * erosion_size + 1 ), + cv::Point( erosion_size, erosion_size ) ); + + /// Apply the erosion operation + cv::erode( src, erosion_dst, element ); + cv::imshow( "Erosion Demo", erosion_dst ); +} + +/** @function Dilation */ +void Dilation( int, void* ) +{ + int dilation_type; + if (dilation_elem == 0) + dilation_type = cv::MORPH_RECT; + else if (dilation_elem == 1) + dilation_type = cv::MORPH_CROSS; + else if (dilation_elem == 2) + dilation_type = cv::MORPH_ELLIPSE; + cv::Mat element = cv::getStructuringElement( dilation_type, + cv::Size( 2 * dilation_size + 1, + 2 * dilation_size + 1 ), + cv::Point( dilation_size, dilation_size ) ); + /// Apply the dilation operation + cv::dilate( src, dilation_dst, element ); + cv::imshow( "Dilation Demo", dilation_dst ); +} diff --git a/code/artificial_intelligence/src/image_processing/houghTransform/main.cpp b/code/artificial_intelligence/src/image_processing/houghTransform/main.cpp deleted file mode 100644 index ec19ab23d9..0000000000 --- a/code/artificial_intelligence/src/image_processing/houghTransform/main.cpp +++ /dev/null @@ -1,143 +0,0 @@ -#include -#include -#include -#include -#include - -#define WINDOW_NAME "Hough Transformation" -#define THETA_GRANULARITY (4*100) -#define RHO_GRANULARITY 1 - -IplImage *img_read; -IplImage *img_edges; -IplImage *img_sine; -int *img_sine_arr; -int threshold; - -CvSize img_attrib_dim; -CvSize img_attrib_sine; -int max_rho; - -/***************************************************************** - * create and destroy gui items - *****************************************************************/ -void create_gui() { - cvNamedWindow(WINDOW_NAME); - - max_rho = sqrt(img_attrib_dim.width*img_attrib_dim.width + img_attrib_dim.height*img_attrib_dim.height); - - printf("Image diagonal size (max rho): %d\n", max_rho); - img_attrib_sine.width = THETA_GRANULARITY; - img_attrib_sine.height = RHO_GRANULARITY * max_rho * 2; - - img_sine_arr = (int *)malloc(img_attrib_sine.width*img_attrib_sine.height*sizeof(int)); - img_edges = cvCreateImage(img_attrib_dim, IPL_DEPTH_8U, 1); - img_sine = cvCreateImage(img_attrib_sine, IPL_DEPTH_8U, 1); - cvZero(img_sine); -} - -void destroy_gui() { - cvDestroyWindow(WINDOW_NAME); - cvReleaseImage(&img_read); - cvReleaseImage(&img_edges); - cvReleaseImage(&img_sine); -} - -/***************************************************************** - * display a message and wait for escape key to continue - *****************************************************************/ -void disp_msg(const char *msg) { - printf("%s. Press escape to continue.\n", msg); - char c; - do { - c = cvWaitKey(500); - } while (27 != c); -} - -/***************************************************************** - * main. - * 1. read image - * 2. detect edges - * 3. hough transform to detect lines - *****************************************************************/ -int main(int argc, char **argv) { - if(argc < 3) { - printf("Usage: %s \n", argv[0]); - return 1; - } - - img_read = cvLoadImage(argv[1]); - if(NULL == img_read) { - printf("Error loading image %s\n", argv[1]); - return -1; - } - img_attrib_dim = cvGetSize(img_read); - threshold = atoi(argv[2]); - - create_gui(); - - cvShowImage(WINDOW_NAME, img_read); - printf("Original image size: %d x %d\n", img_attrib_dim.width, img_attrib_dim.height); - disp_msg("This is the original image"); - - // detect edges - cvCvtColor(img_read, img_edges, CV_BGR2GRAY); - cvLaplace(img_edges, img_edges, 3); - cvThreshold(img_edges, img_edges, 200, 255, CV_THRESH_BINARY); - cvShowImage(WINDOW_NAME, img_edges); - disp_msg("This is the edge detected image"); - printf("working...\n"); - - // for each pixel in the edge - int max_dest = 0; - int min_dest = INT_MAX; - for(int y=0; y < img_edges->height; y++) { - uchar *row_ptr = (uchar*) (img_edges->imageData + y*img_edges->widthStep); - for(int x=0; x < img_edges->width; x++) { - if(*(row_ptr+x) > 0) { - for(int theta_div=0; theta_div < THETA_GRANULARITY; theta_div++) { - double theta = (CV_PI * theta_div / THETA_GRANULARITY) - (CV_PI / 2); - int rho = (int)round(cos(theta)*x + sin(theta)*y + max_rho); - int *dest = img_sine_arr + rho*img_attrib_sine.width + theta_div; - int d_val = *dest = *dest + 1; - if(d_val > max_dest) max_dest = d_val; - if(d_val < min_dest) min_dest = d_val; - } - } - } - } - - // scale the intensity for contrast - float div = ((float)max_dest)/255; - printf("max_dest: %d, min_dest: %d, scale: %f\n", max_dest, min_dest, div); - for(int y=0; y < img_sine->height; y++) { - uchar *row_ptr = (uchar*) (img_sine->imageData + y*img_sine->widthStep); - for(int x=0; x < img_sine->width; x++) { - int val = (*((img_sine_arr + y*img_attrib_sine.width) + x))/div; - if (val < 0) val = 0; - *(row_ptr + x) = val; - } - } - - // find rho and theta at maximum positions (within the threshold) - int possible_edge = round((float)max_dest/div) - threshold; - printf("possible edges beyond %d\n", possible_edge); - for(int y=0; y < img_sine->height; y++) { - uchar *row_ptr = (uchar*) (img_sine->imageData + y*img_sine->widthStep); - for(int x=0; x < img_sine->width; x++) { - int val = *(row_ptr + x); - if(possible_edge <= val) { - float theta_rad = (CV_PI * x / THETA_GRANULARITY) - (CV_PI/2); - float theta_deg = theta_rad * 180 / CV_PI; - printf("val: %d at rho %d, theta %f (%f degrees)\n", val, y-max_rho, theta_rad, theta_deg); - } - } - } - - // display the plotted intensity graph of the hough space - cvShowImage(WINDOW_NAME, img_sine); - disp_msg("this is the hough space image"); - - destroy_gui(); - return 0; -} diff --git a/code/artificial_intelligence/src/image_processing/houghtransform/main.cpp b/code/artificial_intelligence/src/image_processing/houghtransform/main.cpp new file mode 100644 index 0000000000..9f34bbd3b3 --- /dev/null +++ b/code/artificial_intelligence/src/image_processing/houghtransform/main.cpp @@ -0,0 +1,162 @@ +#include +#include +#include +#include +#include + +#define WINDOW_NAME "Hough Transformation" +#define THETA_GRANULARITY (4 * 100) +#define RHO_GRANULARITY 1 + +IplImage *img_read; +IplImage *img_edges; +IplImage *img_sine; +int *img_sine_arr; +int threshold; + +CvSize img_attrib_dim; +CvSize img_attrib_sine; +int max_rho; + +/***************************************************************** +* create and destroy gui items +*****************************************************************/ +void create_gui() +{ + cvNamedWindow(WINDOW_NAME); + + max_rho = sqrt( + img_attrib_dim.width * img_attrib_dim.width + img_attrib_dim.height * + img_attrib_dim.height); + + printf("Image diagonal size (max rho): %d\n", max_rho); + img_attrib_sine.width = THETA_GRANULARITY; + img_attrib_sine.height = RHO_GRANULARITY * max_rho * 2; + + img_sine_arr = (int *)malloc(img_attrib_sine.width * img_attrib_sine.height * sizeof(int)); + img_edges = cvCreateImage(img_attrib_dim, IPL_DEPTH_8U, 1); + img_sine = cvCreateImage(img_attrib_sine, IPL_DEPTH_8U, 1); + cvZero(img_sine); +} + +void destroy_gui() +{ + cvDestroyWindow(WINDOW_NAME); + cvReleaseImage(&img_read); + cvReleaseImage(&img_edges); + cvReleaseImage(&img_sine); +} + +/***************************************************************** +* display a message and wait for escape key to continue +*****************************************************************/ +void disp_msg(const char *msg) +{ + printf("%s. Press escape to continue.\n", msg); + char c; + do + c = cvWaitKey(500); + while (27 != c); +} + +/***************************************************************** +* main. +* 1. read image +* 2. detect edges +* 3. hough transform to detect lines +*****************************************************************/ +int main(int argc, char **argv) +{ + if (argc < 3) + { + printf("Usage: %s \n", argv[0]); + return 1; + } + + img_read = cvLoadImage(argv[1]); + if (NULL == img_read) + { + printf("Error loading image %s\n", argv[1]); + return -1; + } + img_attrib_dim = cvGetSize(img_read); + threshold = atoi(argv[2]); + + create_gui(); + + cvShowImage(WINDOW_NAME, img_read); + printf("Original image size: %d x %d\n", img_attrib_dim.width, img_attrib_dim.height); + disp_msg("This is the original image"); + + // detect edges + cvCvtColor(img_read, img_edges, CV_BGR2GRAY); + cvLaplace(img_edges, img_edges, 3); + cvThreshold(img_edges, img_edges, 200, 255, CV_THRESH_BINARY); + cvShowImage(WINDOW_NAME, img_edges); + disp_msg("This is the edge detected image"); + printf("working...\n"); + + // for each pixel in the edge + int max_dest = 0; + int min_dest = INT_MAX; + for (int y = 0; y < img_edges->height; y++) + { + uchar *row_ptr = (uchar*) (img_edges->imageData + y * img_edges->widthStep); + for (int x = 0; x < img_edges->width; x++) + { + if (*(row_ptr + x) > 0) + for (int theta_div = 0; theta_div < THETA_GRANULARITY; theta_div++) + { + double theta = (CV_PI * theta_div / THETA_GRANULARITY) - (CV_PI / 2); + int rho = (int)round(cos(theta) * x + sin(theta) * y + max_rho); + int *dest = img_sine_arr + rho * img_attrib_sine.width + theta_div; + int d_val = *dest = *dest + 1; + if (d_val > max_dest) + max_dest = d_val; + if (d_val < min_dest) + min_dest = d_val; + } + } + } + + // scale the intensity for contrast + float div = ((float)max_dest) / 255; + printf("max_dest: %d, min_dest: %d, scale: %f\n", max_dest, min_dest, div); + for (int y = 0; y < img_sine->height; y++) + { + uchar *row_ptr = (uchar*) (img_sine->imageData + y * img_sine->widthStep); + for (int x = 0; x < img_sine->width; x++) + { + int val = (*((img_sine_arr + y * img_attrib_sine.width) + x)) / div; + if (val < 0) + val = 0; + *(row_ptr + x) = val; + } + } + + // find rho and theta at maximum positions (within the threshold) + int possible_edge = round((float)max_dest / div) - threshold; + printf("possible edges beyond %d\n", possible_edge); + for (int y = 0; y < img_sine->height; y++) + { + uchar *row_ptr = (uchar*) (img_sine->imageData + y * img_sine->widthStep); + for (int x = 0; x < img_sine->width; x++) + { + int val = *(row_ptr + x); + if (possible_edge <= val) + { + float theta_rad = (CV_PI * x / THETA_GRANULARITY) - (CV_PI / 2); + float theta_deg = theta_rad * 180 / CV_PI; + printf("val: %d at rho %d, theta %f (%f degrees)\n", val, y - max_rho, theta_rad, + theta_deg); + } + } + } + + // display the plotted intensity graph of the hough space + cvShowImage(WINDOW_NAME, img_sine); + disp_msg("this is the hough space image"); + + destroy_gui(); + return 0; +} diff --git a/code/artificial_intelligence/src/image_processing/Image_Stitching/a.out b/code/artificial_intelligence/src/image_processing/image_stitching/a.out similarity index 100% rename from code/artificial_intelligence/src/image_processing/Image_Stitching/a.out rename to code/artificial_intelligence/src/image_processing/image_stitching/a.out diff --git a/code/artificial_intelligence/src/image_processing/image_stitching/imagestitching.cpp b/code/artificial_intelligence/src/image_processing/image_stitching/imagestitching.cpp new file mode 100644 index 0000000000..21a0c0a3a5 --- /dev/null +++ b/code/artificial_intelligence/src/image_processing/image_stitching/imagestitching.cpp @@ -0,0 +1,330 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char* argv[]) +{ +// Default parameters + std::vector img_names; + double scale = 1; + std::string features_type = "orb"; //"surf" or "orb" features type + float match_conf = 0.3f; + float conf_thresh = 1.f; + std::string adjuster_method = "ray"; //"reproj" or "ray" adjuster method + bool do_wave_correct = true; + cv::detail::WaveCorrectKind wave_correct_type = cv::detail::WAVE_CORRECT_HORIZ; + std::string warp_type = "spherical"; + int expos_comp_type = cv::detail::ExposureCompensator::GAIN_BLOCKS; + std::string seam_find_type = "gc_color"; + + float blend_strength = 5; + int blend_type = cv::detail::Blender::MULTI_BAND; + std::string result_name = "img/panorama_result.jpg"; + double start_time = cv::getTickCount(); + // 1-Input images + if (argc > 1) + for (int i = 1; i < argc; i++) + img_names.push_back(argv[i]); + else + { + img_names.push_back("./panorama1.jpg"); + img_names.push_back("./panorama2.jpg"); + } + // Check if have enough images + int num_images = static_cast(img_names.size()); + if (num_images < 2) + { + std::cout << "Need more images" << std::endl; return -1; + } + // 2- Resize images and find features steps + std::cout << "Finding features..." << std::endl; + double t = cv::getTickCount(); + cv::Ptr finder; + if (features_type == "surf") + finder = cv::makePtr(); + else if (features_type == "orb") + finder = cv::makePtr(); + else + { + std::cout << "Unknown 2D features type: '" << features_type << std::endl; return -1; + } + + cv::Mat full_img, img; + std::vector features(num_images); + std::vector images(num_images); + + std::vector full_img_sizes(num_images); + for (int i = 0; i < num_images; ++i) + { + full_img = cv::imread(img_names[i]); + full_img_sizes[i] = full_img.size(); + if (full_img.empty()) + { + std::cout << "Can't open image " << img_names[i] << std::endl; return -1; + } + resize(full_img, img, cv::Size(), scale, scale); + images[i] = img.clone(); + (*finder)(img, features[i]); + features[i].img_idx = i; + std::cout << "Features in image #" << i + 1 << " are : " << features[i].keypoints.size() << + std::endl; + } + finder->collectGarbage(); + full_img.release(); + img.release(); + std::cout << "Finding features, time: " << + ((cv::getTickCount() - t) / cv::getTickFrequency()) << " sec" << std::endl; + // 3- cv::Match features + std::cout << "Pairwise matching" << std::endl; + t = cv::getTickCount(); + std::vector pairwise_matches; + BestOf2Nearestcv::Matcher matcher(false, match_conf); + matcher(features, pairwise_matches); + matcher.collectGarbage(); + std::cout << "Pairwise matching, time: " << + ((cv::getTickCount() - t) / cv::getTickFrequency()) << " sec" << std::endl; + // 4- Select images and matches subset to build panorama + std::vector indices = leaveBiggestComponent(features, pairwise_matches, conf_thresh); + std::vector img_subset; + std::vector img_names_subset; + std::vector full_img_sizes_subset; + + for (size_t i = 0; i < indices.size(); ++i) + { + img_names_subset.push_back(img_names[indices[i]]); + img_subset.push_back(images[indices[i]]); + full_img_sizes_subset.push_back(full_img_sizes[indices[i]]); + } + + images = img_subset; + img_names = img_names_subset; + full_img_sizes = full_img_sizes_subset; + // Estimate camera parameters rough + HomographyBasedEstimator estimator; + std::cout << "0\n"; + std::vector cameras; + estimator(features, pairwise_matches, cameras); + // // if (!estimator(features, pairwise_matches, cameras)) + // // {std::cout <<"Homography estimation failed." << std::endl; return -1; } + std::cout << "1\n"; + for (size_t i = 0; i < cameras.size(); ++i) + { + cv::Mat R; + std::cout << "2\n"; + cameras[i].R.convertTo(R, CV_32F); + cameras[i].R = R; + std::cout << "Initial intrinsic #" << indices[i] + 1 << ":\n" << cameras[i].K() << + std::endl; + } + // 5- Refine camera parameters globally + cv::Ptr adjuster; + if (adjuster_method == "reproj") + // "reproj" method + adjuster = cv::makePtr(); + else // "ray" method + adjuster = cv::makePtr(); + adjuster->setConfThresh(conf_thresh); + if (!(*adjuster)(features, pairwise_matches, cameras)) + { + std::cout << "Camera parameters adjusting failed." << std::endl; return -1; + } + // Find median focal length + std::vector focals; + + + for (size_t i = 0; i < cameras.size(); ++i) + { + std::cout << "Camera #" << indices[i] + 1 << ":\n" << cameras[i].K() << std::endl; + focals.push_back(cameras[i].focal); + } + sort(focals.begin(), focals.end()); + float warped_image_scale; + if (focals.size() % 2 == 1) + warped_image_scale = static_cast(focals[focals.size() / 2]); + else + warped_image_scale = + static_cast(focals[focals.size() / 2 - 1] + focals[focals.size() / 2]) * 0.5f; + // 6- Wave correlation (optional) + if (do_wave_correct) + { + std::vector rmats; + for (size_t i = 0; i < cameras.size(); ++i) + rmats.push_back(cameras[i].R.clone()); + waveCorrect(rmats, wave_correct_type); + for (size_t i = 0; i < cameras.size(); ++i) + cameras[i].R = rmats[i]; + } + // 7- Warp images + std::cout << "Warping images (auxiliary)... " << std::endl; + t = cv::getTickCount(); + std::vector corners(num_images); + std::vector masks_warped(num_images); + std::vector images_warped(num_images); + std::vector sizes(num_images); + std::vector masks(num_images); + // Prepare images masks + for (int i = 0; i < num_images; ++i) + { + masks[i].create(images[i].size(), CV_8U); + masks[i].setTo(cv::Scalar::all(255)); + } + // Map projections + cv::Ptr warper_creator; + if (warp_type == "rectilinear") + warper_creator = cv::makePtr(2.0f, 1.0f); + else if (warp_type == "cylindrical") + warper_creator = cv::makePtr(); + else if (warp_type == "spherical") + warper_creator = cv::makePtr(); + else if (warp_type == "stereographic") + warper_creator = cv::makePtr(); + else if (warp_type == "panini") + warper_creator = cv::makePtr(2.0f, 1.0f); + + if (!warper_creator) + { + std::cout << "Can't create the following warper" << warp_type << std::endl; return 1; + } + cv::Ptr warper = + warper_creator->create(static_cast(warped_image_scale * scale)); + + for (int i = 0; i < num_images; ++i) + { + cv::Mat_ K; + cameras[i].K().convertTo(K, CV_32F); + float swa = (float)scale; + K(0, 0) *= swa; K(0, 2) *= swa; + K(1, 1) *= swa; K(1, 2) *= swa; + corners[i] = warper->warp(images[i], K, cameras[i].R, INTER_LINEAR, BORDER_REFLECT, + images_warped[i]); + + sizes[i] = images_warped[i].size(); + warper->warp(masks[i], K, cameras[i].R, cv::INTER_NEAREST, cv::BORDER_CONSTANT, + masks_warped[i]); + } + std::vector images_warped_f(num_images); + + for (int i = 0; i < num_images; ++i) + images_warped[i].convertTo(images_warped_f[i], CV_32F); + + std::cout << "Warping images, time: " << ((cv::getTickCount() - t) / cv::getTickFrequency()) << + " sec" << std::endl; + // 8- Compensate exposure errors + cv::Ptr compensatcv::detail::or = + ExposureCompensator::createDefault(expos_comp_type); + compensator->feed(corners, images_warped, masks_warped); + // 9- Find seam masks + cv::Ptr seam_finder; + if (seam_find_type == "no") + seam_finder = cv::makePtr(); + else if (seam_find_type == "voronoi") + seam_finder = cv::makePtr(); + else if (seam_find_type == "gc_color") + seam_finder = cv::makePtr(GraphCutSeamFinderBase::COST_COLOR); + else if (seam_find_type == "gc_colorgrad") + seam_finder = cv::makePtr(GraphCutSeamFinderBase::COST_COLOR_GRAD); + else if (seam_find_type == "dp_color") + seam_finder = cv::makePtr(DpSeamFinder::COLOR); + else if (seam_find_type == "dp_colorgrad") + seam_finder = cv::makePtr(DpSeamFinder::COLOR_GRAD); + if (!seam_finder) + { + std::cout << "Can't create the following seam finder" << seam_find_type << std::endl; + return 1; + } + + + seam_finder->find(images_warped_f, corners, masks_warped); + // Release unused memory + images.clear(); + images_warped.clear(); + images_warped_f.clear(); + masks.clear(); + // 10- Create a blender + cv::Ptr blender = cv::detail::Blender::createDefault(blend_type, false); + cv::Size dst_sz = resultRoi(corners, sizes).size(); + float blend_width = sqrt(static_cast(dst_sz.area())) * blend_strength / 100.f; + + if (blend_width < 1.f) + blender = cv::detail::Blender::createDefault(cv::detail::Blender::NO, false); + else if (blend_type == cv::detail::Blender::MULTI_BAND) + { + MultiBandcv::detail::Blender* mb = + dynamic_cast(blender.get()); + mb->setNumBands(static_cast(ceil(log(blend_width) / log(2.)) - 1.)); + std::cout << "Multi-band blender, number of bands: " << mb->numBands() << std::endl; + } + else if (blend_type == cv::detail::Blender::FEATHER) + { + Feathercv::detail::Blender* fb = dynamic_cast(blender.get()); + fb->setSharpness(1.f / blend_width); + std::cout << "Feather blender, sharpness: " << fb->sharpness() << std::endl; + } + blender->prepare(corners, sizes); + // 11- Compositing step + std::cout << "Compositing..." << std::endl; + t = cv::getTickCount(); + cv::Mat img_warped, img_warped_s; + + + + cv::Mat dilated_mask, seam_mask, mask, mask_warped; + for (int img_idx = 0; img_idx < num_images; ++img_idx) + { + std::cout << "Compositing image #" << indices[img_idx] + 1 << std::endl; + // 11.1- Read image and resize it if necessary + full_img = cv::imread(img_names[img_idx]); + if (abs(scale - 1) > 1e-1) + resize(full_img, img, cv::Size(), scale, scale); + else + img = full_img; + full_img.release(); + cv::Size img_size = img.size(); + cv::Mat K; + cameras[img_idx].K().convertTo(K, CV_32F); + // 11.2- Warp the current image + warper->warp(img, K, cameras[img_idx].R, INTER_LINEAR, BORDER_REFLECT, img_warped); + // Warp the current image mask + mask.create(img_size, CV_8U); + mask.setTo(cv::Scalar::all(255)); + warper->warp(mask, K, cameras[img_idx].R, cv::INTER_NEAREST, cv::BORDER_CONSTANT, + mask_warped); + // 11.3- Compensate exposure error step + compensator->apply(img_idx, corners[img_idx], img_warped, mask_warped); + img_warped.convertTo(img_warped_s, CV_16S); + img_warped.release(); + img.release(); + mask.release(); + dilate(masks_warped[img_idx], dilated_mask, cv::Mat()); + resize(dilated_mask, seam_mask, mask_warped.size()); + + + mask_warped = seam_mask & mask_warped; + // 11.4- Blending images step + blender->feed(img_warped_s, mask_warped, corners[img_idx]); + } + cv::Mat result, result_mask; + blender->blend(result, result_mask); + std::cout << "Compositing, time: " << ((cv::getTickCount() - t) / cv::getTickFrequency()) << + " sec" << std::endl; + imwrite(result_name, result); + // imshow(result_name,result); + // waitKey(8000); + std::cout << "Finished, total time: " << + ((cv::getTickCount() - start_time) / cv::getTickFrequency()) << " sec" << std::endl; + return 0; +} diff --git a/code/artificial_intelligence/src/image_processing/Image_Stitching/img/panorama3_1.jpeg b/code/artificial_intelligence/src/image_processing/image_stitching/img/panorama3_1.jpeg similarity index 100% rename from code/artificial_intelligence/src/image_processing/Image_Stitching/img/panorama3_1.jpeg rename to code/artificial_intelligence/src/image_processing/image_stitching/img/panorama3_1.jpeg diff --git a/code/artificial_intelligence/src/image_processing/Image_Stitching/img/panorama3_2.jpeg b/code/artificial_intelligence/src/image_processing/image_stitching/img/panorama3_2.jpeg similarity index 100% rename from code/artificial_intelligence/src/image_processing/Image_Stitching/img/panorama3_2.jpeg rename to code/artificial_intelligence/src/image_processing/image_stitching/img/panorama3_2.jpeg diff --git a/code/artificial_intelligence/src/image_processing/Image_Stitching/img/panorama_result.jpg b/code/artificial_intelligence/src/image_processing/image_stitching/img/panorama_result.jpg similarity index 100% rename from code/artificial_intelligence/src/image_processing/Image_Stitching/img/panorama_result.jpg rename to code/artificial_intelligence/src/image_processing/image_stitching/img/panorama_result.jpg diff --git a/code/artificial_intelligence/src/image_processing/install-opencv.sh b/code/artificial_intelligence/src/image_processing/install_opencv.sh similarity index 100% rename from code/artificial_intelligence/src/image_processing/install-opencv.sh rename to code/artificial_intelligence/src/image_processing/install_opencv.sh diff --git a/code/artificial_intelligence/src/image_processing/prewittfilter/prewitt.cpp b/code/artificial_intelligence/src/image_processing/prewittfilter/prewitt.cpp new file mode 100644 index 0000000000..e62ee80216 --- /dev/null +++ b/code/artificial_intelligence/src/image_processing/prewittfilter/prewitt.cpp @@ -0,0 +1,72 @@ +#include +#include +#include + + + + +// Computes the x component of the gradient vector +// at a given point in a image. +// returns gradient in the x direction +int xGradient(cv::Mat image, int x, int y) +{ + return image.at(y - 1, x - 1) + + image.at(y, x - 1) + + image.at(y + 1, x - 1) + - image.at(y - 1, x + 1) + - image.at(y, x + 1) + - image.at(y + 1, x + 1); +} + +// Computes the y component of the gradient vector +// at a given point in a image +// returns gradient in the y direction + +int yGradient(cv::Mat image, int x, int y) +{ + return image.at(y - 1, x - 1) + + image.at(y - 1, x) + + image.at(y - 1, x + 1) + - image.at(y + 1, x - 1) + - image.at(y + 1, x) + - image.at(y + 1, x + 1); +} + +int main() +{ + + cv::Mat src, dst; + int gx, gy, sum; + + // Load an image + src = cv::imread("lena.jpg", CV_LOAD_IMAGE_GRAYSCALE); + dst = src.clone(); + if (!src.data) + return -1; + + for (int y = 0; y < src.rows; y++) + for (int x = 0; x < src.cols; x++) + dst.at(y, x) = 0.0; + + for (int y = 1; y < src.rows - 1; y++) + for (int x = 1; x < src.cols - 1; x++) + { + gx = xGradient(src, x, y); + gy = yGradient(src, x, y); + sum = abs(gx) + abs(gy); + sum = sum > 255 ? 255 : sum; + sum = sum < 0 ? 0 : sum; + dst.at(y, x) = sum; + } + + cv::namedWindow("final"); + cv::imshow("final", dst); + + cv::namedWindow("initial"); + cv::imshow("initial", src); + + cv::waitKey(); + + + return 0; +} diff --git a/code/artificial_intelligence/src/image_processing/sobelfilter/sobel.cpp b/code/artificial_intelligence/src/image_processing/sobelfilter/sobel.cpp new file mode 100644 index 0000000000..35e037af5e --- /dev/null +++ b/code/artificial_intelligence/src/image_processing/sobelfilter/sobel.cpp @@ -0,0 +1,71 @@ +#include +#include +#include + + + +// Computes the x component of the gradient vector +// at a given point in a image. +// returns gradient in the x direction +int xGradient(cv::Mat image, int x, int y) +{ + return image.at(y - 1, x - 1) + + 2 * image.at(y, x - 1) + + image.at(y + 1, x - 1) + - image.at(y - 1, x + 1) + - 2 * image.at(y, x + 1) + - image.at(y + 1, x + 1); +} + +// Computes the y component of the gradient vector +// at a given point in a image +// returns gradient in the y direction + +int yGradient(cv::Mat image, int x, int y) +{ + return image.at(y - 1, x - 1) + + 2 * image.at(y - 1, x) + + image.at(y - 1, x + 1) + - image.at(y + 1, x - 1) + - 2 * image.at(y + 1, x) + - image.at(y + 1, x + 1); +} + +int main() +{ + + cv::Mat src, dst; + int gx, gy, sum; + + // Load an image + src = cv::imread("lena.jpg", CV_LOAD_IMAGE_GRAYSCALE); + dst = src.clone(); + if (!src.data) + return -1; + + for (int y = 0; y < src.rows; y++) + for (int x = 0; x < src.cols; x++) + dst.at(y, x) = 0.0; + + for (int y = 1; y < src.rows - 1; y++) + for (int x = 1; x < src.cols - 1; x++) + { + gx = xGradient(src, x, y); + gy = yGradient(src, x, y); + sum = abs(gx) + abs(gy); + sum = sum > 255 ? 255 : sum; + sum = sum < 0 ? 0 : sum; + dst.at(y, x) = sum; + } + + cv::namedWindow("final"); + cv::imshow("final", dst); + + cv::namedWindow("initial"); + cv::imshow("initial", src); + + cv::waitKey(); + + + return 0; +} diff --git a/code/artificial_intelligence/src/ISODATA_Clustering/ISODATA.py b/code/artificial_intelligence/src/isodata_clustering/isodata.py similarity index 100% rename from code/artificial_intelligence/src/ISODATA_Clustering/ISODATA.py rename to code/artificial_intelligence/src/isodata_clustering/isodata.py diff --git a/code/artificial_intelligence/src/ISODATA_Clustering/readme.md b/code/artificial_intelligence/src/isodata_clustering/readme.md similarity index 100% rename from code/artificial_intelligence/src/ISODATA_Clustering/readme.md rename to code/artificial_intelligence/src/isodata_clustering/readme.md diff --git a/code/artificial_intelligence/src/k_Nearest_Neighbours/iris.data b/code/artificial_intelligence/src/k_nearest_neighbours/iris.data similarity index 100% rename from code/artificial_intelligence/src/k_Nearest_Neighbours/iris.data rename to code/artificial_intelligence/src/k_nearest_neighbours/iris.data diff --git a/code/artificial_intelligence/src/k_Nearest_Neighbours/k_Nearest_Neighbours.py b/code/artificial_intelligence/src/k_nearest_neighbours/k_nearest_neighbours.py similarity index 100% rename from code/artificial_intelligence/src/k_Nearest_Neighbours/k_Nearest_Neighbours.py rename to code/artificial_intelligence/src/k_nearest_neighbours/k_nearest_neighbours.py diff --git a/code/artificial_intelligence/src/Linear_Regression/README.md b/code/artificial_intelligence/src/linear_regression/README.md similarity index 100% rename from code/artificial_intelligence/src/Linear_Regression/README.md rename to code/artificial_intelligence/src/linear_regression/README.md diff --git a/code/artificial_intelligence/src/Linear_Regression/linear_regression.java b/code/artificial_intelligence/src/linear_regression/linear_regression.java similarity index 100% rename from code/artificial_intelligence/src/Linear_Regression/linear_regression.java rename to code/artificial_intelligence/src/linear_regression/linear_regression.java diff --git a/code/artificial_intelligence/src/Linear_Regression/linear_regression.py b/code/artificial_intelligence/src/linear_regression/linear_regression.py similarity index 100% rename from code/artificial_intelligence/src/Linear_Regression/linear_regression.py rename to code/artificial_intelligence/src/linear_regression/linear_regression.py diff --git a/code/artificial_intelligence/src/Linear_Regression/linear_regression.swift b/code/artificial_intelligence/src/linear_regression/linear_regression.swift similarity index 100% rename from code/artificial_intelligence/src/Linear_Regression/linear_regression.swift rename to code/artificial_intelligence/src/linear_regression/linear_regression.swift diff --git a/code/artificial_intelligence/src/Linear_Regression/linear_regression.js b/code/artificial_intelligence/src/linear_regression/linear_regression/linear_regression.js similarity index 100% rename from code/artificial_intelligence/src/Linear_Regression/linear_regression.js rename to code/artificial_intelligence/src/linear_regression/linear_regression/linear_regression.js diff --git a/code/artificial_intelligence/src/linear_regression/linearregression.js b/code/artificial_intelligence/src/linear_regression/linearregression.js new file mode 100644 index 0000000000..c6eff448a7 --- /dev/null +++ b/code/artificial_intelligence/src/linear_regression/linearregression.js @@ -0,0 +1,73 @@ +/** +* Author: Daniel Hernández (https://github.com/DHDaniel) + +* Description: Multivariate linear regression that uses the normal equation +* as an optimizer. The normal equation is fine to use +* when n, the number of features being worked with, is +* less than 10,000. Beyond that, it is best to use +* other methods like gradient descent. + +* Requirements: +* - mathjs (install using npm) +*/ + +// this is installed using npm: `npm install mathjs` +const math = require("mathjs"); + +/** +* Solves the normal equation and returns the optimum thetas for +* the model hypothesis. +* @param {mathjs.matrix} X - a matrix of m x n (rows x columns), where m is the number of records and n is the number of features. It is common practice to add a leading 1 to each row m, in order to account for the y-intercept in regression. +* @param {mathjs.matrix} y - a vector of m x 1 (rows x columns), where m is the number of records. Contains the labeled values for each corresponding X row. +* @returns {mathjs.matrix} A n x 1 matrix containing the optimal thetas. +*/ +const normalEqn = function normalEqn(X, y) { + // computing the equation theta = (X^T * X)^-1 * X^T * y + var thetas = math.multiply(math.transpose(X), X); + thetas = math.multiply(math.inv(thetas), math.transpose(X)); + thetas = math.multiply(thetas, y); + // returning a vector containing thetas for hypothesis + return thetas; +} + +/** +* Trains and returns a function that serves as a model for predicting values y based on an input X +* @param {mathjs.matrix} X - a matrix of m x n (rows x columns), where m is the number of records and n is the number of features. It is common practice to add a leading 1 to each row m, in order to account for the y-intercept in regression. +* @param {mathjs.matrix} y - a vector of m x 1 (rows x columns), where m is the number of records. Contains the labeled values for each corresponding X row. +* @returns {function} A function that accepts a matrix X, and returns predictions for each row. +*/ +const train = function train(X, y) { + // getting optimal thetas using normal equation + var thetas = normalEqn(X, y); + // creating a model that accepts + const model = function (X) { + // create predictions by multiplying theta^T * X, creating a model that looks like (theta_1 * x_1) + (theta_2 * x_2) + (theta_3 * x_3) etc. + return math.multiply(math.transpose(thetas), X); + } + return model; +} + + + +/* TESTS */ + +// test values for X and y +var Xmatrix = math.matrix([[2, 1, 3], [7, 1, 9], [1, 8, 1], [3, 7, 4]]); +var ylabels = math.matrix([[2], [5], [5], [6]]); + +// should show thetas (in the _data part of object) to be 0.008385744234748138, 0.5681341719077577, 0.4863731656184376 +console.log(normalEqn(Xmatrix, ylabels)); + +// test values #2 +Xmatrix = math.matrix([[1], [2], [3], [4]]); +ylabels = math.matrix([[1], [2], [3], [4]]); + +// should show theta of 1 (which forms a perfectly diagonal line if plotted) +console.log(normalEqn(Xmatrix, ylabels)); + +// test values #3 +Xmatrix = math.matrix([[1, 5], [1, 2], [1, 4], [1, 5]]); +ylabels = math.matrix([[1], [6], [4], [2]]); + +// should show thetas of 9.25 and -1.5 +console.log(normalEqn(Xmatrix, ylabels)); diff --git a/code/artificial_intelligence/src/Logistic_Regression/README.md b/code/artificial_intelligence/src/logistic_regression/README.md similarity index 100% rename from code/artificial_intelligence/src/Logistic_Regression/README.md rename to code/artificial_intelligence/src/logistic_regression/README.md diff --git a/code/artificial_intelligence/src/Logistic_Regression/Logistic_Regression.py b/code/artificial_intelligence/src/logistic_regression/logistic_regression.py similarity index 100% rename from code/artificial_intelligence/src/Logistic_Regression/Logistic_Regression.py rename to code/artificial_intelligence/src/logistic_regression/logistic_regression.py diff --git a/code/artificial_intelligence/src/naive_bayes/Naive_Bayes.py b/code/artificial_intelligence/src/naive_bayes/naive_bayes.py similarity index 100% rename from code/artificial_intelligence/src/naive_bayes/Naive_Bayes.py rename to code/artificial_intelligence/src/naive_bayes/naive_bayes.py diff --git a/code/artificial_intelligence/src/nearest_sequence_memory/nsm_MATLAB/main.m b/code/artificial_intelligence/src/nearest_sequence_memory/nsm_matlab/main.m similarity index 100% rename from code/artificial_intelligence/src/nearest_sequence_memory/nsm_MATLAB/main.m rename to code/artificial_intelligence/src/nearest_sequence_memory/nsm_matlab/main.m diff --git a/code/artificial_intelligence/src/nearest_sequence_memory/nsm_MATLAB/nsm_agent.m b/code/artificial_intelligence/src/nearest_sequence_memory/nsm_matlab/nsm_agent.m similarity index 100% rename from code/artificial_intelligence/src/nearest_sequence_memory/nsm_MATLAB/nsm_agent.m rename to code/artificial_intelligence/src/nearest_sequence_memory/nsm_matlab/nsm_agent.m diff --git a/code/artificial_intelligence/src/nearest_sequence_memory/nsm_MATLAB/simulator.m b/code/artificial_intelligence/src/nearest_sequence_memory/nsm_matlab/simulator.m similarity index 100% rename from code/artificial_intelligence/src/nearest_sequence_memory/nsm_MATLAB/simulator.m rename to code/artificial_intelligence/src/nearest_sequence_memory/nsm_matlab/simulator.m diff --git a/code/artificial_intelligence/src/Neural_Style_Transfer/neural_style_transfer.ipynb b/code/artificial_intelligence/src/neural_style_transfer/neural_style_transfer.ipynb similarity index 100% rename from code/artificial_intelligence/src/Neural_Style_Transfer/neural_style_transfer.ipynb rename to code/artificial_intelligence/src/neural_style_transfer/neural_style_transfer.ipynb diff --git a/code/artificial_intelligence/src/Neural_Style_Transfer/neural_style_transfer.py b/code/artificial_intelligence/src/neural_style_transfer/neural_style_transfer.py similarity index 100% rename from code/artificial_intelligence/src/Neural_Style_Transfer/neural_style_transfer.py rename to code/artificial_intelligence/src/neural_style_transfer/neural_style_transfer.py diff --git a/code/artificial_intelligence/src/q_learning/qLearning.js b/code/artificial_intelligence/src/q_learning/qlearning.js similarity index 100% rename from code/artificial_intelligence/src/q_learning/qLearning.js rename to code/artificial_intelligence/src/q_learning/qlearning.js diff --git a/code/artificial_intelligence/src/SAT/togasat.cpp b/code/artificial_intelligence/src/sat/togasat.cpp similarity index 100% rename from code/artificial_intelligence/src/SAT/togasat.cpp rename to code/artificial_intelligence/src/sat/togasat.cpp diff --git a/code/artificial_intelligence/src/support_vector_machine/SVM.py b/code/artificial_intelligence/src/support_vector_machine/svm.py similarity index 100% rename from code/artificial_intelligence/src/support_vector_machine/SVM.py rename to code/artificial_intelligence/src/support_vector_machine/svm.py diff --git a/code/artificial_intelligence/src/TSP/algo.md b/code/artificial_intelligence/src/tsp/algo.md similarity index 100% rename from code/artificial_intelligence/src/TSP/algo.md rename to code/artificial_intelligence/src/tsp/algo.md diff --git a/code/artificial_intelligence/src/TSP/euc_100 b/code/artificial_intelligence/src/tsp/euc_100 similarity index 100% rename from code/artificial_intelligence/src/TSP/euc_100 rename to code/artificial_intelligence/src/tsp/euc_100 diff --git a/code/artificial_intelligence/src/TSP/euc_250 b/code/artificial_intelligence/src/tsp/euc_250 similarity index 100% rename from code/artificial_intelligence/src/TSP/euc_250 rename to code/artificial_intelligence/src/tsp/euc_250 diff --git a/code/artificial_intelligence/src/TSP/euc_500 b/code/artificial_intelligence/src/tsp/euc_500 similarity index 100% rename from code/artificial_intelligence/src/TSP/euc_500 rename to code/artificial_intelligence/src/tsp/euc_500 diff --git a/code/artificial_intelligence/src/TSP/Makefile b/code/artificial_intelligence/src/tsp/makefile similarity index 100% rename from code/artificial_intelligence/src/TSP/Makefile rename to code/artificial_intelligence/src/tsp/makefile diff --git a/code/artificial_intelligence/src/TSP/noneuc_100 b/code/artificial_intelligence/src/tsp/noneuc_100 similarity index 100% rename from code/artificial_intelligence/src/TSP/noneuc_100 rename to code/artificial_intelligence/src/tsp/noneuc_100 diff --git a/code/artificial_intelligence/src/TSP/noneuc_250 b/code/artificial_intelligence/src/tsp/noneuc_250 similarity index 100% rename from code/artificial_intelligence/src/TSP/noneuc_250 rename to code/artificial_intelligence/src/tsp/noneuc_250 diff --git a/code/artificial_intelligence/src/TSP/noneuc_500 b/code/artificial_intelligence/src/tsp/noneuc_500 similarity index 100% rename from code/artificial_intelligence/src/TSP/noneuc_500 rename to code/artificial_intelligence/src/tsp/noneuc_500 diff --git a/code/artificial_intelligence/src/TSP/salesman.cpp b/code/artificial_intelligence/src/tsp/salesman.cpp similarity index 100% rename from code/artificial_intelligence/src/TSP/salesman.cpp rename to code/artificial_intelligence/src/tsp/salesman.cpp diff --git a/code/backtracking/src/algorithm-x/README.md b/code/backtracking/src/algorithm_x/README.md similarity index 100% rename from code/backtracking/src/algorithm-x/README.md rename to code/backtracking/src/algorithm_x/README.md diff --git a/code/backtracking/src/algorithm-x/algo-x.cpp b/code/backtracking/src/algorithm_x/algo_x.cpp similarity index 100% rename from code/backtracking/src/algorithm-x/algo-x.cpp rename to code/backtracking/src/algorithm_x/algo_x.cpp diff --git a/code/backtracking/src/crossword_puzzle/CrosswordPuzzle.java b/code/backtracking/src/crossword_puzzle/crosswordpuzzle.java similarity index 100% rename from code/backtracking/src/crossword_puzzle/CrosswordPuzzle.java rename to code/backtracking/src/crossword_puzzle/crosswordpuzzle.java diff --git a/code/backtracking/src/knight_tour/knight_tour_withoutBT.c b/code/backtracking/src/knight_tour/knight_tour_withoutbt.c similarity index 100% rename from code/backtracking/src/knight_tour/knight_tour_withoutBT.c rename to code/backtracking/src/knight_tour/knight_tour_withoutbt.c diff --git a/code/backtracking/src/n_queen/nQueen.hs b/code/backtracking/src/n_queen/nqueen.hs similarity index 100% rename from code/backtracking/src/n_queen/nQueen.hs rename to code/backtracking/src/n_queen/nqueen.hs diff --git a/code/backtracking/src/n_queen/NQueen.java b/code/backtracking/src/n_queen/nqueen.java similarity index 100% rename from code/backtracking/src/n_queen/NQueen.java rename to code/backtracking/src/n_queen/nqueen.java diff --git a/code/backtracking/src/n_queen/NQueen_Backtracking.cpp b/code/backtracking/src/n_queen/nqueen_backtracking.cpp similarity index 100% rename from code/backtracking/src/n_queen/NQueen_Backtracking.cpp rename to code/backtracking/src/n_queen/nqueen_backtracking.cpp diff --git a/code/backtracking/src/n_queen/Nqueen_Backtracking.rs b/code/backtracking/src/n_queen/nqueen_backtracking.rs similarity index 100% rename from code/backtracking/src/n_queen/Nqueen_Backtracking.rs rename to code/backtracking/src/n_queen/nqueen_backtracking.rs diff --git a/code/backtracking/src/n_queen/NQueen_BitImp.cpp b/code/backtracking/src/n_queen/nqueen_bitimp.cpp similarity index 100% rename from code/backtracking/src/n_queen/NQueen_BitImp.cpp rename to code/backtracking/src/n_queen/nqueen_bitimp.cpp diff --git a/code/backtracking/src/n_queen/NQueen_Bitset.cpp b/code/backtracking/src/n_queen/nqueen_bitset.cpp similarity index 100% rename from code/backtracking/src/n_queen/NQueen_Bitset.cpp rename to code/backtracking/src/n_queen/nqueen_bitset.cpp diff --git a/code/backtracking/src/number_of_ways_in_maze/noOfWaysinMaze.c b/code/backtracking/src/number_of_ways_in_maze/noofwaysinmaze.c similarity index 100% rename from code/backtracking/src/number_of_ways_in_maze/noOfWaysinMaze.c rename to code/backtracking/src/number_of_ways_in_maze/noofwaysinmaze.c diff --git a/code/backtracking/src/powerset/PowerSet.java b/code/backtracking/src/powerset/powerset.java similarity index 100% rename from code/backtracking/src/powerset/PowerSet.java rename to code/backtracking/src/powerset/powerset.java diff --git a/code/backtracking/src/subset_sum/Subset_Sum.c b/code/backtracking/src/subset_sum/subset_sum.c similarity index 100% rename from code/backtracking/src/subset_sum/Subset_Sum.c rename to code/backtracking/src/subset_sum/subset_sum.c diff --git a/code/backtracking/src/subset_sum/Subset_Sum_Duplicates.py b/code/backtracking/src/subset_sum/subset_sum_duplicates.py similarity index 100% rename from code/backtracking/src/subset_sum/Subset_Sum_Duplicates.py rename to code/backtracking/src/subset_sum/subset_sum_duplicates.py diff --git a/code/backtracking/src/subset_sum/SubsetSum.java b/code/backtracking/src/subset_sum/subsetsum.java similarity index 100% rename from code/backtracking/src/subset_sum/SubsetSum.java rename to code/backtracking/src/subset_sum/subsetsum.java diff --git a/code/backtracking/src/subset_sum/SubsetSum.py b/code/backtracking/src/subset_sum/subsetsum.py similarity index 100% rename from code/backtracking/src/subset_sum/SubsetSum.py rename to code/backtracking/src/subset_sum/subsetsum.py diff --git a/code/backtracking/src/sudoku_solve/SudokuSolve.c b/code/backtracking/src/sudoku_solve/sudokusolve.c similarity index 100% rename from code/backtracking/src/sudoku_solve/SudokuSolve.c rename to code/backtracking/src/sudoku_solve/sudokusolve.c diff --git a/code/backtracking/src/sudoku_solve/SudokuSolve.cpp b/code/backtracking/src/sudoku_solve/sudokusolve.cpp similarity index 100% rename from code/backtracking/src/sudoku_solve/SudokuSolve.cpp rename to code/backtracking/src/sudoku_solve/sudokusolve.cpp diff --git a/code/bit_manipulation/src/bit_division/bitDivision.c b/code/bit_manipulation/src/bit_division/bitdivision.c similarity index 100% rename from code/bit_manipulation/src/bit_division/bitDivision.c rename to code/bit_manipulation/src/bit_division/bitdivision.c diff --git a/code/bit_manipulation/src/bit_division/bitDivision.go b/code/bit_manipulation/src/bit_division/bitdivision.go similarity index 100% rename from code/bit_manipulation/src/bit_division/bitDivision.go rename to code/bit_manipulation/src/bit_division/bitdivision.go diff --git a/code/bit_manipulation/src/bit_division/BitDivision.java b/code/bit_manipulation/src/bit_division/bitdivision.java similarity index 100% rename from code/bit_manipulation/src/bit_division/BitDivision.java rename to code/bit_manipulation/src/bit_division/bitdivision.java diff --git a/code/bit_manipulation/src/bit_division/bitDivision.js b/code/bit_manipulation/src/bit_division/bitdivision.js similarity index 100% rename from code/bit_manipulation/src/bit_division/bitDivision.js rename to code/bit_manipulation/src/bit_division/bitdivision.js diff --git a/code/bit_manipulation/src/bit_division/bitDivison.py b/code/bit_manipulation/src/bit_division/bitdivison.py similarity index 100% rename from code/bit_manipulation/src/bit_division/bitDivison.py rename to code/bit_manipulation/src/bit_division/bitdivison.py diff --git a/code/bit_manipulation/src/byte_swapper/ByteSwapper.java b/code/bit_manipulation/src/byte_swapper/byteswapper.java similarity index 100% rename from code/bit_manipulation/src/byte_swapper/ByteSwapper.java rename to code/bit_manipulation/src/byte_swapper/byteswapper.java diff --git a/code/bit_manipulation/src/convert_number_binary/ConvertNumberBinary.java b/code/bit_manipulation/src/convert_number_binary/convertnumberbinary.java similarity index 100% rename from code/bit_manipulation/src/convert_number_binary/ConvertNumberBinary.java rename to code/bit_manipulation/src/convert_number_binary/convertnumberbinary.java diff --git a/code/bit_manipulation/src/convert_number_binary/intToBinary.py b/code/bit_manipulation/src/convert_number_binary/inttobinary.py similarity index 100% rename from code/bit_manipulation/src/convert_number_binary/intToBinary.py rename to code/bit_manipulation/src/convert_number_binary/inttobinary.py diff --git a/code/bit_manipulation/src/count_set_bits/CountSetBits.java b/code/bit_manipulation/src/count_set_bits/countsetbits.java similarity index 100% rename from code/bit_manipulation/src/count_set_bits/CountSetBits.java rename to code/bit_manipulation/src/count_set_bits/countsetbits.java diff --git a/code/bit_manipulation/src/count_set_bits/countSetBits.js b/code/bit_manipulation/src/count_set_bits/countsetbits.js similarity index 100% rename from code/bit_manipulation/src/count_set_bits/countSetBits.js rename to code/bit_manipulation/src/count_set_bits/countsetbits.js diff --git a/code/bit_manipulation/src/flip_bits/FlipBits.java b/code/bit_manipulation/src/flip_bits/flipbits.java similarity index 100% rename from code/bit_manipulation/src/flip_bits/FlipBits.java rename to code/bit_manipulation/src/flip_bits/flipbits.java diff --git a/code/bit_manipulation/src/lonely_integer/LonelyInt.java b/code/bit_manipulation/src/lonely_integer/lonelyint.java similarity index 100% rename from code/bit_manipulation/src/lonely_integer/LonelyInt.java rename to code/bit_manipulation/src/lonely_integer/lonelyint.java diff --git a/code/bit_manipulation/src/lonely_integer/LonelyInt.js b/code/bit_manipulation/src/lonely_integer/lonelyint.js similarity index 100% rename from code/bit_manipulation/src/lonely_integer/LonelyInt.js rename to code/bit_manipulation/src/lonely_integer/lonelyint.js diff --git a/code/bit_manipulation/src/lonely_integer/LonelyInteger.c b/code/bit_manipulation/src/lonely_integer/lonelyinteger.c similarity index 100% rename from code/bit_manipulation/src/lonely_integer/LonelyInteger.c rename to code/bit_manipulation/src/lonely_integer/lonelyinteger.c diff --git a/code/bit_manipulation/src/lonely_integer/lonelyInteger.cpp b/code/bit_manipulation/src/lonely_integer/lonelyinteger.cpp similarity index 100% rename from code/bit_manipulation/src/lonely_integer/lonelyInteger.cpp rename to code/bit_manipulation/src/lonely_integer/lonelyinteger.cpp diff --git a/code/bit_manipulation/src/lonely_integer/lonelyInteger.go b/code/bit_manipulation/src/lonely_integer/lonelyinteger.go similarity index 100% rename from code/bit_manipulation/src/lonely_integer/lonelyInteger.go rename to code/bit_manipulation/src/lonely_integer/lonelyinteger.go diff --git a/code/bit_manipulation/src/lonely_integer/lonelyInteger.py b/code/bit_manipulation/src/lonely_integer/lonelyinteger.py similarity index 100% rename from code/bit_manipulation/src/lonely_integer/lonelyInteger.py rename to code/bit_manipulation/src/lonely_integer/lonelyinteger.py diff --git a/code/bit_manipulation/src/power_of_2/PowerOf2.cs b/code/bit_manipulation/src/power_of_2/powerof2.cs similarity index 100% rename from code/bit_manipulation/src/power_of_2/PowerOf2.cs rename to code/bit_manipulation/src/power_of_2/powerof2.cs diff --git a/code/bit_manipulation/src/power_of_2/PowerOf2.java b/code/bit_manipulation/src/power_of_2/powerof2.java similarity index 100% rename from code/bit_manipulation/src/power_of_2/PowerOf2.java rename to code/bit_manipulation/src/power_of_2/powerof2.java diff --git a/code/bit_manipulation/src/thrice_unique_number/threeUnique.cpp b/code/bit_manipulation/src/thrice_unique_number/threeunique.cpp similarity index 100% rename from code/bit_manipulation/src/thrice_unique_number/threeUnique.cpp rename to code/bit_manipulation/src/thrice_unique_number/threeunique.cpp diff --git a/code/bit_manipulation/src/thrice_unique_number/ThriceUniqueNumber.java b/code/bit_manipulation/src/thrice_unique_number/thriceuniquenumber.java similarity index 100% rename from code/bit_manipulation/src/thrice_unique_number/ThriceUniqueNumber.java rename to code/bit_manipulation/src/thrice_unique_number/thriceuniquenumber.java diff --git a/code/bit_manipulation/src/thrice_unique_number/uniqueNumber.py b/code/bit_manipulation/src/thrice_unique_number/uniquenumber.py similarity index 100% rename from code/bit_manipulation/src/thrice_unique_number/uniqueNumber.py rename to code/bit_manipulation/src/thrice_unique_number/uniquenumber.py diff --git a/code/bit_manipulation/src/xor_swap/xorSwap.go b/code/bit_manipulation/src/xor_swap/xorswap.go similarity index 100% rename from code/bit_manipulation/src/xor_swap/xorSwap.go rename to code/bit_manipulation/src/xor_swap/xorswap.go diff --git a/code/cellular_automaton/src/conways_game_of_life/Conway.java b/code/cellular_automaton/src/conways_game_of_life/conway.java similarity index 100% rename from code/cellular_automaton/src/conways_game_of_life/Conway.java rename to code/cellular_automaton/src/conways_game_of_life/conway.java diff --git a/code/cellular_automaton/src/conways_game_of_life/game_of_life_C_SDL.c b/code/cellular_automaton/src/conways_game_of_life/game_of_life_c_sdl.c similarity index 100% rename from code/cellular_automaton/src/conways_game_of_life/game_of_life_C_SDL.c rename to code/cellular_automaton/src/conways_game_of_life/game_of_life_c_sdl.c diff --git a/code/cellular_automaton/src/conways_game_of_life/GameOfLife.hs b/code/cellular_automaton/src/conways_game_of_life/gameoflife.hs similarity index 100% rename from code/cellular_automaton/src/conways_game_of_life/GameOfLife.hs rename to code/cellular_automaton/src/conways_game_of_life/gameoflife.hs diff --git a/code/cellular_automaton/src/elementary_cellular_automata/ElementaryCellularAutomaton.java b/code/cellular_automaton/src/elementary_cellular_automata/elementarycellularautomaton.java similarity index 100% rename from code/cellular_automaton/src/elementary_cellular_automata/ElementaryCellularAutomaton.java rename to code/cellular_automaton/src/elementary_cellular_automata/elementarycellularautomaton.java diff --git a/code/cellular_automaton/src/langtons_ant/LangtonAnt.cpp b/code/cellular_automaton/src/langtons_ant/langtonant.cpp similarity index 100% rename from code/cellular_automaton/src/langtons_ant/LangtonAnt.cpp rename to code/cellular_automaton/src/langtons_ant/langtonant.cpp diff --git a/code/cellular_automaton/src/langtons_ant/LangtonAnt.html b/code/cellular_automaton/src/langtons_ant/langtonant.html similarity index 100% rename from code/cellular_automaton/src/langtons_ant/LangtonAnt.html rename to code/cellular_automaton/src/langtons_ant/langtonant.html diff --git a/code/cellular_automaton/src/langtons_ant/LangtonAnt.java b/code/cellular_automaton/src/langtons_ant/langtonant.java similarity index 100% rename from code/cellular_automaton/src/langtons_ant/LangtonAnt.java rename to code/cellular_automaton/src/langtons_ant/langtonant.java diff --git a/code/cellular_automaton/src/langtons_ant/LangtonAnt.py b/code/cellular_automaton/src/langtons_ant/langtonant.py similarity index 100% rename from code/cellular_automaton/src/langtons_ant/LangtonAnt.py rename to code/cellular_automaton/src/langtons_ant/langtonant.py diff --git a/code/compression/src/lossless_compression/lempel-ziv-welch/README.md b/code/compression/src/lossless_compression/lempel_ziv_welch/README.md similarity index 100% rename from code/compression/src/lossless_compression/lempel-ziv-welch/README.md rename to code/compression/src/lossless_compression/lempel_ziv_welch/README.md diff --git a/code/compression/src/lossless_compression/lempel-ziv-welch/lzw.cpp b/code/compression/src/lossless_compression/lempel_ziv_welch/lzw.cpp similarity index 100% rename from code/compression/src/lossless_compression/lempel-ziv-welch/lzw.cpp rename to code/compression/src/lossless_compression/lempel_ziv_welch/lzw.cpp diff --git a/code/compression/src/lossless_compression/lempel-ziv-welch/lzw.py b/code/compression/src/lossless_compression/lempel_ziv_welch/lzw.py similarity index 100% rename from code/compression/src/lossless_compression/lempel-ziv-welch/lzw.py rename to code/compression/src/lossless_compression/lempel_ziv_welch/lzw.py diff --git a/code/computational_geometry/src/area_of_polygon/AreaOfPolygon.java b/code/computational_geometry/src/area_of_polygon/areaofpolygon.java similarity index 100% rename from code/computational_geometry/src/area_of_polygon/AreaOfPolygon.java rename to code/computational_geometry/src/area_of_polygon/areaofpolygon.java diff --git a/code/computational_geometry/src/area_of_triangle/AreaOfTriangle.java b/code/computational_geometry/src/area_of_triangle/areaoftriangle.java similarity index 100% rename from code/computational_geometry/src/area_of_triangle/AreaOfTriangle.java rename to code/computational_geometry/src/area_of_triangle/areaoftriangle.java diff --git a/code/computational_geometry/src/chans_algorithm/chans_algorithm.cpp b/code/computational_geometry/src/chans_algorithm/chans_algorithm.cpp index 81659483c7..e04a96b734 100644 --- a/code/computational_geometry/src/chans_algorithm/chans_algorithm.cpp +++ b/code/computational_geometry/src/chans_algorithm/chans_algorithm.cpp @@ -1,266 +1,275 @@ - #include - #include - #include - #include // For qsort() algorithm - #include // For pair() STL - #define RIGHT_TURN -1 // CW - #define LEFT_TURN 1 // CCW - #define COLLINEAR 0 // Collinear + #include + #include + #include + #include // For qsort() algorithm + #include // For pair() STL + #define RIGHT_TURN -1 // CW + #define LEFT_TURN 1 // CCW + #define COLLINEAR 0 // Collinear - using namespace std ; +using namespace std; - /* - Class to handle the 2D Points! - */ - class Point - { - public: +/* + * Class to handle the 2D Points! + */ +class Point +{ +public: - int x; - int y; - Point (int newx=0,int newy=0) - { - x=newx; - y=newy; - } - /* - Overloaded == operator to check for equality between 2 objects of class Point - */ - friend bool operator== (const Point& p1,const Point& p2) - { - return p1.x==p2.x && p1.y==p2.y ; - } - /* - Overloaded != operator to check for non-equality between 2 objects of class Point - */ - friend bool operator!= (const Point& p1,const Point& p2) - { - return !(p1.x==p2.x && p1.y==p2.y); - } - /* - Overloaded ostream << operator to check for print object of class Point to STDOUT - */ - friend ostream& operator<<(ostream& output,const Point& p) - { - output<<"("< 0)? -1: 1; // CW: -1 or CCW: 1 - } +/* + * Returns orientation of the line joining Points p and q and line joining Points q and r + * Returns -1 : CW orientation + +1 : CCW orientation + * 0 : Collinear + * @param p: Object of class Point aka first Point + * @param q: Object of class Point aka second Point + * @param r: Object of class Point aka third Point + */ +int orientation(Point p, Point q, Point r) +{ + int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + if (val == 0) + return 0; // Collinear + return (val > 0) ? -1 : 1; // CW: -1 or CCW: 1 +} - /* - Predicate function used while sorting the Points using qsort() inbuilt function in C++ - @param p: Object of class Point aka first Point - @param p: Object of class Point aka second Point - */ - int compare(const void *vp1, const void *vp2) - { - Point *p1 = (Point *)vp1; - Point *p2 = (Point *)vp2; - int orient = orientation(p0, *p1, *p2); - if (orient == 0) - return (dist(p0, *p2) >= dist(p0, *p1))? -1 : 1; - return (orient == 1)? -1: 1; - } +/* + * Predicate function used while sorting the Points using qsort() inbuilt function in C++ + * @param p: Object of class Point aka first Point + * @param p: Object of class Point aka second Point + */ +int compare(const void *vp1, const void *vp2) +{ + Point *p1 = (Point *)vp1; + Point *p2 = (Point *)vp2; + int orient = orientation(p0, *p1, *p2); + if (orient == 0) + return (dist(p0, *p2) >= dist(p0, *p1)) ? -1 : 1; + return (orient == 1) ? -1 : 1; +} - /* - Returns the index of the Point to which the tangent is drawn from Point p. - Uses a modified Binary Search Algorithm to yield tangent in O(log n) complexity - @param v: vector of objects of class Points representing the hull aka the vector of hull Points - @param p: Object of class Point from where tangent needs to be drawn - */ - int tangent(vector v,Point p) - { - int l=0; - int r= v.size(); - int l_before = orientation(p, v[0], v[v.size()-1]); - int l_after = orientation(p, v[0], v[(l + 1) % v.size()]); - while (l < r) - { - int c = ((l + r)>>1); - int c_before = orientation(p, v[c], v[(c - 1) % v.size()]); - int c_after = orientation(p, v[c], v[(c + 1) % v.size()]); - int c_side = orientation(p, v[l], v[c]); - if (c_before != RIGHT_TURN and c_after != RIGHT_TURN) - return c; - else if ((c_side == LEFT_TURN) and (l_after == RIGHT_TURN or l_before == l_after) or (c_side == RIGHT_TURN and c_before == RIGHT_TURN)) - r = c; - else - l = c + 1 ; - l_before = -c_after; - l_after = orientation(p, v[l], v[(l + 1) % v.size()]); - } - return l; - } +/* + * Returns the index of the Point to which the tangent is drawn from Point p. + * Uses a modified Binary Search Algorithm to yield tangent in O(log n) complexity + * @param v: vector of objects of class Points representing the hull aka the vector of hull Points + * @param p: Object of class Point from where tangent needs to be drawn + */ +int tangent(vector v, Point p) +{ + int l = 0; + int r = v.size(); + int l_before = orientation(p, v[0], v[v.size() - 1]); + int l_after = orientation(p, v[0], v[(l + 1) % v.size()]); + while (l < r) + { + int c = ((l + r) >> 1); + int c_before = orientation(p, v[c], v[(c - 1) % v.size()]); + int c_after = orientation(p, v[c], v[(c + 1) % v.size()]); + int c_side = orientation(p, v[l], v[c]); + if (c_before != RIGHT_TURN and c_after != RIGHT_TURN) + return c; + else if ((c_side == LEFT_TURN) and (l_after == RIGHT_TURN or l_before == + l_after) or (c_side == RIGHT_TURN and c_before == + RIGHT_TURN)) + r = c; + else + l = c + 1; + l_before = -c_after; + l_after = orientation(p, v[l], v[(l + 1) % v.size()]); + } + return l; +} - /* - Returns the pair of integers representing the Hull # and the Point in that Hull which is the extreme amongst all given Hull Points - @param hulls: Vector containing the hull Points for various hulls stored as individual vectors. - */ - pair extreme_hullpt_pair(vector >& hulls) - { - int h= 0,p= 0; - for (int i=0; i extreme_hullpt_pair(vector>& hulls) +{ + int h = 0, p = 0; + for (int i = 0; i < hulls.size(); ++i) + { + int min_index = 0, min_y = hulls[i][0].y; + for (int j = 1; j < hulls[i].size(); ++j) + if (hulls[i][j].y < min_y) + { + min_y = hulls[i][j].y; + min_index = j; + } + if (hulls[i][min_index].y < hulls[h][p].y) + { + h = i; + p = min_index; + } + } + return make_pair(h, p); +} - /* - Returns the pair of integers representing the Hull # and the Point in that Hull to which the Point lPoint will be joined - @param hulls: Vector containing the hull Points for various hulls stored as individual vectors. - @param lPoint: Pair of the Hull # and the leftmost extreme Point contained in that hull, amongst all the obtained hulls - */ - pair next_hullpt_pair(vector >& hulls, pair lPoint) - { - Point p = hulls[lPoint.first][lPoint.second]; - pair next = make_pair(lPoint.first, (lPoint.second + 1) % hulls[lPoint.first].size()); - for (int h=0; h< hulls.size(); h++){ - if(h != lPoint.first){ - int s= tangent(hulls[h],p); - Point q= hulls[next.first][next.second]; - Point r= hulls[h][s]; - int t= orientation(p,q,r); - if( t== RIGHT_TURN || (t==COLLINEAR) && dist(p,r)>dist(p,q)) - next = make_pair(h,s); - } - } - return next; - } +/* + * Returns the pair of integers representing the Hull # and the Point in that Hull to which the Point lPoint will be joined + * @param hulls: Vector containing the hull Points for various hulls stored as individual vectors. + * @param lPoint: Pair of the Hull # and the leftmost extreme Point contained in that hull, amongst all the obtained hulls + */ +pair next_hullpt_pair(vector>& hulls, pair lPoint) +{ + Point p = hulls[lPoint.first][lPoint.second]; + pair next = make_pair(lPoint.first, (lPoint.second + 1) % hulls[lPoint.first].size()); + for (int h = 0; h < hulls.size(); h++) + if (h != lPoint.first) + { + int s = tangent(hulls[h], p); + Point q = hulls[next.first][next.second]; + Point r = hulls[h][s]; + int t = orientation(p, q, r); + if (t == RIGHT_TURN || (t == COLLINEAR) && dist(p, r) > dist(p, q)) + next = make_pair(h, s); + } + return next; +} - /* - Constraint to find the outermost boundary of the Points by checking if the Points lie to the left otherwise adding the given Point p - Returns the Hull Points - @param v: Vector of all the Points - @param p: New Point p which will be checked to be in the Hull Points or not - */ - vector keep_left (vector& v,Point p) - { - while(v.size()>1 && orientation(v[v.size()-2],v[v.size()-1],p) != LEFT_TURN) - v.pop_back(); - if(!v.size() || v[v.size()-1] != p) - v.push_back(p); - return v; - } +/* + * Constraint to find the outermost boundary of the Points by checking if the Points lie to the left otherwise adding the given Point p + * Returns the Hull Points + * @param v: Vector of all the Points + * @param p: New Point p which will be checked to be in the Hull Points or not + */ +vector keep_left (vector& v, Point p) +{ + while (v.size() > 1 && orientation(v[v.size() - 2], v[v.size() - 1], p) != LEFT_TURN) + v.pop_back(); + if (!v.size() || v[v.size() - 1] != p) + v.push_back(p); + return v; +} - /* - Graham Scan algorithm to find convex hull from the given set of Points - @param Points: List of the given Points in the cluster (as obtained by Chan's Algorithm grouping) - Returns the Hull Points in a vector - */ - vector GrahamScan(vector& Points) - { - if(Points.size()<=1) - return Points; - qsort(&Points[0], Points.size(), sizeof(Point), compare); - vector lower_hull; - for(int i=0; i upper_hull; - for(int i=0; i GrahamScan(vector& Points) +{ + if (Points.size() <= 1) + return Points; + qsort(&Points[0], Points.size(), sizeof(Point), compare); + vector lower_hull; + for (int i = 0; i < Points.size(); ++i) + lower_hull = keep_left(lower_hull, Points[i]); + reverse(Points.begin(), Points.end()); + vector upper_hull; + for (int i = 0; i < Points.size(); ++i) + upper_hull = keep_left(upper_hull, Points[i]); + for (int i = 1; i < upper_hull.size(); ++i) + lower_hull.push_back(upper_hull[i]); + return lower_hull; +} - /* - Implementation of Chan's Algorithm to compute Convex Hull in O(nlogh) complexity - */ - vector chansalgorithm(vector v) - { - for(int t=0; t< v.size(); ++t){ - for(int m=1; m< (1<<(1< > hulls; - for(int i=0;i chunk; - if(v.begin()+i+m <= v.end()) - chunk.assign(v.begin()+i,v.begin()+i+m); - else - chunk.assign(v.begin()+i,v.end()); - hulls.push_back(GrahamScan(chunk)); - } - cout<<"\nM (Chunk Size): "< > hull; - hull.push_back(extreme_hullpt_pair(hulls)); - for(int i=0; i p= next_hullpt_pair(hulls,hull[hull.size()-1]); - vector output; - if(p==hull[0]){ - for(int j=0; j chansalgorithm(vector v) +{ + for (int t = 0; t < v.size(); ++t) + for (int m = 1; m < (1 << (1 << t)); ++m) + { + vector> hulls; + for (int i = 0; i < v.size(); i = i + m) + { + vector chunk; + if (v.begin() + i + m <= v.end()) + chunk.assign(v.begin() + i, v.begin() + i + m); + else + chunk.assign(v.begin() + i, v.end()); + hulls.push_back(GrahamScan(chunk)); + } + cout << "\nM (Chunk Size): " << m << "\n"; + for (int i = 0; i < hulls.size(); ++i) + { + cout << "Convex Hull for Hull #" << i << " (Obtained using Graham Scan!!)\n"; + for (int j = 0; j < hulls[i].size(); ++j) + cout << hulls[i][j] << " "; + cout << "\n"; + } + vector> hull; + hull.push_back(extreme_hullpt_pair(hulls)); + for (int i = 0; i < m; ++i) + { + pair p = next_hullpt_pair(hulls, hull[hull.size() - 1]); + vector output; + if (p == hull[0]) + { + for (int j = 0; j < hull.size(); ++j) + output.push_back(hulls[hull[j].first][hull[j].second]); + return output; + } + hull.push_back(p); + } + } +} - int main() - { - int T=0,x=0,y=0; - cout<<"Enter Total Number of points"\n"; - cin>>T; - if(T<=0) - return -1; - Point Points[T]; - for(int i=0;i>x>>y; - Points[i].x=x; - Points[i].y=y; - } - vector v(Points,Points+T); - vector output = chansalgorithm(v); - cout<<"\n-------------------- After Using Chan's Algorithm --------------------\n"; - cout<<"\n******************** CONVEX HULL ********************\n"; - for(int i=0; i< output.size(); ++i) - cout<> T; + if (T <= 0) + return -1; + Point Points[T]; + for (int i = 0; i < T; ++i) + { + cin >> x >> y; + Points[i].x = x; + Points[i].y = y; + } + vector v(Points, Points + T); + vector output = chansalgorithm(v); + cout << " \ n-------------------- After Using Chan + 's Algorithm --------------------\n"; + cout << "\n******************** CONVEX HULL ********************\n"; + for (int i = 0; i < output.size(); ++i) + cout << output[i] << " "; + cout << "\n"; + return 0; +} diff --git a/code/computational_geometry/src/distance_between_points/DistanceBetweenPoints.java b/code/computational_geometry/src/distance_between_points/distancebetweenpoints.java similarity index 100% rename from code/computational_geometry/src/distance_between_points/DistanceBetweenPoints.java rename to code/computational_geometry/src/distance_between_points/distancebetweenpoints.java diff --git a/code/computational_geometry/src/graham_scan/graham_scan_alternative.cpp b/code/computational_geometry/src/graham_scan/graham_scan_alternative.cpp index 03236598e4..35e9a0fc26 100644 --- a/code/computational_geometry/src/graham_scan/graham_scan_alternative.cpp +++ b/code/computational_geometry/src/graham_scan/graham_scan_alternative.cpp @@ -3,16 +3,16 @@ #include using namespace std; // Part of Cosmos by OpenGenus Foundation -// A C++ program to find convex hull of a set of points. +// A C++ program to find convex hull of a set of points. struct Point { int x, y; }; - + // A globle point needed for sorting points with reference // to the first point Used in compare function of qsort() Point p0; - + // A utility function to find next to top in a stack Point nextToTop(stack &S) { @@ -22,7 +22,7 @@ Point nextToTop(stack &S) S.push(p); return res; } - + // A utility function to swap two points int swap(Point &p1, Point &p2) { @@ -30,15 +30,15 @@ int swap(Point &p1, Point &p2) p1 = p2; p2 = temp; } - + // A utility function to return square of distance // between p1 and p2 int distSq(Point p1, Point p2) { - return (p1.x - p2.x)*(p1.x - p2.x) + - (p1.y - p2.y)*(p1.y - p2.y); + return (p1.x - p2.x) * (p1.x - p2.x) + + (p1.y - p2.y) * (p1.y - p2.y); } - + // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear @@ -48,108 +48,110 @@ int orientation(Point p, Point q, Point r) { int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - - if (val == 0) return 0; // colinear - return (val > 0)? 1: 2; // clock or counterclock wise + + if (val == 0) + return 0; // colinear + return (val > 0) ? 1 : 2; // clock or counterclock wise } - + // A function used by library function qsort() to sort an array of // points with respect to the first point int compare(const void *vp1, const void *vp2) { - Point *p1 = (Point *)vp1; - Point *p2 = (Point *)vp2; - - // Find orientation - int o = orientation(p0, *p1, *p2); - if (o == 0) - return (distSq(p0, *p2) >= distSq(p0, *p1))? -1 : 1; - - return (o == 2)? -1: 1; + Point *p1 = (Point *)vp1; + Point *p2 = (Point *)vp2; + + // Find orientation + int o = orientation(p0, *p1, *p2); + if (o == 0) + return (distSq(p0, *p2) >= distSq(p0, *p1)) ? -1 : 1; + + return (o == 2) ? -1 : 1; } - + // Prints convex hull of a set of n points. void convexHull(Point points[], int n) { - // Find the bottommost point - int ymin = points[0].y, min = 0; - for (int i = 1; i < n; i++) - { - int y = points[i].y; - - // Pick the bottom-most or chose the left - // most point in case of tie - if ((y < ymin) || (ymin == y && - points[i].x < points[min].x)) - ymin = points[i].y, min = i; - } - - // Place the bottom-most point at first position - swap(points[0], points[min]); - - // Sort n-1 points with respect to the first point. - // A point p1 comes before p2 in sorted ouput if p2 - // has larger polar angle (in counterclockwise - // direction) than p1 - p0 = points[0]; - qsort(&points[1], n-1, sizeof(Point), compare); - - // If two or more points make same angle with p0, - // Remove all but the one that is farthest from p0 - // Remember that, in above sorting, our criteria was - // to keep the farthest point at the end when more than - // one points have same angle. - int m = 1; // Initialize size of modified array - for (int i=1; i S; - S.push(points[0]); - S.push(points[1]); - S.push(points[2]); - - // Process remaining n-3 points - for (int i = 3; i < m; i++) - { - // Keep removing top while the angle formed by - // points next-to-top, top, and points[i] makes - // a non-left turn - while (orientation(nextToTop(S), S.top(), points[i]) != 2) - S.pop(); - S.push(points[i]); - } - - // Now stack has the output points, print contents of stack - while (!S.empty()) - { - Point p = S.top(); - cout << "(" << p.x << ", " << p.y <<")" << endl; - S.pop(); - } + // Find the bottommost point + int ymin = points[0].y, min = 0; + for (int i = 1; i < n; i++) + { + int y = points[i].y; + + // Pick the bottom-most or chose the left + // most point in case of tie + if ((y < ymin) || (ymin == y && + points[i].x < points[min].x)) + ymin = points[i].y, min = i; + } + + // Place the bottom-most point at first position + swap(points[0], points[min]); + + // Sort n-1 points with respect to the first point. + // A point p1 comes before p2 in sorted ouput if p2 + // has larger polar angle (in counterclockwise + // direction) than p1 + p0 = points[0]; + qsort(&points[1], n - 1, sizeof(Point), compare); + + // If two or more points make same angle with p0, + // Remove all but the one that is farthest from p0 + // Remember that, in above sorting, our criteria was + // to keep the farthest point at the end when more than + // one points have same angle. + int m = 1; // Initialize size of modified array + for (int i = 1; i < n; i++) + { + // Keep removing i while angle of i and i+1 is same + // with respect to p0 + while (i < n - 1 && orientation(p0, points[i], + points[i + 1]) == 0) + i++; + + + points[m] = points[i]; + m++; // Update size of modified array + } + + // If modified array of points has less than 3 points, + // convex hull is not possible + if (m < 3) + return; + + // Create an empty stack and push first three points + // to it. + stack S; + S.push(points[0]); + S.push(points[1]); + S.push(points[2]); + + // Process remaining n-3 points + for (int i = 3; i < m; i++) + { + // Keep removing top while the angle formed by + // points next-to-top, top, and points[i] makes + // a non-left turn + while (orientation(nextToTop(S), S.top(), points[i]) != 2) + S.pop(); + S.push(points[i]); + } + + // Now stack has the output points, print contents of stack + while (!S.empty()) + { + Point p = S.top(); + cout << "(" << p.x << ", " << p.y << ")" << endl; + S.pop(); + } } - + // Driver program to test above functions int main() { Point points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}}; - int n = sizeof(points)/sizeof(points[0]); + int n = sizeof(points) / sizeof(points[0]); convexHull(points, n); return 0; } diff --git a/code/computational_geometry/src/graham_scan/GrahamScan.java b/code/computational_geometry/src/graham_scan/grahamscan.java similarity index 100% rename from code/computational_geometry/src/graham_scan/GrahamScan.java rename to code/computational_geometry/src/graham_scan/grahamscan.java diff --git a/code/computational_geometry/src/jarvis_march/jarvis_march_alternative.cpp b/code/computational_geometry/src/jarvis_march/jarvis_march_alternative.cpp index 950582997f..a7f616b390 100644 --- a/code/computational_geometry/src/jarvis_march/jarvis_march_alternative.cpp +++ b/code/computational_geometry/src/jarvis_march/jarvis_march_alternative.cpp @@ -1,12 +1,12 @@ // A C++ program to find convex hull of a set of points #include using namespace std; - -struct Point // Structure to store the co-ordinates of every point + +struct Point // Structure to store the co-ordinates of every point { int x, y; -} ; - +}; + // To find orientation of ordered triplet (p, q, r). // The function returns following values // 0 --> p, q and r are colinear @@ -15,83 +15,83 @@ struct Point // Structure to store the co-ordinates of every point int orientation(Point p, Point q, Point r) { - /* - Finding slope ,s = (y2 - y1)/(x2 - x1) ; - s1 = (y3 - y2)/(x3 - x2) ; - if s == s1 points are collinear - s < s1 orientation towards left (left turn) - s > s1 orientation towards right (right turn) - */ - - int val = (q.y - p.y) * (r.x - q.x) - + /* + * Finding slope ,s = (y2 - y1)/(x2 - x1) ; + * s1 = (y3 - y2)/(x3 - x2) ; + * if s == s1 points are collinear + * s < s1 orientation towards left (left turn) + * s > s1 orientation towards right (right turn) + */ + + int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - - if (val == 0) return 0; // colinear - return (val > 0)? 1: 2; // clock or counterclock wise - + + if (val == 0) + return 0; // colinear + return (val > 0) ? 1 : 2; // clock or counterclock wise + } - + // Prints convex hull of a set of n points. void convexHull(Point points[], int n) - { +{ // There must be at least 3 points - if (n < 3) return; - + if (n < 3) + return; + // Initialize Result vector hull; - + // Find the leftmost point - - int l = 0; + + int l = 0; for (int i = 1; i < n; i++) if (points[i].x < points[l].x) l = i; - + // Start from leftmost point, keep moving counterclockwise // until reach the start point again. This loop runs O(h) // times where h is number of points in result or output. - + int p = l, q; do { // Add current point to result hull.push_back(points[p]); - + // Search for a point 'q' such that orientation(p, x, // q) is counterclockwise for all points 'x'. The idea // is to keep track of last visited most counterclock- // wise point in q. If any point 'i' is more counterclock- // wise than q, then update q. - - q = (p+1)%n; + + q = (p + 1) % n; for (int i = 0; i < n; i++) - { - // If i is more counterclockwise than current q, then - // update q - if (orientation(points[p], points[i], points[q]) == 2) - q = i; - } - + // If i is more counterclockwise than current q, then + // update q + if (orientation(points[p], points[i], points[q]) == 2) + q = i; + // Now q is the most counterclockwise with respect to p // Set p as q for next iteration, so that q is added to // result 'hull' p = q; - + } while (p != l); // While we don't come to first point - + // Print Result for (int i = 0; i < hull.size(); i++) cout << "(" << hull[i].x << ", " - << hull[i].y << ")\n"; + << hull[i].y << ")\n"; } - + // Driver program to test above functions int main() { Point points[] = {{0, 3}, {2, 2}, {1, 1}, {2, 1}, {3, 0}, {0, 0}, {3, 3}}; - int n = sizeof(points)/sizeof(points[0]); + int n = sizeof(points) / sizeof(points[0]); convexHull(points, n); return 0; } diff --git a/code/computational_geometry/src/quickhull/quickhull_alternative.cpp b/code/computational_geometry/src/quickhull/quickhull_alternative.cpp index c449ba20d2..8b1bcc8631 100644 --- a/code/computational_geometry/src/quickhull/quickhull_alternative.cpp +++ b/code/computational_geometry/src/quickhull/quickhull_alternative.cpp @@ -1,4 +1,4 @@ -#include +#include using namespace std; // Part of Cosmos by OpenGenus Foundation // C++ program to implement Quick Hull algorithm to find convex hull. @@ -6,24 +6,24 @@ using namespace std; // iPair is integer pairs #define iPair pair - + // Stores the result (points of convex hull) set hull; - + // Returns the side of point p with respect to line // joining points p1 and p2. int findSide(iPair p1, iPair p2, iPair p) { int val = (p.second - p1.second) * (p2.first - p1.first) - (p2.second - p1.second) * (p.first - p1.first); - + if (val > 0) return 1; if (val < 0) return -1; return 0; } - + // Returns the square of distance between // p1 and p2. @@ -32,7 +32,7 @@ int dist(iPair p, iPair q) return (p.second - q.second) * (p.second - q.second) + (p.first - q.first) * (p.first - q.first); } - + // returns a value proportional to the distance // between the point p and the line joining the // points p1 and p2 @@ -40,19 +40,19 @@ int dist(iPair p, iPair q) int lineDist(iPair p1, iPair p2, iPair p) { return abs ((p.second - p1.second) * (p2.first - p1.first) - - (p2.second - p1.second) * (p.first - p1.first)); + (p2.second - p1.second) * (p.first - p1.first)); } - + // End points of line L are p1 and p2. side can have value // 1 or -1 specifying each of the parts made by the line L void quickHull(iPair a[], int n, iPair p1, iPair p2, int side) { int ind = -1; int max_dist = 0; - + // finding the point with maximum distance // from L and also on the specified side of L. - for (int i=0; i max_dist) @@ -61,7 +61,7 @@ void quickHull(iPair a[], int n, iPair p1, iPair p2, int side) max_dist = temp; } } - + // If no point is found, add the end points // of L to the convex hull. if (ind == -1) @@ -70,12 +70,12 @@ void quickHull(iPair a[], int n, iPair p1, iPair p2, int side) hull.insert(p2); return; } - + // Recur for the two parts divided by a[ind] quickHull(a, n, a[ind], p1, -findSide(a[ind], p1, p2)); quickHull(a, n, a[ind], p2, -findSide(a[ind], p2, p1)); } - + void printHull(iPair a[], int n) { // a[i].second -> y-coordinate of the ith point @@ -84,45 +84,45 @@ void printHull(iPair a[], int n) cout << "Convex hull not possible\n"; return; } - + // Finding the point with minimum and // maximum x-coordinate int min_x = 0, max_x = 0; - for (int i=1; i a[max_x].first) max_x = i; } - + // Recursively find convex hull points on // one side of line joining a[min_x] and // a[max_x]. - + quickHull(a, n, a[min_x], a[max_x], 1); - + // Recursively find convex hull points on // other side of line joining a[min_x] and // a[max_x] - + quickHull(a, n, a[min_x], a[max_x], -1); - + cout << "The points in Convex Hull are:\n"; while (!hull.empty()) { - cout << "(" <<( *hull.begin()).first << ", " + cout << "(" << ( *hull.begin()).first << ", " << (*hull.begin()).second << ") "; hull.erase(hull.begin()); } } - + // Driver code int main() { iPair a[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, - {0, 0}, {1, 2}, {3, 1}, {3, 3}}; - int n = sizeof(a)/sizeof(a[0]); + {0, 0}, {1, 2}, {3, 1}, {3, 3}}; + int n = sizeof(a) / sizeof(a[0]); printHull(a, n); return 0; } diff --git a/code/computational_geometry/src/sphere_tetrahedron_intersection/LuVector.hpp b/code/computational_geometry/src/sphere_tetrahedron_intersection/luvector.hpp similarity index 100% rename from code/computational_geometry/src/sphere_tetrahedron_intersection/LuVector.hpp rename to code/computational_geometry/src/sphere_tetrahedron_intersection/luvector.hpp diff --git a/code/computational_geometry/src/sphere_tetrahedron_intersection/sphere_tetrahedron_intersection.cpp b/code/computational_geometry/src/sphere_tetrahedron_intersection/sphere_tetrahedron_intersection.cpp index dae4c2e45b..de35dc1a2e 100644 --- a/code/computational_geometry/src/sphere_tetrahedron_intersection/sphere_tetrahedron_intersection.cpp +++ b/code/computational_geometry/src/sphere_tetrahedron_intersection/sphere_tetrahedron_intersection.cpp @@ -13,7 +13,7 @@ using Vec3 = LUV::LuVector<3, double>; // Returns the solid angle of sphere cap contended by a cone. -// Apex of the cone is center of the sphere. +// Apex of the cone is center of the sphere. double SolidAngleCap(double apexAngle) { return 2.0 * LUV::pi * (1.0 - std::cos(apexAngle)); @@ -28,17 +28,17 @@ double SolidAngleSphtri(const Vec3& v1, const Vec3& v2, const Vec3& v3) double ang2 = std::acos(LUV::Dot(v3, v1)); double angSum = (ang0 + ang1 + ang2) / 2.0; return 4.0 * std::atan(std::sqrt( - std::tan(angSum / 2.0) * - std::tan((angSum - ang0) / 2.0) * - std::tan((angSum - ang1) / 2.0) * - std::tan((angSum - ang2) / 2.0) - )); + std::tan(angSum / 2.0) * + std::tan((angSum - ang0) / 2.0) * + std::tan((angSum - ang1) / 2.0) * + std::tan((angSum - ang2) / 2.0) + )); } // Returns the volume of spherical cap. double VolumeCap(double radius, double height) { - return radius * radius * height * LUV::pi * (2.0 / 3.0); + return radius * radius * height * LUV::pi * (2.0 / 3.0); } // Returns the volume of cone. @@ -70,22 +70,22 @@ double VolumeSphtri(const Vec3& v1, const Vec3& v2, const Vec3& v3, double radiu class ObservationTetrahedron { public: - + // Cartesian coordinates of vertices: Vec3 posR, posA, posB, posC; - + // Distances from posR: double lenA, lenB, lenC; - + // Direction of sphere-edge intersection points as radius increases: Vec3 prdA, prdB, prdC, prdD, prdE, prdF; - + // Some angles between lines: double angBAC, angERA, angFAE; - + // Max. solid angle contended by OT double solidAngleFull; - + // Constructor ObservationTetrahedron(const Vec3& vR, const Vec3& vA, const Vec3& vB, const Vec3& vC) { @@ -93,97 +93,97 @@ class ObservationTetrahedron posA = vA; posB = vB; posC = vC; - + Vec3 AmR = vA - vR; Vec3 BmR = vB - vR; Vec3 CmR = vC - vR; Vec3 BmA = vB - vA; Vec3 CmA = vC - vA; Vec3 CmB = vC - vB; - + lenA = LUV::Length(AmR); lenB = LUV::Length(BmR); lenC = LUV::Length(CmR); - + prdA = AmR / lenA; prdB = BmR / lenB; prdC = CmR / lenC; prdD = BmA / LUV::Length(BmA); prdE = CmA / LUV::Length(CmA); prdF = CmB / LUV::Length(CmB); - + angBAC = std::acos(LUV::Dot(prdD, prdE)); solidAngleFull = SolidAngleSphtri(prdA, prdB, prdC); } - + // Solid angle of the sphere subtended by OT as a function of sphere radius. double GetSolidAngle(double radius) { RecalculateForRadius(radius); - + if (radius >= lenC) return 0; - + else if (radius >= lenB) return SolidAngleSphtri(dirA, dirC, dirF) - - SolidAngleCap(angERA) * angFAE / (2.0 * LUV::pi); - + SolidAngleCap(angERA) * angFAE / (2.0 * LUV::pi); + else if (radius >= lenA) return solidAngleFull - - SolidAngleCap(angERA) * angBAC / (2.0 * LUV::pi); - + SolidAngleCap(angERA) * angBAC / (2.0 * LUV::pi); + return solidAngleFull; } - + // Surface area of the sphere subtended by OT as a function of sphere radius. double GetSurfaceArea(double radius) { return GetSolidAngle(radius) * radius * radius; } - + // Volume of OT-sphere intersection, as a function of sphere radius. double GetVolume(double radius) { RecalculateForRadius(radius); - + if (radius >= lenC) return VolumeTetrahedron(posR, posA, posB, posC); - + else if (radius >= lenB) return VolumeSphtri(dirA, dirC, dirF, radius) - ( VolumeCap(radius, LUV::Length(prpA - posA)) - VolumeCone(prlE, lenA) - ) * angFAE / (2.0 * LUV::pi) + - VolumeTetrahedron(posR, posA, posB, prpF); - + ) * angFAE / (2.0 * LUV::pi) + + VolumeTetrahedron(posR, posA, posB, prpF); + else if (radius >= lenA) return VolumeSphtri(dirA, dirB, dirC, radius) - ( VolumeCap(radius, LUV::Length(prpA - posA)) - VolumeCone(prlE, lenA) - ) * angBAC / (2.0 * LUV::pi); - + ) * angBAC / (2.0 * LUV::pi); + return VolumeSphtri(dirA, dirB, dirC, radius); } - + private: // Angles of RBF triangle double angRBF, angBFR, angFRB; - + // Distance of sphere-edge intersections: double prlA, prlB, prlC, prlD, prlE, prlF; //R->A, R->B, R->C, A->B, A->C, B->C - + // Positions of sphere-edge intersections: Vec3 prpA, prpB, prpC, prpD, prpE, prpF; - + // Positions relative to posR: // All have the length = radius Vec3 vecA, vecB, vecC, vecD, vecE, vecF; - + // Directions from posR: Vec3 dirA, dirB, dirC, dirD, dirE, dirF; - + // OT vertices are not actually dependent on the radius of the sphere, only the center. // But some values need to be calculated for each radius. void RecalculateForRadius(double radius) @@ -191,7 +191,7 @@ class ObservationTetrahedron angRBF = std::acos(LUV::Dot(posR - posB, posC - posB)); angBFR = std::asin(lenB * std::sin(angRBF) / radius); angFRB = LUV::pi - (angRBF + angBFR); - + prlA = radius; prlB = radius; prlC = radius; @@ -205,71 +205,70 @@ class ObservationTetrahedron prpD = posA + prdD * prlD; prpE = posA + prdE * prlE; prpF = posB + prdF * prlF; - + vecA = prpA - posR; vecB = prpB - posR; vecC = prpC - posR; vecD = prpD - posR; vecE = prpE - posR; vecF = prpF - posR; - + dirA = vecA / LUV::Length(vecA); dirB = vecB / LUV::Length(vecB); dirC = vecC / LUV::Length(vecC); dirD = vecD / LUV::Length(vecD); dirE = vecE / LUV::Length(vecE); dirF = vecF / LUV::Length(vecF); - + angERA = std::acos(LUV::Dot(dirE, dirA)); Vec3 vecAF = prpF - posA; Vec3 vecAE = prpE - posA; angFAE = std::acos(LUV::Dot(vecAF, vecAE) / (LUV::Length(vecAF) * LUV::Length(vecAE))); } - + }; // Main class for the intersection. class SphereTetrahedronIntersection { - + public: - + // Constructor, // vecTetA..D are vertices of the tetrahedron. // vecSphCenter is the center of the sphere. - SphereTetrahedronIntersection(const Vec3& vecTetA, const Vec3& vecTetB, const Vec3& vecTetC, const Vec3& vecTetD, const Vec3& vecSphCenter) + SphereTetrahedronIntersection(const Vec3& vecTetA, const Vec3& vecTetB, const Vec3& vecTetC, + const Vec3& vecTetD, const Vec3& vecSphCenter) { // Adding OTs for each face of the tetrahedron. AddOtForFace(vecTetA, vecTetB, vecTetC, vecTetD, vecSphCenter); AddOtForFace(vecTetB, vecTetC, vecTetD, vecTetA, vecSphCenter); AddOtForFace(vecTetC, vecTetD, vecTetA, vecTetB, vecSphCenter); AddOtForFace(vecTetD, vecTetA, vecTetB, vecTetC, vecSphCenter); - + // Calculating OT signs. for (int idf = 0; idf < 4; ++idf) - { for (int idl = 0; idl < 3; ++idl) { int ids = 3 * idf + idl; int idp = 2 * ids; int idm = idp + 1; - + obsTetSgn.push_back( LUV::Dot(obsTet[idp].prdA, dirN[idf]) * LUV::Dot(obsTet[idp].prdF, dirL[ids]) * LUV::Dot(obsTet[idp].prdD, dirU[ids]) - ); - + ); + obsTetSgn.push_back( -1 * LUV::Dot(obsTet[idm].prdA, dirN[idf]) * LUV::Dot(obsTet[idm].prdF, dirL[ids]) * LUV::Dot(obsTet[idm].prdD, dirU[ids]) - ); + ); } - } } - + // Solid angle subtended by tetrahedron, as a function of sphere radius. double GetSolidAngle(double radius) { @@ -281,13 +280,13 @@ class SphereTetrahedronIntersection } return solidAngle; } - + // Surface area subtended by tetrahedron, as a function of sphere radius. double GetSurfaceArea(double radius) { return GetSolidAngle(radius) * radius * radius; } - + // Sphere-tetrahedron intersection volume, as a function of sphere radius. double GetVolume(double radius) { @@ -299,16 +298,16 @@ class SphereTetrahedronIntersection } return volume; } - + private: std::vector obsTet; //24 in total std::vector obsTetSgn; - + std::vector dirN; std::vector dirU; std::vector dirL; - + void AddOtForEdge(const Vec3& vecM, const Vec3& vecP, const Vec3& vecT, const Vec3& vecR) { Vec3 PmM = vecP - vecM; @@ -320,8 +319,9 @@ class SphereTetrahedronIntersection obsTet.push_back(ObservationTetrahedron(vecR, vecA, vecB, vecP)); obsTet.push_back(ObservationTetrahedron(vecR, vecA, vecB, vecM)); } - - void AddOtForFace(const Vec3& vecA, const Vec3& vecB, const Vec3& vecC, const Vec3& vecU , const Vec3& vecR) + + void AddOtForFace(const Vec3& vecA, const Vec3& vecB, const Vec3& vecC, const Vec3& vecU, + const Vec3& vecR) { Vec3 vecN = vecU - LUV::ProjPlane(vecU, vecA, LUV::PlaneNormal(vecA, vecB, vecC)); dirN.push_back(vecN / LUV::Length(vecN)); @@ -329,24 +329,25 @@ class SphereTetrahedronIntersection AddOtForEdge(vecB, vecC, vecA, vecR); AddOtForEdge(vecC, vecA, vecB, vecR); } - + }; // An example usage... int main() -{ +{ // Tetrahedron with a volume of 1000 Vec3 vecTetA(0, 0, 0); Vec3 vecTetB(10, 0, 0); Vec3 vecTetC(0, 20, 0); Vec3 vecTetD(0, 0, 30); - + // Center of the sphere Vec3 vecSphCenter(0, 0, 0); // Intersection class - SphereTetrahedronIntersection testIntersection(vecTetA, vecTetB, vecTetC, vecTetD, vecSphCenter); - + SphereTetrahedronIntersection testIntersection(vecTetA, vecTetB, vecTetC, vecTetD, + vecSphCenter); + // Demonstrating that numerical integral of surface area is equal to analytical calculation of volume: int stepCount = 10000; double radiusStart = 0; @@ -354,13 +355,11 @@ int main() double radiusDelta = (radiusEnd - radiusStart) / stepCount; double volumeNumerical = 0; for (double radius = radiusStart; radius < radiusEnd; radius += radiusDelta) - { volumeNumerical += testIntersection.GetSurfaceArea(radius) * radiusDelta; - } double volumeAnalytical = testIntersection.GetVolume(radiusEnd); - + // These 2 values must be almost equal: std::cout << volumeAnalytical << ", " << volumeNumerical << std::endl; - + return 0; -} \ No newline at end of file +} diff --git a/code/computer_graphics/src/diamond_square/diamond_square.py b/code/computer_graphics/src/diamond_square/diamond_square.py new file mode 100644 index 0000000000..60126d129d --- /dev/null +++ b/code/computer_graphics/src/diamond_square/diamond_square.py @@ -0,0 +1,144 @@ +import numpy as np + + +def show_as_height_map(height, mat): + from mpl_toolkits.mplot3d import Axes3D + import matplotlib.pyplot as plt + + x, y = np.meshgrid(np.arange(height), np.arange(height)) + fig = plt.figure() + ax = fig.add_subplot(111, projection="3d") + ax.plot_surface(x, y, mat) + plt.title("height map") + plt.show() + + +def update_pixel(pixel, mean, magnitude): + return mean + (2 * pixel * magnitude) - magnitude + + +def main(n, smooth_factor, plot_enable): + height = (1 << n) + 1 + mat = np.random.random((height, height)) + + i = height - 1 + + magnitude = 1 + + # seeds init + mat[0, 0] = update_pixel(mat[0, 0], 0, magnitude) + mat[0, height - 1] = update_pixel( + mat[0, height - 1], 0, magnitude + ) + mat[height - 1, height - 1] = update_pixel( + mat[height - 1, height - 1], 0, magnitude + ) + mat[0, height - 1] = update_pixel( + mat[0, height - 1], 0, magnitude + ) + + while i > 1: + id_ = i >> 1 + magnitude *= smooth_factor + for xIndex in range( + id_, height, i + ): # Beginning of the Diamond Step + for yIndex in range(id_, height, i): + mean = ( + mat[xIndex - id_, yIndex - id_] + + mat[xIndex - id_, yIndex + id_] + + mat[xIndex + id_, yIndex + id_] + + mat[xIndex + id_, yIndex - id_] + ) / 4 + mat[xIndex, yIndex] = update_pixel( + mat[xIndex, yIndex], mean, magnitude + ) + for xIndex in range( + 0, height, id_ + ): # Beginning of the Square Step + if xIndex % i == 0: + shift = id_ + else: + shift = 0 + + for yIndex in range(shift, height, i): + sum_ = 0 + n = 0 + if xIndex >= id_: + sum_ += mat[xIndex - id_, yIndex] + n += 1 + + if xIndex + id_ < height: + sum_ += mat[xIndex + id_, yIndex] + n += 1 + + if yIndex >= id_: + sum_ += mat[xIndex, yIndex - id_] + n += 1 + + if yIndex + id_ < height: + sum_ += mat[xIndex, yIndex + id_] + n += 1 + + mean = sum_ / n + mat[xIndex, yIndex] = update_pixel( + mat[xIndex, yIndex], mean, magnitude + ) + i = id_ + + if plot_enable: + show_as_height_map(height, mat) + + return mat + + +def check_smooth_factor(value): + fvalue = float(value) + if fvalue < 0 or fvalue > 1: + raise argparse.ArgumentTypeError( + "%s is an invalid smooth factor value" % value + ) + return fvalue + + +def check_positive(value): + ivalue = int(value) + if ivalue <= 0: + raise argparse.ArgumentTypeError( + "%s is an invalid positive int value" % value + ) + return ivalue + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser( + description="machine generated calculation" + ) + parser.add_argument( + "-n", + help="the size of the image will be 2**n + 1", + required=False, + default=8, + type=check_positive, + ) + + parser.add_argument( + "-s", + help="smooth factor, needs to be in range of [0, 1], value of 0 means image is very smooth," + "value of 1 means image is very rough", + required=False, + default=0.5, + type=check_smooth_factor, + ) + + parser.add_argument( + "-p", + help="plot with matplotlib", + action="store_true", + ) + + args = parser.parse_args() + + main(args.n, args.s, args.p) diff --git a/code/computer_graphics/src/diamond_square/DiamondSquare.java b/code/computer_graphics/src/diamond_square/diamondsquare.java similarity index 100% rename from code/computer_graphics/src/diamond_square/DiamondSquare.java rename to code/computer_graphics/src/diamond_square/diamondsquare.java diff --git a/code/cryptography/src/aes_128/AES_128.py b/code/cryptography/src/aes_128/aes_128.py similarity index 100% rename from code/cryptography/src/aes_128/AES_128.py rename to code/cryptography/src/aes_128/aes_128.py diff --git a/code/cryptography/src/aes_128/aes_csharp/AESCipher.cs b/code/cryptography/src/aes_128/aes_csharp/aescipher.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/AESCipher.cs rename to code/cryptography/src/aes_128/aes_csharp/aescipher.cs diff --git a/code/cryptography/src/aes_128/aes_csharp/AESConsts.cs b/code/cryptography/src/aes_128/aes_csharp/aesconsts.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/AESConsts.cs rename to code/cryptography/src/aes_128/aes_csharp/aesconsts.cs diff --git a/code/cryptography/src/aes_128/aes_csharp/AESDecipher.cs b/code/cryptography/src/aes_128/aes_csharp/aesdecipher.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/AESDecipher.cs rename to code/cryptography/src/aes_128/aes_csharp/aesdecipher.cs diff --git a/code/cryptography/src/aes_128/aes_csharp/AESKeyGen.cs b/code/cryptography/src/aes_128/aes_csharp/aeskeygen.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/AESKeyGen.cs rename to code/cryptography/src/aes_128/aes_csharp/aeskeygen.cs diff --git a/code/cryptography/src/aes_128/aes_csharp/example/StreamCipher.cs b/code/cryptography/src/aes_128/aes_csharp/example/streamcipher.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/example/StreamCipher.cs rename to code/cryptography/src/aes_128/aes_csharp/example/streamcipher.cs diff --git a/code/cryptography/src/aes_128/aes_csharp/example/StreamCipherException.cs b/code/cryptography/src/aes_128/aes_csharp/example/streamcipherexception.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/example/StreamCipherException.cs rename to code/cryptography/src/aes_128/aes_csharp/example/streamcipherexception.cs diff --git a/code/cryptography/src/aes_128/aes_csharp/Helpers.cs b/code/cryptography/src/aes_128/aes_csharp/helpers.cs similarity index 100% rename from code/cryptography/src/aes_128/aes_csharp/Helpers.cs rename to code/cryptography/src/aes_128/aes_csharp/helpers.cs diff --git a/code/cryptography/src/affine_cipher/Affine.java b/code/cryptography/src/affine_cipher/affine.java similarity index 100% rename from code/cryptography/src/affine_cipher/Affine.java rename to code/cryptography/src/affine_cipher/affine.java diff --git a/code/cryptography/src/affine_cipher/AffineKotlin.kt b/code/cryptography/src/affine_cipher/affinekotlin.kt similarity index 100% rename from code/cryptography/src/affine_cipher/AffineKotlin.kt rename to code/cryptography/src/affine_cipher/affinekotlin.kt diff --git a/code/cryptography/src/caesar_cipher/CaesarCipher.java b/code/cryptography/src/caesar_cipher/caesarcipher.java similarity index 100% rename from code/cryptography/src/caesar_cipher/CaesarCipher.java rename to code/cryptography/src/caesar_cipher/caesarcipher.java diff --git a/code/cryptography/src/morse_cipher/MorseCode.java b/code/cryptography/src/morse_cipher/morsecode.java similarity index 100% rename from code/cryptography/src/morse_cipher/MorseCode.java rename to code/cryptography/src/morse_cipher/morsecode.java diff --git a/code/cryptography/src/rot13_cipher/rotN.c b/code/cryptography/src/rot13_cipher/rotn.c similarity index 100% rename from code/cryptography/src/rot13_cipher/rotN.c rename to code/cryptography/src/rot13_cipher/rotn.c diff --git a/code/cryptography/src/rot13_cipher/rotN.cpp b/code/cryptography/src/rot13_cipher/rotn.cpp similarity index 100% rename from code/cryptography/src/rot13_cipher/rotN.cpp rename to code/cryptography/src/rot13_cipher/rotn.cpp diff --git a/code/cryptography/src/rot13_cipher/RotN.java b/code/cryptography/src/rot13_cipher/rotn.java similarity index 100% rename from code/cryptography/src/rot13_cipher/RotN.java rename to code/cryptography/src/rot13_cipher/rotn.java diff --git a/code/cryptography/src/rot13_cipher/rotN.js b/code/cryptography/src/rot13_cipher/rotn.js similarity index 100% rename from code/cryptography/src/rot13_cipher/rotN.js rename to code/cryptography/src/rot13_cipher/rotn.js diff --git a/code/cryptography/src/rsa/RSA.java b/code/cryptography/src/rsa/rsa.java similarity index 100% rename from code/cryptography/src/rsa/RSA.java rename to code/cryptography/src/rsa/rsa.java diff --git a/code/data_structures/src/hashs/bloom_filter/bloomFilter.go b/code/data_structures/src/hashs/bloom_filter/bloomfilter.go similarity index 100% rename from code/data_structures/src/hashs/bloom_filter/bloomFilter.go rename to code/data_structures/src/hashs/bloom_filter/bloomfilter.go diff --git a/code/data_structures/src/linked_list/linked_list.cpp b/code/data_structures/src/linked_list/linked_list.cpp index f08a963a3f..de66e40a51 100644 --- a/code/data_structures/src/linked_list/linked_list.cpp +++ b/code/data_structures/src/linked_list/linked_list.cpp @@ -25,7 +25,7 @@ class Linkedlist bool isEmpty() const; void print() const; T getPos(int pos) const; - void insert(int pos,const T& data); + void insert(int pos, const T& data); void deletePos(int pos); void modify(int pos, const T& date); int find(const T& date); @@ -38,7 +38,9 @@ class Linkedlist }; template -Linkedlist::Linkedlist() : header(nullptr), length(0) {}; +Linkedlist::Linkedlist() : header(nullptr), length(0) +{ +}; template Linkedlist::Linkedlist(const Linkedlist &list) : header(nullptr), length(0) @@ -55,14 +57,10 @@ template Linkedlist& Linkedlist::operator= (const Linkedlist &rhs) { if (this == &rhs) - { return *this; - } destroy(); for (int i = 1; i <= rhs.size(); ++i) - { rearAdd(rhs.getPos(i)); - } return *this; } @@ -79,9 +77,7 @@ void Linkedlist::headAdd(const T& date) pNode->date = date; pNode->pNext = nullptr; if (header == nullptr) - { header = pNode; - } else { pNode->pNext = header; @@ -97,17 +93,13 @@ void Linkedlist::rearAdd(const T& date) pNode->date = date; pNode->pNext = nullptr; if (header == nullptr) - { header = pNode; - } else { Node* rear = header; while (rear->pNext != nullptr) - { rear = rear->pNext; - } - rear->pNext = pNode; + rear->pNext = pNode; } length++; } @@ -135,9 +127,7 @@ void Linkedlist::print() const pTemp = pTemp->pNext; count++; if (count % 5 == 0) - { std::cout << std::endl; - } } std::cout << std::endl; } @@ -146,17 +136,13 @@ template T Linkedlist::getPos(int pos) const { if (pos < 1 || pos > length) - { std::cerr << "get element position error!" << std::endl; - } else { int i = 1; Node *pTemp = header; while (i++ < pos) - { pTemp = pTemp->pNext; - } return pTemp->date; } } @@ -165,9 +151,7 @@ template void Linkedlist::insert(int pos, const T& date) { if (pos < 1 || pos > length) - { std::cerr << "insert element position error!" << std::endl; - } else { if (pos == 1) @@ -182,9 +166,7 @@ void Linkedlist::insert(int pos, const T& date) int i = 1; Node *pTemp = header; while (++i < pos) - { pTemp = pTemp->pNext; - } Node *pInsert = new Node; pInsert->date = date; pInsert->pNext = pTemp->pNext; @@ -199,9 +181,7 @@ template void Linkedlist::deletePos(int pos) { if (pos < 0 || pos > length) - { std::cerr << "delete element position error!" << std::endl; - } else { Node *deleteElement; @@ -215,9 +195,7 @@ void Linkedlist::deletePos(int pos) int i = 0; Node *pTemp = header; while (++i < pos) - { pTemp = pTemp->pNext; - } deleteElement = pTemp->pNext; pTemp->pNext = deleteElement->pNext; } @@ -231,23 +209,17 @@ template void Linkedlist::modify(int pos, const T& date) { if (pos < 1 || pos > length) - { std::cerr << "modify element position error!" << std::endl; - } else { if (pos == 1) - { header->date = date; - } else { Node *pTemp = header; int i = 1; while (i++ < pos) - { pTemp = pTemp->pNext; - } pTemp->date = date; } } @@ -279,7 +251,6 @@ void Linkedlist::sort() if (length > 1) { for (int i = length; i > 0; --i) - { for (int j = 1; j < i; j++) { T left = getPos(j); @@ -290,7 +261,6 @@ void Linkedlist::sort() modify(j + 1, left); } } - } } return; } @@ -313,9 +283,7 @@ int main() { Linkedlist link; for (int i = 10; i > 0; --i) - { link.rearAdd(i); - } link.print(); std::cout << link.size() << std::endl; Linkedlist link1(link); @@ -332,4 +300,4 @@ int main() link1.destroy(); std::cout << link1.size() << std::endl; return 0; -} \ No newline at end of file +} diff --git a/code/data_structures/src/list/circular_linked_list/CircularLinkedList.java b/code/data_structures/src/list/circular_linked_list/circularlinkedlist.java similarity index 100% rename from code/data_structures/src/list/circular_linked_list/CircularLinkedList.java rename to code/data_structures/src/list/circular_linked_list/circularlinkedlist.java diff --git a/code/data_structures/src/list/doubly_linked_list/C/doubly_linked_list.c b/code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.c similarity index 100% rename from code/data_structures/src/list/doubly_linked_list/C/doubly_linked_list.c rename to code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.c diff --git a/code/data_structures/src/list/doubly_linked_list/C/doubly_linked_list.h b/code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.h similarity index 100% rename from code/data_structures/src/list/doubly_linked_list/C/doubly_linked_list.h rename to code/data_structures/src/list/doubly_linked_list/c/doubly_linked_list.h diff --git a/code/data_structures/src/list/doubly_linked_list/DoublyLinkedList.java b/code/data_structures/src/list/doubly_linked_list/doublylinkedlist.java similarity index 100% rename from code/data_structures/src/list/doubly_linked_list/DoublyLinkedList.java rename to code/data_structures/src/list/doubly_linked_list/doublylinkedlist.java diff --git a/code/data_structures/src/list/singly_linked_list/operations/find/finding_if_element_is _present_in_the_list.c b/code/data_structures/src/list/singly_linked_list/operations/find/finding_if_element_is_present_in_the_list.c similarity index 100% rename from code/data_structures/src/list/singly_linked_list/operations/find/finding_if_element_is _present_in_the_list.c rename to code/data_structures/src/list/singly_linked_list/operations/find/finding_if_element_is_present_in_the_list.c diff --git a/code/data_structures/src/list/singly_linked_list/operations/find/SearchElement_list.java b/code/data_structures/src/list/singly_linked_list/operations/find/searchelement_list.java similarity index 100% rename from code/data_structures/src/list/singly_linked_list/operations/find/SearchElement_list.java rename to code/data_structures/src/list/singly_linked_list/operations/find/searchelement_list.java diff --git a/code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_List_Operations.cpp b/code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_list_operations.cpp similarity index 100% rename from code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_List_Operations.cpp rename to code/data_structures/src/list/singly_linked_list/operations/unclassified/linked_list_operations.cpp diff --git a/code/data_structures/src/list/singly_linked_list/operations/unclassified/LinkedList.java b/code/data_structures/src/list/singly_linked_list/operations/unclassified/linkedlist.java similarity index 100% rename from code/data_structures/src/list/singly_linked_list/operations/unclassified/LinkedList.java rename to code/data_structures/src/list/singly_linked_list/operations/unclassified/linkedlist.java diff --git a/code/data_structures/src/list/singly_linked_list/operations/unclassified/LinkedListeg.java b/code/data_structures/src/list/singly_linked_list/operations/unclassified/linkedlisteg.java similarity index 100% rename from code/data_structures/src/list/singly_linked_list/operations/unclassified/LinkedListeg.java rename to code/data_structures/src/list/singly_linked_list/operations/unclassified/linkedlisteg.java diff --git a/code/data_structures/src/list/singly_linked_list/operations/unclassified/union_intersection_in_list.textClipping b/code/data_structures/src/list/singly_linked_list/operations/unclassified/union_intersection_in_list.textclipping similarity index 100% rename from code/data_structures/src/list/singly_linked_list/operations/unclassified/union_intersection_in_list.textClipping rename to code/data_structures/src/list/singly_linked_list/operations/unclassified/union_intersection_in_list.textclipping diff --git a/code/data_structures/src/queue/double_ended_queue/deque.cpp b/code/data_structures/src/queue/double_ended_queue/deque.cpp index 35088db816..ed92b4b762 100644 --- a/code/data_structures/src/queue/double_ended_queue/deque.cpp +++ b/code/data_structures/src/queue/double_ended_queue/deque.cpp @@ -1,223 +1,221 @@ #include -using namespace std ; -#define MAX 10 +using namespace std; +#define MAX 10 int deque[MAX]; -int leftt =-1 ; -int rightt = -1 ; +int leftt = -1; +int rightt = -1; void inputdeque(void); -void outputdeque(void); +void outputdeque(void); void insertleft(void); -void insertright(void); -void deleteleft(void); -void deleteright(void); -void display(void); - -int main( ) -{ - int option; - cout<<"\n *****MAIN MENU*****"; - cout<<"\n 1.Input restricted deque"; - cout<<"\n 2.Output restricted deque"; - cout<<"\n Enter your option : "; - cin>>option; - - switch (option) - { - case 1: inputdeque(); - break; - case 2: outputdeque(); - break; - } return 0; -} - -void inputdeque( ) -{ - int option; - do - { - cout<<"\n\n INPUT RESTRICTED DEQUE"; - cout<<"\n 1.Insert at right"; - cout<<"\n 2.Delete from left"; - cout<<"\n 3.Delete from right"; - cout<<"\n 4.Display"; - cout<<"\n 5.Quit"; - cout<<"\n Enter your option : "; - - cin>>option ; - switch (option) - { - case 1: insertright(); - break; - case 2: deleteleft(); - break; - case 3: deleteright(); - break; - case 4: display(); - break; - } - - }while (option!=5); -} - -void outputdeque( ) -{ - int option; - do - { - cout<<"\n\n OUTPUT RESTRICTED DEQUE"; - cout<<"\n 1.Insert at right"; - cout<<"\n 2.Insert at left"; - cout<<"\n 3.Delete from left"; - cout<<"\n 4.Display"; - cout<<"\n 5.Quit"; - cout<<"\n Enter your option : "; - - cin>>option ; - switch(option) - { - case 1: insertright(); - break; - case 2: insertleft(); - break; - case 3: deleteleft(); - break; - case 4: display(); - break; - } - }while (option!=5); -} - -void insertright( ) -{ - int val; - cout<<"\n Enter the value to be added:" ; - cin>>val; - if ( (leftt == 0 && rightt == MAX-1 ) || (leftt == rightt+1) ) - { - cout<<"\n OVERFLOW"; - return; - } - if (leftt == -1) // Queue is Empty Inititally - { - leftt = 0; - rightt = 0; - } - else - { - if (rightt == MAX-1) //rightt is at last position of queue - rightt = 0; - else - rightt = rightt+1; - } - deque[rightt] = val ; -} - -void insertleft( ) -{ - int val; - cout<<"\n Enter the value to be added:"; - cin>>val; - - if( (leftt ==0 && rightt == MAX-1) || (leftt == rightt+1) ) - { - cout<<"\n OVERFLOW"; - return; - } - if (leftt == -1) //If queue is initially empty - { - leftt = 0; - rightt = 0; - } - else - { - if(leftt == 0) - leftt = MAX - 1 ; - else - leftt = leftt - 1 ; - } - deque[leftt] = val; +void insertright(void); +void deleteleft(void); +void deleteright(void); +void display(void); + +int main( ) +{ + int option; + cout << "\n *****MAIN MENU*****"; + cout << "\n 1.Input restricted deque"; + cout << "\n 2.Output restricted deque"; + cout << "\n Enter your option : "; + cin >> option; + + switch (option) + { + case 1: inputdeque(); + break; + case 2: outputdeque(); + break; + } return 0; +} + +void inputdeque( ) +{ + int option; + do + { + cout << "\n\n INPUT RESTRICTED DEQUE"; + cout << "\n 1.Insert at right"; + cout << "\n 2.Delete from left"; + cout << "\n 3.Delete from right"; + cout << "\n 4.Display"; + cout << "\n 5.Quit"; + cout << "\n Enter your option : "; + + cin >> option; + switch (option) + { + case 1: insertright(); + break; + case 2: deleteleft(); + break; + case 3: deleteright(); + break; + case 4: display(); + break; + } + + } while (option != 5); } - -void deleteleft( ) -{ - if ( leftt == -1 ) - { - cout<<"\n UNDERFLOW"; - return ; - } - - cout<<"\n The deleted element is : "<< deque[leftt]; - - if (leftt == rightt) /*Queue has only one element */ - { - leftt = -1 ; - rightt = -1 ; - } - else - { - if ( leftt == MAX - 1 ) - leftt = 0; - else - leftt = leftt+1; - } -} - -void deleteright() -{ - if ( leftt == -1 ) - { - cout<<"\n UNDERFLOW"; - return ; - } - - cout<<"\n The element deleted is : "<< deque[rightt]; - - if (leftt == rightt) /*queue has only one element*/ - { - leftt = -1 ; - rightt = -1 ; - } - else - { - if (rightt == 0) - rightt = MAX - 1 ; - else - rightt = rightt - 1 ; - } -} - -void display( ) -{ - int front = leftt, rear = rightt; - if ( front == -1 ) - { - cout<<"\n QUEUE IS EMPTY"; - return; - } - cout<<"\n The elements of the queue are : "; - if (front <= rear ) - { - while (front <= rear) - { - cout << deque[front] <<" "; - front++; - } - } - else - { - while (front <= MAX - 1) - { - cout << deque[front] <<" "; - front++; - } - front = 0; - while (front <= rear) - { - cout<< deque[front]<<" "; - front++; - } - } - cout<> option; + switch (option) + { + case 1: insertright(); + break; + case 2: insertleft(); + break; + case 3: deleteleft(); + break; + case 4: display(); + break; + } + } while (option != 5); +} + +void insertright( ) +{ + int val; + cout << "\n Enter the value to be added:"; + cin >> val; + if ( (leftt == 0 && rightt == MAX - 1 ) || (leftt == rightt + 1) ) + { + cout << "\n OVERFLOW"; + return; + } + if (leftt == -1) // Queue is Empty Inititally + { + leftt = 0; + rightt = 0; + } + else + { + if (rightt == MAX - 1) //rightt is at last position of queue + rightt = 0; + else + rightt = rightt + 1; + } + deque[rightt] = val; +} + +void insertleft( ) +{ + int val; + cout << "\n Enter the value to be added:"; + cin >> val; + + if ( (leftt == 0 && rightt == MAX - 1) || (leftt == rightt + 1) ) + { + cout << "\n OVERFLOW"; + return; + } + if (leftt == -1) //If queue is initially empty + { + leftt = 0; + rightt = 0; + } + else + { + if (leftt == 0) + leftt = MAX - 1; + else + leftt = leftt - 1; + } + deque[leftt] = val; +} + +void deleteleft( ) +{ + if (leftt == -1) + { + cout << "\n UNDERFLOW"; + return; + } + + cout << "\n The deleted element is : " << deque[leftt]; + + if (leftt == rightt) /*Queue has only one element */ + { + leftt = -1; + rightt = -1; + } + else + { + if (leftt == MAX - 1) + leftt = 0; + else + leftt = leftt + 1; + } +} + +void deleteright() +{ + if (leftt == -1) + { + cout << "\n UNDERFLOW"; + return; + } + + cout << "\n The element deleted is : " << deque[rightt]; + + if (leftt == rightt) /*queue has only one element*/ + { + leftt = -1; + rightt = -1; + } + else + { + if (rightt == 0) + rightt = MAX - 1; + else + rightt = rightt - 1; + } +} + +void display( ) +{ + int front = leftt, rear = rightt; + if (front == -1) + { + cout << "\n QUEUE IS EMPTY"; + return; + } + cout << "\n The elements of the queue are : "; + if (front <= rear) + while (front <= rear) + { + cout << deque[front] << " "; + front++; + } + else + { + while (front <= MAX - 1) + { + cout << deque[front] << " "; + front++; + } + front = 0; + while (front <= rear) + { + cout << deque[front] << " "; + front++; + } + } + cout << endl; //NEW LINE } diff --git a/code/data_structures/src/queue/double_ended_queue/deque_queue_library_function.cpp b/code/data_structures/src/queue/double_ended_queue/deque_queue_library_function.cpp index 1875e50690..d24bff163c 100644 --- a/code/data_structures/src/queue/double_ended_queue/deque_queue_library_function.cpp +++ b/code/data_structures/src/queue/double_ended_queue/deque_queue_library_function.cpp @@ -5,54 +5,53 @@ using namespace std; void showdq (deque g) { - deque :: iterator it; // Iterator to iterate over the deque . - - for (it = g.begin(); it != g.end(); ++it) - cout << '\t' << *it; - - cout << "\n"; + deque :: iterator it; // Iterator to iterate over the deque . + + for (it = g.begin(); it != g.end(); ++it) + cout << '\t' << *it; + + cout << "\n"; } int main () { - deque que; - int option , x ; - do - { - - - cout<<"\n\n DEQUEUE USING STL C++ "; - cout<<"\n 1.Insert front"; - cout<<"\n 2.Insert Back"; - cout<<"\n 3.Delete front"; - cout<<"\n 4.Delete Back"; - cout<<"\n 5.Display "; - - cout<<"\n Enter your option : "; - cin>>option; - - switch (option) - { - case 1 : cout<<"\n Enter number : "; - cin>>x; - que.push_front(x); - break; - - case 2 : cout<<"\n Enter number : "; - cin>>x; - que.push_back(x); - break; - - case 3 : que.pop_front(); - break; - - case 4 : que.pop_back(); - break; - case 5 : showdq(que); - break; - } - } while (option!=6); - - return 0; -} + deque que; + int option, x; + do + { + + + cout << "\n\n DEQUEUE USING STL C++ "; + cout << "\n 1.Insert front"; + cout << "\n 2.Insert Back"; + cout << "\n 3.Delete front"; + cout << "\n 4.Delete Back"; + cout << "\n 5.Display "; + + cout << "\n Enter your option : "; + cin >> option; + switch (option) + { + case 1: cout << "\n Enter number : "; + cin >> x; + que.push_front(x); + break; + + case 2: cout << "\n Enter number : "; + cin >> x; + que.push_back(x); + break; + + case 3: que.pop_front(); + break; + + case 4: que.pop_back(); + break; + case 5: showdq(que); + break; + } + } while (option != 6); + + return 0; +} diff --git a/code/data_structures/src/stack/abstract_stack/cpp/arrayStack/ArrayStack.h b/code/data_structures/src/stack/abstract_stack/cpp/arraystack/arraystack.h similarity index 99% rename from code/data_structures/src/stack/abstract_stack/cpp/arrayStack/ArrayStack.h rename to code/data_structures/src/stack/abstract_stack/cpp/arraystack/arraystack.h index 526159750c..962f17ede4 100644 --- a/code/data_structures/src/stack/abstract_stack/cpp/arrayStack/ArrayStack.h +++ b/code/data_structures/src/stack/abstract_stack/cpp/arraystack/arraystack.h @@ -4,7 +4,7 @@ #include #include -#include "../IStack.h" +#include "../istack.h" template class ArrayStack : public IStack { diff --git a/code/data_structures/src/stack/abstract_stack/cpp/arrayStack/arraystackTester.cpp b/code/data_structures/src/stack/abstract_stack/cpp/arraystack/arraystacktester.cpp similarity index 95% rename from code/data_structures/src/stack/abstract_stack/cpp/arrayStack/arraystackTester.cpp rename to code/data_structures/src/stack/abstract_stack/cpp/arraystack/arraystacktester.cpp index 40551fbdca..493408ff7c 100644 --- a/code/data_structures/src/stack/abstract_stack/cpp/arrayStack/arraystackTester.cpp +++ b/code/data_structures/src/stack/abstract_stack/cpp/arraystack/arraystacktester.cpp @@ -1,8 +1,8 @@ #include -#include "../IStack.h" -#include "ArrayStack.h" +#include "../istack.h" +#include "arraystack.h" int main() { diff --git a/code/data_structures/src/stack/abstract_stack/IStack.h b/code/data_structures/src/stack/abstract_stack/cpp/istack.h similarity index 100% rename from code/data_structures/src/stack/abstract_stack/IStack.h rename to code/data_structures/src/stack/abstract_stack/cpp/istack.h diff --git a/code/data_structures/src/stack/abstract_stack/cpp/IStack.h b/code/data_structures/src/stack/abstract_stack/istack.h similarity index 100% rename from code/data_structures/src/stack/abstract_stack/cpp/IStack.h rename to code/data_structures/src/stack/abstract_stack/istack.h diff --git a/code/data_structures/src/stack/balanced_expression/balanced_expression.cpp b/code/data_structures/src/stack/balanced_expression/balanced_expression.cpp new file mode 100644 index 0000000000..4a151757da --- /dev/null +++ b/code/data_structures/src/stack/balanced_expression/balanced_expression.cpp @@ -0,0 +1,38 @@ +#include +#include + +bool checkBalanced(string s) +{ + if (s.length() % 2 != 0) + return false; + std::stack st; + for (const char: s) + { + if (s[i] == '{' || s[i] == '[' || s[i] == '(') + st.push(s[i]); + else + { + char temp = st.top(); + if (s[i] == '}' && temp == '{') + st.pop(); + else if (s[i] == ']' && temp == '[') + st.pop(); + else if (s[i] == ')' && temp == '(') + st.pop(); + else + return false; + } + } + return st.empty(); +} + +int main() +{ + std::string s; + std::cin >> s; + bool res = checkBalanced(s); + if (res) + std::cout << "Expression is balanced"; + else + std::cout << "Expression is not balanced"; +} diff --git a/code/data_structures/src/tree/Van_Emde_Boas_Tree/Van_Emde_Boas_Tree.cpp b/code/data_structures/src/tree/Van_Emde_Boas_Tree/Van_Emde_Boas_Tree.cpp deleted file mode 100644 index 579a2f2e4e..0000000000 --- a/code/data_structures/src/tree/Van_Emde_Boas_Tree/Van_Emde_Boas_Tree.cpp +++ /dev/null @@ -1,361 +0,0 @@ -#include -using namespace std; - -class veb -{ - int u; - int *min; - int *max; - veb *summary; - veb **cluster; - - public: - - veb(int u); - void insert(int x); - void remove(int x); - int* pred(int x); - int minimum(); - int maximum(); -}; - - -veb :: veb(int u) -{ - this -> u = u; - this -> min = NULL; - this -> max =NULL; - - if(u==2) - { - this -> summary = NULL; - this -> cluster = NULL; - } - else - { - int sub_size=sqrt(u); - this -> summary = new veb(sub_size); - this -> cluster = new veb*[sub_size]; - } - -} - - -void veb::insert(int x) -{ - if(u==2) - { - if(x==0) - { - if(max==NULL) - { - max = new int; - min = new int; - *max = x; - *min = x; - } - else - { - *min=x; - } - } - else if(x==1) - { - if(min == NULL) - { - max = new int; - min = new int; - *max = x; - *min = x; - } - else - { - *max=x; - } - } - } - else - { - if(min==NULL) - { - min = new int; - max = new int; - *max = x; - *min = x; - this->insert(x); - } - else - { - if((*min)>x) - { - *min = x; - this -> insert(x); - } - else - { - int subsize = sqrt(u); - int high = x/subsize , low = x%subsize; - if(cluster[high] == NULL) - { - cluster[high] = new veb(subsize); - cluster[high]->insert(low); - summary->insert(high); - } - else - { - cluster[high]->insert(low); - } - if((*max)remove(low); - return; - } - - cluster[high]->remove(low); - - if(cluster[high]->min==NULL) - { - delete cluster[high]; - cluster[high]=NULL; - summary->remove(high); - } - int newminhigh=summary->minimum(); - int newminlow=cluster[newminhigh]->minimum(); - *min=newminhigh*subsize+newminlow; - } - else - { - cluster[high]->remove(low); - - if(cluster[high]->min==NULL) - { - delete cluster[high]; - cluster[high]=NULL; - summary->remove(high); - } - if(x ==*max) - { - int newmaxhigh=summary->maximum(); - int newmaxlow=cluster[newmaxhigh]->maximum(); - *max=newmaxhigh*subsize+newmaxlow; - } - } - - } -} - -int* veb::pred(int x) -{ - if(u==2) - { - if(x==0) - { - return NULL; - } - else if(x==1) - { - if(min==NULL) - { - return NULL; - } - else if((*min)==1) - { - return NULL; - } - else - { - return min; - } - } - else - { - return NULL; - } - } - else - { - if(min==NULL) - { - return NULL; - } - if((*min)>=x) - { - return NULL; - } - if(x>(*max)) - { - return max; - } - int subsize = sqrt(u); - int high = x/subsize; - int low = x%subsize; - if(cluster[high]==NULL) - { - int *pred = summary->pred(high); - int *ans = new int; - *ans = (*pred)*subsize +*(cluster[*pred]->max); - return ans; - } - else - { - int *ans_high = new int; - int *ans_low = new int; - - if(low > *(cluster[high]->min)) - { - *ans_high = high; - ans_low = cluster[high] -> pred(low); - } - else - { - ans_high = summary -> pred(high); - ans_low = cluster[(*ans_high)]->max; - } - - int *ans = new int; - *ans = (*ans_high)*subsize+(*ans_low); - return ans; - } - } - -} - -int veb::minimum() -{ - return *min; -} - -int veb::maximum() -{ - return *max; -} - -void findpred(veb *x,int y) -{ - int *temp=x->pred(y); - if(temp==NULL) - cout<<"no predecesor"< insert(2); - x -> insert(3); - x -> insert(4); - x -> insert(5); - x -> insert(7); - x -> insert(14); - x -> insert(15); - - - cout<minimum()<maximum()< remove(15); - x->remove(5); - - findpred(x,0); - findpred(x,1); - findpred(x,2); - findpred(x,3); - findpred(x,4); - findpred(x,5); - findpred(x,6); - findpred(x,7); - findpred(x,8); - findpred(x,9); - findpred(x,10); - findpred(x,11); - findpred(x,12); - findpred(x,13); - findpred(x,14); - findpred(x,15); - findpred(x,16); - findpred(x,7); - -} \ No newline at end of file diff --git a/code/data_structures/src/tree/b_tree/b_tree/b_tree_C/README.md b/code/data_structures/src/tree/b_tree/b_tree/b_tree_c/README.md similarity index 100% rename from code/data_structures/src/tree/b_tree/b_tree/b_tree_C/README.md rename to code/data_structures/src/tree/b_tree/b_tree/b_tree_c/README.md diff --git a/code/data_structures/src/tree/b_tree/b_tree/b_tree_C/btree.c b/code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.c similarity index 100% rename from code/data_structures/src/tree/b_tree/b_tree/b_tree_C/btree.c rename to code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.c diff --git a/code/data_structures/src/tree/b_tree/b_tree/b_tree_C/btree.h b/code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.h similarity index 100% rename from code/data_structures/src/tree/b_tree/b_tree/b_tree_C/btree.h rename to code/data_structures/src/tree/b_tree/b_tree/b_tree_c/btree.h diff --git a/code/data_structures/src/tree/b_tree/b_tree/b_tree_C/main.c b/code/data_structures/src/tree/b_tree/b_tree/b_tree_c/main.c similarity index 100% rename from code/data_structures/src/tree/b_tree/b_tree/b_tree_C/main.c rename to code/data_structures/src/tree/b_tree/b_tree/b_tree_c/main.c diff --git a/code/data_structures/src/tree/b_tree/two_three_tree/TwoThreeTree.scala b/code/data_structures/src/tree/b_tree/two_three_tree/twothreetree.scala similarity index 100% rename from code/data_structures/src/tree/b_tree/two_three_tree/TwoThreeTree.scala rename to code/data_structures/src/tree/b_tree/two_three_tree/twothreetree.scala diff --git a/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.c b/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.c new file mode 100644 index 0000000000..e256c53698 --- /dev/null +++ b/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.c @@ -0,0 +1,41 @@ +#include +#include + +typedef struct btree { + int data; + struct btree *left; + struct btree *right; +}btree; + +btree *makeTree(int *in , int *post , int start , int end , int *index) { + if (start > end) return NULL; + + btree *nn = (btree*)malloc(sizeof(btree)); + nn -> data = post[*index]; + int i; + for (i = start;i <= end;i++) { + if (post[*index] == in[i]) break; + } + (*index)--; + nn -> right = makeTree(in, post, i+1, end, index); + nn -> left = makeTree(in, post, start, i-1, index); + return nn; +} + +void printPostOrderTree(btree *root) { + if(root == NULL) return; + printPostOrderTree(root -> left); + printPostOrderTree(root -> right); + printf("%d ",root -> data); +} + +int main() +{ + int post[] = {4,5,2,6,7,3,1}; + int in[] = {4,2,5,1,6,3,7}; + int index = 6; + btree *root = makeTree (in, post, 0, 6, &index); + + printPostOrderTree(root); + return 0; +} diff --git a/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.cpp b/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.cpp index cf90d293d0..8069b54361 100644 --- a/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.cpp +++ b/code/data_structures/src/tree/binary_tree/binary_tree/make_binary_tree/from_inorder_and_postorder/make_tree_from_inorder_and_postorder.cpp @@ -5,7 +5,7 @@ using namespace std; template -class TreeNode +class TreeNode { using Treetype = TreeNode; @@ -14,22 +14,24 @@ class TreeNode Treetype * left; Treetype * right; - TreeNode(T data) : data(data), left(NULL), right(NULL) {} + TreeNode(T data) : data(data), left(NULL), right(NULL) + { + } }; template TreeNode* buildTreeHelper(BidiIt in_first, BidiIt in_last, - BidiIt post_first, BidiIt post_last); + BidiIt post_first, BidiIt post_last); TreeNode* buildTree(vector &inorder, vector &postorder) { return buildTreeHelper(begin(inorder), end(inorder), - begin(postorder), end(postorder)); + begin(postorder), end(postorder)); } template TreeNode* buildTreeHelper(BidiIt in_first, BidiIt in_last, - BidiIt post_first, BidiIt post_last) + BidiIt post_first, BidiIt post_last) { if (in_first == in_last) return nullptr; @@ -42,7 +44,7 @@ TreeNode* buildTreeHelper(BidiIt in_first, BidiIt in_last, auto post_left_last = next(post_first, left_size); root->left = buildTreeHelper(in_first, in_root_pos, post_first, post_left_last); root->right = buildTreeHelper(next(in_root_pos), in_last, post_left_last, - prev(post_last)); + prev(post_last)); return root; } @@ -71,14 +73,14 @@ int main() } /* -// test tree is - 1 - / \ - 2 3 - / \ - 4 5 - \ - 6 - / \ - 7 8 -*/ \ No newline at end of file + * // test tree is + * 1 + * / \ + * 2 3 + * / \ + * 4 5 + \ + \ 6 + \ / \ + \ 7 8 + */ diff --git a/code/data_structures/src/tree/segment_tree/segment_Tree_rmq.adb b/code/data_structures/src/tree/segment_tree/segment_tree_rmq.adb similarity index 100% rename from code/data_structures/src/tree/segment_tree/segment_Tree_rmq.adb rename to code/data_structures/src/tree/segment_tree/segment_tree_rmq.adb diff --git a/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.adb b/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.adb new file mode 100644 index 0000000000..1c9e48e243 --- /dev/null +++ b/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq.adb @@ -0,0 +1,142 @@ +with Ada.Integer_Text_IO, Ada.Text_IO; +use Ada.Integer_Text_IO, Ada.Text_IO; +-- Compile: +-- gnatmake segment_Tree_rmq + + +procedure segment_Tree_rmq is + +INT_MAX: constant integer := 999999; +MAXN : constant integer := 100005; +v : array(0..MAXN) of integer; +tree: array(0..4*MAXN) of integer; +n : integer; +q : integer; +a : integer; +b : integer; +c : integer; + +function min(a: integer; b: integer) return integer is + +begin + + if a < b then return a; + else return b; + end if; +end min; + +procedure build(node: integer; l: integer; r: integer) is + + mid: integer; + +begin + + mid := (l + r)/2; + + if l = r then + tree(node) := v(l); + return; + end if; + + build(2 * node, l, mid); + build(2*node+1,mid+1,r); + tree(node) := min( tree(2*node), tree(2*node + 1)); +end build; + + +--Update procedure +procedure update(node: integer; l: integer; r: integer; pos: integer; val: integer) is + + mid: integer := (l + r)/2; + +begin + + if l > pos or r < pos or l > r then + return; + end if; + + if(l = r) then + tree(node) := val; + return; + end if; + + if pos <= mid then + update(2*node,l,mid,pos,val); + else + update(2*node+1,mid+1,r,pos,val); + end if; + tree(node) := min( tree(2*node), tree(2*node + 1)); +end update; + + +--Query function +function query(node : integer; l: integer; r: integer; x: integer; y: integer) return integer is + + mid: integer := (l + r)/2; + p1: integer; + p2: integer; +begin + + if l > r or l > y or r < x then + return INT_MAX; + end if; + if x <= l and r <= y then + return tree(node); + end if; + + p1 := query(2*node,l,mid,x,y); + p2 := query(2*node+1,mid+1,r,x,y); + + if p1 = INT_MAX then + return p2; + end if; + + if p2 = INT_MAX then + return p1; + end if; + + return min(p1, p2); + +end query; + + +begin + Put_Line("Input the array range"); + Get(n); + Put_Line("Input the values"); + for i in 1..n loop + Get(v(i)); + end loop; + + + build(1,0,n-1); + + Put_Line("Input the number of operations"); + + Get(q); + + while q > 0 loop + Put_Line("Input 0 to query and 1 to update"); + Get(a); + Put_Line("Input the STARTING index of the query range"); + Get(b); + Put_Line("Input the ENDING index of the query range"); + Get(c); + + if a = 0 then + Put_Line("Minimum value of the given range"); + Put(query(1,1,n,b,c)); + Put_Line(""); + elsif a = 1 then + update(1,1,n,b,c); + else + Put_Line("Invalid Operation"); + q := q + 1; + end if; + q := q - 1; + + end loop; +end segment_Tree_rmq; + + + diff --git a/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq_with_update.cpp b/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq_with_update.cpp new file mode 100644 index 0000000000..0942fe8e3f --- /dev/null +++ b/code/data_structures/src/tree/space_partitioning_tree/segment_tree/segment_tree_rmq_with_update.cpp @@ -0,0 +1,168 @@ +/* Part of Cosmos by OpenGenus Foundation */ + +/* + * Processes range minimum query. + * Query function returns index of minimum element in given interval. + * Code assumes that length of array can be contained into integer. + */ + +#include +#include +#include + +struct Node +{ + // store the data in variable value + int index; + // store the interval in a pair of integers + std::pair interval; + Node *left; + Node *right; +}; + +// update adds new value to array[x] rather than replace it + +class SegmentTree { +private: + Node *root; + + int build(std::vector &array, Node *node, int L, int R) + { + node->interval = std::make_pair(L, R); + if (L == R) + { + node->index = L; + return node->index; + } + + node->left = new Node; + node->right = new Node; + int leftIndex = build(array, node->left, L, (L + R) / 2); + int rightIndex = build(array, node->right, (L + R) / 2 + 1, R); + + node->index = (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex; + + return node->index; + } + + // returns the index of smallest element in the range [start, end] + int query(Node *node, int start, int end) + { + if (start > end) + return -1; + int L = node->interval.first; + int R = node->interval.second; + + if (R < start || L > end) + return -1; + + if (start <= L && end >= R) + return node->index; + + int leftIndex = query(node->left, start, end); + int rightIndex = query(node->right, start, end); + + if (leftIndex == -1) + return rightIndex; + if (rightIndex == -1) + return leftIndex; + + return (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex; + } + + void update(Node *node, int x, int value) + { + int L = node->interval.first; + int R = node->interval.second; + + if (L == R) + { + array[L] += value; + return; + } + + if (L <= x && (L + R) / 2 >= x) + // x is in left subtree + update(node->left, x, value); + else + // x is in right subtree + update(node->right, x, value); + + int leftIndex = node->left->index; + int rightIndex = node->right->index; + + //update current node + node->index = (array[leftIndex] < array[rightIndex]) ? leftIndex : rightIndex; + } + + // To clear allocated memory at end of program + void clearMem(Node *node) + { + int L = node->interval.first; + int R = node->interval.second; + + if (L != R) + { + clearMem(node->left); + clearMem(node->right); + } + delete node; + } + +public: + std::vector array; + + SegmentTree(std::vector &ar) + { + array = ar; + root = new Node; + build(ar, root, 0, ar.size() - 1); + } + + int query(int L, int R) + { + return query(root, L, R); + } + + void update(int pos, int value) + { + return update(root, pos, value); + } + + ~SegmentTree() + { + clearMem(root); + } +}; + +int main() +{ + // define n and array + int n = 8; + std::vector array = {5, 4, 3, 2, 1, 0, 7, 0}; + + SegmentTree st(array); + + std::cout << "Array:\n"; + for (int i = 0; i < n; ++i) + std::cout << st.array[i] << ' '; + std::cout << '\n'; + + // sample query + std::cout << "The smallest element in the interval [1, 6] is " + << array[st.query(0, 5)] << '\n'; // since array is 0 indexed. + + // change 0 at index 5 to 8 + st.update(5, 8); + array[5] += 8; + + std::cout << "After update, array:\n"; + for (int i = 0; i < n; ++i) + std::cout << st.array[i] << ' '; + std::cout << '\n'; + + std::cout << "The smallest element in the interval [1, 6] after update is " + << array[st.query(0, 5)] << '\n'; + + return 0; +} diff --git a/code/data_structures/src/tree/van_emde_boas_tree/van_emde_boas_tree.cpp b/code/data_structures/src/tree/van_emde_boas_tree/van_emde_boas_tree.cpp new file mode 100644 index 0000000000..7dfad3cfdd --- /dev/null +++ b/code/data_structures/src/tree/van_emde_boas_tree/van_emde_boas_tree.cpp @@ -0,0 +1,330 @@ +#include +using namespace std; + +class veb +{ + int u; + int *min; + int *max; + veb *summary; + veb **cluster; + +public: + + veb(int u); + void insert(int x); + void remove(int x); + int* pred(int x); + int minimum(); + int maximum(); +}; + + +veb :: veb(int u) +{ + this->u = u; + this->min = NULL; + this->max = NULL; + + if (u == 2) + { + this->summary = NULL; + this->cluster = NULL; + } + else + { + int sub_size = sqrt(u); + this->summary = new veb(sub_size); + this->cluster = new veb*[sub_size]; + } + +} + + +void veb::insert(int x) +{ + if (u == 2) + { + if (x == 0) + { + if (max == NULL) + { + max = new int; + min = new int; + *max = x; + *min = x; + } + else + *min = x; + } + else if (x == 1) + { + if (min == NULL) + { + max = new int; + min = new int; + *max = x; + *min = x; + } + else + *max = x; + } + } + else + { + if (min == NULL) + { + min = new int; + max = new int; + *max = x; + *min = x; + this->insert(x); + } + else + { + if ((*min) > x) + { + *min = x; + this->insert(x); + } + else + { + int subsize = sqrt(u); + int high = x / subsize, low = x % subsize; + if (cluster[high] == NULL) + { + cluster[high] = new veb(subsize); + cluster[high]->insert(low); + summary->insert(high); + } + else + cluster[high]->insert(low); + if ((*max) < x) + *max = x; + } + } + } +} + + +void veb::remove(int x) +{ + if (u == 2) + { + + + if (x == 0) + { + if (min != NULL) + { + if (*max == 0) + { + min = NULL; + max = NULL; + } + else + *min = 1; + } + } + else if (max != NULL) + { + + if (*min == 1) + { + min = NULL; + max = NULL; + } + else + *max = 0; + } + + } + else + { + + int subsize = sqrt(u); + int high = x / subsize, low = x % subsize; + if (min == NULL || cluster[high] == NULL) + return; + if (x == *min) + { + + if (x == *max) + { + min = NULL; + max = NULL; + cluster[high]->remove(low); + return; + } + + cluster[high]->remove(low); + + if (cluster[high]->min == NULL) + { + delete cluster[high]; + cluster[high] = NULL; + summary->remove(high); + } + int newminhigh = summary->minimum(); + int newminlow = cluster[newminhigh]->minimum(); + *min = newminhigh * subsize + newminlow; + } + else + { + cluster[high]->remove(low); + + if (cluster[high]->min == NULL) + { + delete cluster[high]; + cluster[high] = NULL; + summary->remove(high); + } + if (x == *max) + { + int newmaxhigh = summary->maximum(); + int newmaxlow = cluster[newmaxhigh]->maximum(); + *max = newmaxhigh * subsize + newmaxlow; + } + } + + } +} + +int* veb::pred(int x) +{ + if (u == 2) + { + if (x == 0) + return NULL; + else if (x == 1) + { + if (min == NULL) + return NULL; + else if ((*min) == 1) + return NULL; + else + return min; + } + else + return NULL; + } + else + { + if (min == NULL) + return NULL; + if ((*min) >= x) + return NULL; + if (x > (*max)) + return max; + int subsize = sqrt(u); + int high = x / subsize; + int low = x % subsize; + if (cluster[high] == NULL) + { + int *pred = summary->pred(high); + int *ans = new int; + *ans = (*pred) * subsize + *(cluster[*pred]->max); + return ans; + } + else + { + int *ans_high = new int; + int *ans_low = new int; + + if (low > *(cluster[high]->min)) + { + *ans_high = high; + ans_low = cluster[high]->pred(low); + } + else + { + ans_high = summary->pred(high); + ans_low = cluster[(*ans_high)]->max; + } + + int *ans = new int; + *ans = (*ans_high) * subsize + (*ans_low); + return ans; + } + } + +} + +int veb::minimum() +{ + return *min; +} + +int veb::maximum() +{ + return *max; +} + +void findpred(veb *x, int y) +{ + int *temp = x->pred(y); + if (temp == NULL) + cout << "no predecesor" << endl; + else + cout << "predecesor of " << y << " is " << *temp << endl; + +} + +int main() +{ + veb *x = new veb(16); + x->insert(2); + x->insert(3); + x->insert(4); + x->insert(5); + x->insert(7); + x->insert(14); + x->insert(15); + + + cout << x->minimum() << endl << x->maximum() << endl; + + + + findpred(x, 0); + findpred(x, 1); + findpred(x, 2); + findpred(x, 3); + findpred(x, 4); + findpred(x, 5); + findpred(x, 6); + findpred(x, 7); + findpred(x, 8); + findpred(x, 9); + findpred(x, 10); + findpred(x, 11); + findpred(x, 12); + findpred(x, 13); + findpred(x, 14); + findpred(x, 15); + findpred(x, 16); + findpred(x, 7); + + x->remove(15); + x->remove(5); + + findpred(x, 0); + findpred(x, 1); + findpred(x, 2); + findpred(x, 3); + findpred(x, 4); + findpred(x, 5); + findpred(x, 6); + findpred(x, 7); + findpred(x, 8); + findpred(x, 9); + findpred(x, 10); + findpred(x, 11); + findpred(x, 12); + findpred(x, 13); + findpred(x, 14); + findpred(x, 15); + findpred(x, 16); + findpred(x, 7); + +} diff --git a/code/design_pattern/src/OOP_patterns/adapter/Adaptor.java b/code/design_pattern/src/OOP_patterns/adapter/adaptor.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Adaptor.java rename to code/design_pattern/src/OOP_patterns/adapter/adaptor.java diff --git a/code/design_pattern/src/OOP_patterns/adapter/Civilian.java b/code/design_pattern/src/OOP_patterns/adapter/civilian.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Civilian.java rename to code/design_pattern/src/OOP_patterns/adapter/civilian.java diff --git a/code/design_pattern/src/OOP_patterns/adapter/Movement.java b/code/design_pattern/src/OOP_patterns/adapter/movement.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Movement.java rename to code/design_pattern/src/OOP_patterns/adapter/movement.java diff --git a/code/design_pattern/src/OOP_patterns/adapter/Soldiers/Adaptee.java b/code/design_pattern/src/OOP_patterns/adapter/soldiers/adaptee.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Soldiers/Adaptee.java rename to code/design_pattern/src/OOP_patterns/adapter/soldiers/adaptee.java diff --git a/code/design_pattern/src/OOP_patterns/adapter/Soldiers/General.java b/code/design_pattern/src/OOP_patterns/adapter/soldiers/general.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Soldiers/General.java rename to code/design_pattern/src/OOP_patterns/adapter/soldiers/general.java diff --git a/code/design_pattern/src/OOP_patterns/adapter/Soldiers/Order.java b/code/design_pattern/src/OOP_patterns/adapter/soldiers/order.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Soldiers/Order.java rename to code/design_pattern/src/OOP_patterns/adapter/soldiers/order.java diff --git a/code/design_pattern/src/OOP_patterns/adapter/Soldiers/Soldier.java b/code/design_pattern/src/OOP_patterns/adapter/soldiers/soldier.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/adapter/Soldiers/Soldier.java rename to code/design_pattern/src/OOP_patterns/adapter/soldiers/soldier.java diff --git a/code/design_pattern/src/OOP_patterns/builder/builder/Nationality.java b/code/design_pattern/src/OOP_patterns/builder/builder/nationality.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/builder/builder/Nationality.java rename to code/design_pattern/src/OOP_patterns/builder/builder/nationality.java diff --git a/code/design_pattern/src/OOP_patterns/builder/builder/Person.java b/code/design_pattern/src/OOP_patterns/builder/builder/person.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/builder/builder/Person.java rename to code/design_pattern/src/OOP_patterns/builder/builder/person.java diff --git a/code/design_pattern/src/OOP_patterns/builder/builder/PersonBuilder.java b/code/design_pattern/src/OOP_patterns/builder/builder/personbuilder.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/builder/builder/PersonBuilder.java rename to code/design_pattern/src/OOP_patterns/builder/builder/personbuilder.java diff --git a/code/design_pattern/src/OOP_patterns/builder/Main.java b/code/design_pattern/src/OOP_patterns/builder/main.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/builder/Main.java rename to code/design_pattern/src/OOP_patterns/builder/main.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/DailyRoutineFacade.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/dailyroutinefacade.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/DailyRoutineFacade.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/dailyroutinefacade.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/Eat.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/eat.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/Eat.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/eat.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/EveningRoutineFacade.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/eveningroutinefacade.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/EveningRoutineFacade.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/eveningroutinefacade.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/TakeAShower.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/takeashower.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/TakeAShower.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/takeashower.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/WatchYoutubeVideos.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/watchyoutubevideos.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/WatchYoutubeVideos.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/watchyoutubevideos.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/WriteCode.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/writecode.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/WriteCode.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/evening/routine/writecode.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/BenchPress.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/benchpress.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/BenchPress.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/benchpress.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/Deadlift.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/deadlift.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/Deadlift.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/deadlift.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/GymFacade.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/gymfacade.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/GymFacade.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/gymfacade.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/Squat.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/squat.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/Squat.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/gym/squat.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/Develop.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/develop.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/Develop.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/develop.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/EatAtWork.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/eatatwork.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/EatAtWork.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/eatatwork.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/JobFacade.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/jobfacade.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/JobFacade.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/jobfacade.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/Leave.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/leave.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/Leave.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/leave.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/PlayFifa.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/playfifa.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/PlayFifa.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/playfifa.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/WatchYoutubeVideos.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/watchyoutubevideos.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/WatchYoutubeVideos.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/job/watchyoutubevideos.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/Dress.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/dress.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/Dress.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/dress.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/Eat.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/eat.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/Eat.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/eat.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/Leave.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/leave.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/Leave.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/leave.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/MorningRoutineFacade.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/morningroutinefacade.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/MorningRoutineFacade.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/morningroutinefacade.java diff --git a/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/WakeUp.java b/code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/wakeup.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/WakeUp.java rename to code/design_pattern/src/OOP_patterns/facade/daily/tasks/morning/routine/wakeup.java diff --git a/code/design_pattern/src/OOP_patterns/facade/Facade b/code/design_pattern/src/OOP_patterns/facade/facade similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/Facade rename to code/design_pattern/src/OOP_patterns/facade/facade diff --git a/code/design_pattern/src/OOP_patterns/facade/Main.java b/code/design_pattern/src/OOP_patterns/facade/main.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/facade/Main.java rename to code/design_pattern/src/OOP_patterns/facade/main.java diff --git a/code/design_pattern/src/OOP_patterns/factory/gifts/Booze.java b/code/design_pattern/src/OOP_patterns/factory/gifts/booze.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/gifts/Booze.java rename to code/design_pattern/src/OOP_patterns/factory/gifts/booze.java diff --git a/code/design_pattern/src/OOP_patterns/factory/gifts/Car.java b/code/design_pattern/src/OOP_patterns/factory/gifts/car.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/gifts/Car.java rename to code/design_pattern/src/OOP_patterns/factory/gifts/car.java diff --git a/code/design_pattern/src/OOP_patterns/factory/gifts/Gift.java b/code/design_pattern/src/OOP_patterns/factory/gifts/gift.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/gifts/Gift.java rename to code/design_pattern/src/OOP_patterns/factory/gifts/gift.java diff --git a/code/design_pattern/src/OOP_patterns/factory/gifts/Nothing.java b/code/design_pattern/src/OOP_patterns/factory/gifts/nothing.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/gifts/Nothing.java rename to code/design_pattern/src/OOP_patterns/factory/gifts/nothing.java diff --git a/code/design_pattern/src/OOP_patterns/factory/gifts/Toy.java b/code/design_pattern/src/OOP_patterns/factory/gifts/toy.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/gifts/Toy.java rename to code/design_pattern/src/OOP_patterns/factory/gifts/toy.java diff --git a/code/design_pattern/src/OOP_patterns/factory/GiftType.java b/code/design_pattern/src/OOP_patterns/factory/gifttype.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/GiftType.java rename to code/design_pattern/src/OOP_patterns/factory/gifttype.java diff --git a/code/design_pattern/src/OOP_patterns/factory/Roulette.java b/code/design_pattern/src/OOP_patterns/factory/roulette.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/factory/Roulette.java rename to code/design_pattern/src/OOP_patterns/factory/roulette.java diff --git a/code/design_pattern/src/OOP_patterns/observer_java/Demo.java b/code/design_pattern/src/OOP_patterns/observer_java/demo.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/observer_java/Demo.java rename to code/design_pattern/src/OOP_patterns/observer_java/demo.java diff --git a/code/design_pattern/src/OOP_patterns/observer_java/Main.java b/code/design_pattern/src/OOP_patterns/observer_java/main.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/observer_java/Main.java rename to code/design_pattern/src/OOP_patterns/observer_java/main.java diff --git a/code/design_pattern/src/OOP_patterns/observer_java/observer/network/Artist.java b/code/design_pattern/src/OOP_patterns/observer_java/observer/network/artist.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/observer_java/observer/network/Artist.java rename to code/design_pattern/src/OOP_patterns/observer_java/observer/network/artist.java diff --git a/code/design_pattern/src/OOP_patterns/observer_java/observer/network/Fan.java b/code/design_pattern/src/OOP_patterns/observer_java/observer/network/fan.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/observer_java/observer/network/Fan.java rename to code/design_pattern/src/OOP_patterns/observer_java/observer/network/fan.java diff --git a/code/design_pattern/src/OOP_patterns/observer_java/observer/Observer.java b/code/design_pattern/src/OOP_patterns/observer_java/observer/observer.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/observer_java/observer/Observer.java rename to code/design_pattern/src/OOP_patterns/observer_java/observer/observer.java diff --git a/code/design_pattern/src/OOP_patterns/observer_java/observer/Subject.java b/code/design_pattern/src/OOP_patterns/observer_java/observer/subject.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/observer_java/observer/Subject.java rename to code/design_pattern/src/OOP_patterns/observer_java/observer/subject.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/demo/Demo.java b/code/design_pattern/src/OOP_patterns/proxy/demo/demo.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/demo/Demo.java rename to code/design_pattern/src/OOP_patterns/proxy/demo/demo.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/Main.java b/code/design_pattern/src/OOP_patterns/proxy/main.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/Main.java rename to code/design_pattern/src/OOP_patterns/proxy/main.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/RegisteredUsers.java b/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/registeredusers.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/protection/proxy/RegisteredUsers.java rename to code/design_pattern/src/OOP_patterns/proxy/protection/proxy/registeredusers.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/User.java b/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/user.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/protection/proxy/User.java rename to code/design_pattern/src/OOP_patterns/proxy/protection/proxy/user.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/UserProxy.java b/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/userproxy.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/protection/proxy/UserProxy.java rename to code/design_pattern/src/OOP_patterns/proxy/protection/proxy/userproxy.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/ValidUser.java b/code/design_pattern/src/OOP_patterns/proxy/protection/proxy/validuser.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/protection/proxy/ValidUser.java rename to code/design_pattern/src/OOP_patterns/proxy/protection/proxy/validuser.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/Demo.java b/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/demo.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/Demo.java rename to code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/demo.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/UltraHDVideo.java b/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/ultrahdvideo.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/UltraHDVideo.java rename to code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/ultrahdvideo.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/Video.java b/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/video.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/Video.java rename to code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/video.java diff --git a/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/VideoProxy.java b/code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/videoproxy.java similarity index 100% rename from code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/VideoProxy.java rename to code/design_pattern/src/OOP_patterns/proxy/virtual/proxy/videoproxy.java diff --git a/code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.py b/code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.py new file mode 100644 index 0000000000..0ee955e302 --- /dev/null +++ b/code/design_pattern/src/OOP_patterns/singleton_pattern/singleton_pattern.py @@ -0,0 +1,18 @@ +# Part of Cosmos by OpenGenus Foundation + +class Singleton: + __instance = None + + @property + def x(self): + return self.__x + + @x.setter + def x(self, value): + self.__x = value + + @staticmethod + def instance(): + if not Singleton.__instance: + Singleton.__instance = Singleton() + return Singleton.__instance diff --git a/code/design_pattern/src/builder_pattern/Builder.cs b/code/design_pattern/src/builder_pattern/builder.cs similarity index 100% rename from code/design_pattern/src/builder_pattern/Builder.cs rename to code/design_pattern/src/builder_pattern/builder.cs diff --git a/code/design_pattern/src/functional-patterns/README.md b/code/design_pattern/src/functional_patterns/README.md similarity index 100% rename from code/design_pattern/src/functional-patterns/README.md rename to code/design_pattern/src/functional_patterns/README.md diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/build.sbt b/code/design_pattern/src/functional_patterns/functional_patterns/scala/build.sbt new file mode 100644 index 0000000000..e69de29bb2 diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/project/build.properties b/code/design_pattern/src/functional_patterns/functional_patterns/scala/project/build.properties new file mode 100644 index 0000000000..c4dc11b267 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/project/build.properties @@ -0,0 +1 @@ +sbt.version = 1.1.0 diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/arrows/arrow/arrow.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/arrows/arrow/arrow.scala new file mode 100644 index 0000000000..299c3ded11 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/arrows/arrow/arrow.scala @@ -0,0 +1,5 @@ +package arrows.arrow + +trait Arrow { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/applicative/functor/applicativefunctor.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/applicative/functor/applicativefunctor.scala new file mode 100644 index 0000000000..6a952b28fa --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/applicative/functor/applicativefunctor.scala @@ -0,0 +1,26 @@ +package functors.applicative.functor + +import scala.language.higherKinds + +/** + * Applicative is an intermediate between functor and monad. + * + * Its importance are dominated by: + * - ability to apply functions of more parameters + * For example: + * val f = (x: Int)(y: Int) => x + y + * If we apply the above function to a functor Future(10).map(f), + * the result will be a Future(x => 10 + x). And you can't map that any further. + * A way to extract the result is needed, hence applicative functors, where you can do something like: + * val f = (x: Int)(y: Int) => x + y + * val r: Future[Int -> Int] = Future(10).map(f) + * Future(20).apply(r) => should return 30 + * + * - can apply functions wrapped into a functor context + * + * - can combine multiple functors into one single product + */ + +trait ApplicativeFunctor[F[_]] { + def apply[A, B](fa: F[A])(f: F[A => B]): F[A] => F[B] +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/bifunctor/bifunctor.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/bifunctor/bifunctor.scala new file mode 100644 index 0000000000..d6a426d94a --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/bifunctor/bifunctor.scala @@ -0,0 +1,26 @@ +package functors.bifunctor + +import scala.language.higherKinds + +/** + * + * Similar to a functor, the BiFunctor must satisfy the functor laws: + * 1. bimap f id id = id + * first f id = id + * second f id = id + * + * Applying a function over the identity, should return the identity. + * + * 2. bimap f g = first f . second g + * + * Asociativity: applying bimap f g should be equal to applying f to first and g to second. + * + * BiFunctors include: Either, N-Tuples + */ +trait BiFunctor[F[_, _]] { + def biMap[A, B, C, D](fab: F[A, B])(f: A => C)(g: B => D): F[B, D] + + def first[A, C](fab: F[A, _])(f: A => C): F[C, _] + + def second[B, D](fab: F[_, B])(f: B => D): F[_, D] +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/contravariant/contravariant.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/contravariant/contravariant.scala new file mode 100644 index 0000000000..1b1dd97ddb --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/contravariant/contravariant.scala @@ -0,0 +1,5 @@ +package functors.contravariant + +trait Contravariant { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/functor/functor.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/functor/functor.scala new file mode 100644 index 0000000000..ae7c9d5f4f --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/functor/functor.scala @@ -0,0 +1,34 @@ +package functors.functor + +import scala.language.higherKinds + +/** + * ADT which aspires to be a functor must preserve 2 laws: + * 1. fmap over the identity functor of the ADT should coincide with the original ADT + * fmap(identity, adt) === adt + * + * 2. The composition of 2 functions and mapping the resulting function over a functor + * should be the same as mapping the first function over the functor and then the second one. + * fmap(f compose g, adt) === fmap(f, fmap(g, adt)) + * + * Some functors include: List, Set, Map, Option, etc. + */ +trait Functor[A, F[_]] { + // something might be fishy with the id + def id: A + def fmap[B](fA: F[A])(f: A => B): F[B] +} + +object FunctorImplicits { + implicit def listFunctor[A]: Functor[A, List] = new Functor[A, List] { + override def id: A = ??? + + override def fmap[B](fA: List[A])(f: A => B): List[B] = fA.map(f) + } + + implicit def optionFunctor[A]: Functor[A, Option] = new Functor[A, Option] { + override def id: A = ??? + + override def fmap[B](fA: Option[A])(f: A => B): Option[B] = fA.map(f) + } +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/multifunctor/multifunctor.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/multifunctor/multifunctor.scala new file mode 100644 index 0000000000..e91451a4c0 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/multifunctor/multifunctor.scala @@ -0,0 +1,5 @@ +package functors.multifunctor + +trait Multifunctor { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/profunctor/profunctor.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/profunctor/profunctor.scala new file mode 100644 index 0000000000..517b0dc15a --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/functors/profunctor/profunctor.scala @@ -0,0 +1,5 @@ +package functors.profunctor + +trait Profunctor { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/main.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/main.scala new file mode 100644 index 0000000000..970967716c --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/main.scala @@ -0,0 +1,2 @@ +object Main extends App{ +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/comonad/comonad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/comonad/comonad.scala new file mode 100644 index 0000000000..f6b4ad799b --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/comonad/comonad.scala @@ -0,0 +1,5 @@ +package monads.comonad + +trait Comonad { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/costate/monad/costatemonad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/costate/monad/costatemonad.scala new file mode 100644 index 0000000000..88e9c5edb4 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/costate/monad/costatemonad.scala @@ -0,0 +1,5 @@ +package monads.costate.monad + +trait CostateMonad { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/free/monad/freemonad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/free/monad/freemonad.scala new file mode 100644 index 0000000000..55f0512431 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/free/monad/freemonad.scala @@ -0,0 +1,5 @@ +package monads.free.monad + +trait FreeMonad { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/gonad/gonad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/gonad/gonad.scala new file mode 100644 index 0000000000..f98943adfd --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/gonad/gonad.scala @@ -0,0 +1,5 @@ +package monads.gonad + +trait Gonad { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/io/monad/iomonad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/io/monad/iomonad.scala new file mode 100644 index 0000000000..12c6763e6a --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/io/monad/iomonad.scala @@ -0,0 +1,5 @@ +package monads.io.monad + +trait IOMonad { + +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/monad/monad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/monad/monad.scala new file mode 100644 index 0000000000..be34940c60 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/monad/monad.scala @@ -0,0 +1,17 @@ +package monads.monad + +import scala.language.higherKinds + +trait Monad[T, M[_]] { + def flatMap[S](fA: T => M[S])(f: M[T]): M[S] +} + +object MonadImplicits { + implicit def listMonad[T]: Monad[T, List] = new Monad[T, List] { + override def flatMap[S](fA: T => List[S])(f: List[T]): List[S] = f.flatMap(fA) + } + + implicit def optionMonad[T]: Monad[T, Option] = new Monad[T, Option] { + override def flatMap[S](fA: T => Option[S])(f: Option[T]): Option[S] = f.flatMap(fA) + } +} diff --git a/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/state/monad/statemonad.scala b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/state/monad/statemonad.scala new file mode 100644 index 0000000000..860477fcd6 --- /dev/null +++ b/code/design_pattern/src/functional_patterns/functional_patterns/scala/src/main/scala/monads/state/monad/statemonad.scala @@ -0,0 +1,10 @@ +package monads.state.monad + +/** + * The equivalent of Memento design pattern in OOP on steroids, + * state monads deal with maintaining previous states WHILE generating new ones. + */ + +trait StateMonad[S, A] { + def apply(f: S => (S, A)): StateMonad[S, A] +} diff --git a/code/design_pattern/src/iterator_pattern/Class.java b/code/design_pattern/src/iterator_pattern/class.java similarity index 100% rename from code/design_pattern/src/iterator_pattern/Class.java rename to code/design_pattern/src/iterator_pattern/class.java diff --git a/code/design_pattern/src/iterator_pattern/ClassIterator.java b/code/design_pattern/src/iterator_pattern/classiterator.java similarity index 100% rename from code/design_pattern/src/iterator_pattern/ClassIterator.java rename to code/design_pattern/src/iterator_pattern/classiterator.java diff --git a/code/design_pattern/src/iterator_pattern/Iterator.java b/code/design_pattern/src/iterator_pattern/iterator.java similarity index 100% rename from code/design_pattern/src/iterator_pattern/Iterator.java rename to code/design_pattern/src/iterator_pattern/iterator.java diff --git a/code/design_pattern/src/iterator_pattern/Main.java b/code/design_pattern/src/iterator_pattern/main.java similarity index 100% rename from code/design_pattern/src/iterator_pattern/Main.java rename to code/design_pattern/src/iterator_pattern/main.java diff --git a/code/design_pattern/src/iterator_pattern/Student.java b/code/design_pattern/src/iterator_pattern/student.java similarity index 100% rename from code/design_pattern/src/iterator_pattern/Student.java rename to code/design_pattern/src/iterator_pattern/student.java diff --git a/code/design_pattern/src/oop_patterns/README.md b/code/design_pattern/src/oop_patterns/README.md new file mode 100644 index 0000000000..35c3e09ee2 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/README.md @@ -0,0 +1,12 @@ +# cosmos +Your personal library of every design pattern code that you will ever encounter + +Opposed to the OOP design patterns, functional design patterns could be replaced by one single word: functions. +Everything in functional programming is about functions and laws. +Most FP design patterns follow these "patterns": +1. a set of laws that need to be met in order for some functions to be applied over some data +2. a set of functions that need to be implemented according to the user specific data + +Generally, one would desire for these patterns to be designed shapelessly ( using generics ). +In order for that to be succesfully done, the language of choice generally has to support generics and higher-kinded types. +Collaborative effort by [OpenGenus](https://github.com/opengenus) diff --git a/code/design_pattern/src/oop_patterns/adapter/adaptor.java b/code/design_pattern/src/oop_patterns/adapter/adaptor.java new file mode 100644 index 0000000000..21a33152b5 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/adaptor.java @@ -0,0 +1,22 @@ +package Adapter; + +import Adapter.Soldiers.Adaptee; +import Adapter.Soldiers.General; + +public class Adaptor implements Movement { + public Adaptee adaptee; + + public General general; + + public Adaptor(Adaptee adaptee, General general) { + this.adaptee = adaptee; + this.general = general; + } + + + @Override + public void walk() { + adaptee.changeWalkStyle(general.receiveOrder()); + adaptee.walk(); + } +} diff --git a/code/design_pattern/src/oop_patterns/adapter/civilian.java b/code/design_pattern/src/oop_patterns/adapter/civilian.java new file mode 100644 index 0000000000..362739ada1 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/civilian.java @@ -0,0 +1,8 @@ +package Adapter; + +public class Civilian implements Movement { + @Override + public void walk() { + System.out.println("I'm having a beautiful stroll in my happy, little peaceful town."); + } +} diff --git a/code/design_pattern/src/oop_patterns/adapter/movement.java b/code/design_pattern/src/oop_patterns/adapter/movement.java new file mode 100644 index 0000000000..4eeee0e628 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/movement.java @@ -0,0 +1,5 @@ +package Adapter; + +public interface Movement { + void walk(); +} diff --git a/code/design_pattern/src/oop_patterns/adapter/soldiers/adaptee.java b/code/design_pattern/src/oop_patterns/adapter/soldiers/adaptee.java new file mode 100644 index 0000000000..b6e36a926b --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/soldiers/adaptee.java @@ -0,0 +1,7 @@ +package Adapter.Soldiers; + +public interface Adaptee { + void walk(); + + void changeWalkStyle(Order newStyle); +} diff --git a/code/design_pattern/src/oop_patterns/adapter/soldiers/general.java b/code/design_pattern/src/oop_patterns/adapter/soldiers/general.java new file mode 100644 index 0000000000..a147e9f601 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/soldiers/general.java @@ -0,0 +1,22 @@ +package Adapter.Soldiers; + +import Adapter.Movement; + +import java.util.List; + +public class General { + private Order order; + + public List troopsUnderCommand; + + public void setOrder(Order order) { + this.order = order; + } + + public Order receiveOrder() { + if (order == null) + return Order.AT_EASE; + + return order; + } +} diff --git a/code/design_pattern/src/oop_patterns/adapter/soldiers/order.java b/code/design_pattern/src/oop_patterns/adapter/soldiers/order.java new file mode 100644 index 0000000000..4ae459dcf1 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/soldiers/order.java @@ -0,0 +1,5 @@ +package Adapter.Soldiers; + +public enum Order { + WALKING, RUNNING, STROLLING, LIMPING, AT_EASE +} diff --git a/code/design_pattern/src/oop_patterns/adapter/soldiers/soldier.java b/code/design_pattern/src/oop_patterns/adapter/soldiers/soldier.java new file mode 100644 index 0000000000..c00dbac5f7 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/adapter/soldiers/soldier.java @@ -0,0 +1,15 @@ +package Adapter.Soldiers; + +public class Soldier implements Adaptee { + private Order order; + + @Override + public void walk() { + System.out.println("IM " + order + ", SIR, YES, SIR!"); + } + + @Override + public void changeWalkStyle(Order newStyle) { + this.order = newStyle; + } +} diff --git a/code/design_pattern/src/oop_patterns/builder/builder/nationality.java b/code/design_pattern/src/oop_patterns/builder/builder/nationality.java new file mode 100644 index 0000000000..68c4535e3d --- /dev/null +++ b/code/design_pattern/src/oop_patterns/builder/builder/nationality.java @@ -0,0 +1,5 @@ +package builder; + +public enum Nationality { + Ro, En, Gr, Br, Ru, Aus +} diff --git a/code/design_pattern/src/oop_patterns/builder/builder/person.java b/code/design_pattern/src/oop_patterns/builder/builder/person.java new file mode 100644 index 0000000000..b3dcf15904 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/builder/builder/person.java @@ -0,0 +1,49 @@ +package builder; + +import java.util.Date; + +public class Person { + private String firstname; + private String lastname; + + private Date birthdate; + private Nationality nationality; + private boolean isProgrammer; + private Integer iq; + private boolean isPoor; + private boolean isPopular; + private boolean isEmployed; + + Person(String firstname, + String lastname, + Date birthdate, + Nationality nationality, + boolean isProgrammer, + Integer iq, + boolean isPoor, boolean isPopular, boolean isEmployed) { + this.firstname = firstname; + this.lastname = lastname; + this.birthdate = birthdate; + this.nationality = nationality; + this.isProgrammer = isProgrammer; + this.iq = iq; + this.isPoor = isPoor; + this.isPopular = isPopular; + this.isEmployed = isEmployed; + } + + @Override + public String toString() { + return "Person{" + + "firstname='" + this.firstname + '\'' + + ", lastname='" + this.lastname + '\'' + + ", birthdate=" + this.birthdate + + ", nationality=" + this.nationality + + ", isProgrammer=" + this.isProgrammer + + ", iq=" + this.iq + + ", isPoor=" + this.isPoor + + ", isPopular=" + this.isPopular + + ", isEmployed=" + this.isEmployed + + '}'; + } +} diff --git a/code/design_pattern/src/oop_patterns/builder/builder/personbuilder.java b/code/design_pattern/src/oop_patterns/builder/builder/personbuilder.java new file mode 100644 index 0000000000..94d570b6fc --- /dev/null +++ b/code/design_pattern/src/oop_patterns/builder/builder/personbuilder.java @@ -0,0 +1,77 @@ +package builder; + +import org.omg.CORBA.DynAnyPackage.InvalidValue; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.function.Consumer; + +public class PersonBuilder { + private String firstname; + private String lastname; + + private Date birthdate; + private Nationality nationality = Nationality.Ro; + private boolean isProgrammer = false; + private Integer iq = 100; + private boolean isPoor = false; + private boolean isPopular = false; + private boolean isEmployed = true; + + public PersonBuilder with(Consumer builderFunction) { + builderFunction.accept(this); + return this; + } + + public Person createPerson() { + return new Person(firstname, lastname, birthdate, nationality, isProgrammer, iq, isPoor, + isPopular, isEmployed); + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public void setBirthdate(String birthdate) throws InvalidValue, ParseException { + SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); + Date d = sdf.parse("01-01-1950"); + Date date = sdf.parse(birthdate); + if (date.after(d)) + this.birthdate = date; + else throw new InvalidValue("You're too old!!"); + } + + public void setNationality(Nationality nationality) { + this.nationality = nationality; + } + + public void setProgrammer(boolean isProgrammer) { + this.isProgrammer = isProgrammer; + } + + public void setIq(Integer iq) throws InvalidValue { + if (iq < 30) + throw new InvalidValue("Don't try anything crazy."); + + this.iq = iq; + } + + public void setPoor(boolean isPoor) { + this.isPoor = isPoor; + } + + public void setPopular(boolean isPopular) { + this.isPopular = isPopular; + } + + public void setEmployed(boolean isEmployed) { + this.isEmployed = isEmployed; + } + + +} diff --git a/code/design_pattern/src/oop_patterns/builder/main.java b/code/design_pattern/src/oop_patterns/builder/main.java new file mode 100644 index 0000000000..673952a7ba --- /dev/null +++ b/code/design_pattern/src/oop_patterns/builder/main.java @@ -0,0 +1,27 @@ +import builder.Nationality; +import builder.Person; +import builder.PersonBuilder; +import org.omg.CORBA.DynAnyPackage.InvalidValue; + +import java.text.ParseException; + +public class Main { + + public static void main(String[] args) { + Person person = new PersonBuilder() + .with(personBuilder -> { + personBuilder.setFirstname("Mr."); + personBuilder.setLastname("John"); + personBuilder.setNationality(Nationality.En); + personBuilder.setProgrammer(true); + try { + personBuilder.setBirthdate("01-01-1900"); + } catch (InvalidValue | ParseException invalidValue) { + invalidValue.printStackTrace(); + } + }) + .createPerson(); + + System.out.println(person); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/dailyroutinefacade.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/dailyroutinefacade.java new file mode 100644 index 0000000000..1e52d56b25 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/dailyroutinefacade.java @@ -0,0 +1,15 @@ +package daily.tasks; + +import daily.tasks.evening.routine.EveningRoutineFacade; +import daily.tasks.gym.GymFacade; +import daily.tasks.job.JobFacade; +import daily.tasks.morning.routine.MorningRoutineFacade; + +public class DailyRoutineFacade { + public DailyRoutineFacade() { + new MorningRoutineFacade(); + new JobFacade(); + new GymFacade(); + new EveningRoutineFacade(); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/eat.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/eat.java new file mode 100644 index 0000000000..03173dcae5 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/eat.java @@ -0,0 +1,7 @@ +package daily.tasks.evening.routine; + +class Eat { + Eat() { + System.out.println("Dinner - or mostly not"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/eveningroutinefacade.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/eveningroutinefacade.java new file mode 100644 index 0000000000..7e487f6912 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/eveningroutinefacade.java @@ -0,0 +1,11 @@ +package daily.tasks.evening.routine; + +public class EveningRoutineFacade { + public EveningRoutineFacade() { + System.out.println("\n\n\t\tEvening Routine\n\n"); + new Eat(); + new TakeAShower(); + new WriteCode(); + new WatchYoutubeVideos(); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/takeashower.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/takeashower.java new file mode 100644 index 0000000000..b64fbec7cb --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/takeashower.java @@ -0,0 +1,7 @@ +package daily.tasks.evening.routine; + +class TakeAShower { + TakeAShower() { + System.out.println("Im taking a good ol' scrub"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/watchyoutubevideos.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/watchyoutubevideos.java new file mode 100644 index 0000000000..f5774d3f7d --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/watchyoutubevideos.java @@ -0,0 +1,7 @@ +package daily.tasks.evening.routine; + +class WatchYoutubeVideos { + WatchYoutubeVideos() { + System.out.println("Im watching some youtube videos"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/writecode.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/writecode.java new file mode 100644 index 0000000000..b35fe2619b --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/evening/routine/writecode.java @@ -0,0 +1,7 @@ +package daily.tasks.evening.routine; + +class WriteCode { + WriteCode() { + System.out.println("Probably writing some Scala code"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/benchpress.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/benchpress.java new file mode 100644 index 0000000000..71502e1d39 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/benchpress.java @@ -0,0 +1,7 @@ +package daily.tasks.gym; + +class BenchPress { + BenchPress() { + System.out.println("Gotta bench 140 at least"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/deadlift.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/deadlift.java new file mode 100644 index 0000000000..f921177574 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/deadlift.java @@ -0,0 +1,7 @@ +package daily.tasks.gym; + +class Deadlift { + Deadlift() { + System.out.println("Deadlifting 100kg at least"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/gymfacade.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/gymfacade.java new file mode 100644 index 0000000000..f70b145879 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/gymfacade.java @@ -0,0 +1,10 @@ +package daily.tasks.gym; + +public class GymFacade { + public GymFacade() { + System.out.println("\n\n\t\tGym Routine\n\n"); + new Deadlift(); + new BenchPress(); + new Squat(); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/squat.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/squat.java new file mode 100644 index 0000000000..7cc1161e2e --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/gym/squat.java @@ -0,0 +1,7 @@ +package daily.tasks.gym; + +class Squat { + Squat() { + System.out.println("Squatting is awesome"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/develop.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/develop.java new file mode 100644 index 0000000000..4745ee43ce --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/develop.java @@ -0,0 +1,7 @@ +package daily.tasks.job; + +class Develop { + Develop() { + System.out.println("I'm writing some basic code"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/eatatwork.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/eatatwork.java new file mode 100644 index 0000000000..853d10b6c8 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/eatatwork.java @@ -0,0 +1,7 @@ +package daily.tasks.job; + +class EatAtWork { + EatAtWork() { + System.out.println("This shaorma tastes great!"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/jobfacade.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/jobfacade.java new file mode 100644 index 0000000000..68eb353f05 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/jobfacade.java @@ -0,0 +1,15 @@ +package daily.tasks.job; + +public class JobFacade { + public JobFacade() { + System.out.println("\n\n\t\tJob Routine\n\n"); + new Develop(); + new WatchYoutubeVideos(); + new PlayFifa(); + new EatAtWork(); + new Develop(); + new Develop(); + new WatchYoutubeVideos(); + new Leave(); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/leave.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/leave.java new file mode 100644 index 0000000000..9bc603a7b6 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/leave.java @@ -0,0 +1,7 @@ +package daily.tasks.job; + +class Leave { + Leave() { + System.out.println("I'm leaving home"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/playfifa.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/playfifa.java new file mode 100644 index 0000000000..7ad1fdc934 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/playfifa.java @@ -0,0 +1,7 @@ +package daily.tasks.job; + +class PlayFifa { + PlayFifa() { + System.out.println("I'm playing fifa"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/watchyoutubevideos.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/watchyoutubevideos.java new file mode 100644 index 0000000000..f1dce699d3 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/job/watchyoutubevideos.java @@ -0,0 +1,7 @@ +package daily.tasks.job; + +class WatchYoutubeVideos { + WatchYoutubeVideos() { + System.out.println("I'm watching Youtube videos"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/dress.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/dress.java new file mode 100644 index 0000000000..6dbe34f203 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/dress.java @@ -0,0 +1,7 @@ +package daily.tasks.morning.routine; + +class Dress { + Dress() { + System.out.println("Dress"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/eat.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/eat.java new file mode 100644 index 0000000000..606a8cddf7 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/eat.java @@ -0,0 +1,7 @@ +package daily.tasks.morning.routine; + +class Eat { + Eat() { + System.out.println("Im eating"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/leave.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/leave.java new file mode 100644 index 0000000000..2fa47777ee --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/leave.java @@ -0,0 +1,7 @@ +package daily.tasks.morning.routine; + +class Leave { + Leave() { + System.out.println("Im leaving home"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/morningroutinefacade.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/morningroutinefacade.java new file mode 100644 index 0000000000..981e702e1f --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/morningroutinefacade.java @@ -0,0 +1,11 @@ +package daily.tasks.morning.routine; + +public class MorningRoutineFacade { + public MorningRoutineFacade() { + System.out.println("\n\n\t\tMorning Routine\n\n"); + new WakeUp(); + new Eat(); + new Dress(); + new Leave(); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/wakeup.java b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/wakeup.java new file mode 100644 index 0000000000..98e8005184 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/daily/tasks/morning/routine/wakeup.java @@ -0,0 +1,7 @@ +package daily.tasks.morning.routine; + +class WakeUp { + WakeUp() { + System.out.println("Woken up"); + } +} diff --git a/code/design_pattern/src/oop_patterns/facade/facade b/code/design_pattern/src/oop_patterns/facade/facade new file mode 100644 index 0000000000..8c0bf84ab0 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/facade @@ -0,0 +1,6 @@ +The whole purpose of Facade is to "aggregate" multiple classes and functionality into a single place, thus acting like +well... a Facade - beautiful on the outside, but hiding all the complexity of the "inside building". The example +is taken to the extreme to showcase it properly - imagine each class that is managed has a fuckton of logic behind it +that is quite specific and quite hard to understand. + +By using the Facade design pattern, that logic is encapsulated in the Facade and easily used. \ No newline at end of file diff --git a/code/design_pattern/src/oop_patterns/facade/main.java b/code/design_pattern/src/oop_patterns/facade/main.java new file mode 100644 index 0000000000..aaf8f3068f --- /dev/null +++ b/code/design_pattern/src/oop_patterns/facade/main.java @@ -0,0 +1,8 @@ +import daily.tasks.DailyRoutineFacade; + +public class Main { + + public static void main(String[] args) { + new DailyRoutineFacade(); + } +} diff --git a/code/design_pattern/src/oop_patterns/factory/gifts/booze.java b/code/design_pattern/src/oop_patterns/factory/gifts/booze.java new file mode 100644 index 0000000000..e5877ff6c6 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/gifts/booze.java @@ -0,0 +1,8 @@ +package factory.gifts; + +public class Booze implements Gift { + @Override + public String message() { + return "You won booze - get drunk"; + } +} diff --git a/code/design_pattern/src/oop_patterns/factory/gifts/car.java b/code/design_pattern/src/oop_patterns/factory/gifts/car.java new file mode 100644 index 0000000000..cdc1b4ff68 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/gifts/car.java @@ -0,0 +1,8 @@ +package factory.gifts; + +public class Car implements Gift { + @Override + public String message() { + return "Nobody wins a car, it's a prank, bro"; + } +} diff --git a/code/design_pattern/src/oop_patterns/factory/gifts/gift.java b/code/design_pattern/src/oop_patterns/factory/gifts/gift.java new file mode 100644 index 0000000000..7f3c2a1f1d --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/gifts/gift.java @@ -0,0 +1,5 @@ +package factory.gifts; + +public interface Gift { + String message(); +} diff --git a/code/design_pattern/src/oop_patterns/factory/gifts/nothing.java b/code/design_pattern/src/oop_patterns/factory/gifts/nothing.java new file mode 100644 index 0000000000..e9895a4ea8 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/gifts/nothing.java @@ -0,0 +1,8 @@ +package factory.gifts; + +public class Nothing implements Gift { + @Override + public String message() { + return "YOU WON NOTHING!"; + } +} diff --git a/code/design_pattern/src/oop_patterns/factory/gifts/toy.java b/code/design_pattern/src/oop_patterns/factory/gifts/toy.java new file mode 100644 index 0000000000..150bc47fb4 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/gifts/toy.java @@ -0,0 +1,8 @@ +package factory.gifts; + +public class Toy implements Gift { + @Override + public String message() { + return "You won a toy! Be happy"; + } +} diff --git a/code/design_pattern/src/oop_patterns/factory/gifttype.java b/code/design_pattern/src/oop_patterns/factory/gifttype.java new file mode 100644 index 0000000000..76d2370d45 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/gifttype.java @@ -0,0 +1,35 @@ +package factory; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Random; + +public enum GiftType { + Nothing, Car, Toy, Booze, Error; + + public GiftType fromString(String from) { + if (from.equalsIgnoreCase("nothing")) + return Nothing; + + if (from.equalsIgnoreCase("car")) + return Car; + + if (from.equalsIgnoreCase("toy")) + return Toy; + + if (from.equalsIgnoreCase("booze")) + return Booze; + + return Error; + } + + private static final List VALUES = + Collections.unmodifiableList(Arrays.asList(values())); + private static final int SIZE = VALUES.size(); + private static final Random RANDOM = new Random(); + + public static GiftType randomGift() { + return VALUES.get(RANDOM.nextInt(SIZE)); + } +} diff --git a/code/design_pattern/src/oop_patterns/factory/roulette.java b/code/design_pattern/src/oop_patterns/factory/roulette.java new file mode 100644 index 0000000000..4d95928479 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/factory/roulette.java @@ -0,0 +1,36 @@ +package factory; + +import factory.gifts.*; + +import java.util.Scanner; + +public class Roulette { + public void run() throws InterruptedException { + while (true) { + Scanner input = new Scanner(System.in); + + System.out.println("Let's see what the russian roulette will give you"); + + System.out.println(generateGift(GiftType.randomGift()).message()); + + Thread.sleep(3000); + } + } + + public Gift generateGift(GiftType gift) { + switch (gift) { + case Booze: + return new Booze(); + case Car: + return new Car(); + case Nothing: + return new Nothing(); + case Toy: + return new Toy(); + case Error: + throw new InvalidValue("Russian roulette is confused"); + default: + return new Nothing(); + } + } +} diff --git a/code/design_pattern/src/oop_patterns/observer_java/demo.java b/code/design_pattern/src/oop_patterns/observer_java/demo.java new file mode 100644 index 0000000000..c5a289bcd2 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_java/demo.java @@ -0,0 +1,27 @@ +import observer.Observer; +import observer.Subject; +import observer.network.Artist; +import observer.network.Fan; + +public class Demo { + public void startDemo() { + Observer f1 = new Fan("Robert"); + Observer f2 = new Fan("David"); + Observer f3 = new Fan("Gangplank"); + + Subject s1 = new Artist("Erik Mongrain"); + Subject s2 = new Artist("Antoine Dufour"); + + s1.subscribe(f1); + s1.subscribe(f2); + + s2.subscribe(f2); + s2.subscribe(f3); + + s1.addNotification("New album coming out!!"); + s2.addNotification("I'll be having a concert in Romania!"); + + s1.addNotification("Im so happy!"); + s2.addNotification("How does this work?"); + } +} diff --git a/code/design_pattern/src/oop_patterns/observer_java/main.java b/code/design_pattern/src/oop_patterns/observer_java/main.java new file mode 100644 index 0000000000..8e17cb3c72 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_java/main.java @@ -0,0 +1,6 @@ +public class Main { + + public static void main(String[] args) { + new Demo().startDemo(); + } +} diff --git a/code/design_pattern/src/oop_patterns/observer_java/observer/network/artist.java b/code/design_pattern/src/oop_patterns/observer_java/observer/network/artist.java new file mode 100644 index 0000000000..66437d63a2 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_java/observer/network/artist.java @@ -0,0 +1,55 @@ +package observer.network; + +import observer.Observer; +import observer.Subject; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Artist implements Subject { + private Set observers; + + private String name; + + private List updates; + + public Artist(String name) { + this.name = name; + this.observers = new HashSet<>(); + this.updates = new ArrayList<>(); + } + + public Artist(Set observers) { + this.observers = observers; + this.updates = new ArrayList<>(); + } + + @Override + public String getLastNotification() { + return "[ " + this.name + " ] " + this.updates.get(this.updates.size() - 1); + } + + @Override + public void addNotification(String notification) { + System.out.println("[ " + this.name + " ] " + notification); + updates.add(notification); + this.notifyObservers(); + } + + @Override + public void subscribe(Observer o) { + this.observers.add(o); + } + + @Override + public void unsubscribe(Observer o) { + this.observers.remove(o); + } + + @Override + public void notifyObservers() { + observers.forEach(o -> o.receiveNotification(this)); + } +} diff --git a/code/design_pattern/src/oop_patterns/observer_java/observer/network/fan.java b/code/design_pattern/src/oop_patterns/observer_java/observer/network/fan.java new file mode 100644 index 0000000000..13d90923c1 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_java/observer/network/fan.java @@ -0,0 +1,33 @@ +package observer.network; + +import observer.Observer; + +import java.util.*; + +public class Fan implements Observer { + private String name; + private Set followedSubjects; + + public Fan(String name) { + this.followedSubjects = new HashSet<>(); + this.name = name; + } + + public Fan(Set subjectsToFollow) { + this.followedSubjects = subjectsToFollow; + } + + public void addSubject(Artist subject) { + subject.subscribe(this); + this.followedSubjects.add(subject); + } + + public Set getFollowedSubjects() { + return new HashSet<>(followedSubjects); + } + + @Override + public void receiveNotification(observer.Subject from) { + System.out.println("[" + this.name + "] " + from.getLastNotification()); + } +} diff --git a/code/design_pattern/src/oop_patterns/observer_java/observer/observer.java b/code/design_pattern/src/oop_patterns/observer_java/observer/observer.java new file mode 100644 index 0000000000..b74e0aae18 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_java/observer/observer.java @@ -0,0 +1,5 @@ +package observer; + +public interface Observer { + void receiveNotification(Subject from); +} diff --git a/code/design_pattern/src/oop_patterns/observer_java/observer/subject.java b/code/design_pattern/src/oop_patterns/observer_java/observer/subject.java new file mode 100644 index 0000000000..b2c78e0964 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_java/observer/subject.java @@ -0,0 +1,13 @@ +package observer; + +public interface Subject { + void subscribe(Observer o); + + void unsubscribe(Observer o); + + void notifyObservers(); + + String getLastNotification(); + + void addNotification(T notification); +} diff --git a/code/design_pattern/src/oop_patterns/observer_pattern/observer_pattern.cpp b/code/design_pattern/src/oop_patterns/observer_pattern/observer_pattern.cpp new file mode 100644 index 0000000000..cde494e104 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_pattern/observer_pattern.cpp @@ -0,0 +1,118 @@ +/* + * observer_pattern.cpp + * + * Created on: 26 May 2017 + * Author: yogeshb2 + */ + +#include +#include +#include + +using namespace std; + +class IWeatherChanger +{ +public: + virtual ~IWeatherChanger() + { + } + virtual void onTemperatureChange(int temperature) = 0; +}; + +class ITemperature +{ +public: + virtual ~ITemperature() + { + } + virtual void addSubscriber(IWeatherChanger* w) = 0; + virtual void removeSubscriber(IWeatherChanger* w) = 0; + virtual void notifyAllSubscriber() = 0; +}; + +class Weather : public ITemperature +{ +public: + Weather() : temperature(0) + { + + } + void addSubscriber(IWeatherChanger* w) + { + if (w) + subscriberlist.push_back(w); + } + void removeSubscriber(IWeatherChanger* w) + { + //TODO + if (w) + { + vector::iterator it = + find(subscriberlist.begin(), subscriberlist.end(), w); + if (it != subscriberlist.end()) + subscriberlist.erase(it); + else + cout << "Not a registered subscriber" << endl; + } + } + void notifyAllSubscriber() + { + if (!subscriberlist.empty()) + { + vector::iterator it; + for (it = subscriberlist.begin(); it != subscriberlist.end(); ++it) + (*it)->onTemperatureChange(temperature); + } + } + void changeTemperature(int temp) + { + temperature = temp; + notifyAllSubscriber(); + } +private: + int temperature; + vector subscriberlist; + +}; + + +class NewsChannel : public IWeatherChanger +{ +public: + NewsChannel() + { + + } + NewsChannel(string name) + { + this->name = name; + } + void onTemperatureChange(int temperature) + { + cout << "Channel name : " << name << " Temperature : " << temperature; + cout << "\n"; + } +private: + string name; + +}; + +int main() +{ + Weather weather; + NewsChannel fox("Fox News"); + NewsChannel times("Times News"); + weather.addSubscriber(&fox); + weather.addSubscriber(×); + + weather.changeTemperature(25); + + weather.changeTemperature(20); + + weather.removeSubscriber(&fox); + + weather.changeTemperature(10); + + return 0; +} diff --git a/code/design_pattern/src/oop_patterns/observer_pattern/observer_pattern.rs b/code/design_pattern/src/oop_patterns/observer_pattern/observer_pattern.rs new file mode 100644 index 0000000000..01a7a5ae82 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/observer_pattern/observer_pattern.rs @@ -0,0 +1,79 @@ +// Part of Cosmos by OpenGenus Foundation +use std::collections::HashMap; + +#[derive(Debug, Clone, Copy)] +enum WeatherType { + Clear, + Rain, + Snow, +} + +#[derive(Debug, Clone, Copy)] +enum WeatherObserverMessage { + WeatherChanged(WeatherType), +} + +trait WeatherObserver { + fn notify(&mut self, msg: WeatherObserverMessage); +} + +struct WeatherObserverExample { + name: &'static str, +} + +impl WeatherObserver for WeatherObserverExample { + fn notify(&mut self, msg: WeatherObserverMessage) { + println!("{} was notified: {:?}", self.name, msg); + } +} + +struct Weather { + weather: WeatherType, + observers: HashMap>, + observer_id_counter: usize +} + +impl Weather { + pub fn attach_observer(&mut self, observer: Box) -> usize { + self.observers.insert(self.observer_id_counter, observer); + self.observer_id_counter += 1; + self.observer_id_counter - 1 + } + + pub fn detach_observer(&mut self, id: usize) -> Option> { + self.observers.remove(&id) + } + + pub fn set_weather(&mut self, weather_type: WeatherType) { + self.weather = weather_type; + self.notify_observers(WeatherObserverMessage::WeatherChanged(weather_type)); + } + + pub fn notify_observers(&mut self, msg: WeatherObserverMessage) { + for obs in self.observers.values_mut() { + obs.notify(msg); + } + } +} + +fn main() { + let mut weather = Weather { + weather: WeatherType::Clear, + observers: HashMap::new(), + observer_id_counter: 0 + }; + + let first_obs = weather.attach_observer(Box::new(WeatherObserverExample { + name: "First Observer", + })); + + weather.set_weather(WeatherType::Rain); + + weather.detach_observer(first_obs); + + weather.attach_observer(Box::new(WeatherObserverExample { + name: "Second Observer", + })); + + weather.set_weather(WeatherType::Snow); +} diff --git a/code/design_pattern/src/oop_patterns/proxy/demo/demo.java b/code/design_pattern/src/oop_patterns/proxy/demo/demo.java new file mode 100644 index 0000000000..772b9e27c3 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/demo/demo.java @@ -0,0 +1,57 @@ +package demo; + +import protection.proxy.User; +import protection.proxy.UserProxy; +import virtual.proxy.UltraHDVideo; +import virtual.proxy.Video; +import virtual.proxy.VideoProxy; + +public class Demo { + public void protectionProxyRun() { + User rob = new UserProxy("Robert", "123"); + User david = new UserProxy("David", "pass"); + User gangplank = new UserProxy("Gangplank", "12312312"); + + rob.login(); + david.login(); + gangplank.login(); + + rob.download(); + david.download(); + gangplank.login(); + + rob.upload(); + david.upload(); + gangplank.upload(); + } + + public void virtualProxyRun() throws InterruptedException { + System.out.println("Trying the proxy version first - 3 videos and playing just 1"); + long startTime = System.currentTimeMillis(); + + Video v1 = new VideoProxy("Erik Mongrain - Alone in the mist"); + Video v2 = new VideoProxy("Antoine Dufour - Drowning"); + Video v3 = new VideoProxy("Jake McGuire - For Scale The Summit"); + + v3.play(); + long endTime = System.currentTimeMillis(); + + long duration = (endTime - startTime); + + System.out.println("It took " + (duration / 1000) + " seconds to run"); + System.out.println("Now for the not-proxy version"); + startTime = System.currentTimeMillis(); + + Video v4 = new UltraHDVideo("Erik Mongrain - Alone in the mist"); + Video v5 = new UltraHDVideo("Antoine Dufour - Drowning"); + Video v6 = new UltraHDVideo("Jake McGuire - For Scale The Summit"); + + v6.play(); + + endTime = System.currentTimeMillis(); + + duration = endTime - startTime; + + System.out.println("It took " + (duration / 1000.0) + " seconds to run"); + } +} diff --git a/code/design_pattern/src/oop_patterns/proxy/main.java b/code/design_pattern/src/oop_patterns/proxy/main.java new file mode 100644 index 0000000000..5dbe0c7776 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/main.java @@ -0,0 +1,8 @@ +import demo.Demo; + +public class Main { + + public static void main(String[] args) throws InterruptedException { + new Demo().protectionProxyRun(); + } +} diff --git a/code/design_pattern/src/oop_patterns/proxy/protection/proxy/registeredusers.java b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/registeredusers.java new file mode 100644 index 0000000000..021d22328e --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/registeredusers.java @@ -0,0 +1,14 @@ +package protection.proxy; + +import java.util.HashMap; +import java.util.Map; + +public class RegisteredUsers { + static Map registered = new HashMap(){ + { + put("Robert", "123"); + put("David", "pass"); + put("Gangplank", "Illaoi"); + } + }; +} diff --git a/code/design_pattern/src/oop_patterns/proxy/protection/proxy/user.java b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/user.java new file mode 100644 index 0000000000..3c8875967b --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/user.java @@ -0,0 +1,7 @@ +package protection.proxy; + +public interface User { + void login(); + void download(); + void upload(); +} diff --git a/code/design_pattern/src/oop_patterns/proxy/protection/proxy/userproxy.java b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/userproxy.java new file mode 100644 index 0000000000..f03a5652e6 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/userproxy.java @@ -0,0 +1,43 @@ +package protection.proxy; + +import java.util.Objects; + +public class UserProxy implements User { + private String username; + private String password; + Boolean isLogged; + private User user; + + public UserProxy(String username, String password) { + this.username = username; + this.password = password; + } + + + @Override + public void login() { + if (Objects.equals(RegisteredUsers.registered.get(username), password)){ + this.user = new ValidUser(username, password); + System.out.println("Login successful - welcome back, " + this.username + " !"); + } + else + System.out.println("Invalid credentials for " + this.username + " !"); + + } + + @Override + public void download() { + if (this.user == null) + System.out.println("User credentials invalid " + this.username + "!"); + else + user.download(); + } + + @Override + public void upload() { + if (this.user == null) + System.out.println("User credentials invalid " + this.username + " !"); + else + user.upload(); + } +} diff --git a/code/design_pattern/src/oop_patterns/proxy/protection/proxy/validuser.java b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/validuser.java new file mode 100644 index 0000000000..776e21993e --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/protection/proxy/validuser.java @@ -0,0 +1,26 @@ +package protection.proxy; + +class ValidUser implements User { + String username; + String password; + + ValidUser(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public void login() { + System.out.println(">" + this.username + ": Successfully logged, welcome!"); + } + + @Override + public void download() { + System.out.println(">" + this.username + ": Downloading"); + } + + @Override + public void upload() { + System.out.println(">" + this.username + ": Uploading"); + } +} diff --git a/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/demo.java b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/demo.java new file mode 100644 index 0000000000..4703c7864e --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/demo.java @@ -0,0 +1,5 @@ +package virtual.proxy; + +public class Demo { + +} diff --git a/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/ultrahdvideo.java b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/ultrahdvideo.java new file mode 100644 index 0000000000..a29d76bbd0 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/ultrahdvideo.java @@ -0,0 +1,20 @@ +package virtual.proxy; + +public class UltraHDVideo implements Video { + public String name; + + public UltraHDVideo(String path) throws InterruptedException { + this.name = path; + loadVideo(); + } + + @Override + public void play() { + System.out.println("4k video is being played - " + name); + } + + private void loadVideo() throws InterruptedException { + Thread.sleep(5000); + System.out.println("Video has been loaded - " + name); + } +} diff --git a/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/video.java b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/video.java new file mode 100644 index 0000000000..79b4d9fd3d --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/video.java @@ -0,0 +1,5 @@ +package virtual.proxy; + +public interface Video { + void play(); +} diff --git a/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/videoproxy.java b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/videoproxy.java new file mode 100644 index 0000000000..440c24bb99 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/proxy/virtual/proxy/videoproxy.java @@ -0,0 +1,22 @@ +package virtual.proxy; + +public class VideoProxy implements Video { + + public String name; + public Video realVideo; + + public VideoProxy(String name) { + this.name = name; + } + + @Override + public void play() { + try { + this.realVideo = new UltraHDVideo(name); + } catch (InterruptedException e) { + e.printStackTrace(); + } + + realVideo.play(); + } +} diff --git a/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.cpp b/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.cpp new file mode 100644 index 0000000000..8038d3c84c --- /dev/null +++ b/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.cpp @@ -0,0 +1,78 @@ +#include +#include + +template +class Singleton +{ +public: + static T* GetInstance(); + static void destroy(); + +private: + + Singleton(Singleton const&) + { + }; + Singleton& operator=(Singleton const&) + { + }; + +protected: + static T* m_instance; + + Singleton() + { + m_instance = static_cast (this); + }; + ~Singleton() + { + }; +}; + +template +T * Singleton::m_instance = 0; + +template +T* Singleton::GetInstance() +{ + if (!m_instance) + Singleton::m_instance = new T(); + + return m_instance; +} + +template +void Singleton::destroy() +{ + delete Singleton::m_instance; + Singleton::m_instance = 0; +} + +class TheCow : public Singleton +{ +public: + void SetSays(std::string &whatToSay) + { + whatISay = whatToSay; + }; + void Speak(void) + { + std::cout << "I say" << whatISay << "!" << std::endl; + }; +private: + std::string whatISay; +}; + +void SomeFunction(void) +{ + std::string say("moo"); + TheCow::GetInstance()->SetSays(say); +} + +int main () +{ + std::string say("meow"); + TheCow::GetInstance()->SetSays(say); + SomeFunction(); + TheCow::GetInstance()->Speak(); +} diff --git a/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.java b/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.java new file mode 100644 index 0000000000..f673e91118 --- /dev/null +++ b/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.java @@ -0,0 +1,32 @@ + +/** + * Singleton Design Pattern + * + * @author Sagar Rathod + * @version 1.0 + * + */ + +class Singleton { + + private volatile transient static Singleton singletonInstance; + + private Singleton() {} + + public static synchronized Singleton getInstance() { + + if ( singletonInstance == null ) { + singletonInstance = new Singleton(); + } + return singletonInstance; + } +} + +public class SingletonPattern { + + public static void main(String[] args) { + + Singleton instance = Singleton.getInstance(); + System.out.println(instance == Singleton.getInstance()); + } +} diff --git a/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.php b/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.php new file mode 100644 index 0000000000..f085a0fe4b --- /dev/null +++ b/code/design_pattern/src/oop_patterns/singleton_pattern/singleton_pattern.php @@ -0,0 +1,24 @@ + +#include +#include +#include + + +/* Prototypes */ +int getBiggerSize(const std::string &number1, const std::string &number2); +void checkNumbers(int size, std::string &number1, std::string &number2); +std::string KaratsubaMultiply(std::string &number1, std::string &number2, int limit); +std::string AddNumbers(std::string &number1, std::string &number2); +void removeNonSignificantZeros(std::string &c); +void splitString(std::string original, std::string &sub1, std::string &sub2); + +int main() +{ + std::string number1, number2; + + std::cout << "Insert the first number \n"; + std::cin >> number1; + std::cout << "Insert the second number \n"; + std::cin >> number2; + + int size = getBiggerSize(number1, number2); + checkNumbers(size, number1, number2); + + std::string result = KaratsubaMultiply(number1, number2, number1.length()); + //Returns number to original without non-significant zeros + removeNonSignificantZeros(number1); + removeNonSignificantZeros(number2); + std::cout << "Result " << number1 << " * " << number2 << " = " << result << "\n"; +} + +int getBiggerSize(const std::string &number1, const std::string &number2) +{ + int numb1Length = number1.length(); + int numb2Length = number2.length(); + return (numb1Length > numb2Length) ? numb1Length : numb2Length; +} + +void checkNumbers(int size, std::string &number1, std::string &number2) +{ + int newSize = 0, nZeros = 0; + newSize = getBiggerSize(number1, number2); + + nZeros = newSize - number1.length(); + number1.insert(number1.begin(), nZeros, '0'); + nZeros = newSize - number2.length(); + number2.insert(number2.begin(), nZeros, '0'); + + if (number1.length() % 2 != 0) + number1.insert(number1.begin(), 1, '0'); + if (number2.length() % 2 != 0) + number2.insert(number2.begin(), 1, '0'); +} + +std::string KaratsubaMultiply(std::string &number1, std::string &number2, int limit) +{ + int n = number1.length(), s; + std::string w, x, y, z; + std::string final1, final2, final3; + std::string total; + + if (n == 1) + { + int integer1, integer2, aux; + integer1 = atoi (number1.c_str()); + integer2 = atoi (number2.c_str()); + aux = integer1 * integer2; + //We can replace two next lines with -> total = to_string(aux) using c++11 + std::ostringstream temp; + temp << aux; + total = temp.str(); + removeNonSignificantZeros (total); + return total; + } + else + { + s = n / 2; + splitString (number1, w, x); + splitString (number2, y, z); + + final1 = KaratsubaMultiply (w, y, n); + final1.append(2 * s, '0'); + + std::string wz = KaratsubaMultiply (w, z, n); + std::string xy = KaratsubaMultiply (x, y, n); + final2 = AddNumbers (wz, xy); + final2.append(s, '0'); + + final3 = KaratsubaMultiply (x, z, n); + total = AddNumbers (final1, final2); + return AddNumbers (total, final3); + } +} + +void removeNonSignificantZeros(std::string &c) +{ + int acum = 0; + for (int i = 0; i < c.length(); ++i) + { + if (c[i] != '0') + break; + else + acum++; + } + if (c.length() != acum) + c = c.substr(acum, c.length()); + else + c = c.substr(acum - 1, c.length()); +} + +void splitString(std::string original, std::string &sub1, std::string &sub2) +{ + int n, n1, n2; + sub1 = sub2 = ""; + n = original.length(); + + if (n % 2 == 0) + { + n1 = n / 2; + n2 = n1; + } + else + { + n1 = (n + 1) / 2; + n2 = n1 - 1; + } + + sub1 = original.substr(0, n1); + sub2 = original.substr(n1, n); + + if (sub1.length() % 2 != 0 && sub2.length() > 2) + sub1.insert(sub1.begin(), 1, '0'); + if (sub2.length() > 2 && sub2.length() % 2 != 0) + sub2.insert(sub2.begin(), 1, '0'); +} + +std::string AddNumbers(std::string &number1, std::string &number2) +{ + int x, y, aux = 0, aux2 = 0; + int digitos = getBiggerSize(number1, number2); + std::string total, total2, cadena; + int n1 = number1.length(); + int n2 = number2.length(); + + if (n1 > n2) + number2.insert(number2.begin(), n1 - n2, '0'); + else + number1.insert(number1.begin(), n2 - n1, '0'); + + for (int i = digitos - 1; i >= 0; i--) + { + x = number1[i] - '0'; + y = number2[i] - '0'; + aux = x + y + aux2; + + if (aux >= 10) + { + aux2 = 1; + aux = aux % 10; + } + else + aux2 = 0; + + total2 = '0' + aux; + total.insert(0, total2); + if (i == 0 && aux2 == 1) + { + total2 = "1"; + total.insert(0, total2); + removeNonSignificantZeros(total); + return total; + } + } + removeNonSignificantZeros(total); + return total; +} diff --git a/code/divide_conquer/src/quick_sort/QuickSort.java b/code/divide_conquer/src/quick_sort/quicksort.java similarity index 100% rename from code/divide_conquer/src/quick_sort/QuickSort.java rename to code/divide_conquer/src/quick_sort/quicksort.java diff --git a/code/divide_conquer/src/Strassen_matrix_multiplication/main.cpp b/code/divide_conquer/src/strassen_matrix_multiplication/main.cpp similarity index 69% rename from code/divide_conquer/src/Strassen_matrix_multiplication/main.cpp rename to code/divide_conquer/src/strassen_matrix_multiplication/main.cpp index 09f1cc21f8..f35de50460 100644 --- a/code/divide_conquer/src/Strassen_matrix_multiplication/main.cpp +++ b/code/divide_conquer/src/strassen_matrix_multiplication/main.cpp @@ -12,20 +12,21 @@ #include #include -std::vector> generator(int m, int n) { +std::vector> generator(int m, int n) +{ std::mt19937 rng; rng.seed(std::random_device()()); - std::uniform_int_distribution dist6(0,1); + std::uniform_int_distribution dist6(0, 1); std::vector> ans; - for (int i = 0;i < m;i++) { + for (int i = 0; i < m; i++) + { std::vector row; - for (int j = 0; j < n; j++) { - if ((i + j) % 5 != 5) { + for (int j = 0; j < n; j++) + { + if ((i + j) % 5 != 5) row.push_back(dist6(rng)); - } - else { + else row.push_back(0); - } } ans.push_back(row); } @@ -33,55 +34,54 @@ std::vector> generator(int m, int n) { } -int f(const std::vector>& a) { +int f(const std::vector>& a) +{ return a[0][0]; } -std::vector> retriever(const std::vector>& matrix, int x, int y) { +std::vector> retriever(const std::vector>& matrix, int x, int y) +{ std::vector> ans; - for (int i = 0; i < x; i++) { + for (int i = 0; i < x; i++) + { std::vector row; - for (int j = 0; j < y; j++) { + for (int j = 0; j < y; j++) row.push_back(matrix[i][j]); - } ans.push_back(row); } return ans; } -std::vector> converter(const std::vector>& matrix) { +std::vector> converter(const std::vector>& matrix) +{ auto noOfRows = matrix.size(); auto noOfCols = matrix[0].size(); std::vector>::size_type t = 1; std::vector>::size_type p; - if(x > y) { + if (x > y) p = noOfRows; - } - else { + else p = noOfCols; - } - while (t < p) { + while (t < p) t *= 2; - } p = t; int flag = 0; std::vector> ans; - for (vector>::size_type i = 0; i < p; i++) { - if (i >= noOfRows) { + for (vector>::size_type i = 0; i < p; i++) + { + if (i >= noOfRows) flag = 1; - } std::vector row; - for (std::vector::size_type j = 0; j < p; j++) { - if (flag == 1) { + for (std::vector::size_type j = 0; j < p; j++) + { + if (flag == 1) row.push_back(0); - } - else{ - if (j >= noOfCols) { + else + { + if (j >= noOfCols) row.push_back(0); - } - else{ + else row.push_back(matrix[i][j]); - } } } ans.push_back(row); @@ -89,20 +89,25 @@ std::vector> converter(const std::vector>& mat return ans; } -void print(const std::vector>& grid) { - for (std::vector>::size_type i = 0; i < grid.size(); i++) { - for (std::vector::size_type j = 0; j < grid[i].size(); j++) { +void print(const std::vector>& grid) +{ + for (std::vector>::size_type i = 0; i < grid.size(); i++) + { + for (std::vector::size_type j = 0; j < grid[i].size(); j++) std::cout << grid[i][j] << ' '; - } std::cout << std::endl; } } -std::vector> add(const std::vector>& a, const std::vector>& b) { +std::vector> add(const std::vector>& a, + const std::vector>& b) +{ std::vector> ans; - for (std::vector>::size_type i = 0; i < a.size(); i++) { + for (std::vector>::size_type i = 0; i < a.size(); i++) + { vector row; - for (std::vector::size_type j = 0; j < a[i].size(); j++) { + for (std::vector::size_type j = 0; j < a[i].size(); j++) + { int temp = a[i][j] + b[i][j]; row.push_back(temp); } @@ -111,11 +116,15 @@ std::vector> add(const std::vector>& a, const return ans; } -std::vector> subtract(const std::vector>& a, const std::vector>& b) { +std::vector> subtract(const std::vector>& a, + const std::vector>& b) +{ std::vector> ans; - for (std::vector>::size_type i = 0; i < a.size(); i++) { + for (std::vector>::size_type i = 0; i < a.size(); i++) + { vector row; - for (std::vector::size_type j = 0; j < a[i].size(); j++) { + for (std::vector::size_type j = 0; j < a[i].size(); j++) + { int temp = a[i][j] - b[i][j]; row.push_back(temp); } @@ -126,16 +135,19 @@ std::vector> subtract(const std::vector>& a, c -std::vector> naive_multi(const std::vector>& a, const std::vector>& b) { +std::vector> naive_multi(const std::vector>& a, + const std::vector>& b) +{ int s = 0; std::vector> ans; - for (std::vector>::size_type i = 0; i < a.size(); i++) { + for (std::vector>::size_type i = 0; i < a.size(); i++) + { vector row; - for (std::vector::size_type j = 0; j < b[i].size(); j++) { + for (std::vector::size_type j = 0; j < b[i].size(); j++) + { s = 0; - for (std::vector::size_type k = 0; k < a[i].size(); k++) { + for (std::vector::size_type k = 0; k < a[i].size(); k++) s += a[i][k] * b[k][j]; - } row.push_back(s); } ans.push_back(row); @@ -144,65 +156,68 @@ std::vector> naive_multi(const std::vector>& a } -std::vector> strassen(const std::vector>& m1, const std::vector>& m2) { +std::vector> strassen(const std::vector>& m1, + const std::vector>& m2) +{ std::vector>::size_type s1 = m1.size(); std::vector>::size_type s2 = m2.size(); - if (s1 > 2 && s2 > 2) { - std::vector> a,b,c,d,e,f,g,h,ans; - for (std::vector>::size_type i = 0; i < m1.size() / 2; i++) { + if (s1 > 2 && s2 > 2) + { + std::vector> a, b, c, d, e, f, g, h, ans; + for (std::vector>::size_type i = 0; i < m1.size() / 2; i++) + { vector row; - for (std::vector::size_type j = 0; j < m1[i].size() / 2; j++) { + for (std::vector::size_type j = 0; j < m1[i].size() / 2; j++) row.push_back(m1[i][j]); - } a.push_back(row); } - for (std::vector>::size_type i = 0; i < m1.size() / 2; i++) { + for (std::vector>::size_type i = 0; i < m1.size() / 2; i++) + { vector row; - for (std::vector::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) { + for (std::vector::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) row.push_back(m1[i][j]); - } b.push_back(row); } - for (std::vector>::size_type i = m1.size() / 2; i < m1.size(); i++) { + for (std::vector>::size_type i = m1.size() / 2; i < m1.size(); i++) + { vector row; - for (std::vector::size_type j = 0; j < m1[i].size() / 2; j++) { + for (std::vector::size_type j = 0; j < m1[i].size() / 2; j++) row.push_back(m1[i][j]); - } c.push_back(row); } - for (std::vector>::size_type i = m1.size() / 2; i < m1.size(); i++) { + for (std::vector>::size_type i = m1.size() / 2; i < m1.size(); i++) + { vector row; - for (std::vector::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) { + for (std::vector::size_type j = m1[i].size() / 2; j < m1[i].size(); j++) row.push_back(m1[i][j]); - } d.push_back(row); } - for (std::vector>::size_type i = 0; i < m2.size() / 2; i++) { + for (std::vector>::size_type i = 0; i < m2.size() / 2; i++) + { vector row; - for (std::vector::size_type j = 0; j < m2[i].size() / 2; j++) { + for (std::vector::size_type j = 0; j < m2[i].size() / 2; j++) row.push_back(m2[i][j]); - } e.push_back(row); } - for (std::vector>::size_type i = 0; i < m2.size() / 2; i++) { + for (std::vector>::size_type i = 0; i < m2.size() / 2; i++) + { vector row; - for (std::vector::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) { + for (std::vector::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) row.push_back(m2[i][j]); - } f.push_back(row); } - for (std::vector>::size_type i = m2.size() / 2; i < m2.size(); i++) { + for (std::vector>::size_type i = m2.size() / 2; i < m2.size(); i++) + { vector row; - for (std::vector::size_type j = 0; j < m2[i].size() / 2; j++) { + for (std::vector::size_type j = 0; j < m2[i].size() / 2; j++) row.push_back(m2[i][j]); - } g.push_back(row); } - for (std::vector>::size_type i = m2.size() / 2; i < m2.size(); i++) { + for (std::vector>::size_type i = m2.size() / 2; i < m2.size(); i++) + { vector row; - for (std::vector::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) { + for (std::vector::size_type j = m2[i].size() / 2; j < m2[i].size(); j++) row.push_back(m2[i][j]); - } h.push_back(row); } @@ -224,121 +239,127 @@ std::vector> strassen(const std::vector>& m1, int flag1, flag2; - for (std::vector>::size_type i = 0; i < m1.size(); i++) { + for (std::vector>::size_type i = 0; i < m1.size(); i++) + { std::vector row; - if (i < m1.size() / 2) { + if (i < m1.size() / 2) flag1 = 0; - } - else { + else flag1 = 1; - } - for (std::vector::size_type j = 0; j < m2[i].size(); j++) { - if ( j < m2[i].size()/2) { - if ( flag1 == 0) { + for (std::vector::size_type j = 0; j < m2[i].size(); j++) + { + if (j < m2[i].size() / 2) + { + if (flag1 == 0) row.push_back(c1[i][j]); - } - else { - row.push_back(c3[i-m1.size()/2][j]); - } + else + row.push_back(c3[i - m1.size() / 2][j]); } - else { - if ( flag1 == 0) { - row.push_back(c2[i][j-m2[i].size()/2]); - } - else { - row.push_back(c4[i-m1.size()/2][j-m2[i].size()/2]); - } + else + { + if (flag1 == 0) + row.push_back(c2[i][j - m2[i].size() / 2]); + else + row.push_back(c4[i - m1.size() / 2][j - m2[i].size() / 2]); } } ans.push_back(row); } return ans; } - else{ + else + { std::vector> v; v = naive_multi(m1, m2); return v; } } -std::vector> fast_multi(const std::vector>& m1, const std::vector>& m2){ +std::vector> fast_multi(const std::vector>& m1, + const std::vector>& m2) +{ std::vector ranges, ranges_c, ind; std::vector> ans; - for(std::vector>::size_type i = 0; i < m1.size(); i++){ + for (std::vector>::size_type i = 0; i < m1.size(); i++) + { int a = 0; int b = 0; - for(std::vector>::size_type j = 0; j < m1[i].size(); j++){ - if (m1[j][i] != 0) { + for (std::vector>::size_type j = 0; j < m1[i].size(); j++) + { + if (m1[j][i] != 0) a += 1; - } - if (m2[i][j] != 0) { - b+= 1; - } + if (m2[i][j] != 0) + b += 1; } - ranges.push_back(a*b); - ranges_c.push_back(a*b); + ranges.push_back(a * b); + ranges_c.push_back(a * b); } sort(ranges.begin(), ranges.end()); int comp, index; - for (std::vector>::size_type i = 0; i < m1.size(); i++) { + for (std::vector>::size_type i = 0; i < m1.size(); i++) + { int s = 0; - for (std::vector>::size_type j = 0; j <= i; j++) { + for (std::vector>::size_type j = 0; j <= i; j++) s += ranges[j]; - } - s += (m1.size()-i-1)*m1.size()*m1.size(); - if (i == 0) { + s += (m1.size() - i - 1) * m1.size() * m1.size(); + if (i == 0) + { comp = s; index = 1; } - else { - if (s < comp) { - comp = s; - index = i+1; - } + else if (s < comp) + { + comp = s; + index = i + 1; } } - for ( int g = 0; g < index; g++) { - for (std::vector>::size_type i = 0; i < m1.size(); i++) { - if (ranges_c[i] == ranges[g]) { + for (int g = 0; g < index; g++) + { + for (std::vector>::size_type i = 0; i < m1.size(); i++) + if (ranges_c[i] == ranges[g]) + { ind.push_back(i); break; } - } } - for (std::vector>::size_type i = 0; i < m1.size(); i++ ) { + for (std::vector>::size_type i = 0; i < m1.size(); i++) + { int flag; int flag_search = 0; - for (std::vector::size_type j = 0; j < ind.size(); j++ ) { - if (i == ind[j]) { + for (std::vector::size_type j = 0; j < ind.size(); j++) + if (i == ind[j]) + { flag_search = 1; break; } - } std::vector> row, col; - for (std::vector::size_type j = 0; j < ind.size(); j++) { + for (std::vector::size_type j = 0; j < ind.size(); j++) + { std::vector temp1, temp2; temp1.push_back(m1[j][i]); temp2.push_back(m2[i][j]); col.push_back(temp1); row.push_back(temp2); } - if (i == 0) { - if (flag_search == 1) { + if (i == 0) + { + if (flag_search == 1) ans = naive_multi(col, row); - } - else { + else + { std::vector> row_c, col_c; row_c = converter(row); col_c = converter(col); ans = retriever(strassen(col_c, row_c), m1.size(), m1.size()); } } - else { + else + { std::vector> v1, v2; - if (flag_search == 1) { + if (flag_search == 1) v1 = naive_multi(col, row); - } - else { + else + { std::vector> row_c, col_c; row_c = converter(row); col_c = converter(col); @@ -351,7 +372,8 @@ std::vector> fast_multi(const std::vector>& m1 } -int main() { +int main() +{ std::vector> matrix1, matrix2, v1, v2, v3; int i1, j1; int i2, j2; @@ -361,22 +383,26 @@ int main() { std::cout << "enter the dimensions of matrix2\n"; std::cin >> i2 >> j2; std::cout << '\n'; - int x,y; - for (x = 0; x< i1; x++) { + int x, y; + for (x = 0; x < i1; x++) + { std::vector row; - for (y = 0; y < j1; y++) { + for (y = 0; y < j1; y++) + { int temp; - std::cout << "enter the " << x+1 << " , " << y+1 << " element for matrix1 - "; + std::cout << "enter the " << x + 1 << " , " << y + 1 << " element for matrix1 - "; std::cin >> temp; row.push_back(temp); } matrix1.push_back(row); } - for (x = 0; x< i2; x++) { + for (x = 0; x < i2; x++) + { std::vector row; - for (y = 0; y < j2; y++) { + for (y = 0; y < j2; y++) + { int temp; - std::cout << "enter the " << x+1 << " , " << y+1 << " element for matrix2 - "; + std::cout << "enter the " << x + 1 << " , " << y + 1 << " element for matrix2 - "; std::cin >> temp; row.push_back(temp); } @@ -392,12 +418,12 @@ int main() { //print(m2); //cout <<"a\n"; /* - m3 = generator(1024, 1024); - m4 = generator(1024, 1024); - */ + * m3 = generator(1024, 1024); + * m4 = generator(1024, 1024); + */ auto start = std::chrono::high_resolution_clock::now(); - v1 = retriever(naive_multi(m1, m2), i1 , j2); + v1 = retriever(naive_multi(m1, m2), i1, j2); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast(start - stop); @@ -414,14 +440,14 @@ int main() { std::cout << "tiime taken by function" << duration2.count() << endl; /* - auto start_3 = std::chrono::high_resolution_clock::now(); - v3 = retriever(fast_multi(m1, m2), i_1, j_2); - auto stop_3 = std::chrono::high_resolution_clock::now(); - auto duration_3 = std::chrono::duration_cast(start_3 - stop_3); - - - cout << "tiime taken by function" << duration_3.count() << endl; - */ + * auto start_3 = std::chrono::high_resolution_clock::now(); + * v3 = retriever(fast_multi(m1, m2), i_1, j_2); + * auto stop_3 = std::chrono::high_resolution_clock::now(); + * auto duration_3 = std::chrono::duration_cast(start_3 - stop_3); + * + * + * cout << "tiime taken by function" << duration_3.count() << endl; + */ //print(v2); print(v1); diff --git a/code/divide_conquer/src/Strassen_matrix_multiplication/Strassen.py b/code/divide_conquer/src/strassen_matrix_multiplication/strassen.py similarity index 100% rename from code/divide_conquer/src/Strassen_matrix_multiplication/Strassen.py rename to code/divide_conquer/src/strassen_matrix_multiplication/strassen.py diff --git a/code/dynamic_programming/src/Array_Median/median.c b/code/dynamic_programming/src/array_median/median.c similarity index 100% rename from code/dynamic_programming/src/Array_Median/median.c rename to code/dynamic_programming/src/array_median/median.c diff --git a/code/dynamic_programming/src/Array_Median/median.cpp b/code/dynamic_programming/src/array_median/median.cpp similarity index 100% rename from code/dynamic_programming/src/Array_Median/median.cpp rename to code/dynamic_programming/src/array_median/median.cpp diff --git a/code/dynamic_programming/src/Array_Median/Median.java b/code/dynamic_programming/src/array_median/median.java similarity index 100% rename from code/dynamic_programming/src/Array_Median/Median.java rename to code/dynamic_programming/src/array_median/median.java diff --git a/code/dynamic_programming/src/Array_Median/median.php b/code/dynamic_programming/src/array_median/median.php similarity index 100% rename from code/dynamic_programming/src/Array_Median/median.php rename to code/dynamic_programming/src/array_median/median.php diff --git a/code/dynamic_programming/src/Array_Median/median.py b/code/dynamic_programming/src/array_median/median.py similarity index 100% rename from code/dynamic_programming/src/Array_Median/median.py rename to code/dynamic_programming/src/array_median/median.py diff --git a/code/dynamic_programming/src/Array_Median/median.rb b/code/dynamic_programming/src/array_median/median.rb similarity index 100% rename from code/dynamic_programming/src/Array_Median/median.rb rename to code/dynamic_programming/src/array_median/median.rb diff --git a/code/dynamic_programming/src/Array_Median/median.rs b/code/dynamic_programming/src/array_median/median.rs similarity index 100% rename from code/dynamic_programming/src/Array_Median/median.rs rename to code/dynamic_programming/src/array_median/median.rs diff --git a/code/dynamic_programming/src/digit_dp/digit_dp.cpp b/code/dynamic_programming/src/digit_dp/digit_dp.cpp index c1dcc6e94d..8dd8a21f31 100644 --- a/code/dynamic_programming/src/digit_dp/digit_dp.cpp +++ b/code/dynamic_programming/src/digit_dp/digit_dp.cpp @@ -34,27 +34,23 @@ long digit_dp(string num, long pos, long count, long f) return 0; } - if(dp[pos][count][f] != -1) + if (dp[pos][count][f] != -1) return dp[pos][count][f]; long result = 0; long limit; if (f == 0) - { /* Digits we placed so far matches with the prefix of b * So if we place any digit > num[pos] in the current position, then * the number will become greater than b - */ + */ limit = num[pos] - '0'; - } else - { /* The number has already become smaller than b. * We can place any digit now. */ limit = 9; - } // Try to place all the valid digits such that the number doesn't exceed b for (long dgt = 0; dgt <= limit; dgt++) @@ -102,4 +98,4 @@ int main() long ans = solve(b) - solve(a) + check(a); cout << ans << "\n"; return 0; -} \ No newline at end of file +} diff --git a/code/dynamic_programming/src/edit_distance/edit_distance.php b/code/dynamic_programming/src/edit_distance/edit_distance.php new file mode 100644 index 0000000000..d124b1fce1 --- /dev/null +++ b/code/dynamic_programming/src/edit_distance/edit_distance.php @@ -0,0 +1,47 @@ + pii; #define mp make_pair //cosmos: knapsack 0-1 -int knapsack(int value[], int weight[], int n_items, int maixumWeight) +int knapsack(int value[], int weight[], int n_items, int maximumWeight) { - int dp[n_items + 1][maixumWeight + 1]; + int dp[n_items + 1][maximumWeight + 1]; - for (int w = 0; w <= maixumWeight; w++) + for (int w = 0; w <= maximumWeight; w++) dp[0][w] = 0; for (int i = 0; i <= n_items; i++) dp[i][0] = 0; for (int i = 1; i <= n_items; i++) - for (int w = 1; w <= maixumWeight; w++) + for (int w = 1; w <= maximumWeight; w++) { if (weight[i - 1] <= w) dp[i][w] = max(value[i - 1] + dp[i - 1][w - weight[i - 1]], dp[i - 1][w]); @@ -33,7 +33,7 @@ int knapsack(int value[], int weight[], int n_items, int maixumWeight) dp[i][w] = dp[i - 1][w]; } - return dp[n_items][maixumWeight]; + return dp[n_items][maximumWeight]; } int main() @@ -43,9 +43,9 @@ int main() int value[] = {12, 1000, 30, 10, 1000}; int weight[] = {19, 120, 20, 1, 120}; - int n_tems = 5; - int maixumWeight = 40; + int n_items = 5; + int maximumWeight = 40; - cout << knapsack(value, weight, n_tems, maixumWeight) << endl; //values of the items, weights, number of items and the maximum weight + cout << knapsack(value, weight, n_items, maximumWeight) << endl; //values of the items, weights, number of items and the maximum weight return 0; } diff --git a/code/dynamic_programming/src/knapsack/Knapsack.java b/code/dynamic_programming/src/knapsack/knapsack.java similarity index 100% rename from code/dynamic_programming/src/knapsack/Knapsack.java rename to code/dynamic_programming/src/knapsack/knapsack.java diff --git a/code/dynamic_programming/src/longest_bitonic_sequence/longestBitonicSeq.cpp b/code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicseq.cpp similarity index 100% rename from code/dynamic_programming/src/longest_bitonic_sequence/longestBitonicSeq.cpp rename to code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicseq.cpp diff --git a/code/dynamic_programming/src/longest_bitonic_sequence/longestBitonicSequence.java b/code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicsequence.java similarity index 100% rename from code/dynamic_programming/src/longest_bitonic_sequence/longestBitonicSequence.java rename to code/dynamic_programming/src/longest_bitonic_sequence/longestbitonicsequence.java diff --git a/code/dynamic_programming/src/longest_common_subsequence/Longest_Common_Subsequence.py b/code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.py similarity index 100% rename from code/dynamic_programming/src/longest_common_subsequence/Longest_Common_Subsequence.py rename to code/dynamic_programming/src/longest_common_subsequence/longest_common_subsequence.py diff --git a/code/dynamic_programming/src/longest_common_subsequence/longestCommonSubsequence.go b/code/dynamic_programming/src/longest_common_subsequence/longestcommonsubsequence.go similarity index 100% rename from code/dynamic_programming/src/longest_common_subsequence/longestCommonSubsequence.go rename to code/dynamic_programming/src/longest_common_subsequence/longestcommonsubsequence.go diff --git a/code/dynamic_programming/src/longest_common_subsequence/LongestCommonSubsequence.java b/code/dynamic_programming/src/longest_common_subsequence/longestcommonsubsequence.java similarity index 100% rename from code/dynamic_programming/src/longest_common_subsequence/LongestCommonSubsequence.java rename to code/dynamic_programming/src/longest_common_subsequence/longestcommonsubsequence.java diff --git a/code/dynamic_programming/src/longest_common_subsequence/LongestCommonSubsequenceRec.java b/code/dynamic_programming/src/longest_common_subsequence/longestcommonsubsequencerec.java similarity index 100% rename from code/dynamic_programming/src/longest_common_subsequence/LongestCommonSubsequenceRec.java rename to code/dynamic_programming/src/longest_common_subsequence/longestcommonsubsequencerec.java diff --git a/code/dynamic_programming/src/matrix_chain_multiplication/MatrixChainMultiplication.java b/code/dynamic_programming/src/matrix_chain_multiplication/matrixchainmultiplication.java similarity index 100% rename from code/dynamic_programming/src/matrix_chain_multiplication/MatrixChainMultiplication.java rename to code/dynamic_programming/src/matrix_chain_multiplication/matrixchainmultiplication.java diff --git a/code/dynamic_programming/src/Optimal_Binary_Search_Tree/Optimal_BST.py b/code/dynamic_programming/src/optimal_binary_search_tree/optimal_bst.py similarity index 100% rename from code/dynamic_programming/src/Optimal_Binary_Search_Tree/Optimal_BST.py rename to code/dynamic_programming/src/optimal_binary_search_tree/optimal_bst.py diff --git a/code/dynamic_programming/src/shortest_common_supersequence/SCS.java b/code/dynamic_programming/src/shortest_common_supersequence/scs.java similarity index 100% rename from code/dynamic_programming/src/shortest_common_supersequence/SCS.java rename to code/dynamic_programming/src/shortest_common_supersequence/scs.java diff --git a/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/README.MD b/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/README.MD similarity index 100% rename from code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/README.MD rename to code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/README.MD diff --git a/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_stack.c b/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.c similarity index 100% rename from code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_stack.c rename to code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.c diff --git a/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_stack.h b/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.h similarity index 100% rename from code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_stack.h rename to code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_stack.h diff --git a/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_struct.c b/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.c similarity index 100% rename from code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_struct.c rename to code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.c diff --git a/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_struct.h b/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.h similarity index 100% rename from code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/lgraph_struct.h rename to code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/lgraph_struct.h diff --git a/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/main.c b/code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/main.c similarity index 100% rename from code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_C/main.c rename to code/graph_algorithms/src/adjacency_lists_graph_representation/adjacency_lists_in_c/main.c diff --git a/code/graph_algorithms/src/Bipartite_check/Bipartite_check.java b/code/graph_algorithms/src/bipartite_check/bipartite_check.java similarity index 100% rename from code/graph_algorithms/src/Bipartite_check/Bipartite_check.java rename to code/graph_algorithms/src/bipartite_check/bipartite_check.java diff --git a/code/graph_algorithms/src/breadth_first_search/Bfs.java b/code/graph_algorithms/src/breadth_first_search/bfs.java similarity index 100% rename from code/graph_algorithms/src/breadth_first_search/Bfs.java rename to code/graph_algorithms/src/breadth_first_search/bfs.java diff --git a/code/graph_algorithms/src/count_of_ways_n/Count_of_ways_n.cpp b/code/graph_algorithms/src/count_of_ways_n/count_of_ways_n.cpp similarity index 100% rename from code/graph_algorithms/src/count_of_ways_n/Count_of_ways_n.cpp rename to code/graph_algorithms/src/count_of_ways_n/count_of_ways_n.cpp diff --git a/code/graph_algorithms/src/cycle_undirected_graph/CheckCycle.java b/code/graph_algorithms/src/cycle_undirected_graph/checkcycle.java similarity index 100% rename from code/graph_algorithms/src/cycle_undirected_graph/CheckCycle.java rename to code/graph_algorithms/src/cycle_undirected_graph/checkcycle.java diff --git a/code/graph_algorithms/src/cycle_undirected_graph/cycleGraph.cpp b/code/graph_algorithms/src/cycle_undirected_graph/cyclegraph.cpp similarity index 100% rename from code/graph_algorithms/src/cycle_undirected_graph/cycleGraph.cpp rename to code/graph_algorithms/src/cycle_undirected_graph/cyclegraph.cpp diff --git a/code/graph_algorithms/src/data_structures/adjacency_matrix_C/main.c b/code/graph_algorithms/src/data_structures/adjacency_matrix_c/main.c similarity index 100% rename from code/graph_algorithms/src/data_structures/adjacency_matrix_C/main.c rename to code/graph_algorithms/src/data_structures/adjacency_matrix_c/main.c diff --git a/code/graph_algorithms/src/data_structures/adjacency_matrix_C/mgraph_struct.c b/code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.c similarity index 100% rename from code/graph_algorithms/src/data_structures/adjacency_matrix_C/mgraph_struct.c rename to code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.c diff --git a/code/graph_algorithms/src/data_structures/adjacency_matrix_C/mgraph_struct.h b/code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.h similarity index 100% rename from code/graph_algorithms/src/data_structures/adjacency_matrix_C/mgraph_struct.h rename to code/graph_algorithms/src/data_structures/adjacency_matrix_c/mgraph_struct.h diff --git a/code/graph_algorithms/src/depth_first_search/Dfs.java b/code/graph_algorithms/src/depth_first_search/dfs.java similarity index 100% rename from code/graph_algorithms/src/depth_first_search/Dfs.java rename to code/graph_algorithms/src/depth_first_search/dfs.java diff --git a/code/graph_algorithms/src/depth_first_search/Dfs.kt b/code/graph_algorithms/src/depth_first_search/dfs.kt similarity index 100% rename from code/graph_algorithms/src/depth_first_search/Dfs.kt rename to code/graph_algorithms/src/depth_first_search/dfs.kt diff --git a/code/graph_algorithms/src/dijkstra_shortest_path/Dijkstra.java b/code/graph_algorithms/src/dijkstra_shortest_path/dijkstra.java similarity index 100% rename from code/graph_algorithms/src/dijkstra_shortest_path/Dijkstra.java rename to code/graph_algorithms/src/dijkstra_shortest_path/dijkstra.java diff --git a/code/graph_algorithms/src/dijkstra_shortest_path/Dijkstra.py b/code/graph_algorithms/src/dijkstra_shortest_path/dijkstra.py similarity index 100% rename from code/graph_algorithms/src/dijkstra_shortest_path/Dijkstra.py rename to code/graph_algorithms/src/dijkstra_shortest_path/dijkstra.py diff --git a/code/graph_algorithms/src/dijkstra_shortest_path/Dijkstra_Algorithm.c b/code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_algorithm.c similarity index 100% rename from code/graph_algorithms/src/dijkstra_shortest_path/Dijkstra_Algorithm.c rename to code/graph_algorithms/src/dijkstra_shortest_path/dijkstra_algorithm.c diff --git a/code/graph_algorithms/src/floyd_warshall_algorithm/floydWarshall.c b/code/graph_algorithms/src/floyd_warshall_algorithm/floydwarshall.c similarity index 100% rename from code/graph_algorithms/src/floyd_warshall_algorithm/floydWarshall.c rename to code/graph_algorithms/src/floyd_warshall_algorithm/floydwarshall.c diff --git a/code/graph_algorithms/src/floyd_warshall_algorithm/FloydWarshall.java b/code/graph_algorithms/src/floyd_warshall_algorithm/floydwarshall.java similarity index 100% rename from code/graph_algorithms/src/floyd_warshall_algorithm/FloydWarshall.java rename to code/graph_algorithms/src/floyd_warshall_algorithm/floydwarshall.java diff --git a/code/graph_algorithms/src/ford_fulkerson_maximum_flow/FordFulkersonUsingBfs.java b/code/graph_algorithms/src/ford_fulkerson_maximum_flow/fordfulkersonusingbfs.java similarity index 100% rename from code/graph_algorithms/src/ford_fulkerson_maximum_flow/FordFulkersonUsingBfs.java rename to code/graph_algorithms/src/ford_fulkerson_maximum_flow/fordfulkersonusingbfs.java diff --git a/code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp b/code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp index 8db64af5ae..c96c9809da 100644 --- a/code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp +++ b/code/graph_algorithms/src/kuhn_munkres_algorithm/kuhn_munkres_algorithm.cpp @@ -32,7 +32,7 @@ class KuhnMunkresAlgorithm public: explicit KuhnMunkresAlgorithm(const std::shared_ptr Input) noexcept - : LeftsCount_(Input->size()), + : LeftsCount_(Input->size()), RightsCount_((*Input)[0].size()), leftsVisited_(LeftsCount_), rightsVisited_(RightsCount_), @@ -50,7 +50,8 @@ class KuhnMunkresAlgorithm std::vector run() noexcept { // Initialize the matching. At the beginning, no match exists in the matching. - std::vector matching(RightsCount_, -1/* -1 means this right node is unmatched. */); + std::vector matching(RightsCount_, + -1 /* -1 means this right node is unmatched. */); // Initialize labels of Left nodes (labels of right nodes are already initialized to 0). for (ptrdiff_t Left = 0; Left < LeftsCount_; ++Left) @@ -98,7 +99,7 @@ class KuhnMunkresAlgorithm for (ptrdiff_t right = 0; right < RightsCount_; ++right) { if (rightsVisited_[right]) - continue; // Only an unvisited right node counts. + continue; // Only an unvisited right node counts. _WeightType t = leftsLabel_[Left] + rightsLabel_[right] - (*Input_)[Left][right]; if (t == 0) // In an equal subgraph. @@ -119,37 +120,37 @@ class KuhnMunkresAlgorithm } private: - const ptrdiff_t LeftsCount_; - const ptrdiff_t RightsCount_; - _WeightType diff_ = UpperLimit_; + const ptrdiff_t LeftsCount_; + const ptrdiff_t RightsCount_; + _WeightType diff_ = UpperLimit_; std::vector leftsVisited_; std::vector rightsVisited_; std::vector<_WeightType> leftsLabel_; std::vector<_WeightType> rightsLabel_; const std::shared_ptr Input_; public: - static constexpr _WeightType UpperLimit_ = std::numeric_limits<_WeightType>::max() / 3; - static constexpr _WeightType LowerLimit_ = -UpperLimit_; + static constexpr _WeightType UpperLimit_ = std::numeric_limits<_WeightType>::max() / 3; + static constexpr _WeightType LowerLimit_ = -UpperLimit_; }; -int main() { - const int non = KuhnMunkresAlgorithm::LowerLimit_; - const auto input = std::make_shared::InputType>( - std::initializer_list>{ - { 200, non, 180, 180, non, 190, non, 195 }, - { non, non, non, 170, 185, 186, 187, non }, - { non, 189, 170, 166, 160, non, non, 191 }, - { 160, 167, non, non, 200, 198, 195, 202 }, - { non, 170, 184, non, 202, 198, 169, 205 }, - { non, non, 187, 204, non, 185, 200, non }, - { 170, 170, 170, 170, 170, 170, 170, 170 }, - { non, 170, 169, 174, non, non, non, 197 } - }); - KuhnMunkresAlgorithm algorithm{input}; - std::vector result = algorithm.run(); - for (ptrdiff_t i = 0; i < result.size(); ++i) { - std::cout << "right node " << i << " is matched with left node " << result[i] << ".\n"; - } - std::cin.get(); - return 0; +int main() +{ + const int non = KuhnMunkresAlgorithm::LowerLimit_; + const auto input = std::make_shared::InputType>( + std::initializer_list>{ + { 200, non, 180, 180, non, 190, non, 195 }, + { non, non, non, 170, 185, 186, 187, non }, + { non, 189, 170, 166, 160, non, non, 191 }, + { 160, 167, non, non, 200, 198, 195, 202 }, + { non, 170, 184, non, 202, 198, 169, 205 }, + { non, non, 187, 204, non, 185, 200, non }, + { 170, 170, 170, 170, 170, 170, 170, 170 }, + { non, 170, 169, 174, non, non, non, 197 } + }); + KuhnMunkresAlgorithm algorithm{input}; + std::vector result = algorithm.run(); + for (ptrdiff_t i = 0; i < result.size(); ++i) + std::cout << "right node " << i << " is matched with left node " << result[i] << ".\n"; + std::cin.get(); + return 0; } diff --git a/code/graph_algorithms/src/travelling_salesman_mst/Travelling_salesman.cpp b/code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.cpp similarity index 100% rename from code/graph_algorithms/src/travelling_salesman_mst/Travelling_salesman.cpp rename to code/graph_algorithms/src/travelling_salesman_mst/travelling_salesman.cpp diff --git a/code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra-shortest-path.cpp b/code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.cpp similarity index 100% rename from code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra-shortest-path.cpp rename to code/greedy_algorithms/src/dijkstra_shortest_path/dijkstra_shortest_path.cpp diff --git a/code/greedy_algorithms/src/hillclimber/Hillclimber.java b/code/greedy_algorithms/src/hillclimber/hillclimber.java similarity index 100% rename from code/greedy_algorithms/src/hillclimber/Hillclimber.java rename to code/greedy_algorithms/src/hillclimber/hillclimber.java diff --git a/code/greedy_algorithms/src/minimum_coins/minimum-coins.js b/code/greedy_algorithms/src/minimum_coins/minimum_coins.js similarity index 100% rename from code/greedy_algorithms/src/minimum_coins/minimum-coins.js rename to code/greedy_algorithms/src/minimum_coins/minimum_coins.js diff --git a/code/greedy_algorithms/src/minimum_coins/MinimumCoins.hs b/code/greedy_algorithms/src/minimum_coins/minimumcoins.hs similarity index 100% rename from code/greedy_algorithms/src/minimum_coins/MinimumCoins.hs rename to code/greedy_algorithms/src/minimum_coins/minimumcoins.hs diff --git a/code/greedy_algorithms/src/minimum_coins/MinimumCoins.java b/code/greedy_algorithms/src/minimum_coins/minimumcoins.java similarity index 100% rename from code/greedy_algorithms/src/minimum_coins/MinimumCoins.java rename to code/greedy_algorithms/src/minimum_coins/minimumcoins.java diff --git a/code/mathematical-algorithms/factorial/factorial.pl b/code/mathematical_algorithms/mathematical_algorithms/factorial/factorial.pl similarity index 100% rename from code/mathematical-algorithms/factorial/factorial.pl rename to code/mathematical_algorithms/mathematical_algorithms/factorial/factorial.pl diff --git a/code/mathematical_algorithms/src/babylonian_method/Babylonian_method.py b/code/mathematical_algorithms/src/babylonian_method/babylonian_method.py similarity index 100% rename from code/mathematical_algorithms/src/babylonian_method/Babylonian_method.py rename to code/mathematical_algorithms/src/babylonian_method/babylonian_method.py diff --git a/code/mathematical_algorithms/src/count_digits/CountDigits.java b/code/mathematical_algorithms/src/count_digits/count_digits.java similarity index 100% rename from code/mathematical_algorithms/src/count_digits/CountDigits.java rename to code/mathematical_algorithms/src/count_digits/count_digits.java diff --git a/code/mathematical_algorithms/src/factorial/Factorial.kt b/code/mathematical_algorithms/src/factorial/factorial.kt similarity index 100% rename from code/mathematical_algorithms/src/factorial/Factorial.kt rename to code/mathematical_algorithms/src/factorial/factorial.kt diff --git a/code/mathematical_algorithms/src/factorial/factorial-hrw.py b/code/mathematical_algorithms/src/factorial/factorial_hrw.py similarity index 100% rename from code/mathematical_algorithms/src/factorial/factorial-hrw.py rename to code/mathematical_algorithms/src/factorial/factorial_hrw.py diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/GaussianElimination.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/gaussianelimination.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/GaussianElimination.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/gaussianelimination.scala diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/MatrixType.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/matrixtype.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/MatrixType.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/matrixtype.scala diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/Solution.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/solution.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/Solution.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/gaussian/elimination/solution.scala diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/Main.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/main.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/Main.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/main.scala diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/Epsilon.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/epsilon.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/Epsilon.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/epsilon.scala diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/Matrix.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/matrix.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/Matrix.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/matrix.scala diff --git a/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/RegularMatrix.scala b/code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/regularmatrix.scala similarity index 100% rename from code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/RegularMatrix.scala rename to code/mathematical_algorithms/src/gaussian_elimination/scala/src/main/scala/structures/regularmatrix.scala diff --git a/code/mathematical_algorithms/src/karatsuba_multiplication/karatsuba_multiplication.cpp b/code/mathematical_algorithms/src/karatsuba_multiplication/karatsuba_multiplication.cpp new file mode 100644 index 0000000000..c4ec32ce7f --- /dev/null +++ b/code/mathematical_algorithms/src/karatsuba_multiplication/karatsuba_multiplication.cpp @@ -0,0 +1,91 @@ +#include + +// To pad both input strings with 0's so they have same size +int equalLength(std::string &bitStr1, std::string &bitStr2) +{ + + int strLen1 = bitStr1.size(); + int strLen2 = bitStr2.size(); + + if (strLen1 > strLen2) + { + int numZerosToPad = strLen1 - strLen2; + for (int i = 0; i < numZerosToPad; i++) + bitStr2 = '0' + bitStr2; + } + else if (strLen2 > strLen1) + { + int numZerosToPad = strLen2 - strLen1; + for (int i = 0; i < numZerosToPad; i++) + bitStr1 = '0' + bitStr1; + } + + return std::max(strLen1, strLen2); +} + +std::string addBitStrings(std::string bitStr1, std::string bitStr2) +{ + std::string result = ""; + int len = equalLength(bitStr1, bitStr2); + + //For first bit addition carry is 0 + int carry = 0; + for (int i = len - 1; i >= 0; --i) + { + // We need to convert '0' or '1' to 0 or 1. Subtracting '0' from the character, subtracts + // their ascii values which results in 0 or 1. + int bit1 = bitStr1[i] - '0'; + int bit2 = bitStr2[i] - '0'; + + // XOR to add the bits and the previous carry + // Adding '0' so that 0 or 1 can be cast to '0' or '1' + char sum = (char)((bit1 ^ bit2 ^ carry) + '0'); + result = sum + result; + + // Boolean expression for carry(full adder carry expression) + carry = (bit1 & bit2) | (bit2 & carry) | (bit1 & carry); + + } + + // if overflow, then add a leading 1 + if (carry) + result = '1' + result; + + return result; +} + +long long int karatsubaMultiply(std::string x, std::string y) +{ + int n = equalLength(x, y); + + //Recursion base cases(when length of the bit string is 0 or 1) + if (n == 0) + return 0; + if (n == 1) + // Single bit multiplication. + return (x[0] - '0') * (y[0] - '0'); + + int firstHalfLen = n / 2; + int secondHalfLen = (n - firstHalfLen); + std::string Xleft = x.substr(0, firstHalfLen); + std::string Xright = x.substr(firstHalfLen, secondHalfLen); + + std::string Yleft = y.substr(0, firstHalfLen); + std::string Yright = y.substr(firstHalfLen, secondHalfLen); + + long long int product1 = karatsubaMultiply(Xleft, Yleft); + long long int product2 = karatsubaMultiply(Xright, Yright); + long long int product3 = karatsubaMultiply(addBitStrings(Xleft, Xright), + addBitStrings(Yleft, Yright)); + + return product1 * (1 << (2 * secondHalfLen)) + (product3 - product1 - product2) * + (1 << secondHalfLen) + product2; +} + +int main() +{ + std::cout << "Product of 1011 and 110 = " << karatsubaMultiply("1011", "110") << "\n"; + std::cout << "Product of 1111 and 0 = " << karatsubaMultiply("1111", "0") << "\n"; + std::cout << "Product of 100000 and 10 = " << karatsubaMultiply("100000", "10") << "\n"; + std::cout << "Product of 101 and 101101 = " << karatsubaMultiply("101", "101101") << "\n"; +} diff --git a/code/mathematical_algorithms/src/primality_tests/solovay-strassen_primality_test/solovay-strassen_primality_test.cpp b/code/mathematical_algorithms/src/primality_tests/solovay_strassen_primality_test/solovay_strassen_primality_test.cpp similarity index 100% rename from code/mathematical_algorithms/src/primality_tests/solovay-strassen_primality_test/solovay-strassen_primality_test.cpp rename to code/mathematical_algorithms/src/primality_tests/solovay_strassen_primality_test/solovay_strassen_primality_test.cpp diff --git a/code/mathematical_algorithms/src/reverse_number/Reverse_a_number.c b/code/mathematical_algorithms/src/reverse_number/reverse_a_number.c similarity index 100% rename from code/mathematical_algorithms/src/reverse_number/Reverse_a_number.c rename to code/mathematical_algorithms/src/reverse_number/reverse_a_number.c diff --git a/code/mathematical_algorithms/src/smallest_digit_in_number/Smallest_digit_in_number.hs b/code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.hs similarity index 100% rename from code/mathematical_algorithms/src/smallest_digit_in_number/Smallest_digit_in_number.hs rename to code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.hs diff --git a/code/mathematical_algorithms/src/square_free_number/square_free_number.cpp b/code/mathematical_algorithms/src/square_free_number/square_free_number.cpp index ecdede3b88..debf8fcc1d 100644 --- a/code/mathematical_algorithms/src/square_free_number/square_free_number.cpp +++ b/code/mathematical_algorithms/src/square_free_number/square_free_number.cpp @@ -4,20 +4,18 @@ bool isSquareFree(int n) { - - if(n % 2 == 0) + + if (n % 2 == 0) n /= 2; - if(n % 2 == 0) + if (n % 2 == 0) return false; - for(int i = 3; i <= std::sqrt(n); i += 2) - { - if(n % i == 0) + for (int i = 3; i <= std::sqrt(n); i += 2) + if (n % i == 0) { n /= i; - if(n % i == 0) + if (n % i == 0) return false; } - } return true; } @@ -26,7 +24,7 @@ int main() int n; std::cout << "Enter a number: "; std::cin >> n; - if(isSquareFree(n)) + if (isSquareFree(n)) std::cout << n << " is square free number"; else std::cout << n << " is not a square free number"; diff --git a/code/mathematical_algorithms/src/square_free_number/SquareFreeNumber.java b/code/mathematical_algorithms/src/square_free_number/squarefreenumber.java similarity index 100% rename from code/mathematical_algorithms/src/square_free_number/SquareFreeNumber.java rename to code/mathematical_algorithms/src/square_free_number/squarefreenumber.java diff --git a/code/mathematical_algorithms/src/tribonacci_numbers/Tribonnaci.java b/code/mathematical_algorithms/src/tribonacci_numbers/tribonnaci.java similarity index 100% rename from code/mathematical_algorithms/src/tribonacci_numbers/Tribonnaci.java rename to code/mathematical_algorithms/src/tribonacci_numbers/tribonnaci.java diff --git a/code/networking/src/PacketSniffer/README.md b/code/networking/src/packetsniffer/README.md similarity index 100% rename from code/networking/src/PacketSniffer/README.md rename to code/networking/src/packetsniffer/README.md diff --git a/code/networking/src/PacketSniffer/img/ethernet.png b/code/networking/src/packetsniffer/img/ethernet.png similarity index 100% rename from code/networking/src/PacketSniffer/img/ethernet.png rename to code/networking/src/packetsniffer/img/ethernet.png diff --git a/code/networking/src/PacketSniffer/img/IP.png b/code/networking/src/packetsniffer/img/ip.png similarity index 100% rename from code/networking/src/PacketSniffer/img/IP.png rename to code/networking/src/packetsniffer/img/ip.png diff --git a/code/networking/src/PacketSniffer/img/TCP.png b/code/networking/src/packetsniffer/img/tcp.png similarity index 100% rename from code/networking/src/PacketSniffer/img/TCP.png rename to code/networking/src/packetsniffer/img/tcp.png diff --git a/code/networking/src/PacketSniffer/img/UDP.png b/code/networking/src/packetsniffer/img/udp.png similarity index 100% rename from code/networking/src/PacketSniffer/img/UDP.png rename to code/networking/src/packetsniffer/img/udp.png diff --git a/code/networking/src/PacketSniffer/packetSniffer.py b/code/networking/src/packetsniffer/packetsniffer.py similarity index 100% rename from code/networking/src/PacketSniffer/packetSniffer.py rename to code/networking/src/packetsniffer/packetsniffer.py diff --git a/code/networking/src/validate_IP/README.md b/code/networking/src/validate_ip/README.md similarity index 100% rename from code/networking/src/validate_IP/README.md rename to code/networking/src/validate_ip/README.md diff --git a/code/networking/src/validate_IP/ipv4_check.go b/code/networking/src/validate_ip/ipv4_check.go similarity index 100% rename from code/networking/src/validate_IP/ipv4_check.go rename to code/networking/src/validate_ip/ipv4_check.go diff --git a/code/networking/src/validate_IP/is_valid_ip.php b/code/networking/src/validate_ip/is_valid_ip.php similarity index 100% rename from code/networking/src/validate_IP/is_valid_ip.php rename to code/networking/src/validate_ip/is_valid_ip.php diff --git a/code/networking/src/validate_IP/Validate_connection_ipv4.py b/code/networking/src/validate_ip/validate_connection_ipv4.py similarity index 100% rename from code/networking/src/validate_IP/Validate_connection_ipv4.py rename to code/networking/src/validate_ip/validate_connection_ipv4.py diff --git a/code/networking/src/validate_IP/validate_ip.c b/code/networking/src/validate_ip/validate_ip.c similarity index 100% rename from code/networking/src/validate_IP/validate_ip.c rename to code/networking/src/validate_ip/validate_ip.c diff --git a/code/networking/src/validate_IP/validate_ip.rb b/code/networking/src/validate_ip/validate_ip.rb similarity index 100% rename from code/networking/src/validate_IP/validate_ip.rb rename to code/networking/src/validate_ip/validate_ip.rb diff --git a/code/networking/src/validate_IP/validate_ip.sh b/code/networking/src/validate_ip/validate_ip.sh similarity index 100% rename from code/networking/src/validate_IP/validate_ip.sh rename to code/networking/src/validate_ip/validate_ip.sh diff --git a/code/networking/src/validate_IP/validate_ipv4.c b/code/networking/src/validate_ip/validate_ip/validate_ipv4.c similarity index 100% rename from code/networking/src/validate_IP/validate_ipv4.c rename to code/networking/src/validate_ip/validate_ip/validate_ipv4.c diff --git a/code/networking/src/validate_IP/validate_ipv6.c b/code/networking/src/validate_ip/validate_ip/validate_ipv6.c similarity index 100% rename from code/networking/src/validate_IP/validate_ipv6.c rename to code/networking/src/validate_ip/validate_ip/validate_ipv6.c diff --git a/code/networking/src/validate_IP/validate_ipv4.js b/code/networking/src/validate_ip/validate_ipv4.js similarity index 100% rename from code/networking/src/validate_IP/validate_ipv4.js rename to code/networking/src/validate_ip/validate_ipv4.js diff --git a/code/networking/src/validate_IP/validate_ipv4.py b/code/networking/src/validate_ip/validate_ipv4.py similarity index 100% rename from code/networking/src/validate_IP/validate_ipv4.py rename to code/networking/src/validate_ip/validate_ipv4.py diff --git a/code/networking/src/validate_IP/validate_ipv6.py b/code/networking/src/validate_ip/validate_ipv6.py similarity index 100% rename from code/networking/src/validate_IP/validate_ipv6.py rename to code/networking/src/validate_ip/validate_ipv6.py diff --git a/code/online_challenges/src/project_euler/problem_010/problem_010.cpp b/code/online_challenges/src/project_euler/problem_010/problem_010.cpp index b19c540c07..d050fb4269 100644 --- a/code/online_challenges/src/project_euler/problem_010/problem_010.cpp +++ b/code/online_challenges/src/project_euler/problem_010/problem_010.cpp @@ -14,7 +14,7 @@ long long int sumOfPrimesUpto(size_t limit) // Function that implements the Siev for (size_t j = (2 * i); j < limit; j += i) primesBoolArray[j] = false; } - + return sum; } diff --git a/code/online_challenges/src/project_euler/problem_020/Problem_020.java b/code/online_challenges/src/project_euler/problem_020/problem_020.java similarity index 100% rename from code/online_challenges/src/project_euler/problem_020/Problem_020.java rename to code/online_challenges/src/project_euler/problem_020/problem_020.java diff --git a/code/online_challenges/src/project_euler/problem_021/problem_021.cpp b/code/online_challenges/src/project_euler/problem_021/problem_021.cpp index 42fa9b022b..f0bd8b079c 100644 --- a/code/online_challenges/src/project_euler/problem_021/problem_021.cpp +++ b/code/online_challenges/src/project_euler/problem_021/problem_021.cpp @@ -3,7 +3,7 @@ int sumProperDivisors(int n) { int sum = 0; - for (int i = 1; i*i <= n; ++i) + for (int i = 1; i * i <= n; ++i) if (n % i == 0) { sum += i; diff --git a/code/online_challenges/src/project_euler/problem_034/problem_034.cpp b/code/online_challenges/src/project_euler/problem_034/problem_034.cpp index c02fd89356..a48b2ea4ee 100644 --- a/code/online_challenges/src/project_euler/problem_034/problem_034.cpp +++ b/code/online_challenges/src/project_euler/problem_034/problem_034.cpp @@ -1,11 +1,11 @@ #include #include -int factorial (std::size_t n) -{ - int fact = 1; - for(std::size_t i = 1; i <= n; ++i) - fact *= i; +int factorial (std::size_t n) +{ + int fact = 1; + for (std::size_t i = 1; i <= n; ++i) + fact *= i; return fact; } @@ -13,13 +13,13 @@ int main() { std::vector factorials(10); constexpr std::size_t maxDigitFactorial = 2540162; - for(int i = 0;i < 10; ++i) + for (int i = 0; i < 10; ++i) factorials[i] = factorial(i); std::size_t num = 3, sum = 0; while (num < maxDigitFactorial) { std::size_t temp = 0; - for(std::size_t i = num; i > 0; i /= 10) + for (std::size_t i = num; i > 0; i /= 10) temp += factorials[i % 10]; if (temp == num) sum += num; diff --git a/code/online_challenges/src/project_euler/problem_037/problem_037.cpp b/code/online_challenges/src/project_euler/problem_037/problem_037.cpp index 65ee40af71..c82513522a 100644 --- a/code/online_challenges/src/project_euler/problem_037/problem_037.cpp +++ b/code/online_challenges/src/project_euler/problem_037/problem_037.cpp @@ -26,7 +26,7 @@ bool isTruncPrime(std::size_t number, const std::array& primesList) { for (std::size_t i = 10; i < number; i *= 10) if (!primesList[number % i]) // If the right truncated part is not prime - return false; + return false; for (; number >= 1; number /= 10) if (!primesList[number]) // If the left truncated part is not prime return false; diff --git a/code/operating_system/src/shell/C/README.md b/code/operating_system/src/shell/c/README.md similarity index 100% rename from code/operating_system/src/shell/C/README.md rename to code/operating_system/src/shell/c/README.md diff --git a/code/operating_system/src/shell/C/Makefile b/code/operating_system/src/shell/c/makefile similarity index 100% rename from code/operating_system/src/shell/C/Makefile rename to code/operating_system/src/shell/c/makefile diff --git a/code/operating_system/src/shell/C/Shell.c b/code/operating_system/src/shell/c/shell.c similarity index 100% rename from code/operating_system/src/shell/C/Shell.c rename to code/operating_system/src/shell/c/shell.c diff --git a/code/randomized_algorithms/src/random_from_stream/Random_number_selection_from_a_stream.cpp b/code/randomized_algorithms/src/random_from_stream/random_number_selection_from_a_stream.cpp similarity index 100% rename from code/randomized_algorithms/src/random_from_stream/Random_number_selection_from_a_stream.cpp rename to code/randomized_algorithms/src/random_from_stream/random_number_selection_from_a_stream.cpp diff --git a/code/search/src/binary_search/binary_search_2.cpp b/code/search/src/binary_search/binary_search_2.cpp index 9a8e3dc70c..ff282d1ca2 100644 --- a/code/search/src/binary_search/binary_search_2.cpp +++ b/code/search/src/binary_search/binary_search_2.cpp @@ -34,7 +34,7 @@ int binarySearch(std::vector &v, int key) else l = m; } - + return (v[l] == key) ? l : -1; } diff --git a/code/search/src/linear_search/SentinelLinearSearch.cpp b/code/search/src/linear_search/sentinellinearsearch.cpp similarity index 100% rename from code/search/src/linear_search/SentinelLinearSearch.cpp rename to code/search/src/linear_search/sentinellinearsearch.cpp diff --git a/code/search/src/ternary_search/Ternary_search.java b/code/search/src/ternary_search/ternary_search.java similarity index 100% rename from code/search/src/ternary_search/Ternary_search.java rename to code/search/src/ternary_search/ternary_search.java diff --git a/code/selection_algorithms/src/median-of-medians/median_of_medians.c b/code/selection_algorithms/src/median_of_medians/median_of_medians.c similarity index 100% rename from code/selection_algorithms/src/median-of-medians/median_of_medians.c rename to code/selection_algorithms/src/median_of_medians/median_of_medians.c diff --git a/code/selection_algorithms/src/median-of-medians/median_of_medians.hs b/code/selection_algorithms/src/median_of_medians/median_of_medians.hs similarity index 100% rename from code/selection_algorithms/src/median-of-medians/median_of_medians.hs rename to code/selection_algorithms/src/median_of_medians/median_of_medians.hs diff --git a/code/selection_algorithms/src/median-of-medians/median_of_medians.py b/code/selection_algorithms/src/median_of_medians/median_of_medians.py similarity index 100% rename from code/selection_algorithms/src/median-of-medians/median_of_medians.py rename to code/selection_algorithms/src/median_of_medians/median_of_medians.py diff --git a/code/selection_algorithms/src/Quick_select.java b/code/selection_algorithms/src/quick_select.java similarity index 100% rename from code/selection_algorithms/src/Quick_select.java rename to code/selection_algorithms/src/quick_select.java diff --git a/code/sorting/circle_sort/README.md b/code/sorting/circle_sort/README.md new file mode 100644 index 0000000000..d8ca06ec0a --- /dev/null +++ b/code/sorting/circle_sort/README.md @@ -0,0 +1,14 @@ +# Circle Sort + +The **circle sort** algorithm can be visualized by drawing concentric circles on an array of integers. The elements of the array lying on the same circle diametrically opposite to each other are compared and if found in the wrong order they are swapped. This goes on in a recursive fashion in which the array is divided into sub-arrays on which the above process is repeated until we get pairs of sorted elements which when put together form a sorted array. + +In short below two steps are repeated while there are swap operations involved in the steps. + +*Compare the first element to the last element, then the second element to the second last element, etc. +*Then split the array in two and recurse until there is only one single element in the array. + +It can be better explained by the image below + +![alt text](http://contribute.geeksforgeeks.org/wp-content/uploads/CircleSort.png "Circle Sorting") + +This article is obtained as a reference from [Geeksforgeeks](http://www.geeksforgeeks.org/circle-sort/) diff --git a/code/sorting/src/bubble_sort/Bubble_sort.f b/code/sorting/src/bubble_sort/bubble_sort.f similarity index 100% rename from code/sorting/src/bubble_sort/Bubble_sort.f rename to code/sorting/src/bubble_sort/bubble_sort.f diff --git a/code/sorting/src/pigeonhole_sort/PigeonHoleSort.scala b/code/sorting/src/pigeonhole_sort/pigeonholesort.scala similarity index 100% rename from code/sorting/src/pigeonhole_sort/PigeonHoleSort.scala rename to code/sorting/src/pigeonhole_sort/pigeonholesort.scala diff --git a/code/square_root_decomposition/src/MOs_Algorithm/MOs_Algorithm.cpp b/code/square_root_decomposition/src/mos_algorithm/mos_algorithm.cpp similarity index 100% rename from code/square_root_decomposition/src/MOs_Algorithm/MOs_Algorithm.cpp rename to code/square_root_decomposition/src/mos_algorithm/mos_algorithm.cpp diff --git a/code/string_algorithms/src/arithmetic_on_large_numbers/string_addition.cpp b/code/string_algorithms/src/arithmetic_on_large_numbers/string_addition.cpp index fff193736a..39139342f0 100644 --- a/code/string_algorithms/src/arithmetic_on_large_numbers/string_addition.cpp +++ b/code/string_algorithms/src/arithmetic_on_large_numbers/string_addition.cpp @@ -9,7 +9,7 @@ std::string strAdd(std::string s, std::string r) // precondition for empty strings assert(s.length() > 0 && r.length() > 0); - + if (r.length() < s.length()) r.insert(r.begin(), s.length() - r.length(), '0'); else if (r.length() > s.length()) diff --git a/code/string_algorithms/src/finite_automata/C/makefile b/code/string_algorithms/src/finite_automata/c/c/makefile similarity index 100% rename from code/string_algorithms/src/finite_automata/C/makefile rename to code/string_algorithms/src/finite_automata/c/c/makefile diff --git a/code/string_algorithms/src/finite_automata/C/dfa.c b/code/string_algorithms/src/finite_automata/c/dfa.c similarity index 100% rename from code/string_algorithms/src/finite_automata/C/dfa.c rename to code/string_algorithms/src/finite_automata/c/dfa.c diff --git a/code/string_algorithms/src/finite_automata/C/dfa.h b/code/string_algorithms/src/finite_automata/c/dfa.h similarity index 100% rename from code/string_algorithms/src/finite_automata/C/dfa.h rename to code/string_algorithms/src/finite_automata/c/dfa.h diff --git a/code/string_algorithms/src/finite_automata/C/main.c b/code/string_algorithms/src/finite_automata/c/main.c similarity index 100% rename from code/string_algorithms/src/finite_automata/C/main.c rename to code/string_algorithms/src/finite_automata/c/main.c diff --git a/code/string_algorithms/src/finite_automata/C/types.c b/code/string_algorithms/src/finite_automata/c/types.c similarity index 100% rename from code/string_algorithms/src/finite_automata/C/types.c rename to code/string_algorithms/src/finite_automata/c/types.c diff --git a/code/string_algorithms/src/finite_automata/C/types.h b/code/string_algorithms/src/finite_automata/c/types.h similarity index 100% rename from code/string_algorithms/src/finite_automata/C/types.h rename to code/string_algorithms/src/finite_automata/c/types.h diff --git a/code/string_algorithms/src/finite_automata/SearchStringUsingDFA.java b/code/string_algorithms/src/finite_automata/searchstringusingdfa.java similarity index 100% rename from code/string_algorithms/src/finite_automata/SearchStringUsingDFA.java rename to code/string_algorithms/src/finite_automata/searchstringusingdfa.java diff --git a/code/string_algorithms/src/finite_automata/SearchStringUsingDFA.rs b/code/string_algorithms/src/finite_automata/searchstringusingdfa.rs similarity index 100% rename from code/string_algorithms/src/finite_automata/SearchStringUsingDFA.rs rename to code/string_algorithms/src/finite_automata/searchstringusingdfa.rs diff --git a/code/string_algorithms/src/kasai_algorithm/kasai_algorithm.cpp b/code/string_algorithms/src/kasai_algorithm/kasai_algorithm.cpp index db8da28c36..148eb31cea 100644 --- a/code/string_algorithms/src/kasai_algorithm/kasai_algorithm.cpp +++ b/code/string_algorithms/src/kasai_algorithm/kasai_algorithm.cpp @@ -43,4 +43,4 @@ int main() for (int i = 0; i < lcpArray.size(); i++) // => 1 3 0 0 2 0 std::cout << lcpArray[i] << " "; return 0; -} \ No newline at end of file +} diff --git a/code/string_algorithms/src/levenshtein_distance/README.md b/code/string_algorithms/src/levenshtein_distance/README.md new file mode 100644 index 0000000000..5bc03219d4 --- /dev/null +++ b/code/string_algorithms/src/levenshtein_distance/README.md @@ -0,0 +1,66 @@ +# Levenshtein Distance + +The Levenshtein distance between two strings measures the similarity between them by calculating the **minimum number of one-character insertions, deletions, or substitutions required to change one string into another**. This edit distance is often used in spell chekers, plagiarism detectors, and OCR. + +For example, each of these examples have a Levensthein distance of 1 with `cosmos`: +- cosmo**t**s (addition of t in the middle) +- cosmos**k** (addition of k at the end) +- cosms (deletion of o in the middle) +- cosmo (deletion of s at the end) +- cosm**a**s (substitution of o to a) + +## Recursive algorithm + +Recursively solving this problem is simple, but computationally very inefficient because it recalculates the distance between substrings it has already covered. + +Function LevDistance(String S, String T): + +1. If either (length of `S`) or (length of `T`) is `0`, return the maximum of (length of `S`) and (length of `T`) + - This is because the minium edit distance between a nonempty string and an empty string is always the length of the nonempty string +2. Else, return minimum of: + - LevDistance(`S` without the last character, `T`) + - LevDistance(`S`, `T` without last character) + - LevDistance(`S` without the last character, `T` without the last character) + +## Iterative matrix algorithm + +This algorithm is more efficient than the recursive one because the matrix stores the distance calculations for substrings, saving computational time. + +Function LevDistance(String S, String T): + +1. Variable `SL` = length of `S` and `TL` = length of `T` +2. Create an empty `matrix` (2d array) of height `SL` and width `TL` +3. Fill the first row with numbers from `0` to `TL` +4. Fill the first column with numbres from `0` to `SL` +5. For each character `s` of `S` (from `i` = `1` to `SL`): + - For each character `t` of `T` (from `j` = `1` to `TL`): + - if `s` equals `t`, the `cost` is `0` + - if `s` does not equal `t`, the `cost` is `1` + - set `matrix[i][j]` to the minimum of: + - `matrix[i - 1, j] + 1` (this is for deletion) + - `matrix[i, j - 1] + 1` (this is for insertion) + - `matrix[i - 1, j - 1] + cost` (this is for substitution) +6. Return `matrix[SL, TL]` + +Each bottom-up dynamic program works by setting each cell's value to the minimum edit distance between the substrings of S and T. + +### Example matrix + +This is the final Levenshtein distance matrix for the strings "cosmos" and "catmouse". The minimum edit distance is the value in the bottom right corner: 4. + +| | | c | a | t | m | o | u | s | e | +|-------|---|---|---|---|---|---|---|---|---| +| | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | +| **c** | 1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | +| **o** | 2 | 1 | 1 | 2 | 3 | 3 | 4 | 5 | 6 | +| **s** | 3 | 2 | 2 | 2 | 3 | 4 | 4 | 4 | 5 | +| **m** | 4 | 3 | 3 | 3 | 2 | 3 | 4 | 5 | 5 | +| **o** | 5 | 4 | 4 | 4 | 3 | 2 | 3 | 4 | 5 | +| **s** | 6 | 5 | 5 | 5 | 4 | 3 | 3 | 3 | **4** | + +--- +

+ A massive collaborative effort by OpenGenus Foundation +

+ +--- diff --git a/code/string_algorithms/src/levenshtein_distance/LevenshteinDistance.java b/code/string_algorithms/src/levenshtein_distance/levenshteindistance.java similarity index 100% rename from code/string_algorithms/src/levenshtein_distance/LevenshteinDistance.java rename to code/string_algorithms/src/levenshtein_distance/levenshteindistance.java diff --git a/code/string_algorithms/src/morse_code/morsecode.cpp b/code/string_algorithms/src/morse_code/morsecode.cpp index 6b3da90e05..528fec8aee 100644 --- a/code/string_algorithms/src/morse_code/morsecode.cpp +++ b/code/string_algorithms/src/morse_code/morsecode.cpp @@ -77,9 +77,8 @@ std::string finder(const std::vector> &mp, std::str char val = value[0]; for (const auto &it : mp) if (it.first == val) - { return it.second; - } + } return std::string{}; } diff --git a/code/string_algorithms/src/palindrome_checker/Palindrome.java b/code/string_algorithms/src/palindrome_checker/palindrome.java similarity index 100% rename from code/string_algorithms/src/palindrome_checker/Palindrome.java rename to code/string_algorithms/src/palindrome_checker/palindrome.java diff --git a/code/string_algorithms/src/palindrome_checker/Palindrome.kt b/code/string_algorithms/src/palindrome_checker/palindrome.kt similarity index 100% rename from code/string_algorithms/src/palindrome_checker/Palindrome.kt rename to code/string_algorithms/src/palindrome_checker/palindrome.kt diff --git a/code/string_algorithms/src/palindrome_checker/Palindrome.purs b/code/string_algorithms/src/palindrome_checker/palindrome.purs similarity index 100% rename from code/string_algorithms/src/palindrome_checker/Palindrome.purs rename to code/string_algorithms/src/palindrome_checker/palindrome.purs diff --git a/code/string_algorithms/src/pangram_checker/Pangram.java b/code/string_algorithms/src/pangram_checker/pangram.java similarity index 100% rename from code/string_algorithms/src/pangram_checker/Pangram.java rename to code/string_algorithms/src/pangram_checker/pangram.java diff --git a/code/string_algorithms/src/pangram_checker/pangram-checker.js b/code/string_algorithms/src/pangram_checker/pangram_checker.js similarity index 100% rename from code/string_algorithms/src/pangram_checker/pangram-checker.js rename to code/string_algorithms/src/pangram_checker/pangram_checker.js diff --git a/code/string_algorithms/src/password_strength_checker/pw_checker.cs b/code/string_algorithms/src/password_strength_checker/pw_checker.cs index 70a75c057b..ecb7afcefe 100644 --- a/code/string_algorithms/src/password_strength_checker/pw_checker.cs +++ b/code/string_algorithms/src/password_strength_checker/pw_checker.cs @@ -10,7 +10,7 @@ class Program { static bool chk_strength(string password) { - return (password.Length < 8 && !password.Any(ch => !char.IsLetterOrDigit(ch)) && !password.Any(char.IsDigit) && !password.Any(char.IsUpper)); + return (password.Length > 8 && password.Any(ch => !char.IsLetterOrDigit(ch)) && password.Any(char.IsDigit) && password.Any(char.IsUpper)); } static void Main(string[] args) { @@ -20,7 +20,8 @@ static void Main(string[] args) { Console.WriteLine("Strong!!!"); } - else { + else + { Console.WriteLine("Weak :("); } diff --git a/code/string_algorithms/src/rabin_karp_algorithm/rabin-karp.c b/code/string_algorithms/src/rabin_karp_algorithm/rabin_karp.c similarity index 100% rename from code/string_algorithms/src/rabin_karp_algorithm/rabin-karp.c rename to code/string_algorithms/src/rabin_karp_algorithm/rabin_karp.c diff --git a/code/string_algorithms/src/rabin_karp_algorithm/RabinKarp.java b/code/string_algorithms/src/rabin_karp_algorithm/rabinkarp.java similarity index 100% rename from code/string_algorithms/src/rabin_karp_algorithm/RabinKarp.java rename to code/string_algorithms/src/rabin_karp_algorithm/rabinkarp.java diff --git a/code/string_algorithms/src/suffix_array/suffixArray.java b/code/string_algorithms/src/suffix_array/suffixarray.java similarity index 100% rename from code/string_algorithms/src/suffix_array/suffixArray.java rename to code/string_algorithms/src/suffix_array/suffixarray.java diff --git a/code/unclassified/src/average/Average.class b/code/unclassified/src/average/average.class similarity index 100% rename from code/unclassified/src/average/Average.class rename to code/unclassified/src/average/average.class diff --git a/code/unclassified/src/average/Average.java b/code/unclassified/src/average/average.java similarity index 100% rename from code/unclassified/src/average/Average.java rename to code/unclassified/src/average/average.java diff --git a/code/unclassified/src/biggest_of_n_numbers/Biggest_of_n_numbers.java b/code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.java similarity index 100% rename from code/unclassified/src/biggest_of_n_numbers/Biggest_of_n_numbers.java rename to code/unclassified/src/biggest_of_n_numbers/biggest_of_n_numbers.java diff --git a/code/unclassified/src/fifteen_puzzle/Makefile b/code/unclassified/src/fifteen_puzzle/makefile similarity index 100% rename from code/unclassified/src/fifteen_puzzle/Makefile rename to code/unclassified/src/fifteen_puzzle/makefile diff --git a/code/unclassified/src/leap_year/README.txt b/code/unclassified/src/leap_year/readme.txt similarity index 100% rename from code/unclassified/src/leap_year/README.txt rename to code/unclassified/src/leap_year/readme.txt diff --git a/code/unclassified/src/minimum_subarray_size_with_degree/minSubarraySizeWithDegree.cpp b/code/unclassified/src/minimum_subarray_size_with_degree/minsubarraysizewithdegree.cpp similarity index 100% rename from code/unclassified/src/minimum_subarray_size_with_degree/minSubarraySizeWithDegree.cpp rename to code/unclassified/src/minimum_subarray_size_with_degree/minsubarraysizewithdegree.cpp diff --git a/code/unclassified/src/optimized_fibonacci/optimized_fibonacci.cpp b/code/unclassified/src/optimized_fibonacci/optimized_fibonacci.cpp new file mode 100644 index 0000000000..cd5077d9a3 --- /dev/null +++ b/code/unclassified/src/optimized_fibonacci/optimized_fibonacci.cpp @@ -0,0 +1,28 @@ +/* Fibonacci Series implemented using Memoization */ +#include + +long long fibonacci (int n) +{ + static long long fib[100] = {}; // initialises the array with all elements as 0 + fib[1] = 0; + fib[2] = 1; + + if (n == 1 || n == 2) + return fib[n]; + else if (fib[n] != 0) + return fib[n]; + else + { + fib[n] = fibonacci (n - 1) + fibonacci (n - 2); + return fib[n]; + } +} + +int main () +{ + int n; + std::cout << "Enter number of terms: "; + std::cin >> n; + for (int i = 1; i <= n; i++) + std::cout << fibonacci (i) << std::endl; +} diff --git a/code/unclassified/src/smallest_number_to_the_left/smallest.cpp b/code/unclassified/src/smallest_number_to_the_left/smallest.cpp index 8c748c0455..d81b1d4380 100644 --- a/code/unclassified/src/smallest_number_to_the_left/smallest.cpp +++ b/code/unclassified/src/smallest_number_to_the_left/smallest.cpp @@ -1,4 +1,4 @@ -//Part of Cosmos by OpenGenus Foundation +//Part of Cosmos by OpenGenus Foundation // C++ implementation of simple algorithm to find @@ -6,39 +6,38 @@ #include #include using namespace std; - + // Prints smaller elements on left side of every element void printPrevSmaller(int arr[], int n) { // Create an empty stack stack S; - + // Traverse all array elements - for (int i=0; i= arr[i]) S.pop(); - + // If all elements in S were greater than arr[i] if (S.empty()) cout << "_, "; else //Else print the nearest smaller element cout << S.top() << ", "; - + // Push this element S.push(arr[i]); } } - + int main() { int arr[] = {1, 3, 0, 2, 5}; - int n = sizeof(arr)/sizeof(arr[0]); + int n = sizeof(arr) / sizeof(arr[0]); printPrevSmaller(arr, n); return 0; } - diff --git a/code/utility/src/palindrome/palindrome_check/Palindrome.py b/code/utility/src/palindrome/palindrome_check/palindrome.py similarity index 100% rename from code/utility/src/palindrome/palindrome_check/Palindrome.py rename to code/utility/src/palindrome/palindrome_check/palindrome.py diff --git a/code/utility/src/palindrome/palindrome_check/palindrome_check.c b/code/utility/src/palindrome/palindrome_check/palindrome_check.c new file mode 100644 index 0000000000..7a5f9f11cb --- /dev/null +++ b/code/utility/src/palindrome/palindrome_check/palindrome_check.c @@ -0,0 +1,31 @@ +#include +#include + +int isPalindrome(char *arr) +{ + int length = strlen(arr); + int i, j; + for(i = 0, j = length - 1; i < length / 2; ++i, --j) + { + if(arr[i] != arr[j]) + { + return 0; + } + } + return 1; +} + +int main() +{ + printf("%d\n", isPalindrome("terabyte")); + printf("%d\n", isPalindrome("nitin")); + printf("%d\n", isPalindrome("gurkirat")); + printf("%d\n", isPalindrome("lol")); + + + // Output + // 0 + // 1 + // 0 + // 1 +} \ No newline at end of file diff --git a/code/utility/src/palindrome/palindrome_check/palindrome_check.cs b/code/utility/src/palindrome/palindrome_check/palindrome_check.cs new file mode 100644 index 0000000000..aa1f37c4b3 --- /dev/null +++ b/code/utility/src/palindrome/palindrome_check/palindrome_check.cs @@ -0,0 +1,25 @@ +using System; + +namespace Palindrome +{ + class Program + { + public static bool isPalindrome(string str) + { + for (int i = 0, j = str.Length - 1; i < str.Length / 2; ++i, --j) + { + if(str[i] != str[j]) + { + return false; + } + } + return true; + } + + public static void Main() + { + Console.WriteLine(isPalindrome("lol")); // True + Console.WriteLine(isPalindrome("lolwa")); // False + } + } +} \ No newline at end of file diff --git a/code/utility/src/palindrome/palindrome_check/palindrome_check.js b/code/utility/src/palindrome/palindrome_check/palindrome_check.js new file mode 100644 index 0000000000..3b9c45b5a9 --- /dev/null +++ b/code/utility/src/palindrome/palindrome_check/palindrome_check.js @@ -0,0 +1,16 @@ + +function isPalindrome (str) +{ + return [...str].reverse().join("") == str; +} + +console.log(isPalindrome("lol")); +console.log(isPalindrome("nitin")); +console.log(isPalindrome("terabyte")); +console.log(isPalindrome("tbhaxor")); + +// Output +// true +// true +// false +// false \ No newline at end of file diff --git a/scripts/build_cpp.sh b/scripts/build_cpp.sh index 3d37ce7197..ec95fac22f 100755 --- a/scripts/build_cpp.sh +++ b/scripts/build_cpp.sh @@ -6,13 +6,13 @@ echo "" echo "###############################" echo "# generating dependencies ... #" echo "###############################" -make -f generate_dependencies.make +make -f generate_dependencies.make || exit 1 echo "" echo "#########################" echo "# compiling sources ... #" echo "#########################" -make -f testing.make +make -f testing.make || exit 1 cd "$cosmos_root_path/scripts" echo "" diff --git a/third_party/namanager b/third_party/namanager new file mode 160000 index 0000000000..7d67177731 --- /dev/null +++ b/third_party/namanager @@ -0,0 +1 @@ +Subproject commit 7d67177731594451430d83dd98f4e994a499f612 diff --git a/third_party/namanager_settings.json b/third_party/namanager_settings.json new file mode 100644 index 0000000000..dc99a7f805 --- /dev/null +++ b/third_party/namanager_settings.json @@ -0,0 +1,30 @@ +{ + "CHECK_DIRS": ["code/"], + "DIR_FORMATS": { + "LETTER_CASE": "lower_case", + "SEP": ["dash_to_underscore"] + }, + "DIR_PREFIX": "", + "DIR_PREFIX_MODE": "ignore", + "DIR_SUFFIX": "", + "DIR_SUFFIX_MODE": "ignore", + "FILE_FORMATS": { + "LETTER_CASE": "lower_case", + "SEP": ["dash_to_underscore"] + }, + "FILE_PREFIX": "", + "FILE_PREFIX_MODE": "ignore", + "FILE_SUFFIX": "", + "FILE_SUFFIX_MODE": "ignore", + "IGNORE_DIRS": [ + "/design_pattern/src/OOP_patterns$", + "/artificial_intelligence/src/DBSCAN_clustering$", + "/artificial_intelligence/src/ISODATA_clustering$", + "/artificial_intelligence/src/SAT$", + "/artificial_intelligence/src/TSP$", + "^/$" + ], + "IGNORE_FILES": ["README.MD", "README.md", "Readme.md", "readme.md", ".DS_Store"], + "INCLUDE_DIRS": [], + "INCLUDE_FILES": [] +}