Anagram with JavaScript - javascript

const myAnagram = (arr1, arr2) => {
let str1 = arr1;
let str2 = arr2;
let temp1 = [];
let temp2 = [];
let flag = 0;
if (str1.length !== str2.length) return "Not Anagram statement A";
for (var i = 0; i < str1.length - 1; i++) {
temp1[i] = str1[i];
}
for (var j = 0; j < str2.length - 1; j++) {
temp2[i] = str2[i];
}
temp1.sort();
temp2.sort();
for (var k = 0; k < str1.length - 1; k++) {
if (temp1[j] !== temp2[j]) return "Not Anagram statement C";
return "Anagram! statement D";
}
}

The problem you have is with the identifiers you have used in loops.
Have a look at the corrected code.
function myAnagram(arr1, arr2) {
var str1 = arr1;
var str2 = arr2;
var temp1 = [];
var temp2 = [];
var flag = 0;
if (str1.length !== str2.length) {
return "Not Anagram statement A";
} else {
for (var i = 0; i < str1.length; i++) {
temp1[i] = str1[i];
}
for (var j = 0; j < str2.length; j++) {
temp2[j] = str2[j];
}
temp1.sort();
temp2.sort();
for (var k = 0; k < str1.length; k++) {
if (temp1[k] !== temp2[k]) {
return "Not Anagram statement C";
} else {
return "Anagram! statement D";
}
}
}
}
Hope it helps !!
PS: You can optimize this code to a great extend.

find two strings are equal size
compare the characters and the count of characters matches
const isAnagram = (str1, str2) => {
const compare = (first, next) => {
return first.split('').sort().join('') === next.split('').sort().join('');
}
return str1.length !== str2.length ? false : compare(str1, str2);
}

