Removing the space in the loop javascript - javascript

It is a counter function for descending number. I throw any number and it start to countdown to zero and I add space between them but the Problem is the last space! How can I remove it??
function countDown(number) {
var s = "";
for (let i = number; i >= 0; i--) {
s += i + " ";
}
console.log("{" + s + "}"); // I add the brackets to show the last space
}
countDown(10)
// result is : {10 9 8 7 6 5 4 3 2 1 0 }

This is a great use case for the Array.join function.
function countDown(number) {
const list = [];
for (let i = number; i >= 0; i--) {
list.push(i);
}
console.log("{" + list.join(' ') + "}");
}
countDown(10)
// result is : {10 9 8 7 6 5 4 3 2 1 0}

This is a common pattern that one has to deal with in loops.
Typically you solve this by having a special case in the beggining or end of a loop. In this example it is easy just to have one in the beggining:
function countDown(number) {
var s = number;
for (let i = number - 1; i >= 0; i--) {
s += " " + i;
}
console.log("{" + s + "}"); // I add the brackets to show the last space
}
countDown(10)
// result is : {10 9 8 7 6 5 4 3 2 1 0}
Just assign s to the number in the beggining and decrease the starting number by 1.

With "low-level" Javascript, without builtins, the trick is to add a delimiter before an item, not after it:
function countDown(number) {
let s = String(number)
for (let i = number - 1; i >= 0; i--)
s += ' ' + i
return s
}
console.log(JSON.stringify(countDown(10)))
If builtins are allowed, you don't even need a loop to produce this result:
result = [...new Array(11).keys()].reverse().join(' ')
console.log(result)

Related

How can I get results from a given array with following conditions? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Does return stop a loop?
(7 answers)
Closed 12 months ago.
I'm a beginner in JavaScript and doing an online test to improve my skills. I came across to this question:
Add 1 point for each even number in the array
Add 3 points for each odd number in the array
Add 5 points every time the number 5 appears in the array
So if I am given this array as an example:
([1,2,3,4,5])
the output should be 13
This is what I have got so far:
export function find_total( my_numbers ) {
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] % 2 === 0) {
total = total + 1
}
if(my_numbers[i] % 2 === 1) {
total = total + 3
}
if(my_numbers[i] === 5) {
total = total + 5
}
return total
}
console.log(total)
}
But it is giving me errors. I get the logic in English but couldn't put it in JS.
What would be the right syntax here?
The problem is with your if statements.
function find_total( my_numbers ) {
let total = 0;
for(let i = 0; i < my_numbers.length; i++){
if(my_numbers[i] === 5) {
total = total + 5
}
else if(my_numbers[i] % 2 === 0) {
total = total + 1
}
else if(my_numbers[i] % 2 === 1) {
total = total + 3
}
}
return total;
}
console.log(find_total([1,2,3,4,5]))
This code should print the correct result of 13.
You were not getting an answer of 13 because 5 is odd so has 3 point and 5 point exclusive to 5. The key is not to treat 5 as having point of odd number but having it's own point irrespective of either it is odd or even.
There are following issues in your code:
total in the function find_total is never initialized
return statement is misplaced inside the for loop, it must be outside, signifying return value of the function find_total
Better to console.log the value of the function, instead of logging it inside. eg. console.log(find_total(...))
Fixing these, you will indeed get the return value as 16 for input [1, 2, 3, 4, 5] as pointed out in the comments.
function find_total(my_numbers) {
let total = 0 // Initialize total with a value of 0
for (let i = 0; i < my_numbers.length; i++) {
if (my_numbers[i] % 2 === 0) {
total = total + 1
}
if (my_numbers[i] % 2 === 1) {
total = total + 3
}
if (my_numbers[i] === 5) {
total = total + 5
}
}
return total // return outside the loop
}
console.log(find_total([1, 2, 3, 4, 5])) // console.log outside

Duplicating each character for all permutations of a string

