How can I use for loop to count numbers? - javascript

I need to count numbers upward and have it print out with a string "then" in between: 5 then 6 then 7 then... like this. I am very confused with using the parameters vs function name when you return. My code is below.. but could someone help with this?
function countUp(start) {
start +=
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
}
return start;
}

I would do something like this:
function countSheep(limit){
for (var i = 1; i < limit; i +=1){
console.log(i + " sheep")
}
}
countSheep(10);
I used "sheep" instead of "then", but you get the idea. Since you just want to produce a side effect (print out a "1 then 2.." to the console, you don;t need to build up a string and then have your function return it.
If you did want to build up a string and then have your function return it though, you could do something like this instead:
function countSheep(limit){
var allMySheep = "";
for (var i = 1; i < limit; i +=1){
allMySheep += (i + " sheep, ")
}
return allMySheep;
}
console.log(countSheep(10));
Note: I started my loops at 1 (var i = 1) because I'm counting sheep, not numbers. You'd probably want to start yours at 0 (var i = 0).

We can use JavaScript join function as well to achieve this
Code
function getCountStr(count) {
var str =[];
for (var i = 1; i <= count; i++) {
str.push(i);
}
console.log(str.join(' then '));
}

There are few issues with your code
function countUp(start) {
start += // <<<<< what's this? It's an incomplete (and useless) statement
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
// ^^^^^^^^ why are doing this? you should only write i
}
return start; // you don't need to return anything
}
A cleaned and working version from your code
function countUp(start) {
for(var i = start; i < start + 10; i++) {
console.log(i + " then ");
}
}
But this code will have an extra 'then' at the end like 1 then 2 then, so here's a code that will handle this
function countUp(start) {
// a temporary array to store your numbers
var tmpArr = [];
for (var i = start; i < start + 10; i++) {
// store the count into the array
tmpArr.push(i);
}
// display the count by putting ' then ' between each number
var stringToDisplay = tmpArr.join(' then ');
console.log(stringToDisplay);
document.write(stringToDisplay);
}
countUp(1);

Related

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

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

Compression String does not work for all strings

The idea is to complete the function and produce a compressed form of the string given. An example would be if the given string was aabbcc then you would get a2b2c2
The issue with the code I created is for some reason it does not work with anything right away that is consecutive or consecutive letters at the end. wwww turns into w4 but aa does not turn into a2 and wuenuneubgnjfniwfibwiebfaaa will not turn into wuenuneubgnjfniwfibwiebfa3
function compressedString(message) {
let out = '';
let count = 1;
for (let i = 0; i < message.length; i++) {
let current = message[i];
let next = message[i + 1];
if (current == next) {
count++;
} else {
out += current + String(count);
count = 1;
}
}
}
I test your algorithm, using given example of your question wuenuneubgnjfniwfibwiebfaaa, the output was w1u1e1n1u1n1e1u1b1g1n1j1f1n1i1w1f1i1b1w1i1e1b1f1a3, what sounds strange for the string compression requirement. When I add a nested condition inner first else in for loop, I acquired the correct result, please view the code bellow and let what do you think about:
function compressedString(message) {
let out = '';
let count = 1;
for (let i = 0; i < message.length; i++) {
let current = message[i];
let next = message[i + 1];
if (current == next) {
count++;
} else {
if(count == 1){
out += current;
}else{
out += current + String(count);
}
count = 1;
}
}
return out;
}
Your issue is the way you are handling it in the end. What happens to the variable next when the loop is on the last iteration? You need to add an extra check on your if.
Try this:
function compressedString(message) {
let out = '';
let count = 1;
for (var i = 0; i < message.length; i++){
let current = message[i];
let next = message[i + 1];
if ( i < message.length-1 && message[i] == next) {
count += 1;
} else {
out += current + String(count);
count = 1;
}
}
return out;
}

arr is not defined in Javascript Arrays

the following code is supposed to count the number of heads vs tails. The code below was given to me but I was tasked with counting heads vs tails, I tried with the function function countHeadsAndTails(flips) and below but running into a small issue. I have triple asterisked the line that is giving me an error: arr is not defined (under the function countHeadsAndTails(flips)) I'm sure this is just a silly mistake and I'd hate to waste your time with such an easy fix but I've been banging my head against the wall for the past 30 mins trying to solve it, thanks :)
var NUM_FLIPS = 100;
var headCount = 0, tailCount = 0;
function start(){
var flips = flipCoins();
printArray(flips);
}
// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
var flips = [];
for(var i = 0; i < NUM_FLIPS; i++){
if(Randomizer.nextBoolean()){
flips.push("Heads");
}else{
flips.push("Tails");
}
}
return flips;
}
function printArray(arr){
for(var i = 0; i < arr.length; i++){
println(i + ": " + arr[i]);
}
countHeadsAndTails();
}
function countHeadsAndTails(flips) {
for (var i = 0; i < NUM_FLIPS; i++) {
***if (arr["flips"] === "heads")***
headCount += arr[i];
else
tailCount += arr[i];
}
print("Heads: " + headCount + " " + "Tails: " + tailCount);
}
You have not declared the arr array as global, therefore you have to pass it to functions that are supposed to use it. The arr array is actually flips. I changed your code below to pass the array to the countHeadsAndTails() function and also added a couple other small changes to the same function (see arrows below).
Run and test:
var NUM_FLIPS = 100;
var headCount = 0, tailCount = 0;
function start(){
var flips = flipCoins();
printArray(flips);
}
// This function should flip a coin NUM_FLIPS
// times, and add the result to an array. We
// return the result to the caller.
function flipCoins(){
var flips = [];
for(var i = 0; i < NUM_FLIPS; i++){
if( Math.round(Math.random()) ){ // <- To mimic Randomizer
flips.push("Heads");
} else {
flips.push("Tails");
}
}
return flips;
}
function printArray(arr){
for(var i = 0; i < arr.length; i++){
console.log(i + ": " + arr[i]);
}
countHeadsAndTails(arr); // <- passing array to function
}
function countHeadsAndTails(flips) { // <- array is now called flips again
for (var i = 0; i < NUM_FLIPS; i++) {
if (flips[i] === "Heads") // <- check the ith element, and capital H
headCount++; // <- increment headCount
else
tailCount++; // <- increment tailCount
}
console.log("Heads: " + headCount + " " + "Tails: " + tailCount);
}
start();
Note: I also changed print() and println() to console.log() in order to be consistent with correct JavaScript output syntax.

