get all variations of a string javascript - javascript

I want to get all the variations of a certain string. This string will be broken up by dashes. And the letters can only vary within those dashes.
For instance, let's say I pass DFI3-334-FG12 then I want to get all variations of that string for instance:
FI3-334-G12
FI3-334-F12
FI3-334-FG2
FI3-334-FG1
DI3-334-G12
DI3-334-F12
DI3-334-FG2
DI3-334-FG1
DF3-334-G12
DF3-334-F12
DF3-334-FG2
DF3-334-FG1
DFI-334-G12
DFI-334-F12
DFI-334-FG2
DFI-334-FG1
Can anyone assist with this? I have attempted loops but I only get as far as breaking it up and getting different parts of it:
FI3,DI3,DF3,DFI
334
G12,F12,FG2,FG1
This is my code:
$('#filter').on('click',function() {
var input = $('#code').val();
var parts = input.split("-");
var fixed = Array();
for(var i=0;i<parts.length; i++) {
if(parts[i].length != 3) {
k = 0;
fixed[i] = new Array();
for(var c=0;c<parts[i].length;c++) {
fixed[i][k] = parts[i].replace(parts[i].charAt(c),"");
k++;
}
} else {
fixed[i] = parts[i];
}
}
var final = Array();
$.each(fixed,function(i) {
$('#code_result').append(fixed[i] + "<br>");
})
});

If you know how many segments there are (3 in this case), you can use loops to get every possible combination.
See my example here:
http://jsfiddle.net/a6647m9e/1/
for(var i=0; i<parts[0].length; ++i) {
for(var j=0; j<parts[1].length; ++j) {
for(var k=0; k<parts[2].length; ++k) {
strings.push(parts[0][i]+'-'+parts[1][j]+'-'+parts[2][k]);
}
}
}
And just so you know, you're looking at (2^parts[0].length - 1) * (2^parts[1].length - 1) * (2^parts[2].length - 1) combinations (1575 in this case), taking out the blank combinations.
Note: this is all dependent on what your definition of "all possible combinations" is.

var string= 'DFI3-334-FG12';
var parts = string.split('-');
for(var i=0;i<parts[0].length;i++)
for(var j=0;j<parts[2].length;j++){
p1 = parts[0].substring(0,i)+parts[0].substring(i+1,parts[0].length);
p2 = parts[2].substring(0,j)+parts[2].substring(j+1,parts[2].length);
console.log(p1+'-'+parts[1]+'-'+p2);
}

Related

Perform a merge on two strings

