This question already has answers here:
Algorithm to return all combinations of k elements from n
(77 answers)
Closed 7 years ago.
I need to be able to take a list of strings, and come up with a list of all possible combinations of those strings combined.
["asdf", "ghj","ew","ptum"]
It should get a list something like this, up to n
["agep", "aget", "ageu", ... "fjwm"]
What would I do to get these?
What you are asking is relatively trivial... some for loops can do this fairly easily. Below is one such method you could use.
var input = ["asdf", "ghj", "ew", "ptum"];
function combinations(r, n) {
var o = [];
if (r.constructor.name === "String")
r = r.split("");
if (n.constructor.name === "String")
n = n.split("");
r.forEach(function(i) {
n.forEach(function(j) {
o.push(i + j);
})
})
return o;
}
document.write("<pre>"+JSON.stringify(input.reduce(combinations),null,2)+"</pre>");
You can create an array of letters from the list of strings , like in your case ->
list of strings :
list = ["asdf", "ghj","ew","ptum"]
array of letters would be :-
arr = ["a","s",...,"m"]
then iterate through the array, for each letter make combination with other letters in array ...
the logic will be like this...
//for strings of length 3 ..
for(i in arr){
for(j in arr){
for(k in arr){
if(i!=j && j!=k)
result=i+j+k
}
}
}
p.s I am not into JS , I just told one logic to do this , you can now implent the logic in your language.
Related
This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Closed 2 years ago.
I have an array which looks like this
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"]
As you can see, each element in the array has #n associated with it where n is any number between 0-9. Now based on the n, I want to sort by array in ascending order such that the final output looks like this
[ '#0abc', '#0pol kol', '#1loa', '#2egf', '#2ko pol' ]
So this is what I do
rankWordMap = {}
finalArr = []
arr.forEach(function(entry) {
rank = entry.charAt(1)
if(rankWordMap[rank]) {
rankWordMap[rank].push(entry);
}
else {
rankWordMap[rank] = [entry];
}
})
for (var key in rankWordMap) {
if (rankWordMap.hasOwnProperty(key)) {
finalArr.push(...rankWordMap[key])
}
}
console.log(finalArr)
I get the expected output but as you can see, it's pretty inefficient. Besides I could have hundreds of elements sometimes where I would like to quickly sort it rather than doing it this way.
Is there any shorter way to implement this? I am specifically looking for a regex solution but other solutions are fine too.
No need for regex, just sort based on the integer value of the second character in each entry:
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
arr.sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
console.log(arr);
You could match the first coming digits and take this value for sorting.
var
getValue = string => string.match(/\d+/),
array = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
array.sort((a, b) => getValue(a) - getValue(b));
console.log(array);
I'm very new to javascript and I'm trying to create a function that takes a mixed input of numbers and then loops through the array in order to sort them into two newer arrays so I can manipulate them further.
So if I have an input of
1,a,2,b,3,c,4,d,
I want to make two new arrays of
1,2,3,4 and a,b,c,d
So far I've been able to split the input string at the comma, so that I now have
1a2b3c4d
all I need to be able to do now is just separate the numbers and non-numbers. I was thinking of using two loops: one that checks
if(isNan.array[n] == True )
and then trying to find a way to store the letters into a variable using the loop and then using another loop to do so for the numbers using another if function.
Is this how I should do it, and do you have any advice on how to go about it?
Edit:
I now have this code to check for letters:
if (isNaN(splitResult[L])) {
for (i = 0; i < splitResult; i++) {
letterArray.add(splitResult[L]);
L = L + 1
When I try to output the results to a box to count letters (using the variable L), nothing shows up. I doubt I've made a new array
just for completion, split the string into array first :)
let yourString = '1a2b3c4d';
let yourArray = yourString.split('');
let letterArray = [];
let numberArray = [];
yourArray.forEach(item => {
if(isNaN(item) && typeof item === 'string'){
letterArray.push(item);
}
else if(!isNaN(item) {
numberArray.push(item);
}
});
console.log(letterArray, numberArray);
All you need to do is loop through the array, you can use the Array prototypes forEach. Or you can use the normal for loop to check through each element of the array. You can now check if each element isNaN and then push into the right array appropriately. You can use the snippet below
const yourArray = ['1','a','2','b','3','c','4','d'];
const letterArray = [];
const numberArray = [];
yourArray.forEach((eachItem) => {
if(isNaN(eachItem)){
letterArray.push(eachItem);
} else {
numberArray.push(eachItem);
}
});
console.log(letterArray, numberArray);
This question already has answers here:
Remove items from one array if not in the second array
(5 answers)
Closed 7 years ago.
Good day,
I have two arrays of strings. Strings are just numeric dates (eg: "01/01/2016"...).
I would like to know if there is a good/fast way to compare the two arrays and remove the strings from one array, which are not present in second one.
Example:
First array: ["01/01/2016","02/02/2015", "03/03/2014"]
Second array: ["01/01/2016", "02/02/2015"]
The string "03/03/2014" should be removed from the first array.
I have tried doing it though for() loops of both array lengths, but it seems to be very slow, because the arrays are big (abt. 1000+) indexes in each, like this:
for (var a = 0; a < oilDateArray.length; a++) {
for (var b = 0; b < fuelDateArray.length; b++) {
if (fuelDateArray[b] !== oilDateArray[a]) {
console.log("fuelDateArray not present: " + fuelDateArray[b]);
}
}
}
Is there a specific function/method, which I could use in order to perform the above operation faster?
Thanks in advance and have a nice day!
Try this :
for (var i = 0; i < firstArray.length; i++){
if (secondArray.indexOf(firstArray[i]) == -1){ // indexOf is -1 if not found
firstArray.splice(i, 1); // Remove 1 value at index i
i--; // To re-adjust the index value which is 1 less because of the splice
}
}
It may also be a bit slow, you can try with your array : https://jsfiddle.net/tyrsszaw/4
with jquery
$(array1).filter(array2);
If you have access to Set:
function intersect(arr1, arr2){
var s = new Set(arr1);
return arr2.filter(function(el){
return s.has(el);
});
}
i use jquery for array operations and i'll edit one for your need and paste here, i hope this can help you:
var arr1 = ["01/01/2016","02/02/2015", "03/03/2014"];
var arr2 = ["01/01/2016", "02/02/2015"];
var diff = [];
jQuery.grep(arr2, function(t) {
if (jQuery.inArray(t, arr1) == -1) diff.push(t);
});
alert(diff); // what was different will be alerted
i also found this code on stackoverflow sometime ago.
Update: Here is performance related topic you might be interested
Performance of jQuery.grep vs. Array.filter
tldr;
it says grep is about 3 times faster. So stick with my solution. :)
I want to save all combinations of an array. So for
[a, b, c] I want to save
[ab, ac, ba, bc, ca, cb]
I currently use this method:
for (coordinate in coordinates){
for (coordinate2 in coordinates){
if (coordinate != coordinate2){
newposts.push([fbposts[fbpost].id, coordinates[coordinate], coordinates[coordinate2]]);
}
}
}
but it generates a bunch of duplicates. What's the smoothest way to solve this?
You could use a modified bubble sort algorithm:
var result = [],
arr = 'abc'.split('');
// begin the bubble sort loop
for(var i=0,l=arr.length;i<l-1;i++)
for(var j=i+1;j<l;j++)
{
result.push(arr[i]+arr[j]);
result.push(arr[j]+arr[i]);
}
console.log(result); //["ab", "ba", "ac", "ca", "bc", "cb"]
By looping over the array in this way, you do not even need to check if the result is a duplicate, because it doesn't generate any.
Btw, don't use the for..in synthax for looping over arrays because it may have unexpected results.
Add a check before adding to your new array either by custom function or perhaps
array.indexOf(...)
Custom function similar to how jQuery does it:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
So as you are building your new array of permutations/combinations (been 13+ years since my last stats class), perform a quick check and don't add if true, otherwise add. I believe if you perform an array merge it'll do similar so same performance.
You could take advantage of the fact that you can define a property only once and have something like this:
$(function() {
var arr = ["a","b","c"];
var permutations ={};
$.each(arr, function(index1, val1)
{
$.each(arr, function(index2, val2)
{
permutations[val1+val2] = 0;
});
});
for(var prop in permutations)
{
//in prop you will have your elements: aa,ab...
}
});
permutations would play the role of a dictionary in this case
The logic of generating the combinations is sub optimal as the run time is n square - see this questions for algorithms of generating combinations of k elements out of an n elements array
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?