Generate chunks from string - javascript

before going to problem, i want to generate dynamically like
temp = word[i] for 2,
temp = word[i-1] + word [i] for 3,
temp = word[i-2] + word[i-1] + word [i] for 4
I explained with code and what i have tried
function produceTwoChArray(word) {
var temp = "";
var tempArr = [];
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === 2) {
tempArr.push(temp);
}
temp = word[i];
}
return tempArr;
}
produceTwoChArray("breaking")
above code will produce result as :
["br", "re", "ea", "ak", "ki", "in", "ng"]
So inside the for loop if i change to below codes to produce three letters then
if (temp.length === 3) {
tempArr.push(temp);
}
temp = word[i-1] + word[i];
Result:
["bre", "rea", "eak", "aki", "kin", "ing"]
so adding word[i-1], word[i-2] with temp length 3, 4 and so on..
For dynamically creating the temp statement, i created these Function
1)
function generateWordSequence(n) {
var n = n - 2;
var temp1 = [];
for (var j = n; j >= 0; j--) {
temp1.push("word[i - " + j + "]");
}
temp1 = temp1.join('+').toString();
return temp1;
}
2)
function generateWordSequence(n, word) {
var n = n - 2;
var temp1 = "";
for (var j = n; j >= 0; j--) {
temp1 = temp1 + word[i - j];
}
return temp1;
}
But both above try's are returning as string so it didnt work. When i invoke above fn in produceTwoChArray fn like this
function produceTwoChArray(word, n) {
var temp = "";
var tempArr = [];
var retVar = generateWordSequence(n, word);
for (var i = 0; i < word.length; i++) {
temp += word[i];
if (temp.length === n) {
tempArr.push(temp);
}
temp = retVar;
}
return tempArr;
}
When i tried those all logic inside produceTwochArray itself , i also didnt work.
Please help me out here.

You could take a double slice with mapping part strings.
function part(string, count) {
return [...string.slice(count - 1)].map((_, i) => string.slice(i, i + count));
}
console.log(part("breaking", 2));
console.log(part("breaking", 3));
console.log(part("breaking", 4));

You can use slice method in order to obtain a more easy solution.
function produceArray(str,n){
return str=str.split('').map(function(item,i,str){
return str.slice(i,i+n).join('');
}).filter(a => a.length == n);
}
console.log(produceArray("breaking",2));
console.log(produceArray("breaking",3));
console.log(produceArray("breaking",4));
console.log(produceArray("breaking",5));
console.log(produceArray("breaking",6));

Related

Fixing Fibonacci sequence script (javascript)

I am trying to write a script that will create numbers in Fibonacci order, I don't understand why this is not working.
var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];
function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
if (n>1){
output.push(nextNum);
console.log(output);
}
else if (n<2)
{output.push(1);
console.log(output);}
}
}
In your original code your n never changes as you only assigned it on start.
var output = [];
function fibo (numQuantity) {
for (var i=1; i<numQuantity ; i++)
{
var n = output.length;
var nextNum = output[n-1] + output[n-2];
if (n>1){
output.push(nextNum);
console.log(output);
}
else if (n<2)
{
output.push(1);
console.log(output);
}
}
}
fibo(10)
In Javascript numbers are passed by value not reference so they are not the same object in memory. So when the array length changes your n value stays at 0 because they are not the same object.
function fibo(numQuantity) {
let output = [0, 1];
if(numQuantity < 2) {
return output.slice(0, numQuantity);
}
for(let i = 2; i < numQuantity ; i++) {
const n = output.length
output.push(output[n - 1] + output[n - 2])
}
return output;
}
console.log(fibo(1))
console.log(fibo(2))
console.log(fibo(3))
console.log(fibo(4))
Check this fiddle: https://jsfiddle.net/37a4burz/
You need to add n++ to end of your code and change end condition.
Here is full code:
var output = [];
var n = output.length;
var nextNum = output[n-1] + output[n-2];
function fibo (numQuantity) {
for (var i=1; i<= numQuantity ; i++)
{
if (n==0) {
output.push(0);
console.log(output);
}
else if (n==1) {
output.push(1);
console.log(output);
}
else if (n>1) {
output.push(output[n-1] + output[n-2]);
console.log(output);
}
n++;
}
}
fibo(7);

