why my code doesn't work when I am trying to concatenate a function's return value with a string? - javascript

So, in this code I have a string of 0's and 1's and the length of the string is 32, which will be split in 6 equal parts but the last part will have the length of 2 so I will add (4) 0's after that which will make its length 6. So I wrote a function that will add the remaining 0's which is padding(num).
And that function will be invoked in side the slicing(str) function.
But the code breaks when I try to do execute.
Any help?
Thanks.
// This code works.
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
let f = padding0s(2);
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");
// But this does not..
function padding0s(num) {
let s = "";
for (i = 0; i < 6 - num; i++) {
s += "0";
}
return s;
}
function slicing(str) {
let k = 6;
let res = [];
let temp1 = 0;
for (i = 0; i < str.length; ) {
res.push(str.slice(i, k));
i += 6;
k += 6;
if (res[temp1].length !== 6) {
let f = padding0s(res[temp1].length);
res[temp1] += f;
}
temp1++;
}
console.log(res);
}
slicing("01000011010011110100010001000101");

Always define variables before using them
Not doing so can result in undefined behaviour, which is exactly what is happening in your second case. Here is how:
for (i = 0; i < str.length; ) {...}
// ^ Assignment to undefined variable i
In the above for-loop, by using i before you define it, you are declaring it as a global variable. But so far, so good, as it doesn't matter, if not for this second problem. The real problem is the call to padding0s() in your loop. Let's look at padding0s:
function padding0s(num) {
...
for (i = 0; i < 6 - num; i++) {
s += "0";
}
}
This is another loop using i without defining it. But since i was already defined as a global variable in the parent loop, this loop will be setting its value. So in short, the value of i is always equal to 6 - num in the parent loop. Since your exit condition is i < str.length, with a string of length 32 the loop will run forever.
You can get around this in many ways, one of which you've already posted. The other way would be to use let i or var i instead of i in the parent loop. Even better is to write something like this (but beware that padEnd may not work on old browsers):
function slicing(str) {
return str.match(/.{1,6}/g).map((item) => {
return item.padEnd(6, "0");
});
}
console.log(slicing("01000011010011110100010001000101"));

Related

How can I make my guess-password code's loop work?

I want to write this function "guessPasscode", but don't think my codes work. (the other functions are correct) It is supposed to guess every number from 0000 ~ 9999 as four-digit passcodes.
I run the function and it doesn't print out anything, and I also don't think the function works the way I wanted it to.
var guess = "";
var guessCode ="";
function start() {
var secretPasscode = generateRandomPasscode();
guessPasscode(secretPasscode);
}
// Checks whether the given guess passcode is the correct passcode
function isCorrect(guessCode, correctCode) {
return guessCode == correctCode;
}
// Generates a random 4 digit passcode and returns it as a String
function generateRandomPasscode() {
var randomPasscode = "";
for(var i = 0; i < 4; i++) {
var randomDigit = Randomizer.nextInt(0, 9);
randomPasscode += randomDigit;
}
return randomPasscode;
}
function guessPasscode(secretPasscode){
for (var a = 0; a < 10; a++){
guess += a;
for (var b = 0; b < 10; b++){
guess += b;
for(var c = 0; c < 10; c++){
guess += c;
for (var d = 0; d < 10; d++){
guess += d;
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
break;
}
guess = 0; //I am not sure about this line though
}
}
}
}
if (isCorrect(guessCode, secretPasscode)){
println("Success!");
}
}
I expect it to print "success" and stop the loop after it has found the correct password.
Those nested for loops are really wild and incredibly inefficient. If you want to guess from 0 to 9999, just run the loop through and then pad zeroes to the left.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
for (let i = 0; i < 9999; i++) {
let guess = String(i).padStart(4, '0')
guessAnswer(guess)
//whatever logic here to exit loop on correct guess
}

JavaScript neglecting the else statement

