Take Input from user is number is in Fibonacci series using JavaScript.
I am able to push values in array, but not able to compare
<!DOCTYPE html>
<html>
<head>
<script>
var a = new Array();
var b = prompt("Enter Number");
var i = 0,
j = 1,
k = 0,
l;
while (k < 100) {
a.push(k)
document.write(k + " ")
k = i + j;
i = j;
j = k;
}
document.write("<br>" + a[4] + a.length);
//
for (l = 0; l <= a.length; l++) {
if (a[l] == b) {
document.write(a[l]);
}
</script>
</head>
</body>
</html>
You need to use the indexOf function to find whether b is in a or not :
<script>
var a = new Array();
var b = prompt("Enter Number");
var i=0,j=1,k=0,l;
while(k < 100) {
a.push(k)
document.write(k + " ")
k = i+j;
i=j;
j=k;
}
b = parseInt(b); // Necessary for comparison
var index = a.indexOf(b);
if (index != -1) {
alert (b + ' is in position ' + index + ' of the array');
} else {
alert (b + ' is not in the array');
}
</script>
Related
I know that there are many solutions on the internet for my specific question, but I have been trying to solve it in a specific way and it doesn't work and I really can't understand what is wrong.
In my case I simply want to print the permutations.
Here is my code:
a = "abc";
function f7(a, b) {
//document.write("str: "+a+" b:"+b+"<br>");
if (b.length == 2) {
perm = b + a;
return perm;
}
var c = [];
var str = [];
for (i = 0; i < a.length; i++) {
c[i] = b + a.charAt(i);
str[i] = a.substring(0, i) + a.substring(i + 1);
document.write("i: " + i + " c[i]: " + c[i] + " str[i]: " + str[i] + "<br>");
return f7(str[i], c[i]);
}
//return {str,c}
}
document.write(f7(a, ""));
//g=f7(a,"");
//document.write(g.str+"<br>");
//document.write(g.c+"<br>");
The above code doesn't go beyond the first permutation, and I can't understand why.
Thanks in advance for any advice
Returning value in the loop causes escaping the loop. You are returning the value in for statement that stops immediately before loop complete.
You can use temporary variable to save value in for loop, and then return it.
a = "abc";
function f7(a, b) {
//document.write("str: "+a+" b:"+b+"<br>");
if (b.length == 2) {
perm = b + a;
return perm;
}
var c = [];
var str = [];
var temp = '';
for (i = 0; i < a.length; i++) {
c[i] = b + a.charAt(i);
str[i] = a.substring(0, i) + a.substring(i + 1);
document.write("i: " + i + " c[i]: " + c[i] + " str[i]: " + str[i] + "<br>");
temp += f7(str[i], c[i]);
}
return temp
}
document.write(f7(a, ""));
//g=f7(a,"");
//document.write(g.str+"<br>");
//document.write(g.c+"<br>");
I want to calculate how many Y's & N's appear in an array / range defined:
Cell Range: D4:D42
function myFunction() {
var count = SpreadsheetApp.getActiveSheet().getRange(5, 3, 40, 1);
var numRows = count.getNumRows();
var numCols = count.getNumColumns();
var y = 0;
var n = 0;
for (var i = 1; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++) {
var currentValue = count.getCell(i, j).getValue();
if (currentValue = "y") {
y = y + 1;
} else if (currentValue = "n") {
n = n + 1;
}
}
}
Browser.msgBox("There are " + y + " paid & " + n + " not paid");
}
This returns 40 Y's and 0 N's
Not sure what I am doing wrong here but I think it's a simple fix!
The problem is in this line:
if (currentValue = "y") {
You are assigning "y" to currentValue. To actually check for equality, you should try the "===" operator. Try this and see if it solves your problem:
function myFunction() {
var count = SpreadsheetApp.getActiveSheet().getRange(5, 4, 39, 1);
var numRows = count.getNumRows();
var numCols = count.getNumColumns();
var y = 0;
var n = 0;
for (var i = 1; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++) {
var currentValue = count.getCell(i, j).getValue();
if (currentValue === "y") {
y = y + 1;
} else if (currentValue === "n") {
n = n + 1;
}
}
}
Browser.msgBox("There are " + y + " paid & " + n + " not paid");
}
I also updated the getRange() parameters to match D4:D42. In your code, they matched C5:C44. See the getRange() function documentation.
Here's the code: this Display the table of any number given by user.
function table(num){
var num = prompt("please enter any number");
var x = num;
if (num <= 0){
alert("invalid number or Zero") ;
} else {
for(var i=1; i <= 10; i++){
var y = x * i;
document.write(x + ' X ' + i +' = ' + y + '<br/>') ;
}
}
}
table();
now if -1 entered it display alert("invalid number or Zero"); and code breaks nothing is displayed. What I am looking for is how will it go again to start of function and prompt again for the number.
Recursion is your friend: call the method again
function table(num){
var num = prompt("please enter any number");
var x = num;
if (num <= 0){
alert("invalid number or Zero") ;
table(); // <----------------
} else {
for(var i=1; i <= 10; i++){
var y = x * i;
document.write(x + ' X ' + i +' = ' + y + '<br/>') ;
}
}
}
Apart from that, you might want to consider a slight refactoring, since there are some useless variables/parameters
As has been mentioned before, you'll want to call the table function again (recursion), after the alert().
You can also clean up the function a bit, since there's no need to copy num to x, and a num parameter in the function isn't necessary, because you're initializing num in the function itself, and you have no need to pass it as a parameter:
function table(){
var num = prompt("please enter any number");
if (num <= 0){
alert("invalid number or Zero") ;
table();
} else {
for(var i = 1; i <= 10; i++){
var y = num * i;
document.write(num + ' X ' + i +' = ' + y + '<br/>');
}
}
}
table();
You could use a while loop as well.
Have a fiddle: https://jsfiddle.net/hmea6rLx/
JS code:
function table(num){
var num=0;
while (num <= 0){
num = prompt("please enter any number");
var x = num;
$('#error').html("invalid number or Zero") ;
}
for(var i=1; i <= 10; i++){
var y = x * i;
$('#error').html(x + ' X ' + i +' = ' + y + '<br/>') ;
}
}
table();
Why the parameter (num)?
Your function rewritten in two ways, reusing itself:
document.querySelector('#table').addEventListener('click', start);
document.querySelector('#table2').addEventListener('click', start);
function start() {
return window[this.id]();
}
function table(){
var num = prompt("please enter any number");
if (num <= 0){
log(num + ": invalid number or zero");
return table();
}
for(var i = 1; i <= 10; i += 1){
log(i + ' * ' + num + ' = ' + (i * num));
}
}
// just for fun: more functional
function table2(){
var num = prompt("please enter any number");
var reslt = num <= 0 ? [num + ": invalid number or zero\n"] :
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(
function(v, i) {
return v + ' * ' + num + ' = ' + (v * num);
}
);
log(reslt.join('\n'));
return reslt.length < 10 ? table2() : true;
}
function log(str) {
log.el = log.el || document.querySelector("#result");
log.el.textContent += str+'\n';
}
<button id="table">exec table</button>
<button id="table2">exec table2</button>
<pre id="result"></pre>
I have an array of latitudes and longitudes in javascript, like this:
a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)
and I would like to create a string like this:
s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."
that is, each latlon pair has a comma separating the pair, and the pairs are separated by a space.
I'm a bit stuck here (mostly because I know very little of javascript):
function polylineToKml(p)
{
var s = "";
for (var i = 0; i < p.length; i+=2)
{
var lat = p[i];
var lon = p[i+1]
// now what?
}
}
In a more functional way:
function polylineToKml(p) {
return p.map(function(el, i) {
return el + (i % 2 > 0 ? " " : ",");
}).join("").trim();
}
And if your environment supports ES6:
var polylineToKml = p =>
p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();
One way:
var s = [];
for (var i = 0; i < a.length; i+=2)
{
s.push(a[i] + "," + a[i+1]);
}
s = s.join(" ");
function polylineToKml(p) {
var s = "";
for (var i = 0, l = p.length; i < l; i += 2) {
var lat = p[i];
var lon = p[i + 1];
s += lat + ',' + lon;
// don't add a space at the end
if (i !== l - 2) s += ' ';
}
return s;
}
DEMO
one more way...
function polylineToKml(p){
var s = "";
for (var i = 0; i < p.length - 1; i++){
s += p[i] + ",";
}
s += p[p.length - 1];
return s;
}
You should adopt a proper way to organize your data set, one way is to use JSON array with key-value pairs, e.g.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}
for (var i=0; i < coordinates.length; i++){
document.getElementById("demo").innerHTML +=
coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>
In this way, the coordinates will be represented as such:
coordinates = [
{"latitude":"1.234", "longitude":"2.345"},
{"latitude":"3.456", "longitude":"5.456"},
{"latitude":"4.653", "longitude":"2.567"}
];
Find out more on http://www.w3schools.com/json/default.asp
I would like to get the starting position of the 2nd occurrence of ABC with something like this:
var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16
How would you do it?
const string = "XYZ 123 ABC 456 ABC 789 ABC";
function getPosition(string, subString, index) {
return string.split(subString, index).join(subString).length;
}
console.log(
getPosition(string, 'ABC', 2) // --> 16
)
You can also use the string indexOf without creating any arrays.
The second parameter is the index to start looking for the next match.
function nthIndex(str, pat, n){
var L= str.length, i= -1;
while(n-- && i++<L){
i= str.indexOf(pat, i);
if (i < 0) break;
}
return i;
}
var s= "XYZ 123 ABC 456 ABC 789 ABC";
nthIndex(s,'ABC',3)
/* returned value: (Number)
24
*/
Working off of kennebec's answer, I created a prototype function which will return -1 if the nth occurence is not found rather than 0.
String.prototype.nthIndexOf = function(pattern, n) {
var i = -1;
while (n-- && i++ < this.length) {
i = this.indexOf(pattern, i);
if (i < 0) break;
}
return i;
}
Because recursion is always the answer.
function getPosition(input, search, nth, curr, cnt) {
curr = curr || 0;
cnt = cnt || 0;
var index = input.indexOf(search);
if (curr === nth) {
if (~index) {
return cnt;
}
else {
return -1;
}
}
else {
if (~index) {
return getPosition(input.slice(index + search.length),
search,
nth,
++curr,
cnt + index + search.length);
}
else {
return -1;
}
}
}
Here's my solution, which just iterates over the string until n matches have been found:
String.prototype.nthIndexOf = function(searchElement, n, fromElement) {
n = n || 0;
fromElement = fromElement || 0;
while (n > 0) {
fromElement = this.indexOf(searchElement, fromElement);
if (fromElement < 0) {
return -1;
}
--n;
++fromElement;
}
return fromElement - 1;
};
var string = "XYZ 123 ABC 456 ABC 789 ABC";
console.log(string.nthIndexOf('ABC', 2));
>> 16
This method creates a function that calls for the index of nth occurrences stored in an array
function nthIndexOf(search, n) {
var myArray = [];
for(var i = 0; i < myString.length; i++) { //loop thru string to check for occurrences
if(myStr.slice(i, i + search.length) === search) { //if match found...
myArray.push(i); //store index of each occurrence
}
}
return myArray[n - 1]; //first occurrence stored in index 0
}
a simple solution just add string, character and idx:
function getCharIdx(str,char,n){
let r = 0
for (let i = 0; i<str.length; i++){
if (str[i] === char){
r++
if (r === n){
return i
}
}
}
}
Shorter way and I think easier, without creating unnecessary strings.
const findNthOccurence = (string, nth, char) => {
let index = 0
for (let i = 0; i < nth; i += 1) {
if (index !== -1) index = string.indexOf(char, index + 1)
}
return index
}
Using indexOf and Recursion:
First check if the nth position passed is greater than the total number of substring occurrences. If passed, recursively go through each index until the nth one is found.
var getNthPosition = function(str, sub, n) {
if (n > str.split(sub).length - 1) return -1;
var recursePosition = function(n) {
if (n === 0) return str.indexOf(sub);
return str.indexOf(sub, recursePosition(n - 1) + 1);
};
return recursePosition(n);
};
function getStringReminder(str, substr, occ) {
let index = str.indexOf(substr);
let preindex = '';
let i = 1;
while (index !== -1) {
preIndex = index;
if (occ == i) {
break;
}
index = str.indexOf(substr, index + 1)
i++;
}
return preIndex;
}
console.log(getStringReminder('bcdefgbcdbcd', 'bcd', 3));
I needed a function that could search from the end of the string too so I wrote this:
function getPos(str, char, index, backwards) {
var split = str.split(char);
var result = 0;
var done = false;
split.forEach(function (item, i) {
if (done) {return}
result += item.length
if (!backwards && i === index) {
done = true
return
} else if (backwards && i === split.length - index - 2) {
done = true
return
}
result += char.length
})
return result
}
Usage:
getPos('x x x', 'x', 1, false) // 2
getPos('x x x', 'x', 0, true) // 4
Using String.indexOf:
var stringToMatch = "XYZ 123 ABC 456 ABC 789 ABC";
function yetAnotherGetNthOccurance(string, seek, occurance) {
var index = 0, i = 1;
while (index !== -1) {
index = string.indexOf(seek, index + 1);
if (occurance === i) {
break;
}
i++;
}
if (index !== -1) {
console.log('Occurance found in ' + index + ' position');
}
else if (index === -1 && i !== occurance) {
console.log('Occurance not found in ' + occurance + ' position');
}
else {
console.log('Occurance not found');
}
}
yetAnotherGetNthOccurance(stringToMatch, 'ABC', 2);
// Output: Occurance found in 16 position
yetAnotherGetNthOccurance(stringToMatch, 'ABC', 20);
// Output: Occurance not found in 20 position
yetAnotherGetNthOccurance(stringToMatch, 'ZAB', 1)
// Output: Occurance not found
var getPosition = function(string, subStr, index) {
if(!string.includes(subStr)) return null;
let arrs = string.split(subStr);
if(arrs.length < index) return null;
let result = 0;
for (let i = 0; i < index; i++) {
result += arrs[i].length;
}
result += (index - 1) * subStr.length;
return result;
}
I was playing around with the following code for another question on StackOverflow and thought that it might be appropriate for here. The function printList2 allows the use of a regex and lists all the occurrences in order. (printList was an attempt at an earlier solution, but it failed in a number of cases.)
<html>
<head>
<title>Checking regex</title>
<script>
var string1 = "123xxx5yyy1234ABCxxxabc";
var search1 = /\d+/;
var search2 = /\d/;
var search3 = /abc/;
function printList(search) {
document.writeln("<p>Searching using regex: " + search + " (printList)</p>");
var list = string1.match(search);
if (list == null) {
document.writeln("<p>No matches</p>");
return;
}
// document.writeln("<p>" + list.toString() + "</p>");
// document.writeln("<p>" + typeof(list1) + "</p>");
// document.writeln("<p>" + Array.isArray(list1) + "</p>");
// document.writeln("<p>" + list1 + "</p>");
var count = list.length;
document.writeln("<ul>");
for (i = 0; i < count; i++) {
document.writeln("<li>" + " " + list[i] + " length=" + list[i].length +
" first position=" + string1.indexOf(list[i]) + "</li>");
}
document.writeln("</ul>");
}
function printList2(search) {
document.writeln("<p>Searching using regex: " + search + " (printList2)</p>");
var index = 0;
var partial = string1;
document.writeln("<ol>");
for (j = 0; j < 100; j++) {
var found = partial.match(search);
if (found == null) {
// document.writeln("<p>not found</p>");
break;
}
var size = found[0].length;
var loc = partial.search(search);
var actloc = loc + index;
document.writeln("<li>" + found[0] + " length=" + size + " first position=" + actloc);
// document.writeln(" " + partial + " " + loc);
partial = partial.substring(loc + size);
index = index + loc + size;
document.writeln("</li>");
}
document.writeln("</ol>");
}
</script>
</head>
<body>
<p>Original string is <script>document.writeln(string1);</script></p>
<script>
printList(/\d+/g);
printList2(/\d+/);
printList(/\d/g);
printList2(/\d/);
printList(/abc/g);
printList2(/abc/);
printList(/ABC/gi);
printList2(/ABC/i);
</script>
</body>
</html>