I'm trying to build a collaborative doc editor and implement operational transformation. Imagine we have a string that is manipulated simultaneously by 2 users. They can only add characters, not remove them. We want to incorporate both of their changes.
The original string is: catspider
The first user does this: cat<span id>spider</span>
The second user does this: c<span id>atspi</span>der
I'm trying to write a function that will produce: c<span id>at<span id>spi</span>der</span>
The function I've written is close, but it produces c<span id>at<span i</span>d>spider</span> codepen here
String.prototype.splice = function(start, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start);
};
function merge(saved, working, requested) {
if (!saved || !working || !requested) {
return false;
}
var diffSavedWorking = createDiff(working, saved);
var diffRequestedWorking = createDiff(working, requested);
var newStr = working;
for (var i = 0; i < Math.max(diffRequestedWorking.length, diffSavedWorking.length); i++) {
//splice does an insert `before` -- we will assume that the saved document characters
//should always appear before the requested document characters in this merger operation
//so we first insert requested and then saved, which means that the final string will have the
//original characters first.
if (diffRequestedWorking[i]) {
newStr = newStr.splice(i, diffRequestedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffRequestedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
if (diffSavedWorking[i]) {
newStr = newStr.splice(i, diffSavedWorking[i]);
//we need to update the merge arrays by the number of
//inserted characters.
var length = diffSavedWorking[i].length;
insertNatX(diffSavedWorking, length, i + 1);
insertNatX(diffRequestedWorking, length, i + 1);
}
}
return newStr;
}
//arr1 should be the shorter array.
//returns inserted characters at their
//insertion index.
function createDiff(arr1, arr2) {
var diff = [];
var j = 0;
for (var i = 0; i < arr1.length; i++) {
diff[i] = "";
while (arr2[j] !== arr1[i]) {
diff[i] += arr2[j];
j++;
}
j++;
}
var remainder = arr2.substr(j);
if (remainder) diff[i] = remainder;
return diff;
}
function insertNatX(arr, length, pos) {
for (var j = 0; j < length; j++) {
arr.splice(pos, 0, "");
}
}
var saved = 'cat<span id>spider</span>';
var working = 'catspider';
var requested = 'c<span id>atspi</span>der';
console.log(merge(saved, working, requested));
Would appreciate any thoughts on a better / simpler way to achieve this.

"Look and say sequence" in javascript

1
11
12
1121
122111
112213
122211
....
I was trying to solve this problem. It goes like this.
I need to check the former line and write: the number and how many time it was repeated.
ex. 1 -> 1(number)1(time)
var antsArr = [[1]];
var n = 10;
for (var row = 1; row < n; row++) {
var lastCheckedNumber = 0;
var count = 1;
antsArr[row] = [];
for (var col = 0; col < antsArr[row-1].length; col++) {
if (lastCheckedNumber == 0) {
lastCheckedNumber = 1;
antsArr[row].push(lastCheckedNumber);
} else {
if (antsArr[row-1][col] == lastCheckedNumber) {
count++;
} else {
lastCheckedNumber = antsArr[row-1][col];
}
}
}
antsArr[row].push(count);
antsArr[row].push(lastCheckedNumber);
}
for (var i = 0; i < antsArr.length; i++) {
console.log(antsArr[i]);
}
I have been on this since 2 days ago.
It it so hard to solve by myself. I know it is really basic code to you guys.
But still if someone who has a really warm heart help me out, I will be so happy! :>
Try this:
JSFiddle Sample
function lookAndSay(seq){
var prev = seq[0];
var freq = 0;
var output = [];
seq.forEach(function(s){
if (s==prev){
freq++;
}
else{
output.push(prev);
output.push(freq);
prev = s;
freq = 1;
}
});
output.push(prev);
output.push(freq);
console.log(output);
return output;
}
// Sample: try on the first 11 sequences
var seq = [1];
for (var n=0; n<11; n++){
seq = lookAndSay(seq);
}
Quick explanation
The input sequence is a simple array containing all numbers in the sequence. The function iterates through the element in the sequence, count the frequency of the current occurring number. When it encounters a new number, it pushes the previously occurring number along with the frequency to the output.
Keep the iteration goes until it reaches the end, make sure the last occurring number and the frequency are added to the output and that's it.
I am not sure if this is right,as i didnt know about this sequence before.Please check and let me know if it works.
var hh=0;
function ls(j,j1)
{
var l1=j.length;
var fer=j.split('');
var str='';
var counter=1;
for(var t=0;t<fer.length;t++)
{
if(fer[t]==fer[t+1])
{
counter++;
}
else
{
str=str+""+""+fer[t]+counter;
counter=1;
}
}
console.log(str);
while(hh<5) //REPLACE THE NUMBER HERE TO CHANGE NUMBER OF COUNTS!
{
hh++;
//console.log(hh);
ls(str);
}
}
ls("1");
You can check out the working solution for in this fiddle here
You can solve this by splitting your logic into different modules.
So primarily you have 2 tasks -
For a give sequence of numbers(say [1,1,2]), you need to find the frequency distribution - something like - [1,2,2,1] which is the main logic.
Keep generating new distribution lists until a given number(say n).
So split them into 2 different functions and test them independently.
For task 1, code would look something like this -
/*
This takes an input [1,1,2] and return is freq - [1,2,2,1]
*/
function find_num_freq(arr){
var freq_list = [];
var val = arr[0];
var freq = 1;
for(i=1; i<arr.length; i++){
var curr_val = arr[i];
if(curr_val === val){
freq += 1;
}else{
//Add the values to the freq_list
freq_list.push([val, freq]);
val = curr_val;
freq = 1;
}
}
freq_list.push([val, freq]);
return freq_list;
}
For task 2, it keeps calling the above function for each line of results.
It's code would look something like this -
function look_n_say(n){
//Starting number
var seed = 1;
var antsArr = [[seed]];
for(var i = 0; i < n; i++){
var content = antsArr[i];
var freq_list = find_num_freq(content);
//freq_list give an array of [[ele, freq],[ele,freq]...]
//Flatten so that it's of the form - [ele,freq,ele,freq]
var freq_list_flat = flatten_list(freq_list);
antsArr.push(freq_list_flat);
}
return antsArr;
}
/**
This is used for flattening a list.
Eg - [[1],[1,1],[1,2]] => [1,1,1,1,2]
basically removes only first level nesting
**/
function flatten_list(li){
var flat_li = [];
li.forEach(
function(val){
for(ind in val){
flat_li.push(val[ind]);
}
}
);
return flat_li;
}
The output of this for the first 10 n values -
OUTPUT
n = 1:
[[1],[1,1]]
n = 2:
[[1],[1,1],[1,2]]
n = 3:
[[1],[1,1],[1,2],[1,1,2,1]]
n = 4:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1]]
n = 5:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3]]
n = 6:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1]]
n = 7:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1]]
n = 8:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3]]
n = 9:
[[1],[1,1],[1,2],[1,1,2,1],[1,2,2,1,1,1],[1,1,2,2,1,3],[1,2,2,2,1,1,3,1],[1,1,2,3,1,2,3,1,1,1],[1,2,2,1,3,1,1,1,2,1,3,1,1,3],[1,1,2,2,1,1,3,1,1,3,2,1,1,1,3,1,1,2,3,1]]