This is a slightly odd/unique request. I am trying to achieve a result where e.g "yes" becomes, "yyes", "yees", "yess", "yyees", "yyess", "yyeess".
I have looked at this: Find all lowercase and uppercase combinations of a string in Javascript which completes it for capitalisation, however my understanding is prohibiting me from manipulating this into character duplication (if this method is even possible to use in this way).
export function letterDuplication(level: number, input: string){
const houseLength = input.length;
if (level == 1){
var resultsArray: string[] = [];
const letters = input.split("");
const permCount = 1 << input.length;
for (let perm = 0; perm < permCount; perm++) {
// Update the capitalization depending on the current permutation
letters.reduce((perm, letter, i) => {
if (perm & 1) {
letters[i] = (letter.slice(0, perm) + letter.slice(perm-1, perm) + letter.slice(perm));
} else {
letters[i] = (letter.slice(0, perm - 1) + letter.slice(perm, perm) + letter.slice(perm))
}
return perm >> 1;
}, perm);
var result = letters.join("");
console.log(result);
resultsArray[perm] = result;
}
If I haven't explained this particularly well please let me know and I'll clarify. I'm finding it quite the challenge!
General idea
To get the list of all words we can get from ordered array of letters, we need to get all combinations of letters, passed 1 or 2 times into word, like:
word = 'sample'
array = 's'{1,2} + 'a'{1,2} + 'm'{1,2} + 'p'{1,2} + 'l'{1,2} + 'e'{1,2}
Amount of all possible words equal to 2 ^ word.length (8 for "yes"), so we can build binary table with 8 rows that represent all posible combinations just via convering numbers from 0 to 7 (from decimal to binary):
0 -> 000
1 -> 001
2 -> 010
3 -> 011
4 -> 100
5 -> 101
6 -> 110
7 -> 111
Each decimal we can use as pattern for new word, where 0 means letter must be used once, and 1 - letter must be used twice:
0 -> 000 -> yes
1 -> 001 -> yess
2 -> 010 -> yees
3 -> 011 -> yeess
4 -> 100 -> yyes
5 -> 101 -> yyess
6 -> 110 -> yyees
7 -> 111 -> yyeess
Code
So, your code representation may looks like this:
// Initial word
const word = 'yes';
// List of all possible words
const result = [];
// Iterating (2 ^ word.length) times
for (let i = 0; i < Math.pow(2, word.length); i++) {
// Get binary pattern for each word
const bin = decToBin(i, word.length);
// Make a new word from pattern ...
let newWord = '';
for (let i = 0; i < word.length; i++) {
// ... by adding letter 1 or 2 times based on bin char value
newWord += word[i].repeat(+bin[i] ? 2 : 1);
}
result.push(newWord);
}
// Print result (all possible words)
console.log(result);
// Method for decimal to binary convertion with leading zeroes
// (always returns string with length = len)
function decToBin(x, len) {
let rem, bin = 0, i = 1;
while (x != 0) {
rem = x % 2;
x = parseInt(x / 2);
bin += rem * i;
i = i * 10;
}
bin = bin.toString();
return '0'.repeat(len - bin.length) + bin;
}
Maybe this example can help you. It's a bit not neat and not optimal, but it seems to work:
function getCombinations(word = '') {
const allCombination = [];
const generate = (n, arr, i = 0) => {
if (i === n) {
return allCombination.push([...arr]);
} else {
arr[i] = 0;
generate(n, arr, i + 1);
arr[i] = 1;
generate(n, arr, i + 1);
}
}
generate(word.length, Array(word.length).fill(0));
return allCombination.map((el) => {
return el.map((isCopy, i) => isCopy ? word[i].repeat(2) : word[i]).join('')
});
}
console.log(getCombinations('yes'));
console.log(getCombinations('cat'));

Digital Root (repeated digital sum) code issue

Question : Given n, take the sum of the digits of n. If that value has
more than one digit, continue reducing in this way until a
single-digit number is produced. The input will be a non-negative
integer. Ex- 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 +
5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193
--> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2
function digitalroot(n) {
let a = n;
var sum = 0;
while(a >= 1){
sum += a % 10;
a = Math.trunc(a/10)
}
if(sum > 9){
digitalroot(sum)
}
console.log("Print")
console.log(sum)
return sum
}
I tried above code but not getting correct output with below called input
With this two inputs passed in function: (16), (456)
O/P:
Print
7
Print
6
Print
15
Please help me, I am new to JavaScript
you forgot to return value from function call inside that sum>9 condition.
check recursion here : w3School
function digitalroot(n) {
let a = n;
var sum = 0;
while(a >= 1){
sum += a % 10;
a = Math.trunc(a/10)
}
if(sum > 9){
return digitalroot(sum)
}
return sum
}
console.log(digitalroot(493193));
Check this working example
function digitalroot(n){
console.log(`Value of n = ${n}`)
var digits = (""+n).split("");
for (var i = 0; i < digits.length; i++) {
digits[i] = +digits[i];
}
var finalVal = digits
let result = finalVal.reduce((a, b) => a + b, 0)
console.log(`Final Value with list ${result}`)
}
digitalroot(289)

Converting prefix to infix in JavaScript

I am trying to write a program that takes in an prefix expression and outputs an infix expression. I have examples listed below to help demonstrate what I am talking about. I have pasted my code below, could someone please help me figure out how I can move the symbol between 2 numbers in an expression? Please see example 1 to see my approach on how I tried to get it, but it doesn't work. Any answers would be helpful or tips as to what to do. Thank you for your help!
/* The goal is to take in an expression in prefix notation and output it in infix notation
for example:
+ 1 2 outputs output 1 + 2
+ - 3 4 5 outputs 3 + 4 - 5
% + / - 0 9 3 8 5 outputs 0 % 9 + 3 / 8 - 5
*/
function convert(input){
var x = input.split(''); // splits each variable and stores it in an array
var output = "";
// these are the valid symbols we can take, we will use these later
var symbols = ['+', '-', '*', '/', '%'];
// lets loop through all the values in x, starting at position 0
for(var i = 0; i < x.length; i++){
if(symbols.includes(x[i])) { // we hit a symbol, lets move it between 2 numbers
/* now we need to figure out where to store the symbol. every 2 spaces starting at index 0
we can insert a symbol (so spots like 1 3 5 7 etc). this loop will help us figure out what spot is empty
, and it will store the symbol at that spot [see example 1 for a visualizaton]*/
for(var j = 0; j < input.length; j+=2){
if(output[j] == " "){
// great, we can save the symbol here
output = output + x[i];
}
}
}
// otherwise we have a number on our hands
else{
output = output + x[i];
console.log(output);
}
}
}
console.log(convert("+ 1 2"));
/*
example 1
if I have "+ 1 2"
+ is position 0
1 is position 2
2 is position 4
so the whitespace is at position 1 and 3. these are the spots where we can output the symbols
using the original expression + 1 2
position: value:
-------- | ------
0 | 1
-------- | ------
1 | " "
-------- | ------
2 | +
-------- | ------
3 | " "
-------- | ------
4 | 2
*/
function result_expression(expression, variables) {
let opernads=['+','-','*','/'];
let arr=[...expression.split(" ")];
var len=arr.length;
while(len>0){
let d1=arr[len-1]
let d2=arr[len-2]
let d3=arr[len-3]
if(opernads.includes(d3)){
if(isNaN(d2)){
let tmp=variables[d2]
d2=tmp;
}
if(isNaN(d1)){
let tmp1=variables[d1]
d1=tmp1;
}
let a=d2.toString().concat(d3).concat(d1)
delete arr[len-1]
delete arr[len-2]
delete arr[len-3]
let na=[];
arr[len-3]=eval(a)
arr.forEach(e=>{
if(!(typeof e==='undefined')){
na.push(e)
}
})
arr=[...na]
console.log('arr',arr)
len=arr.length;
// arr=[...newar]
// len=arr.length
}else{
len--
}
if(len==1){
return arr[0]
}
}
}
//let expression="+ 6 * - 4 + 2 3 8";
//let expression="+ 6 * - 4 a b + 2 3 8";
let expression="+ * 6 5 3 2 2";
let variables={a:20,b:1}
let k=result_expression(expression, variables);
console.log('finalresult',k)
So long as you're only using simple expressions, I would suggest dividing the input into two arrays, numbers and symbols, and then merging them together.
var symbols = ['+', '-', '*', '/', '%'];
function convert(input) {
var
response = '',
infixes = [],
numbers = [];
// Divide input into two arrays, infixes (or symbols) and numbers
infixes = input.split(' ').filter(function(o) {
if (symbols.includes(o)) {
return true;
} else {
numbers.push(o);
}
});
// Merge arrays
for (let i = 0; i < numbers.length; i++) {
if (infixes[i]) {
response =
response +
numbers[i] + ' ' +
infixes[i] + ' ';
} else {
response =
response + numbers[i] + ' ';
}
}
response = response.slice(0, -1);
return response;
};
This function works for all your examples, but if you need to make it more intelligent you can easily modify and test the above function on codepen here.

Sort array by frequency

I would like to count how many times is every string in array and sort them by number of times they exist in array
I have this code now
hlasy.sort();
var zaciatok = null;
var pocet = 0;
for (var i = 0; i < hlasy.length; i++) {
if (hlasy[i] != zaciatok) {
if (pocet > 0) {
console.log(zaciatok + ' má ' + pocet + ' hlasov');
}
zaciatok = hlasy[i];
pocet = 1;
} else {
pocet++;
}
}
if (pocet > 0) {
console.log(zaciatok + ' má ' + pocet + ' Hlasov');
}
it works, but it outputs strings from array sorted by alphabet and no by how many times they are in array.
for example, it outputs
apple - 1
banana - 5
cherry - 4
but I need this
banana - 5
cherry - 4
apple - 1
thanks in advance
Two passes. First, compute the number of occurrences of each word:
counter = Object.create(null);
words.forEach(function(word) {
counter[word] = (counter[word] || 0) + 1;
});
Then, sort the array by comparing two words' counts:
words.sort(function(x, y) {
return counter[y] - counter[x];
});

Categories