I created a function which takes in two values..
Both are numbers represented by n & p. What the function does is that it gets the number n and splits it up then squares it to the value of p and sums them in an increasing order like this: n^p + n^(p+1) + n^(p+2) + ...
Here is the function
function digPow(n, p) {
// ...
let num = n.toString();
let pow = p;
let arrn = [];
let arrp = [];
for (let i = 0; i < num.length; i++) {
arrn.push(JSON.parse(num[i]));
}
let index = arrn.join('');
let sindex = index.split('');
for (let j = 0; j < sindex.length; j++) {
let power = p + j;
let indexs = sindex[j];
let Mathpow = Math.pow(indexs, power);
arrp.push(Mathpow);
}
let total = 0;
for (let m in arrp) {
total += arrp[m]
}
let secondVal = total / n;
let totals = total / secondVal;
let mx = [-1]
if (totals.length == n.length) {
return secondVal
} else {
return -1
}
}
Now i created variables and arrays to store up the values and then the if part is my problem.. The if/else statement is meant to let the program check if a particular variable totals is equal to n which is the input.. if true it should return a variable secondVal and if not it should return -1..
So far its only returning secondVal and i'snt returning -1 in cases where it should like:
digPow(92, 1) instead it returns 0.14130434782608695
What do i do?
totals and n are both numbers. They don't have a .length property, so both totals.length and n.length evaluate to undefined. Thus, they are equal to each other.
There are plenty of other weird things going on in your code, too. I'd recommend finding a good JavaScript tutorial and working through it to get a better feel for how the language (and programming in general) works.
Let's start by stripping out the redundant variables and circular-logic code from your function:
function digPow(n, p) {
let num = n.toString();
// let pow = p; // this is never used again
// let arrn = []; // not needed, see below
// let arrp = []; // was only used to contain values that are later summed; can instead just sum them in the first place
// this does the same thing as num.split(''), and isn't needed anyway:
//for (let i = 0; i < num.length; i++) {
// arrn.push(JSON.parse(num[i]));
//}
// this is the same as the original 'num' variable
// let index = arrn.join('');
// This could have been num.split(), but isn't needed anyway
// let sindex = index.split('');
let total = 0; // moved this line here from after the loop below:
for (let j = 0; j < num.length; j++) { // use num.length instead of the redundant sindex
let power = p + j;
// The only reason for the sindex array was to get individual characters from the string, which we can do with .charAt().
//let indexs = sindex[j];
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
//arrp.push(Mathpow); // No need to collect these in an array
total += Mathpow; // do this instead
}
// No need for this loop, since we can sum the total during the previous loop
// let total = 0;
//for (let m in arrp) {
// total += arrp[m]
//}
let secondVal = total / n;
// let totals = total / secondVal;
// The above is the same thing as total / total / n, which is:
let totals = 1/n;
// This is never used
//let mx = [-1]
// This was totals.length and n.length, which for numbers would always be undefined, so would always return true
if (totals == n) {
return secondVal
} else {
return -1
}
}
So the above reduces to this functionally identical code:
function digPow(n, p) {
let num = n.toString();
let total = 0;
for (let j = 0; j < num.length; j++) {
let power = p + j;
let indexs = num.charAt(j);
let Mathpow = Math.pow(indexs, power);
total += Mathpow;
}
let secondVal = total / n;
let totals = 1 / n;
if (totals == n) {
return secondVal
} else {
return -1
}
}
Now let's talk about the logic. The actual output will always be -1, unless the input is 1, due to what's clearly a logic error in the totals variable: the only case where 1/n == n is true is when n==1.
Setting that aside, and looking only at the secondVal variable, some examples of what it's calculating for a given input would be
digPow(123,1) --> (1^1 + 2^2 + 3^3) / 123 --> 14/123
digPow(321,2) --> (3^2 + 2^3 + 1^4) / 321 --> 21/321
digPow(92, 1) --> (9^1 + 2^2) / 92 --> 13/92
I'm pretty sure from your description that that's not what you intended. I'm not at all sure from your description what you did intend, so can't be much help in correcting the function beyond what I've done here.
What I'd suggest is to sit down and think through your algorithm first; make sure you know what you're trying to build before you start building it. There were some syntax problems with your code, but the real issues are with the logic itself. Your original function shows clear signs of "just keep throwing more lines of code at it until something happens" rather than any planned thinking -- that's how you wind up with stuff like "split a string into an array, then join it back into a string, then split that string into another array". Write pseudocode first: break the problem down into steps, think through those steps for some example inputs and make sure it'll produce the output you're looking for. Only then should you bust out the IDE and start writing javascript.

How to get string from odd's array ?