Your loops always skip the last elements since you use < together with str1.length - 1. You should either use for (var i = 0; i < str1.length; ++i) {...} or for (var i = 0; i <= str.length-1; ++i) {...}
Furthermore in your comparison loop you already return when the first characters match (or when they don't). Therefore the loop will never compare the second (or nth) characters. The loop should further compare the characters until you are sure the arrays differ at some point.
You can shrink the function like
function isAnagram(str1, str2) {
if (str1.length !== str2.length) return false
var arr1 = arr2 = []
for (var i = 0; i < str1.length; ++i) {
arr1[i] = str1[i]
arr2[i] = str2[i]
}
arr1.sort()
arr2.sort()
for (var i = 0; i < arr1.length; ++i)
if (arr1[i] !== arr2[i]) return false
return true
}
And then
if (isAnagram("frog","rg0f")) {
console.log("Anagram!")
} else {
console.log("Not Anagram.")
}

Related

how to get the count value based on comparing string in javascript

I have array object in which I compare each string in a array and if one letter is not matching, increment the value. If three characters match with the string then increment the count value, else 0
var obj = ["race", "sack", "grass", "brass", "beat", "pack", "cake"]
fucntion getValue(obj) {
var count = 0
for (var i = 0; i <= obj.length; i++) {
for (var j = 1; j <= obj.length; j++) {
if (obj[i].split("") == obj[j].split("") {
count++;
}
}
}
}
Expected Output
race 1
sack 2 // (pack, cake matches 3 letters with sack so 2)
grass 1
brass 1
beat 0
pack 2
cake 3
function getSameCount(str1, str2) {
let count = 0;
const obj = str2.split("");
for(str of str1){
let idx = obj.findIndex(s => s === str);
if(idx >= 0){
count++;
obj.splice(idx, 1);
}
}
return count;
}
var obj = ["race", "sack", "grass", "brass", "beat", "pack", "cake"]
const res = {}
for (var i = 0; i < obj.length; i++) {
res[obj[i]] = 0
for (var j = 0; j < obj.length; j++) {
if (i != j) {
matchCount = getSameCount(obj[i], obj[j])
if (matchCount === 3) {
res[obj[i]]++
} else {
if (obj[i].length - matchCount == 1) {
res[obj[i]]++
}
}
}
}
}
console.log(res)
You can create an object for output,
parse through each element in the array, replace characters from comparing elements.
check if at least 3 chars got removed if so +1 to respective element.
const arr = ["race", "sack", "grass", "brass", "beat", "pack", "cake"];
const out = Object.fromEntries(arr.map(e => [e, 0]));
for(i in arr) {
for(j in arr) {
if(i == j) continue;
if(arr[i].length !== arr[j].length) continue;
const res = [...arr[i]].reduce((acc, e)=> acc.replace(e, ''), arr[j]);
if(res.length <= arr[j].length - 3) {
out[arr[i]] = out[arr[i]] + 1
}
}
}
console.log(out);

JavaScript Function Insertion Sorting/ Function undefined

I am attempting to write a javascript file that has a insertion sort function, a function to check a sorted array and return true or false, and an insertion sort function that works from the end of the array index to the beginning.
Here is the code i have
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
}
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} }
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
//function sortCheck(arr) {
//for( var i = 0 ; i < arr.length; i++){
// if(arr[i]>rr[i+1]){
// return false
// }
//}
//return true}
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
The issue I am having right now is that sortedArr is undefined when output with console.log, it appears that the issue is that my function is "undefined" but seeing how i define it above, i dont understand how that is.
Your insertionSort function doesn't return a value, it modifies the array passed as an argument. Instead of var sortedArr = insertionSort(arr), just call insertionSort(arr) and then do console.log(arr).
You have to return arr from the function. It is not returning anything that's why you are getting undefined
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i]; var j; for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1]; } arr[j] = val; }
return arr; }
function reverseInsertionSort(arr) {
for(var i = arr.length; i >1; i--)
{ var val = arr[i]; var j;
for(j = i; j > 0 && arr[j-1] > val; j--)
{ arr[j] = arr[j-1]; } arr[j] = val;
} return arr}
var length = Math.floor(Math.random()*100)+1;
var arr = new Array();
for(let i = 0; i < length; i++) {
arr.push(Math.floor(Math.random()*10000)+1);
}
console.log(arr);
var sortedArr = insertionSort(arr);
console.log(sortedArr);
console.log("And with reverse \n");
var reverseSortedArr = reverseInsertionSort(arr);
console.log(reverseSortedArr);
//console.log(sortCheck(sortedArr));
Make sure you return the array from the function(s). Since you currently are not, assigning the function to a variable would not yield any particular value.
function insertionSort(arr) {
for(var i = 1; i < arr.length; i++) {
var val = arr[i];
var j;
for(j = i; j > 0 && arr[j-1] > val; j--) {
arr[j] = arr[j-1];
}
arr[j] = val;
}
return arr
}

Search words in array based on few words

Hi I have a problem how to search for words containing at least part of a word. What I mean words that have word I find in array javascript without built-in function except only PUSH.
This task requires no index.of, slice, substr, substring, regex etc. Only PUSH
This my code so far:
function wordsChecker(sentences, search) {
var result = []
for (var i = 0; i < sentences.length; i++) {
var isCheck = false
for (var j = 0; j < sentences.length; j++) {
for (var k = 0; k < search.length; k++) {
if (sentences[i][j] == search[k]) {
isCheck = true
}
}
}
if (isCheck == true) {
result.push(sentences[i])
}
}
return result
}
console.log(wordsChecker(['broom, room, rox, show room, stroom, root, rote, brother'], 'roo'))
//expected output : [broom, room, show room, stroom, root]
Thanks in advance
At the first you should make correct array. I hope this code work for you
function wordsChecker(sentences, search) {
var result = [], k = 0;
for (var i = 0; i < sentences.length; i++) {
var isCheck = false;
for (var j = 0; j < sentences[i].length; j++) {
while (k < search.length) {
if (sentences[i][j] == search[k]) {
isCheck = true;
k++;
break;
}
else {
isCheck = false;
k = 0;
break;
}
}
}
if (isCheck === true && k === search.length) {
result.push(sentences[i]);
k = 0;
}
}
return result;
}
console.log(wordsChecker(['broom', 'room', 'rox', 'show room', 'stroom', 'root', 'rote', 'brother'], 'roo'));