Javascript procedure to decompress a string of decimal digits

I just started learning JavaScript and I'm extremely annoyed by it.
I want a procedure that decompresses a string of decimal digits like so:
"301051" means "3 zeros, a one, a zero, then 5 ones"
i.e.
"301051"---> "0001011111"
A string of digits of ones and zeros won't be changed at all (and also won't have any more than two consecutive 0's or 1's)
"01001100" ---> "01001100"
I started to work on it, but I'm churning out spaghetti code.
for (i = 0; i < thisString.length;)
{
thisNum = thisString.charCodeAt(i);
if (thisNum > 1)
{
substr = "";
for (j = 0; j < thisNum; j++)
subtr += thisString.charAt(i);
if (i == 0)
thisString = substr + thisString.substring(2
}
}
I don't feel like finishing that because I'm sick of using the limited number of JavaScript string functions. I'm sure the geniuses at Stack Overflow have a 1-line solution for me. Right, guys????
Here's a simple algorithmic solution:
function decompress(str) {
var result = "", char = "";
for (var i = 0; i < str.length; i++) {
char = str.charAt(i);
console.log(char - '0');
if (char > 1) {
result += new Array(+char + 1).join(str.charAt(++i));
} else {
result += char;
}
}
return result;
}
And an even simpler regex solution:
function decompress(str) {
return str.replace(/([2-9])(.)/g, function(m, a, b) {
return new Array(+a + 1).join(b);
});
}
The only magic here is the new Array(+a + 1).join(b) (which is also used by both solutions). The first + turns a (or char) into a number. Then I create an array of a + 1 elements, and join them together with following character as 'glue'. The result is a string of a repetitions of b.
I believe you need something like:
function decompress(thisString) {
var result = '';
for (var i = 0; i < thisString.length; i += 2) {
var thisNum = parseInt(thisString[i], 10);
if (thisNum > 1) {
for (var j = 0; j < thisNum; j++)
result += thisString[i + 1];
} else {
result += (thisString[i] + thisString[i + 1]);
}
}
return result;
}
You have a lot of variables, which are leaking as globals. Make sure you declare each of them using var.

Function to count how many numbers are there with the digits and division value specified

I started making a function that will be able do the following: Count how many 6 digit numbers you can make with the digits 0,1,2,3,4 and 5, that can be divided by 6?
How I currently try to start, is I make an array of all the possible numbers, then take out every number that has any of the numbers' arrays elements in it, then remove the ones that are not dividable with 6.
I got stuck at the second part. I tried making 2 loops to loop in the array of numbers, then inside that loop, create an other one for the length of the allnumbers array to remove all matches.
Then I would use the % operator the same way to get every element out that doesn't return 0.
The code needs to be flexible. If the user asks for eg. digit 6 too, then the code should still work. Any way I could finish this?
My Code is:
var allnumbers = [],j;
var biggestnumber = "999999999999999999999999999999999999999999999999999999999999";
function howmanynumbers(digits,numbers,divideWith){
if (digits && numbers && divideWith){
for (var i = 0; i < 1+Number(biggestnumber.substring(0,digits)); i++ ){
allnumbers.push(i);
}
for (j = 0; j < numbers.length; j++ ){
var matchit = new RegExp(numbers[j]);
}
//not expected to work, I just had this in for reference
if ( String(allnumbers[i]).match(matchit) != [""]){
j = 0;
allnumbers.splice(i,1);
var matchit = new RegExp(numbers[j])
}
}
else {
return false;
}
}
This is my take on the entire solution:
var i;
var allowedDigitsPattern = /^[0-5]+$/i;
var numbers = [];
for (i = 100000; i < 555555; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
And you can look at your results like this:
document.write('There are ' + numbers.length + ' numbers<br>');
// write out the first ten!
for (i = 0; i < 10; i++) {
document.write(numbers[i] + '<br>');
}
Update based on comments...
The configurable version of this would be:
var i;
var lowestDigit = 0;
var highestDigit = 5;
var numberOfDigits = 6;
var allowedDigitsPattern = new RegExp('^[' + lowestDigit + '-' + highestDigit + ']+$', 'gi');
var smallestNumber = '1';
for (i = 1; i < numberOfDigits; i++) {
smallestNumber += '0';
}
var biggestNumber = '';
for (i = 0; i < numberOfDigits; i++) {
biggestNumber += highestDigit.toString();
}
var numbers = [];
for (i = smallestNumber; i < biggestNumber; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
document.write('There are ' + numbers.length + ' numbers<br>');
You need to change the smallest and largest numbers based on the configuration. I have made both the allowable digits and the length of the number configurable.

Categories