Is there any pre-built method for finding all permutations of a given string in JavaScript? - 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>

Related

Longest Common Prefix in Javascript

I am trying to solve the Leet Code challenge 14. Longest Common Prefix:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: strs = ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Constraints:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i] consists of only lower-case English letters.
My solution:
let strs = ["flower", "flow", "flight"];
var longestCommonPrefix = function (strs) {
for (let i = 0; i < strs.length; i++) {
for (let j = 0; j < strs[i].length; j++) {
// console.log(strs[i+2][j]);
if (strs[i][j] == strs[i + 1][j] && strs[i + 1][j] ==strs[i + 2][j]) {
return (strs[i][j]);
} else {
return "0";
}
}
}
};
console.log(longestCommonPrefix(strs));
Output: f
How can I iterate over every character and check if it is same and then go for next and if it fails then the longest common prefix will be returned?
As the longest common prefix must occur in every string of the array you can jus iterate over the length and check if all words have the same char at that index until you find a difference
function prefix(words){
// check border cases size 1 array and empty first word)
if (!words[0] || words.length == 1) return words[0] || "";
let i = 0;
// while all words have the same character at position i, increment i
while(words[0][i] && words.every(w => w[i] === words[0][i]))
i++;
// prefix is the substring from the beginning to the last successfully checked i
return words[0].substr(0, i);
}
console.log(1, prefix([]));
console.log(2, prefix([""]));
console.log(3, prefix(["abc"]));
console.log(4, prefix(["abcdefgh", "abcde", "abe"]));
console.log(5, prefix(["abc", "abc", "abc"]));
console.log(6, prefix(["abc", "abcde", "xyz"]));
Some of the issues:
Your inner loop will encounter a return on its first iteration. This means your loops will never repeat, and the return value will always be one character.
It is wrong to address strs[i+1] and strs[i+2] in your loop, as those indexes will go out of bounds (>= strs.length)
Instead of performing character by character comparison, you could use substring (prefix) comparison (in one operation): this may seem a waste, but as such comparison happens "below" JavaScript code, it is very fast (and as string size limit is 200 characters, this is fine).
The algorithm could start by selecting an existing string as prefix and then shorten it every time there is a string in the input that doesn't have it as prefix. At the end you will be left with the common prefix.
It is good to start with the shortest string as the initial prefix candidate, as the common prefix can certainly not be longer than that.
var longestCommonPrefix = function(strs) {
let prefix = strs.reduce((acc, str) => str.length < acc.length ? str : acc);
for (let str of strs) {
while (str.slice(0, prefix.length) != prefix) {
prefix = prefix.slice(0, -1);
}
}
return prefix;
};
let res = longestCommonPrefix(["flower","flow","flight"]);
console.log(res);
An approach based on sorting by word length, and for the shortest word, for exiting early, an entirely Array.every-based prefix-validation and -aggregation ...
function longestCommonPrefix(arr) {
const charList = [];
const [shortestWord, ...wordList] =
// sort shallow copy by item `length` first.
[...arr].sort((a, b) => a.length - b.length);
shortestWord
.split('')
.every((char, idx) => {
const isValidChar = wordList.every(word =>
word.charAt(idx) === char
);
if (isValidChar) {
charList.push(char);
}
return isValidChar;
});
return charList.join('');
}
console.log(
longestCommonPrefix(["flower","flow","flight"])
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
not the best solution but this should work
function longestPrefix(strs){
if(strs.length <1){
return "";
}
const sharedPrefix=function(str1,str2){
let i=0;
for(;i<Math.min(str1.length,str2.length) /*todo optimize*/;++i){
if(str1[i] !== str2[i]){
break;
}
}
return str1.substr(0,i);
};
let curr = strs[0];
for(let i=1;i<strs.length;++i){
curr=sharedPrefix(curr,strs[i]);
if(curr.length < 1){
// no shared prefix
return "";
}
}
return curr;
}
this:
strs[i][j] == strs[i + 1][j] ==strs[i + 2][j]
makes no sense in JS... or at least, makes no sense in what you are doing... to do this you should use a && operator, like this:
strs[i][j] == strs[i + 1][j] && strs[i + 1][j] ==strs[i + 2][j]
Otherwise JS will evaluate the first condition, and then will evaluate the result of that operation (either true or false) with the third value
In addition to this, consider that you are looping with i over the array, and so i will also be str.length - 1 but in the condition you are referencing strs[i + 2][j] that will be in that case strs[str.length + 1][j] that in your case, makes no sense.
About the solution:
You should consider that the prefix is common to all the values in the array, so you can take in consideration one value, and just check if all the other are equals... the most obvious is the first one, and you will end up with something like this:
let strs = ["flower", "flow", "flight", "dix"];
function longestCommonPrefix (strs) {
// loop over the characters of the first element
for (let j = 0; j < strs[0].length; j++) {
// ignore the first elements since is obvious that is equal to itself
for (let i = 1; i < strs.length; i++) {
/* in case you have like
[
'banana',
'bana'
]
the longest prefix is the second element
*/
if(j >= strs[i].length){
return strs[i]
}
// different i-th element
if(strs[0][j] != strs[i][j]){
return strs[0].substr(0, j)
}
}
}
// all good, then the first element is common to all the other elements
return strs[0]
};
console.log(longestCommonPrefix(strs));
you can do it like this, it works fast enough ~ 110ms
function longestCommonPrefix(strs){
if (strs.length === 0) {
return ''
}
const first = strs[0];
let response = '';
let prefix = '';
for (let i = 0; i < first.length; i++) {
prefix += first[i];
let find = strs.filter(s => s.startsWith(prefix));
if (find.length === strs.length) {
response = prefix;
}
}
return response;
};
let strs = ["flower", "flow", "flight"];
var longestCommonPrefix = function (strs) {
for (let i = 0; i < strs.length; i++) {
for (let j = 0; j < strs[i].length; j++) {
console.log(strs[i+2][j]);
if (strs[i][j] == strs[i + 1][j] && strs[i][j] ==strs[i + 2][j]) {
return (strs[i][j]);
} else {
return "0";
}
}
}
};
console.log(longestCommonPrefix(strs));
This **return ** f
Increase the index while the letter is the same at that index for all words in the list. Then slice on it.
function prefix(words) {
if (words.length === 0) { return '' }
let index = 0;
while (allSameAtIndex(words, index)) {
index++;
}
return words[0].slice(0, index);
}
function allSameAtIndex(words, index) {
let last;
for (const word of words) {
if (last !== undefined && word[index] !== last[index]) {
return false;
}
last = word;
}
return true;
}
I assume you are here for Leetcode problem solution.
var longestCommonPrefix = function(strs) {
let arr = strs.concat().sort();
const a1 = arr[0];
const a2 = arr[arr.length -1];
const length = a1.length;
let i=0;
while(i<length && a1.charAt(i) == a2.charAt(i)) i++;
return a1.substring(0,i);
};
function prefixLen(s1, s2) {
let i = 0;
while (i <= s1.length && s1[i] === s2[i]) i++;
return i;
}
function commonPrefix(arr) {
let k = prefixLen(arr[0], arr[1]);
for (let i = 2; i < arr.length; i++) {
k = Math.min(k, prefixLen(arr[0], arr[i]));
}
return arr[0].slice(0, k);
}
console.log(commonPrefix(['pirate', 'pizza', 'pilates'])) // -> "pi"
var longestCommonPrefix = function(strs) {
let prefix = "";
for(let i = 0; i < strs[0].length; i++) {
for(let j = 1; j < strs.length; j++) {
if(strs[j][i] !== strs[0][i]) return prefix;
}
prefix = prefix + strs[0][i];
}
return prefix;
};
console.log(longestCommonPrefix);
It is as simple as one loop and compare each element of the strings
const longestPrefix = (strs) => {
[word1, word2, word3] = strs;
let prefix = [];
if(strs === null || strs.length <= 2 || strs.length > 3) return 'please
insert 3 elements'
for (let i=0; i < word1.length; i++){
if(word1[i] === word2[i] && word1[i] === word3[i]){
prefix.push(word1[i])
}
}
return prefix.join('')
}
I read in another answer: 'Increase the index while the letter is the same at that index for all words in the list. Then slice on it.'
that's how I came up with this:
const findPrefix = (strs) => {
let i = 0;
while (strs.every((item) => strs[0][i] === item[i])) {
i++;
}
return strs[0].slice(0, i);
};
console.log(findPrefix(["flo", "flow", "flomingo"]));
const findPrefix = (strs) => {
let broke = false;
return strs[0].split("").reduce(
(acc, curr, index) =>
broke || !strs.every((word) => word[index] === curr)
? (broke = true && acc)
: (acc += curr),
""
);
};
console.log(findPrefix(["flower", "flow", "flamingo"]));
Here is my solution, Today I had an interview and the dev asked me the same question, I think I failed because I got stuck hahaha kinda nervous when someone is watching me 😂, anyway I decided to figure it out after the interview is done and this is my answer (without google it I swear) and for those who don't feel comfortable with the common "for loop"
const arr = ["absence", "absolute", "absolutely", "absorb"]
function getPrefix(arr) {
if (arr.length === 0 || arr.some(s => !s)) return null //if it's an empty array or one of its values is null or '', return null
const first = arr[0].split("") // turns the first position of the array, into an array
const res = arr.map(w => {
// mapping the original array
const compare = w.split("") // every item of the array will be converted in another array of its characters
return first.map((l, idx) => (compare[idx] === l ? l : "")).join("") // loop through the "first" array and compare each character
})
const prefix = first.join("").startsWith(res[res.length - 1]) // compare if the first letter starts with the last item of the returned array
? res[res.length - 1] // if true, return the final response which is the prefix
: null // else, return null, which means there is no common prefix
console.log("prefix: ", prefix)
return prefix
}
getPrefix(arr)
let arr = ["flower", "flow", "flight"]
function checkPrefix(array) {
let index = []
for (let i = 0; i <= array[0].length; i++) {
if (check(array[0][i], i, array)) {
index.push(i)
} else {
break;
}
}
console.log(array[0].substring(index[0], index[index.length - 1] + 1));
}
const check = (str, index, stringArr) => {
debugger
let status = true
stringArr.map(ele => {
debugger
if (ele[index] != str) {
status = false
}
})
return status
}
checkPrefix(arr)
/**
* #param {string[]} strs
* #return {string}
*/
var longestCommonPrefix = function(strs) {
let compare = strs[0];
let str = "";
for (let i = 1; i < strs.length; i++) {
let j = 0;
while(compare[j] != undefined && strs[i][j] != undefined) {
if(strs[i][j] == compare[j]) {
str += strs[i][j];
}
else break;
j++;
}
compare = str;
str = "";
}
return compare;
};
Longest common prefix in Javascript (All test case accepted. Asked by many company interviews.)
var longestCommonPrefix = function (strs) {
let string = '';
if (strs.length > 1) {
for (let i = 0; i < strs[0].length; i++) {
let str = strs[0].charAt(i);
for (let s = 0; s < strs.length - 1; s++) {
if (!(strs[s + 1].charAt(i) && strs[s].charAt(i) && strs[s + 1].charAt(i) == strs[s].charAt(i))) {
str = '';
}
}
if (!str) {
break;
}
string += str;
}
return string;
} else {
return strs[0];
}
};
longestCommonPrefix(["flower","flow","flight"]);
Code to find longest prefix
var longestCommonPrefix = function(strs) {
let match = false;
let len = strs[0].length ;
let ans = "";
let prev_ans ="";
if(strs.length ==1){
return strs[0];
}
for (let i = 1; i < strs.length; i++){
if( strs[i-1].length > strs[i].length){
len = strs[i].length;
}
}
for (let i = 1; i < strs.length; i++){
for (let j = 0; j < len; j++){
if(strs[i-1].charAt(j) == strs[i].charAt(j)){
ans += strs[i-1].charAt(j);
match = true;
}
else{
break;
}
}
if(prev_ans != "" && prev_ans !=ans){
if(prev_ans.length > ans.length){
return ans;
}else{
return prev_ans;
}
}
prev_ans = ans;
ans = "";
if (match == false){
return "";
}
}
return prev_ans;
};
console.log(longestCommonPrefix(["flow","fly","flu"]));
My solution:
function longestCommonPrefix(...words) {
words.sort(); // shortest string will be first and the longest last
return (
words[0].split('') // converts shortest word to an array of chars
.map((char, idx) => words[words.length - 1][idx] === char ? char : '\0') // replaces non-matching chars with NULL char
.join('') // converts back to a string
.split('\0') // splits the string by NULL characters
.at(0) // returns the first part
);
}
Usage example:
longestCommonPrefix('abca', 'abda', 'abea'); // 'ab'
let testcases = [
["flower", "flow"], //should return "flow"
["flower", "flow", "flight"], //should return "fl"
["flower", "flow", "fight"], //should return "f"
["flower", "flow", "floor"], //should return "flo"
["flower"], //should return "flower"
]
var longestCommonPrefix = function(strs) {
for(var i=0; i<strs.length; i++){
for(var j=0; j<strs[i].length; j++){
if(strs[i][j] + strs[i][j+1] === strs[i+1][j]+strs[i+1][j+1]){
return strs[i][j]+strs[i][j+1];
}
else {
return "";
}
}
}
};
for (let strs of testcases)
console.log(longestCommonPrefix(strs));

Generate chunks from string

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));

Two chunks of code work separately but not together, where do i err?

Why is it that the following works fine:
var howMany = prompt("How many numbers?");
var myArray = [];
for(var i = 0; i < howMany; i++){
myArray.push(prompt("Enter a number"));
}
alert(myArray);
The code above is intended to ask user how many numbers are they going to put into an array, and it displays the array.
This chunks of code below seems to be fine too.
There is a provided array.
Then the code checks whether the numbers are actually numbers.
After that it adds all the numbers together.
var myArray = [1,2,3,4,5];
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i=0; i<length; i++){
if(typeof array[i]!== typeof first){
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true){
add(myArray);
} else {
console.log("cant do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i=0; i<length; i++){
f+= array[i];
}
alert("The result of addition of this set: " + myArray + " is: " + f);
}
but when i combine the two it does not work. It does not add the numbers.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(prompt("Enter a number"));
}
isDataUniform(myArray);
function isDataUniform(array) {
var first = array[0];
var length = array.length;
for (i = 0; i < length; i++) {
if (typeof array[i] !== typeof first) {
return false;
}
}
return true;
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
Can you be so kind to correct me?
The return value from prompt is a string, not a number.
var n = prompt("Enter a number");
alert("typeof(n) = " + typeof(n));
Even if you enter a numeric value, the code above will display "typeof(n) = string".
You must convert the string into a number.
var howMany = prompt("How many numbers?");
var myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"), 10));
}
The prompt function saves strings, so the problem here is that you are trying to make a sum of strings. Just add a typecast in the add function and the script will work correctly:
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += parseInt(array[i]);
}
}
var howMany = prompt("How many numbers?"),
myArray = [];
for (var i = 0; i < howMany; i++) {
myArray.push(parseInt(prompt("Enter a number"),10));
}
function isDataUniform(array) {
for (i = 0; i < array.length; i++) {
if (typeof array[i] !== "number") {
return false;
}
}
return true;
}
function add(array) {
var f = 0;
var length = array.length;
for (i = 0; i < length; i++) {
f += array[i];
}
alert("Result of addition of this set: " + myArray + " is: " + f);
}
if (isDataUniform(myArray) === true) {
add(myArray);
} else {
console.log("can't do adding");
}

Sort array of strings into array of objects

Okay, so I've been working on a sort function for my application, and I've gotten stuck.
Here's my fiddle.
To explain briefly, this code starts with an array of strings, serials, and an empty array, displaySerials:
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
var displaySerials = [];
The aim of these functions is to output displaySerials as an array of objects with two properties: beginSerial and endSerial. The way that this is intended to work is that the function loops through the array, and tries to set each compatible string in a range with each other, and then from that range create the object where beginSerial is the lowest serial number in range and endSerial is the highest in range.
To clarify, all serials in a contiguous range will have the same prefix. Once that prefix is established then the strings are broken apart from the prefix and compared and sorted numerically.
So based on that, the desired output from the array serials would be:
displaySerials = [
{ beginSerial: "BHU-008", endSerial: "BHU-011" },
{ beginSerial: "BHU-000", endSerial: "BHU-002" },
{ beginSerial: "TYU-969", endSerial: "TYU-970" }
]
I've got it mostly working on my jsfiddle, the only problem is that the function is pushing one duplicate object into the array, and I'm not sure how it is managing to pass my checks.
Any help would be greatly appreciated.
Marc's solution is correct, but I couldn't help thinking it was too much code. This is doing exactly the same thing, starting with sort(), but then using reduce() for a more elegant look.
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"]
serials.sort()
var first = serials.shift()
var ranges = [{begin: first, end: first}]
serials.reduce(mergeRange, ranges[0])
console.log(ranges) // the expected result
// and this is the reduce callback:
function mergeRange(lastRange, s)
{
var parts = s.split(/-/)
var lastParts = lastRange.end.split(/-/)
if (parts[0] === lastParts[0] && parts[1]-1 === +lastParts[1]) {
lastRange.end = s
return lastRange
} else {
var newRange = {begin: s, end: s}
ranges.push(newRange)
return newRange
}
}
I've got a feeling that it's possible to do it without sorting, by recursively merging the results obtained over small pieces of the array (compare elements two by two, then merge results two by two, and so on until you have a single result array). The code wouldn't look terribly nice, but it would scale better and could be done in parallel.
Nothing too sophisticated here, but it should do the trick. Note that I'm sorting the array from the get-go so I can reliably iterate over it.
Fiddle is here: http://jsfiddle.net/qyys9vw1/
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
var myNewObjectArray = [];
var sortedSerials = serials.sort();
//seed the object
var myObject = {};
var previous = sortedSerials[0];
var previousPrefix = previous.split("-")[0];
var previousValue = previous.split("-")[1];
myObject.beginSerial = previous;
myObject.endSerial = previous;
//iterate watching for breaks in the sequence
for (var i=1; i < sortedSerials.length; i++) {
var current = sortedSerials[i];
console.log(current);
var currentPrefix = current.split("-")[0];
var currentValue = current.split("-")[1];
if (currentPrefix === previousPrefix && parseInt(currentValue) === parseInt(previousValue)+1) {
//sequential value found, so update the endSerial with it
myObject.endSerial = current;
previous = current;
previousPrefix = currentPrefix;
previousValue = currentValue;
} else {
//sequence broken; push the object
console.log(currentPrefix, previousPrefix, parseInt(currentValue), parseInt(previousValue)+1);
myNewObjectArray.push(myObject);
//re-seed a new object
previous = current;
previousPrefix = currentPrefix;
previousValue = currentValue;
myObject = {};
myObject.beginSerial = current;
myObject.endSerial = current;
}
}
myNewObjectArray.push(myObject); //one final push
console.log(myNewObjectArray);
I would use underscore.js for this
var bSerialExists = _.findWhere(displaySerials, { beginSerial: displaySettings.beginSerial });
var eSerialExists = _.findWhere(displaySerials, { endSerial: displaySettings.endSerial });
if (!bSerialExists && !eSerialExists)
displaySerials.push(displaySettings);
I ended up solving my own problem because I was much closer than I thought I was. I included a final sort to get rid of duplicate objects after the initial sort was finished.
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
var displaySerials = [];
var mapSerialsForDisplay = function () {
var tempArray = serials;
displaySerials = [];
for (var i = 0; i < tempArray.length; i++) {
// compare current member to all other members for similarity
var currentSerial = tempArray[i];
var range = [currentSerial];
var displaySettings = {
beginSerial: currentSerial,
endSerial: ""
}
for (var j = 0; j < tempArray.length; j++) {
if (i === j) {
continue;
} else {
var stringInCommon = "";
var comparingSerial = tempArray[j];
for (var n = 0; n < currentSerial.length; n++) {
if (currentSerial[n] === comparingSerial[n]) {
stringInCommon += currentSerial[n];
continue;
} else {
var currentRemaining = currentSerial.replace(stringInCommon, "");
var comparingRemaining = comparingSerial.replace(stringInCommon, "");
if (!isNaN(currentRemaining) && !isNaN(comparingRemaining) && stringInCommon !== "") {
range = compareAndAddToRange(comparingSerial, stringInCommon, range);
displaySettings.beginSerial = range[0];
displaySettings.endSerial = range[range.length - 1];
var existsAlready = false;
for (var l = 0; l < displaySerials.length; l++) {
if (displaySerials[l].beginSerial == displaySettings.beginSerial || displaySerials[l].endSerial == displaySettings.endSerial) {
existsAlready = true;
}
}
if (!existsAlready) {
displaySerials.push(displaySettings);
}
}
}
}
}
}
}
for (var i = 0; i < displaySerials.length; i++) {
for (var j = 0; j < displaySerials.length; j++) {
if (i === j) {
continue;
} else {
if (displaySerials[i].beginSerial === displaySerials[j].beginSerial && displaySerials[i].endSerial === displaySerials[j].endSerial) {
displaySerials.splice(j, 1);
}
}
}
}
return displaySerials;
}
var compareAndAddToRange = function (candidate, commonString, arr) {
var tempArray = [];
for (var i = 0; i < arr.length; i++) {
tempArray.push({
value: arr[i],
number: parseInt(arr[i].replace(commonString, ""))
});
}
tempArray.sort(function(a, b) {
return (a.number > b.number) ? 1 : ((b.number > a.number) ? -1 : 0);
});
var newSerial = {
value: candidate,
number: candidate.replace(commonString, "")
}
if (tempArray.indexOf(newSerial) === -1) {
if (tempArray[0].number - newSerial.number === 1) {
tempArray.unshift(newSerial)
} else if (newSerial.number - tempArray[tempArray.length - 1].number === 1) {
tempArray.push(newSerial);
}
}
for (var i = 0; i < tempArray.length; i++) {
arr[i] = tempArray[i].value;
}
arr.sort();
return arr;
}
mapSerialsForDisplay();
console.log(displaySerials);
fiddle to see it work
Here's a function that does this in plain JavaScript.
var serials = ["BHU-009", "BHU-008", "BHU-001", "BHU-010", "BHU-002", "TYU-970", "BHU-011", "TYU-969", "BHU-000"];
function transformSerials(a) {
var result = []; //store array for result
var holder = {}; //create a temporary object
//loop the input array and group by prefix
a.forEach(function(val) {
var parts = val.split('-');
var type = parts[0];
var int = parseInt(parts[1], 10);
if (!holder[type])
holder[type] = { prefix : type, values : [] };
holder[type].values.push({ name : val, value : int });
});
//interate through the temp object and find continuous values
for(var type in holder) {
var last = null;
var groupHolder = {};
//sort the values by integer
var numbers = holder[type].values.sort(function(a,b) {
return parseInt(a.value, 10) > parseInt(b.value, 10);
});
numbers.forEach(function(value, index) {
if (!groupHolder.beginSerial)
groupHolder.beginSerial = value.name;
if (!last || value.value === last + 1) {
last = value.value;
groupHolder.endSerial = value.name;
if (index === numbers.length - 1) {
result.push(groupHolder);
}
}
else {
result.push(groupHolder);
groupHolder = {};
last = null;
}
});
}
return result;
}
console.log(transformSerials(serials));
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Reverse words(not letters) for a string without using .reverse()

The problem I am working on asks for me to write a function reverseMessage() that takes a string message and reverses the order of the words in place.
The answer I first came up with works but apparently doesn't meet the requirements of this task:
function reverseMessage(string) {
return string.split(" ").reverse().join(" ");
}
For example:
var string = "reversed are string your in words the now"
var results = "now the words in your string are reversed"
New solution:
I would like to split this string into an array and then loop through that array and swap the 1st index with the last index, the 2nd index with second to last index, 3rd index with the 3rd to last index, etc... until I meet in the middle.
I am trying to make the two different functions below work:
function reverseMessage(string) {
var array = string.split(" ");
//loop through array and replace first index with last index, second
index with second to last index, third index with third to last index, etc
for (var i = 0; i < array.length/2; i++) {
for (var j = (array.length-1); j > array.length/2; j--) {
array[i] = array[j];
array[j] = array[i];
messageSplit.join(",");
}
};
function reverseMessage2(string) {
var array = string.split(" ");
var newArray = []
for (var i = 0; i < array.length/2; i++) {
newArray.unshift(array[i]++);
newArray.join(",");
return newArray;
}
};
Am I on the right track?
function reverseMessage(string) {
var array = string.split(" ");
var result="";
for (var i = array.length-1; i >=0; i--) {
result+=array[i]+" ";
}
console.log(result);
};
So in yours reverseMessage function You are trying to swap variable for that you are doing
array[i] = array[j];
array[j] = array[i];
Which is giving array[i]=array[j] so let say array[i]="This" and array[j]="That"so according to yours code array[i] will be "That" and array[j] will also be "That" so you can try something like this:
function reverseMessage(string) {
var array = string.split(" ");
//loop through array and replace first index with last index, second
//index with second to last index, third index with third to last index, etc
for (var i = 0,j=(array.length)-1; i < array.length/2; i++) {
temp=array[i]
array[i] = array[j];
array[j]=array[i]
array[j] = temp; j--;}
console.log(array.join(" "));
}; reverseMessage("find you will pain only go you recordings security the into if");
try this one
function reverseMessage( str ) {
var arrStr = [];
var temp ="";
for(var i = 0 ; i < str.length ; i++)
{
if(str[i] === " ")
{
arrStr.push(temp);
temp="";
}
else
{
temp += str[i];
}
}
if(temp.length >= 0)
{
arrStr.push(temp);
}
var result = "";
for(var x=arrStr.length-1 ; x >=0 ; x--)
{
result += " "+arrStr[x];
}
return result;
}
console.log(reverseMessage("I am here"));
Well, someone's gotta do it:
function rev(s){
var a = s.split(/ /),
l = a.length;
i = l/2 | 0;
while (i--) a.splice(i, 1, a.splice(l-1-i, 1, a[i])[0]);
return a.join(' ');
}
document.write(rev('0 1 2 3 4 5 6 7 8 9'));
Using Array.split(), Array.pop(), Array.push() and String.substr():
var flip = function(str) {
var res = "", sp = " ", arr = str.split(sp);
while (arr.length)
res += arr.pop() + sp;
return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));
Using String.lastIndexOf() and String.substr():
var flip = function(str) {
var res = "", i, sp = ' ';
while (str) {
i = str.lastIndexOf(sp);
res += str.substr(i + 1) + sp;
str = str.substr(0, i);
}
return res.substr(0, res.length - 1); //remove last space
};
alert(flip("reversed are string your in words the now"));
What you want to do is split the words message into individual strings reverse them and then add them together, that will reverse them in place. Try
function reverseMessage(message){
var reversedMessage = ''; //A string to hold the reversed message
var words = message.split(' ');
for(var i =0; i< words.length; i++){
reversedMessage += reverse(words[i]) + " ";// add the reversed word to the reversed message, with a space at the end so the words dont touch
}
return reversedMessage
}
//A helper function that reverses a string
function reverse(s) {
var o = '';
for (var i = s.length - 1; i >= 0; i--)
o += s[i];
return o;
}
sources: http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/
with `pop()` ;)
function reverseMessage(string) {
var array = string.split(" ");
var result="";
while (array.length > 0) {
result += array.pop()+" ";
}
console.log(result);
};

Categories