Find the index of the sub-array that does not contain a number

var array = [[2,3,4],[4,5,6],[2,3,9],[7,8,1]];
var number = 3;
If I have this nested array and this variable how do I return the index of the sub-arrays where the number is present. So the final result should be 1 and 3.
Try:
array.reduce((acc, subArr, i) => {
if (!subArr.includes(number)) {
acc.push(i);
}
return acc;
}, [])
The solution using Array.prototype.forEach() and Array.prototype.indexOf() functions:
var arr = [[2,3,4],[4,5,6],[2,3,9],[7,8,1]],
number = 3,
result = [];
arr.forEach(function(v,i){
if (v.indexOf(number) === -1) result.push(i);
});
console.log(result);
function X(a){
var r = [];
for(var i = o ; i < a.length; i++)
for(var j = o ; j < a[i].length; i++)
if(a[i][j] === number)
r.push(i);
return r;
}
i think this should do it. i have just written it here so might have some syntax errors
Since the question is super inconsistent, if you want the index of the subarrays that do have the number, do this:
var foundIndices = [];
for(var y = 0;y < array.length; y++) {
for(var x = 0;x < array[y].length; x++) {
if(array[y][x] == number) {
foundIndices[foundIndices.length] = y;
}
}
}
Otherwise, do this:
var foundIndices = [];
var found = false;
for(var y = 0;y < array.length; y++) {
found = false;
for(var x = 0;x < array[y].length; x++) {
if(array[y][x] == number) {
found = true;
}
}
if(found == false) {
foundIndices[foundIndices.length] = y;
}
}

Get all substrings of a string in JavaScript

I have the following function to get all of the substrings from a string in JavaScript. I know it's not correct but I feel like I am going about it the right way. Any advice would be great.
var theString = 'somerandomword',
allSubstrings = [];
getAllSubstrings(theString);
function getAllSubstrings(str) {
var start = 1;
for ( var i = 0; i < str.length; i++ ) {
allSubstrings.push( str.substring(start,i) );
}
}
console.log(allSubstrings)
Edit: Apologies if my question is unclear. By substring I mean all combinations of letters from the string (do not have to be actual words) So if the string was 'abc' you could have [a, ab, abc, b, ba, bac etc...] Thank you for all the responses.
You need two nested loop for the sub strings.
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString));
.as-console-wrapper { max-height: 100% !important; top: 0; }
A modified version of Accepted Answer. In order to give the minimum string length for permutation
function getAllSubstrings(str, size) {
var i, j, result = [];
size = (size || 0);
for (i = 0; i < str.length; i++) {
for (j = str.length; j - i >= size; j--) {
result.push(str.slice(i, j));
}
}
return result;
}
var theString = 'somerandomword';
console.log(getAllSubstrings(theString, 6));
Below is a recursive solution to the problem
let result = [];
function subsetsOfString(str, curr = '', index = 0) {
if (index == str.length) {
result.push(curr);
return result;
}
subsetsOfString(str, curr, index + 1);
subsetsOfString(str, curr + str[index], index + 1);
}
subsetsOfString("somerandomword");
console.log(result);
An answer with the use of substring function.
function getAllSubstrings(str) {
var res = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j <= str.length; j++) {
res.push(str.substring(i, j));
}
}
return res;
}
var word = "randomword";
console.log(getAllSubstrings(word));
function generateALlSubstrings(N,str){
for(let i=0; i<N; i++){
for(let j=i+1; j<=N; j++){
console.log(str.substring(i, j));
}
}
}
Below is a simple approach to find all substrings
var arr = "abcde";
for(let i=0; i < arr.length; i++){
for(let j=i; j < arr.length; j++){
let bag ="";
for(let k=i; k<j; k++){
bag = bag + arr[k]
}
console.log(bag)
}
}
function getSubstrings(s){
//if string passed is null or undefined or empty string
if(!s) return [];
let substrings = [];
for(let length = 1 ; length <= s.length; length++){
for(let i = 0 ; (i + length) <= s.length ; i++){
substrings.push(s.substr(i, length));
}
}
return substrings;
}

Categories

Resources