Related
Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.
Input: s1 = 'abcd', s2 = 'aad'
Output: 2
Input: s1 = 'geeksforgeeks', s2 = 'platformforgeeks'
Output: 8
I tried to like this:
function getSameCount(str, str2) {
var o = {},
o2 = {};
for (var i = 0; i < str.length - 1; i++) {
if (str[i] in o) {
o[str[i]] = parseInt(o[str[i]] + 1)
} else {
o[str[i]] = 0
}
}
console.log(o);
for (var i = 0; i < str2.length - 1; i++) {
if (str[i] in o2) {
o2[str[i]] = parseInt(o2[str[i]] + 1)
} else {
o2[str[i]] = 0
}
}
console.log(o2);
}
getSameCount('abcd', 'aad')
Use for..in loop and includes method
var s1 = "abcd";
var s2 = "aad";
function match(s1, s2) {
var count = 0;
for(let i in s1) {
s2.includes(s1[i]) ? count++ : false;
}
return count;
}
console.log(match(s1,s2));
We can convert the second input string to an array, then the next step is to iterate over the first input string and find a match in the second input string's character array.
If a match is found, increment the counter and remove that character from the second input string's character array so that it is not considered in the next match:
//Solution:
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;
}
//Test:
console.log(getSameCount("abcd", "aad"));
console.log(getSameCount("geeksforgeeks", "platformforgeeks"));
console.log(getSameCount("aad", "abcd"));
console.log(getSameCount("platformforgeeks", "geeksforgeeks"));
You can create a custom method on the array and find the number of characters which are common in all the words. Below steps are list of procedure to find the common characters in all the string
Create a prototype method on Array , findCommonWord in this case.
This method accepts an array of string, so input will be like
[ "abcd", "aad","geeksforgeeksda","platdformforgeeks"].findCommonWord()
First step is to modify the input, to remove duplicate characters from a string using Set then sort it by ascending order of the length of string. This is because number of loop will be least if we have to find common character , that also have to present in string with least length.
Then create a new array with out the first string and split the first string. split will create a new array and iterate over it and check if this character is present in rest of the string.
var s1 = "abcd",
s2 = "aad",
s3 = "geeksforgeeksda",
s4 = "platdformforgeeks";
Array.prototype.findCommonWord = function() {
let tempArray = this.map(function(item) {
return [...new Set(item.split(''))].join('');
}).sort(function(a, b) {
return a.length - b.length
})
let count = 0;
let firstElm = tempArray[0].split('');
let restElem = tempArray.splice(1);
let countObject = {}
for (let i = 0; i < firstElm.length; i++) {
let z = findIfIncludes(restElem, firstElm[i]);
if (z.length === restElem.length) {
countObject[firstElm[i]] = 1;
} else {
countObject[firstElm[i]] = 0
}
}
function findIfIncludes(arr, char) {
return arr.filter(item => item.includes(char))
}
console.log(countObject)
let totalCount = 0;
for (let keys in countObject) {
if (countObject[keys] > 0) {
totalCount += 1;
}
}
return totalCount;
};
console.log([s1, s2, s3, s4].findCommonWord());
function numberOfSameChars(s1, s2) {
let obj = {};
let counter = 0;
for (let i=0; i<s1.length; i++){
if(s1[i] in obj) {
obj[s1[i]]++;
} else {
obj[s1[i]] = 1;
}
}
for (let i=0; i<s2.length; i++) {
if(s2[i] in obj && obj[s2[i]] > 0) {
obj[s2[i]]--;
counter++;
}
}
return counter;
}
Try this code:
function countMatch(s1,s2){
var count = 0;
while(s1.length && s2.length){
if(s2.includes(s1.charAt(0))){
count++;
s2 = s2.replace(s1.charAt(0),"");
s1 = s1.slice(1);
}
else {
s1 = s1.slice(1);
}
}
return count;
}
console.log(countMatch("abcd","aad"));
//2
I used objects to do this, and I was kind of curious about there being another way, as I wanted to take an algorithmic approach as well, but whatever works works.
Anyways, here's the code:
function commonCharacterCount(s1, s2) {
let string1Counter = {};
let string2Counter = {};
let commonCount = 0;
for(let i = 0; i < s1.length; i++){
if(!string1Counter.hasOwnProperty(s1[i])){
string1Counter[s1[i]] = 0;
}
string1Counter[s1[i]]++;
}
for(let i = 0; i < s2.length; i++){
if(!string2Counter.hasOwnProperty(s2[i])){
string2Counter[s2[i]] = 0;
}
string2Counter[s2[i]]++;
}
for(let key in string1Counter){
if(string2Counter.hasOwnProperty(key)){
if(string1Counter[key] < string2Counter[key]){
commonCount += string1Counter[key];
}
else{
commonCount += string2Counter[key];
}
}
}
return commonCount;
}
The logic is basically to just save all of the characters of each string and their count,check for similarities, and compare the count of common characters. Whichever has the fewer amount of common characters will be the amount shared by both.
O(3N) time complexity, O(2N) space complexity (because of the stored objects).
I guess I can also do "delete object" but seems redundant on just an algorithm IDE because it's not like it's running on a server for any extended period of time.
function commonSameCount(s1, s2) {
var s1Array = s1.split("");
var s2Array = s2.split("");
var count = 0;
let index = 0;
s1Array.filter(s1 => {
index = s2Array.findIndex(s2 => s2 == s1);
if(index >= 0){
count++;
s2Array.splice(index, 1);
}
});
return count;
}
A simple solution using Regex:
index.js
function getSameCount(s1,s2) {
for (let i in s2) {
s1 = s1.replace(s2[i], "1")
}
const result = s1.replace(/[^1]/g, '').length
return result
}
Let's say I'm writing a function like so:
function longestString (someArray) {
// code
}
If someArray = ['word','longer phrase',['a','b','c'],1234567891011121314151617], I would want the function to only return the longest string in the array and ignore the integers and other arrays that may also lie within it. I tried this:
function longestString (someArray) {
return someArray.sort(function (a, b) { return b.length - a.length; })[0];
}
It didn't work, and I am now stuck. :/
Filter only string element and do it
function longestString (someArray) {
return someArray
.filter(function(a){ return typeof(a)=='string' })
.sort(function (a, b) { return b.length - a.length; })[0];
}
Try this:
function longestString(someArray) {
var result = "";
for (var i = 0; i < someArray.length; i++) {
if ((typeof someArray[i] === "string") && (someArray[i].length > result.length)) {
result = someArray[i];
}
}
return result;
}
try to do :
function longestString (someArray) {
$longest_string = '';
foreach ($someArray as $value)
{
$current_length = strlen($longest_string);
if(strlen($value) > $current_length ) $longest_string = $value;
}
return $longest_string;
}
Try this.
var a = ['word', 'longer phrase', ['a', 'b', 'c'], 1234567891011121314151617];
returnLongestString(a);
function returnLongestString(arr) {
var longestString = '';
for (var i = 0; i < arr.length; i++) {
if (typeof arr[i] == "string" && arr[i].length > longestString.length) {
longestString = arr[i];
}
};
return longestString;
}
When I saw this question, it had 0 answers, when I finished writing and testing my function, there were five. But this is my approach:
The key here is to first filter only the strings. Then, list all the lengths on an array. Then using that array you can get a match on the bigger one.
function longestString (someArray) {
//we only need strings, so first we will filter all the data
var stringsOnly = [];
for (var i = 0; i < someArray.length; i++) {
if(typeof(someArray[i]) === 'string'){
stringsOnly.push(someArray[i]);
}
};
//Now with an array of just strings, we can get their indivial lenghts
var stringLengths = [];
for (var i = 0; i < stringsOnly.length; i++) {
var currentString = stringsOnly[i];
stringLengths.push(currentString.length);
};
//Get the max length
var maxLength = Math.max.apply(Math,stringLengths);
//get a string wich length equals to maxLength
for (var i = 0; i < stringsOnly.length; i++) {
var theString = stringsOnly[i];
if(theString.length === maxLength){return theString};
};
}
This function will return the largest string. If more than one string have the same length, It will return the first one. However, if you want to get various strings, you could make some little modificationson the function above:
function multipleLongestString (someArray) {
//we only need strings, so first we will filter all the data
var stringsOnly = [];
for (var i = 0; i < someArray.length; i++) {
if(typeof(someArray[i]) === 'string'){
stringsOnly.push(someArray[i]);
}
};
//Now with an array of just strings, we can get their indivial lenghts
var stringLengths = [];
for (var i = 0; i < stringsOnly.length; i++) {
var currentString = stringsOnly[i];
stringLengths.push(currentString.length);
};
//Get the max length
var maxLength = Math.max.apply(Math,stringLengths);
//modification here
longests = [];
//get a string wich length equals to maxLength
for (var i = 0; i < stringsOnly.length; i++) {
var theString = stringsOnly[i];
if(theString.length === maxLength){longests.push(theString)};
};
return longests;
}
That is an extra that may help you later. But if you just want the largest one, use the first function. I hope that my answer is relevant.
:)
Heres my approach at it. Really all you want to know is if the phrase is longer than the previous and if its a string.
jsFiddle here.
var someArray = ['word','longer phrase',['a','b','c'],1234567891011121314151617]
var longestString = function(arr) {
var longest = "";
for (var i = 0; i < arr.length; i++) {
var value = arr[i];
if (typeof value === "string") {
longest = arr[i];
}
}
alert(longest);
}
longestString(someArray);
I want to store some strings and check, if strings from textarea are equal to stored one.
I decided to start with arrays.
var string = "something like this happens everyday in my life";
var array1 = [
"thing",
"something"
];
var array2 = [
"happens",
"life"
];
I got it how it works with one word strings:
if(string.search(array1) != -1) {
console.log("array1");
}
if(!!~jQuery.inArray(string.search, array1)) {
console.log("array1");
}
But what i need is to compare every item of this sentence to my arrays and get every match. Even if there is several matches in one array.
Please help.
The easiest way to check whether a string contains a given substring is with .indexOf.
var s = "Hello, how are you today? Is everything alright?"
// if you want the search to be case insensitive:
// s = s.toLowerCase();
var myWords = ["how", "everything"];
for (var i = 0; i < myWords.length; i++) {
var pos = s.indexOf(myWords[i]);
if (pos == -1) {
console.log("word", myWords[i], "not found.");
} else {
console.log("word", myWords[i], "found at position", i);
}
}
If you want to store all the matches, you could have a
var matches = [];
and, under the else block, have matches.push(myWords[i]);
If you need to support ≤IE8, then you can use the following function to search for a substring within a string:
var getPosition = function (s, word) {
var len = s.length,
wlen = word.length;
for (var i = 0; i < len - wlen + 1; i++) {
if (s[i] == word[0] && s.slice(i, i + wlen) == word)
return i;
}
return -1;
}
This can be useful, if you don't want to load an external library, i.e., jQuery or Polyfill, just for indexOf.
For now i ended up using this for every array i have. I Ctrl C/V this 10 times, for every
for (var i = 0; i < array.length; i++) {
for (var i = 0; i < states.length; i++) {
var pos = text.indexOf(states[i]);
if (pos == -1) {
console.log("word", states[i], "not found.");
} else {
$( '#log').append( "~STATE~" + "<br>");
}
}
I have different kind of javascript objects, they all have a property 'row'.
var row1 = {
row: 1
};
var row2 = {
row: 2
};
var row3 = {
row: 3
};
var row4 = {
row: 4
};
...
I have an array defined as follow:
var objArray = [];
In this array it's possible to have multiple 'rows'. The sequence is always te same starting from the lower row to a higher row.
Now I want to get the objects that are linked next to each other (like 4 in a row). In my case it's also possible to have 3 in a row, 5 in a row and so on..
Example:
objArray.push(row0);
objArray.push(row1);
objArray.push(row2);
objArray.push(row3);
objArray.push(row5);
objArray.push(row6);
objArray.push(row7);
objArray.push(row9);
objArray.push(row10);
objArray.push(row12);
In this case I need 2 lists, 1 containing row0 to 3 and one containing 5 to 7.
I've tried a bit in this JSFiddle: Here we can see the console output
If you need more clarification, please ask.
Thanks in advance!
I made a fiddle that does just this for you:
for(var i = 0; i < objArray.length; i++) {
if(currentnum !== -1)
{
var result = objArray[i].row - currentnum;
currentnum = objArray[i].row;
if(result === 1)
{
currentarray.push(objArray[i]);
} else {
arrayofarrays.push(currentarray);
currentarray = [];
currentarray.push(objArray[i]);
}
} else {
currentnum = objArray[i].row;
currentarray.push(objArray[i]);
}
}
arrayofarrays.push(currentarray);
http://jsfiddle.net/B76a8/6/
Since you have already figured how to keep the counter and reset it for each new group you can do
var counter = 1,
lastIndex = 0;
//see chrome dev tools, I need to return objects beginning at the 3rd place untill the 7th place in the array
//how do I get these objects?
for (var i = 0; i < objArray.length; i++) {
if ((i < objArray.length - 1 && objArray[i].row + 1 == objArray[i + 1].row) ||
(i == objArray.length - 1 && objArray[i - 1].row == objArray[i].row - 1)) {
counter++;
} else {
// here we output the grouped items
console.log(objArray.slice(lastIndex, counter+lastIndex));
lastIndex = counter+lastIndex;
counter = 1;
}
}
Demo at http://jsfiddle.net/B76a8/7/
output
[Object { row=0}, Object { row=1}]
[Object { row=3}, Object { row=4}, Object { row=5}, Object { row=6}, Object { row=7}, Object { row=8}]
[Object { row=10}]
First, let's sort the array:
objArray.sort(function(a,b){ return a.row - b.row });
Then, for the given n, this should return you next and previous elements:
function getElement(array, n)
{
var ret = [];
for (var i=0; i<array.length; i++)
if (array[i].row == n)
{
if (i > 0) ret.push(array[i-1]);
if (i < array.length-1) ret.push(array[i+1]);
}
return ret;
}
As getting all the other options with the same color is a different thing let's do it through:
function getByColor(array, color)
{
var ret = [];
for (var i=0; i<array.length; i++)
if (array[i].color == color)
ret.push(array[i]);
return ret;
}
Then you can merge both of the arrays by using concat
Here is one to get your brain going! I've not had any luck with it.
[1,2,1,1,2,1,1,1,2,2]
[1,2,1,1,2,1]
I would like to use the second array to find the values in the first, but they must be in the same order.
Once for I would like it to return the next key up from the last key in the second array.
So in this example it would use the first six digits in the first array and then return 6 as the key after the final one in the second array.
var a2 = [1,2,1,1,2,1,1,1,2,2]
var a1 = [1,2,1,1,0,1]
function find(arr1, arr2) {
var len = 1
var result = 0;
var s2 = arr2.toString();
for (len=1;len <= a1.length; len++)
{
var aa1 = arr1.slice(0, len)
var s1 = aa1.toString();
if(s2.indexOf(s1)>=0){
result = aa1.length;
}
else {
break;
}
}
return result;
}
alert(find(a1, a2));
var find = function(haystack, needle) {
var doesMatch = function(offset) {
for (var i = 0; i < needle.length; i++) {
if (haystack[i+offset] !== needle[i]) {
return false;
}
}
return true;
};
for (var j=0; j < haystack.length - needle.length; j++) {
if (doesMatch(j)) {
return j;
}
}
return -1;
};
This is quick, this is dirty, and this is correct only if your data doesn't include any comma.
var needle = [1,2,1,1,2,1];
var haystack = [1,2,1,1,2,1,1,1,2,2];
if ( needle.length <= 0 ) return 0;
var fromStr = ','+haystack.toString()+','
var findStr = ','+needle.toString()+','
// Find ',1,2,1,1,2,1,' in ',1,2,1,1,2,1,1,1,2,2,'
var pos = fromStr.indexOf(findStr);
// Count the end position requested
return pos >= 0 ? fromStr.slice(0,pos+1).match(/,/g).length + needle.length - 1 : -1;
Note: The comma at head and tail is to make sure [22,12] doesn't match [2,1].