Generate Array Javascript

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z].
So it will look like that.
code0, code1 ..., codeA, codeB
The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.
If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.
Thank you.
For a-z using the ASCII table and the JavaScript fromCharCode() function:
var a = [];
for(var i=97; i<=122; i++)
{
a.push("code" + String.fromCharCode(i));
}
For 0-9:
var a = [];
for(var i=0; i<=9; i++)
{
a.push("code" + i);
}
I'm using the unicode hexcode to loop through the whole symbols from 0-z:
var arr = [];
for (var i = 0x30; i < 0x7b;i++){
// skip non word characters
// without regex, faster, but not as elegant:
// if(i==0x3a){i=0x41}
// if(i==0x5b){i=0x61}
char = String.fromCharCode(i);
while(!/\w/.test(char)){char = String.fromCharCode(i++)};
// generate your code
var res = "code"+char;
// use your result
arr.push(res);
}
console.log(arr);
Here goes your example.
Docs:
Unicode Table
for loop
fromCharCode
JS Array and it's methods
you can generate array in javascript by using following code.
var arr = [];
for (var i = 0; i < 5; i++) {
arr.push("code"+ i);
}
please refer following links.
https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array
http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp
a = [];
for(i = 48; i < 91; i++) {
if (i==58) i = 65
a.push("code" + String.fromCharCode(i));
}
alert(a.join(',')) // or cou can print to console of browser: console.log(a);

Multiple regex match in javascript

document.querySelectorAll("table[id^='Table']");
This code selects all tables with the id of Table. But i want to select tables with id of Table2 OR Table7 (or any other numbers). How to do this with regex?
Edit: jQuery is not applicable in my case.
function getTables(tableNumbers) { // Usage: getTables([2, 7]) will return the tables with the ID 'Table2' and 'Table7'. (You can add more numbers; [2,7,3,6])
var allTables = document.querySelectorAll("table[id^='Table']");
var tablesWeWant = [];
for (var i = 0; i < allTables.length; i++) {
if (allTables[i].id.match(/Table[0-9]/)) {
tablesWeWant.push(allTables[i]);
}
}
for (var i = 0; i < tablesWeWant.length; i++) {
if (!tableNumbers.contains(tablesWeWant[i].id.substr(id.length - 1))) {
tableNumbers.splice(i, 1);
}
}
return tablesWeWant;
}
This should return all tables with an ID matching the regex /Table[0-9]/ and ending with a digit contained in the variable tableNumbders.
DISCLAIMER: I'm not a regex expert.
EDIT:
After editing a few times the code above became a bit too long, so I rewrote it like this:
function getTables(tableNumbers) {
var tablesWeWant = [];
for (var i = 0; i < tableNumbers.length; i++) {
tablesWeWant.push(document.querySelector("#Table" + tableNumbers[i]));
}
return tablesWeWant;
}
The second approach works: http://jsfiddle.net/qQ7VT/1/

Javascript Random problem?

var swf=["1.swf","2.swf","3.swf"];
var i = Math.floor(Math.random()*swf.length);
alert(swf[i]); // swf[1] >> 2.swf
This case ,Random output One number.
How to Random output two different numbers ?
var swf = ['1.swf', '2.swf', '3.swf'],
// shuffle
swf = swf.sort(function () { return Math.floor(Math.random() * 3) - 1; });
// use swf[0]
// use swf[1]
Even though the above should work fine, for academical correctness and highest performance and compatibility, you may want to shuffle like this instead:
var n = swf.length;
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = swf[i];
swf[i] = swf[j];
swf[j] = tmp;
}
Credits to tvanfosson and Fisher/Yates. :)
You can use splice to remove the chosen element, then simply select another randomly. The following leaves the original array intact, but if that's not necessary you can use the original and omit the copy. Shown using a loop to demonstrate how to select an arbitrary number of times upto the size of the original array.
var swf=["1.swf","2.swf","3.swf"];
var elementsToChoose = 2;
var copy = swf.slice(0);
var chosen = [];
for (var j = 0; j < elementsToChoose && copy.length; ++j) {
var i = Math.floor(Math.random()*copy.length);
chosen.push( copy.splice(i,1) );
}
for (var j = 0, len = chosen.length; j < len; ++j) {
alert(chosen[j]);
}
I would prefer this way as the bounds are known (you are not getting a random number and comparing it what you already have. It could loop 1 or 1000 times).
var swf = ['1.swf', '2.swf', '3.swf'],
length = swf.length,
i = Math.floor(Math.random() * length);
firstRandom = swf[i];
// I originally used `delete` operator here. It doesn't remove the member, just
// set its value to `undefined`. Using `splice` is the correct way to do it.
swf.splice(i, 1);
length--;
var j = Math.floor(Math.random() * length),
secondRandom = swf[j];
alert(firstRandom + ' - ' + secondRandom);
Patrick DW informed me of delete operator just leaving the value as undefined. I did some Googling and came up with this alternate solution.
Be sure to check Tvanfosson's answer or Deceze's answer for cleaner/alternate solutions.
This is what I would do to require two numbers to be different (could be better answer out there)
var swf=["1.swf","2.swf","3.swf"];
var i = Math.floor(Math.random()*swf.length);
var j;
do {
j = Math.floor(Math.random()*swf.length);
} while (j === i);
alert(swf[i]);
alert(swf[j]);
Edit: should be j===i

Categories

Resources