Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Find the number of characters in a string
- function charCount(str) {
- let result = {};
- for(let char of str) {
- if(/[a-z0-9]/.test(char)) { // includes only lowercase a,b....z and 0,1....9
- result[char] ? result[char]++ : result[char] = 1;
- }
- }
- return result;
- }
- // Find whether the two strings are of anagram
- function anagram(strOne, strTwo) {
- if(strOne.length != strTwo.length) {
- return false;
- }
- let populatedStrOne = {};
- for(let char of strOne) {
- populatedStrOne[char] = (populatedStrOne[char] || 0) + 1;
- }
- for(let char of strTwo) {
- if(!populatedStrOne[char]) {
- return false;
- } else {
- populatedStrOne[char] -= 1;
- }
- }
- return true;
- }
- // Find the coordinates in the given array
- function sumZero(coordinates) {
- let result = [];
- for(let i = 0; i < coordinates.length; i++) {
- for(let j = i + 1; j < coordinates.length; j++) {
- if(coordinates[i] + coordinates[j] == 0) {
- result.push(`${coordinates[i]}, ${coordinates[j]}`);
- }
- }
- }
- return result;
- }
- // Find the unique values in the given array
- function countUniqueValues(arr) {
- let populatedObj = {};
- let result = [];
- for(let el of arr) {
- populatedObj[el] = (populatedObj[el] || 0) + 1;
- }
- for(let key in populatedObj) {
- if(populatedObj[key] == 1) {
- result.push(key);
- }
- }
- return result;
- }
- /* Searching Algorithms
- * LinearSearch
- * BinarySearch
- */
- // Linear Search
- function LinearSearch(arr, num) {
- for(let i = 0; i < arr.length; i++) {
- if(arr[i] == num) {
- return i;
- }
- }
- return -1;
- }
- // Binary Search
- function BinarySearch(arr, num) {
- let start = 0;
- let end = arr.length - 1;
- let middle = Math.floor((start + end) / 2);
- while(num != arr[middle] && start <= end) {
- if(num > arr[middle]) {
- start = middle + 1;
- } else {
- end = middle - 1;
- }
- middle = Math.floor((start + end) / 2);
- }
- return arr[middle] == num ? middle : -1;
- }
- /* Sorting
- * BubbleSort
- */
- // BubbleSort
- function BubbleSort(arr) {
- for(let i = 0; i < arr.length; i++) {
- for(let j = i + 1; j < arr.length; j++) {
- if(arr[i] > arr[j]) {
- let temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- }
- }
- }
- return arr;
- }
- // OptmisedBubbleSort
- function OptimisedBubbleSort(arr) {
- let noSwaps;
- for(let i = 0; i < arr.length; i++) {
- noSwaps = true
- for(let j = i + 1; j < arr.length; j++) {
- if(arr[i] > arr[j]) {
- let temp = arr[i];
- arr[i] = arr[j];
- arr[j] = temp;
- noSwaps = false;
- }
- }
- if(noSwaps) break;
- }
- return arr;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement