Heaps permutation algorithm done the opposite way....? - javascript

I was trying to use Heaps algorithm the opposite way by fixing elements at the beginning of array instead of last. But Im not able to get the results. Although I understood the theory part of this algorithm, it is confusing when I am trying to implement it. Im mainly confused about the swap statements inside the if condition. (please check comment). It would be helpful if someone can tell what the problem is. Thanks for your time.
function permute(string){
var str = string.split(""), strbrr = [];
function swap(strbrr,index1,index2) {
var temp = strbrr[index1];
strbrr[index1] = strbrr[index2];
strbrr[index2] = temp;
}
function permuteHelper(strarr, curr, end) {
if (curr == end)
console.log(strarr);
else{
var fixed = strarr[curr];
for(i=curr; i<=end; i++) {
permuteHelper(strarr,curr+1,end);
(end+1)%2 ? swap(strarr,end,curr) : swap(strarr,i,end); //This is the most confusing part for me. What is the code here?
}
}
}
permuteHelper(str,0,str.length-1);
}
var string1 = "ABCD";
permute(string1);

Related

How do I convert a string to an object

I'm new to programming and I wanted to develop my skills by working on a small project.
I am creating a Sudoku app, using HTML/JavaScript. I have a large number (81) of 'div' elements in HTML, and I want to assign content to them using by changing their innerHTML. Using the two for loops, I go through all 81 variables and re-create their name in 'x', which I then pass to assign_cell() to assemble the code.
puzzle_inc holds the puzzle itself (9..47.8.2..821.. etc; "." denotes empty cell), and I use a counter function to go through its characters one by one, assigning them to each 'div'.
After much testing and searching, I found out that my problem is that x is of 'string' type and the code in assign_cell() will not work. In this case, x will always be equal to something like "c01".
What I've been trying to do is to convert x to an object type. I have tried using JSON.parse() to fix the issue but probably due to my lack of knowledge in the field I have been unsuccessful.
I'm not sure how else to approach this but any help would be really appreciated.
Thank you.
function assign_cell(flag, arr1, arr2) {
if(flag === 1) {
arr1.innerHTML = puzzle_inc[arr2];
} else if(flag === 2) {
arr1.innerHTML = null;
} else {
alert("Error in function assign_cell()");
}
}
for(var i = 0; i < 9; i++){
for(var k = 0; k < 9; k++){
var a = counter();
var x = "c"+i+k;
if(puzzle_inc[a] != '.') {
assign_cell(1, x, a);
} else {
assign_cell(2, x, a);
}
}
}
EDIT: I've been asked for the whole code, to better help answer my question. Please find it below. Thank you for the answers!
PHP
JS
have you tried eval()
var stringval='[1,2,3]';
var value=eval(stringval);
console.log(value);//=>[1, 2, 3]

How to find the missing next character in the array?

I have an array of characters like this:
['a','b','c','d','f']
['O','Q','R','S']
If we see that, there is one letter is missing from each of the arrays. First one has e missing and the second one has P missing. Care to be taken for the case of the character as well. So, if I have a huge Object which has all the letters in order, and check them for the next ones, and compare?
I am totally confused on what approach to follow! This is what I have got till now:
var chars = ("abcdefghijklmnopqrstuvwxyz"+"abcdefghijklmnopqrstuvwxyz".toUpperCase()).split("");
So this gives me with:
["a","b","c","d","e","f","g","h","i","j","k","l","m",
"n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M",
"N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
Which is awesome. Now my question is, how do I like check for the missing character in the range? Some kind of forward lookup?
I tried something like this:
Find the indexOf starting value in the source array.
Compare it with each of them.
If the comparison failed, return the one from the original array?
I think that a much better way is to check for each element in your array if the next element is the next char:
function checkMissingChar(ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) == ar[i-1].charCodeAt(0)+1) {
// console.log('all good');
} else {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(checkMissingChar(a));
console.log(checkMissingChar(b));
Not that I start to check the array with the second item because I compare it to the item before (the first in the Array).
Forward Look-Ahead or Negative Look-Ahead: Well, my solution would be some kind of that. So, if you see this, what I would do is, I'll keep track of them using the Character's Code using charCodeAt, instead of the array.
function findMissingLetter(array) {
var ords = array.map(function (v) {
return v.charCodeAt(0);
});
var prevOrd = "p";
for (var i = 0; i < ords.length; i++) {
if (prevOrd == "p") {
prevOrd = ords[i];
continue;
}
if (prevOrd + 1 != ords[i]) {
return String.fromCharCode(ords[i] - 1);
}
prevOrd = ords[i];
}
}
console.log(findMissingLetter(['a','b','c','d','f']));
console.log(findMissingLetter(['O','Q','R','S']));
Since I come from a PHP background, I use some PHP related terms like ordinal, etc. In PHP, you can get the charCode using the ord().
As Dekel's answer is better than mine, I'll try to propose somewhat more better answer:
function findMissingLetter (ar) {
for (var i = 1; i < ar.length; i++) {
if (ar[i].charCodeAt(0) != ar[i-1].charCodeAt(0)+1) {
return String.fromCharCode(ar[i-1].charCodeAt(0)+1);
}
}
return true;
}
var a = ['a','b','c','d','f']
var b = ['O','Q','R','S']
console.log(findMissingLetter(a));
console.log(findMissingLetter(b));
Shorter and Sweet.

how can i print in javascript a string in parts

I have an exercise from my university that i have a string let's say i have that: "hello" and i want to print it like that:
hhehelhellhello (h he hel hell hello).
the thing that i stack is that they want to do it without loop!
Anyone can help me? :/
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
var strin = "hello"
for (i = 0; i < strin.length; i++) {
document.write(strin.slice(0,i+1))
}
</script>
</body>
</html>
Use recursion. Code:
function r (s, i) {
if (i == undefined) i = 0;
if (i == s.length) return "";
return s.slice(0, i + 1) + r(s, i + 1);
}
r("hello"); // hhehelhellhello
There is probably a more efficient solution, but off the top of my head this should work:
var s = "hello";
var index = 0;
var len = 1;
var newString = '';
function appendToResult(str, index, len) {
newString += str.slice(index, len);
len++;
if (len !== s.length + 1) {
appendToResult(s, index, len);
}
}
appendToResult(s, index, len);
console.log(newString);
Maybe you can try a recursive approach:
function print(word, step){
if(word.length<step) return;
console.log(word.substring(1, step));
}
print('hello', 1);
Have you met.... Recursion?
What you need to achieve is something like this (for a string "hello"):
h
he
hel
hell
hello
A recursive call to a method (say, myPrinter()) could behave similarly:
call myPrinter(hello):
call myPrinter(hell):
call myPrinter(hel):
call myPrinter(he):
call myPrinter(h):
print 'h'
print 'he'
print 'hel'
print 'hell'
print 'hello'
done
So how do we go about writing this magical method of ours?
Take notice that at each call we make another call to our method but with a shorter input (in fact, the input has been truncated by one character from the end).
You could write something like this:
function myPrinter(myString):
myPrinter(myString - last character of myString);
print myString; // and maybe some space
if myString is empty:
return; // do nothing. just return
All that's left for you to do is translating the above idea into clean bug-free code.
Of course we have to loop this way or that way. Yet in the below code it is disguised as a recursive function. Yet i am using no counting variables at all. It has the potential to deceive inexperienced eyes. This is how i would do it;
function makeStringWeird(s){
var extend = (s, r=[]) => s !=="" ? (r.push(s),extend(s.slice(0,s.length-1),r)) : r;
return extend(s).reverse().join("");
}
console.log(makeStringWeird("hello"));
I landed up making two solutions for you. One is by using reduce function which doesn't explicitly uses any loop but when I checked its polyfill it uses a while loop to iterate. The code for that is given below and it can also be seen at this fiddle https://jsfiddle.net/vatsalpande/42590tre/
(function(){
var convertedString = [];
function reducer(previousValue, currentValue){
convertedString.push(previousValue+currentValue);
return previousValue+currentValue;
}
var string = "hello";
var stringArray = string.split("");
var totalVersion= stringArray.reduce(reducer,"");
console.info(convertedString.join(""));
})();
Since this was using iteration I created one more by using recursion alone. Below is the code and the fiddle link
https://jsfiddle.net/vatsalpande/tnxsuw75/
(function(){
var string = "hello";
var stringArray = string.split("");
var convertedValue = [];
function convert(initialValue, index){
if(index < stringArray.length){
convertedValue.push(initialValue+stringArray[index]);
convert(initialValue+stringArray[index], index+1);
}
}
convert("",0);
console.info(convertedValue.join(""));
})();
Hope these be of some help.
Any feedback to improve them is highly appreciated.
Happy Learning :)

Why is my longest array value function in Javascript not working? Newbie help please

This is my first week learning Javascript so this is very new to me. How can I call this function and get it to work. Here is my code.
var ninjaTurtles = ["Leonardo", "Donatello", "Michelangelo", "Raphael"];
function longest(strings) {
var longestName = strings[0];
for (i = 1; i < strings.length; i++) {
if (strings[i].length > longestName.length) {
longestName = strings[i];
}
}
return longestName;
}
longest(ninjaTurtles);
Don't really know what the hell I am doing please help.
EDIT: Okay so I got it to work thanks your help, appreciate it! Now, If i wanted to tweak this same code to get the shortest word out of the array, what do I need to change?
You could turn that entire thing into a one-liner that also handles empty arrays and doesn't pollute the global variable scope using reduce
return strings.reduce(function(a, b) { return a.length > b.length ? a : b }, '')
Demo here - http://jsfiddle.net/xS6Mu/2/

JavaScript converting an array to array of functions

Hello I'm working on a problem that requires me to change an set array of numbers into an array that returns the original numbers as a function. So we get a return of a2 instead of a[2].
I dont want the answer I just need a hint. I know i can loop through the array and use .pop() to get the last value of the array, but then I dont know how to convert it to a function from there. any hints?
var numToFun = [1, 2, 3];
var numToFunLength = numToFun.length;
for (var i = 0; i < numToFunLength; i++) {
(function(num){
numToFun.unshift(function() {
return num;
});
}(numToFun.pop()))
}
DEMO
basically it pops out a number from the last, builds a function with that number returned, and put back into the first of the array. after one full cycle, all of them are functions.
here's the catch: how this works, it's up to you to research
why the loop does not look like the straightforward pop-unshift:
for (var i = 0; i < numToFunLength; i++) {
numToFun.unshift(function() { //put into first a function
return numToFun.pop() //that returns a number
});
}
and why i did this: (HINT: performance)
var numToFunLength = numToFun.length;
There's three important steps here:
Extract the number value from the array. Within a loop with an iterator of i, it might look like this:
var num = numArray[i];
This is important, because i will not retain its value that it had when you created the new function - it'll end up with the last value it had, once the for loop is finished. The function itself might look like this:
function() { return num; }
There's no reference to i any more, which is important - to understand better, read about closures. The final step would be to add the new function to the array of functions that you want.
...and you're done!
EDIT: See other's answers for good explanations of how to do this right, I will fix mine also though
As others have pointed out, one of the tricky things in javascript that many struggle with (myself included, obviously) is that scoping variables in javascript is dissimilar to many other languages; scopes are almost purely defined by functions, not the {} blocks of, for example, a for loop, as java/C would be.
So, below you can see (and in other answers here) a scoping function can aid with such a problem.
var numArray = [12, 33, 55];
var funcArray = [];
var numArrLength = numArray.length; // Don't do this in for loop to avoid the check multiple times
for(var j=0; j < numArrLength; j++) {
var scopeMe = function() {
var numToReturn = numArray[j];
console.log('now loading... ' + numToReturn);
var newFunc = function() {
return numToReturn;
};
return newFunc;
}();
funcArray.push(scopeMe);
};
console.log('now me');
console.log(funcArray);
console.log(funcArray[0]());
console.log(funcArray[1]());
console.log(funcArray[2]());
console.log(funcArray[1]()); // To ensure it's repeatable
EDIT my old bad answer below
What you'll want to do is something like
var funcArray = [];
for(...) {
var newFunc = function() {
return numArray.pop();
}
funcArray.push(newFunc);
}
The key here is that functions in javascript can be named variables, and passed around as such :)

Categories

Resources