I need help... I'm learning JavaScript, and it seems easy, but I may just be overlooking... everything... My problem is I need to return a string of all the even numbers between 0 and num inclusive; ex 7 gets you 0246, etc. I've gotten:
function stringOfEvens(num) {
for (let i = 0; i <= num.length; ++i) {
if (i % 2 === 0 ); {
return i;
}
}
}
I know the whole outlook is to run a for loop that goes from 0 to the number in question appending each time and if that number % 2 = 0, return that number, but something is a miss... I may even be overthinking and approaching this whole thing wrong... It is figuratively driving me mad...
function theJob(limit) {
var res = ''; //initialize as a string so that the other numbers will be appended instead of added
for (i = 0; i <= limit; i += 2) { // step increase by 2 to skip odd numbers
res += i;
}
return res; // returning the resulting string
}
console.log(theJob(10));
You can do this without using the modular function, by simply starting the loop at zero and incrementing by 2 each time the loop iterates...
function stringOfEvens(num) {
var result = "";
for (let i = 0; i <= num; i += 2) {
result += i; // append this even number to the result string
}
return result;
}
console.log(stringOfEvens(10));
You're returning the first number you find. a better approach would be to build the string in the loop then return after that string after the loop. Also no need for num.length if num is an int.
function stringOfEvens(num) {
var stringToReturn = "";
for (let i = 0; i <= num; i++) {
if (i % 2 === 0) {
stringToReturn = stringToReturn + i;
}
}
return stringToReturn;
}
function stringOfEvens(num) {
var str= ' ';
for(var i = 0; i <= num; i = i + 2){
str += i;
}
return str;
}
console.log(stringOfEvens(10))
Just for fun, since it's not particularly efficient:
const stringOfEvens = n => Array(~~(n/2)+1).fill().map((_, i) => 2*i).join("")
or annotated:
const stringOfEvens = n => // arrow function definition, returning:
Array(~~(n / 2) +1) // a sparse array of the required length
.fill() // made unsparse, so .map works
.map((_, i) => 2 * i) // then containing the even numbers
.join("") // and converted to a string
or alternatively (and more efficiently) using Array.from which can call an explicit map function in place:
const stringOfEvens = n => Array.from(Array(~~(n/2)+1), (_, i) => 2*i).join("")

JavaScript, brackets on for loop causing errors?

I have a function that takes an input of a string and a single char that will count how many times that char appears in that string.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++)
if (str.charAt(i) == letter)
num += 1;
return num;
}
console.log(count("BBC", "B"));
//output 2
It works fine like this, but this took me some time to figure out. Its second hand nature for me to always put brackets on a for loop but when i do that, the function doesn't work as i anticipated it would, like so:
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter)
num += 1;
return num;
}
}
console.log(count("BBC", "B"));
//outputs 1
Why are the brackets causing it to act this way?
Why are the brackets causing it to act this way?
Because you have the return statement inside of the for loop block. At the end of the block, the function returns.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) { // block start
if (str.charAt(i) == letter)
num += 1;
return num; // exit function in first loop
} // block end
}
It's not the braces (brackets are []), it's the placement of the return statement. The return statement is in the first iteration of the loop (i = 0). If you add an extra set of braces (as seen below), it becomes more obvious.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter) {
num += 1;
}
return num; // <-- This return exits the function
}
}
console.log(count("BBC", "B"));
//outputs 1
In the First one return statement was outside for loop, but in the second one return statement is inside the for loop. That made the difference.
Try the below code.
function count(str, letter) {
var num = 0;
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) == letter)
num += 1;
}
return num;
}
console.log(count("BBC", "B"));
your loop gets terminated after first iteration.
So if you try to get the occurrence of "B" in "XBBBB...B" it will return 0.
Try to debug your code and place brackets at right position.
Learn to debug your js code using browser.

undefined is returned in JavaScript function

When I call this function, sending for example: abc as the parameter,
the function returns: undefinedcba. I can't figure out why it's adding
'undefined' to my returned value. I'm probably overlooking something obvious
but I can't spot it. Thank you.
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Strings are 0-indexed. str[str.length] does not exist.
j needs to start at str.length - 1.
Or, just return str_arr1.join();
The index of the string starts at 0, so string.length is always one number bigger than index of the last character in the string.
In the second for loop, use
for(var j=str.length -1; j >= 0; j--) {
The error is in the second for statement. See the solution:
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length-1; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Because when you pass 'abc' there are only 3 characters in it.
So arrray str_arr have elements at index 0, 1 and 2.
But you are looping for str.length i.e. for 3 times and str_arr[3] is not defined.
You should do this,
function FirstReverse(str) {
var str_arr1 = new Array();
var ans = '';
for(i=0; i < str.length; i++) {
str_arr1.push(str.charAt(i));
}
for(j=str.length-1; j >= 0; j--) {
ans += str_arr1[j];
}
return ans;
}
Looks like you want to reverse a string, which you can do in this javascript one liner
function reverse(s){
return s.split("").reverse().join("");
}
The reason you are getting an undefined is because your j starts with str.length, whereas it should be str.length-1. str_arr1[str.length] is out of bounds and therefore will be undefined.

Categories