Output the sorted array to main element

I am new to javascript and working with DOM, so please bear with me.
I have an array called num that I want to sort and display. The sort is a selection sort that returns the number of moves it took.
I can display the unsorted array but can't figure out how to call my sort function and then display the sorted array to the screen. My code is below:
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
listlist
list[min] = temp;
count += 3;
}
return count;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
{
var html = "";
html += "Original:" + num + "<br>";
selection(num, fn);
html += "Sorted:" + num + "<br>";
}
demoP.innerHTML = html;
<div id="content"></div>
arr is undefined, you should use list instead. Returning count returns the number of operations (after it's been initialized), return list instead. And as list is local to the function, you need to set num to the return value of the function call.
<span id='content'/>
<script>
function fn(a, b) {
if (a < b)
return true;
}
function selection(list, fun) {
var min, temp, count=0,
len = list.length;
for (var i = 0; i < len; i++) {
min = i;
for (var j = i + 1; j < len; j++) {
if (fun(list[j], list[min])) {
min = j;
}
}
temp = list[i];
list[i] = list[min];
list[min] = temp;
count += 3;
}
return list;
}
var num = [10, 1, 3, 5, 2, 9, 8, 6, 7, 4];
var demoP = document.getElementById("content");
var html = "";
html += "Original:" + num + "<br>";
num= selection(num, fn);
html += "Sorted:" + num + "<br>";
demoP.innerHTML = html;
</script>

Sort string without any builtin methods

I want to sort a string in javascript without using a built in method, just by using for's and comparisons like 'a' > 'b';
Something that doesn't work:
function replaceAt(str, i, char) {
return str.substr(0,i) + char + str.substr(i + 1)
}
function swap(str, i1, i2) {
return replaceAt(replaceAt(str, i1, str[i2]),i2,str[i1]);
}
function sort(str) {
var sorted = str;
for (var i = 0; i < str.length; i++) {
if (str[i] > str[i + 1]) {
str = swap(str, i, i+1)
}
}
return str;
}
Pseudo-code or books, courses recommendations on programming are welcome!
Your code is not applying any sort algorithm logic, I recommend you to read atleast 1 to solve your problem.
Below is the program, which produces the expected output from your program using selection sort.
swap and replace functions works fine.
function sort(str) {
var sorted = str;
//Selection sort
for (var i = 0; i < str.length; i++) {
for(var j = i + 1; j < str.length - 1; j++) {
if (str[i] < str[j]) {
str = swap(str, i, j)
}
}
}
return str;
}
console.log(sort("zaasfweqrouoicxzvjlmmknkniqwerpopzxcvdfaa"));
//output: aaaaccdeeffiijkklmmnnoooppqqrrsuvvwwxxzzz
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
function sort(arr) {
arr = arr.split("");
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr.length; j++) {
if (arr[j] > arr[i]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
}
}
}
return arr.join("");
}
console.log(sort("dcna"));
Note: no need of using temp variable
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
array=[4, 10, 2, 9, 6, 3, 13, 5];
function arrayOperations()
{
var count = array.length - 1,
temp,
j,
i;
for (j = 0; j < count; j++)
{
for (i = 0; i < count; i++)
{
if (array[i] > array[i + 1])
{
temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
}
document.write("ascending order is <br>")
for(k=0;k<=array.length-1;k++){
document.write(array[k]+ "<br>");
}
document.write("descending order is <br>")
for(k=array.length-1;k>=0;k--){
document.write(array[k]+ "<br>");
}
document.write("biggest number is <br>")
for(k=array.length-1;k>=0;k--){
if((array[k])>array[k-1]){
document.write(array[k]+"<br>")
break;
}
}
document.write("smallest number is <br>")
for(k=0;k<=array.length;k++){
if((array[k])<array[k+1]){
document.write(array[k]+"<br>")
break;
}
}
}
</script>
<title></title>
</head>
<body>
array=[4, 10, 2, 9, 6, 3, 13, 5]
<br>
<input type="button" onclick="arrayOperations()" value="find">
</body>
</html>
//generic sort function to sort a word
function sortArray(str){
let strr = str.split('');
for(var index = 0 ;index <strr.length ;index ++ ){
for(var index1 = 0;index1<(strr.length-index) ;index1++){
let temp;
if( strr[index1] > strr[index1+1] ){
temp = strr[index1] ;
strr[index1] = strr[index1 +1];
strr[index1+1] =temp;
}
}
}
return(strr.join(''));
}
//data set to sort
let data = "Hey Goodmorning How are you";
let result;
let data1 =data.split(' ');
data1.forEach(value => {
value = sortArray(value.toLowerCase());
if(result){
result += " ";
result += value;
}
else {result = value;}
});
console.log(result);

Return Sorted Array Without Modifying Original Array

I'm having trouble with a function returning the original array as opposed to the sorted array. I tried to slice the array and return the sorted but it is not working. Any ideas on how to fix this?
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
return newArray;
}
I fixed the function:
function sortArr( comparator, array ){
/*your code here*/
var i, x;
var min;
var newArray = array.slice();
for(i = 0; i < newArray.length - 1; i++)
{
min = i;
for(x = i + 1; x < newArray.length; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
min = x;
}
}
if(min != i){
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
}
}
return newArray;
}
Copy the array with slice and then use native sort:
function sortArr(comparator, array) {
return array.slice().sort(function(a,b) {
return comparator(a,b) * 2 - 1;
});
}
Your sorting algorithm doesn't look quite right. For a start the swapping of values should be inside the if statement. I would also advise to look at #Oriol's solution which is far more elegant.
function sortArr( comparator, array ){
var newArray = array.slice();
for(var i = 0; i < newArray.size; i++)
{
var min = i;
for(var x = i; x < newArray.size; x++)
{
if(comparator(newArray[min],newArray[x]) == true)
{
var temp = newArray[i];
newArray[i] = newArray[min];
newArray[min] = temp;
min = x;
}
}
}
return newArray;
}
{"index.js":"var globalArray = [5, 6, 3, 2, 9];
function nonMutatingSort(arr) {
let newArr = globalArray.slice();\n let emptyArr = [];
return emptyArr.concat(newArr).sort();
}
nonMutatingSort(globalArray);"}

Is there any pre-built method for finding all permutations of a given string in JavaScript?

I'm a newbie to the JavaScript world. As the title mentions, I want to know whether there is any pre-built method in JavaScript to find all possible permutations of a given string.
For example, given the input:
the
Desired output:
the
teh
eht
eth
het
hte
//string permutation
function permutation(start, string) {
//base case
if ( string.length == 1 ) {
return [ start + string ];
} else {
var returnResult = [];
for (var i=0; i < string.length; i++) {
var result = permutation (string[i], string.substr(0, i) + string.substr(i+1));
for (var j=0; j<result.length; j++) {
returnResult.push(start + result[j]);
}
}
return returnResult;
}
}
permutation('','123') will return
["123", "132", "213", "231", "312", "321"]
function permutations(str){
if (str.length === 1) {
return str;
}
var permut = [];
for (var i=0; i<str.length; i++){
var s = str[0];
var _new = permutations(str.slice(1, str.length));
for(var j=0; j<_new.length; j++) {
permut.push(s + _new[j]);
}
str = str.substr(1, str.length -1) + s;
}
return permut;
}
permutations('the');
//output returns:[ 'the', 'teh', 'het', 'hte', 'eth', 'eht' ]
No pre-built, but writing such function is possible.. here is one relatively simple way using two functions:
function FindAllPermutations(str, index, buffer) {
if (typeof str == "string")
str = str.split("");
if (typeof index == "undefined")
index = 0;
if (typeof buffer == "undefined")
buffer = [];
if (index >= str.length)
return buffer;
for (var i = index; i < str.length; i++)
buffer.push(ToggleLetters(str, index, i));
return FindAllPermutations(str, index + 1, buffer);
}
function ToggleLetters(str, index1, index2) {
if (index1 != index2) {
var temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
}
return str.join("");
}
Usage:
var arrAllPermutations = FindAllPermutations("the");
Live test case: http://jsfiddle.net/yahavbr/X79vz/1/
This is just basic implementation, it won't remove duplicates and has no optimization. However for small strings you won't have any problem, add time measure like in the above test case and see what's your reasonable limit.
This is similar but finds all anagrams/permutations from an array of words. I had this question in an interview. Given an array of words ['cat', 'dog', 'tac', 'god', 'act'], return an array with all the anagrams grouped together. Makes sure the anagrams are unique.
var arr = ['cat', 'dog', 'tac', 'god', 'act'];
var allAnagrams = function(arr) {
var anagrams = {};
arr.forEach(function(str) {
var recurse = function(ana, str) {
if (str === '')
anagrams[ana] = 1;
for (var i = 0; i < str.length; i++)
recurse(ana + str[i], str.slice(0, i) + str.slice(i + 1));
};
recurse('', str);
});
return Object.keys(anagrams);
}
console.log(allAnagrams(arr));
//["cat", "cta", "act", "atc", "tca", "tac", "dog", "dgo", "odg", "ogd", "gdo", "god"]
Assuming a large string to search, you could use a regular expression
to examine a set of possibles that first matches the letters and the total number of letters,
and return the matches that use the same letter set as the pattern.
//(case-insensitive)
function lettersets(str, pat){
var A= [], M, tem,
rx= RegExp('\\b(['+pat+']{'+pat.length+'})\\b', 'gi'),
pattern= pat.toLowerCase().split('').sort().join('');
while((M= rx.exec(str))!= null){
tem= M[1].toLowerCase().split('').sort();
if(tem.join('')=== pattern) A.push(M[1]);
};
return A;
}
lettersets(s, 'the').sort();
function swap(a, b, str) {
if (a == b)
str = str;
else {
str = str.split("");
var temp = str[a];
str[a] = str[b];
str[b] = temp;
str = str.join("");
}
}
function anagram(a1, b1, ar) {
if (a1 == b1)
document.write(ar + "<br/>");
else
for (i = a1; i < b1; i++) {
swap(a1, b1, ar);
anagram((a1) ++, b1, ar);
swap(a1, b1, ar);
}
}
Well there isnt any built in function in js(i dont believe it to be in any coding language)......and anyways this is the fully functioning program, it omits any repetitions and also displays the number of permutations.....
var n=0;
var counter=0;
var storarr=new Array();
function swap(a,b,str) { //swaps the terms str[a] and str[b] and returns the final str
str = str.split("");
var temp = str[a];
str[a] = str[b];
str[b] = temp;
return str.join("");
}
function anagram(_a,_b,ar) { //actual function which produces the anagrams
if(_a == _b) {
storarr[n]=ar;
n++;
counter++;
}
else {
for(var i= _a;i<= _b;i++) {
ar=swap(_a,i,ar);
anagram(_a+1,_b,ar);
ar=swap(_a,i,ar);
}
}
}
function factorial(a) { //return a!
var x=1;
for(var i=1;i<=a;i++)
x=x*i;
return x;
}
var strl=prompt("Enter String:","");
var l=strl.length;
anagram(0,l-1,strl);
storarr.sort(); //sorts the storarr alphabetically
var storlen=storarr.length;
var cai=0;
var counterarr = new Array();
strl.split("");
for(var i=0;i<l;i=i+c) { //determines the number of times a term is repeating
var c=1;
for(var j=i+1;j<l;j++) {
if(strl[i]==strl[j])
c++;
}
counterarr[cai]=c;
cai++;
}
var yellow=1;
for(var i=0;i<counterarr.length;i++) { //multiplies the terms of the counter array
yellow=yellow*factorial(counterarr[i]);
}
counter=counter/yellow;
document.write("Count : " + counter + "<br />");
for(var i=0;i<storlen;i=i+yellow) { //prints the non-flagged terms in storarr
document.write(storarr[i] + "<br />");
}
strl.join("");
<pre>
<script>
var count = 0;
var duplicate = false;
function FindAllPermutations(str, index) {
for (var i = index; i < str.length; i++) {
var newstr;
if (index == i) newstr = str;
else newstr = SwapLetters(str, index, i);
if (!duplicate) {
count++;
document.write(newstr + "\n");
if (i == index) duplicate = true;
} else if (i != index) duplicate = false;
FindAllPermutations(newstr, index + 1);
}
}
function SwapLetters(str, index1, index2) {
if (index1 == index2) return str;
str = str.split("");
var temp = str[index1];
str[index1] = str[index2];
str[index2] = temp;
return str.join("");
}
FindAllPermutations("ABCD", 0); // will output all 24 permutations with no duplicates
document.write("Count: " + count);
</script>

Categories