Map Characters & Sum Ended
Description
You are given a number stored in a variable with the nameN
You are also, given a string, whose length is stored in a variable with the nameK, and the string is stored in a variable with the namestr
You have to map all lower case English characters, starting from the value stored inN.
For example, if the value stored inN = 30, then the mapping of the characters will be as follows
a-30
b-31
c-32
d-33
e-34
f-35
g-36
h-37
i-38
j-39
k-40
l-41
m-42
n-43
o-44
p-45
q-46
r-47
s-48
t-49
u-50
v-51
w-52
x-53
y-54
z-55
Finally, you have to print the sum of all the characters, present in the stringstr, according to the values mapped above
For example, if the value stored instr = "abc", then the required output will be
30 + 31 + 32 = 93, which is the required output
Input
The first line of the input contains the value stored inN
The second line of the input contains the value stored inK
The last line of the input contains the value stored in thestr
Output
Print the sum of characters, according to the values mapped, as shown in the problem statement
Sample Input 1
30
3
abc
Sample Output 1
93
Hint
In the sample test case, the value stored inN = 30, then the mapping of the characters will be as follows
a-30
b-31
c-32
d-33
e-34
f-35
g-36
h-37
i-38
j-39
k-40
l-41
m-42
n-43
o-44
p-45
q-46
r-47
s-48
t-49
u-50
v-51
w-52
x-53
y-54
z-55
Finally, you have to print the sum of all the characters, present in the stringstr, according to the values mapped above
For example, if the value stored instr = "abc", then the required output will be
30 + 31 + 32 = 93, which is the required output
code in image
function mapCharAndSum(n, str) {
let alphabet = [ ...Array(26).keys() ]
let alphabetWithValues = alphabet.map(num => [ String.fromCharCode(97 + num), n + num ])
let values = Array.from(str).map(char => alphabetWithValues.find(item => item[0] === char)[1])
return values.join(' + ') + ' = ' + values.reduce((sum, value) => sum + value)
}
console.log(mapCharAndSum(30, 'abc'))
// Output: 30 + 31 + 32 = 93
console.log(mapCharAndSum(0, 'stackoverflow'))
// Output: 18 + 19 + 0 + 2 + 10 + 14 + 21 + 4 + 17 + 5 + 11 + 14 + 22 = 157
console.log(mapCharAndSum(15, 'stack overflow'))
// Crashes, because ' ' is not part of the alphabet and there is no error handling
Related
I have an array that contains several countries followed by an option and a number.
0 " UK One 150 "
1 " Switzerland Two 70 "
2 " China Two 120 "
3 " Switzerland One 45 "
4 " China One 90 "
5 " UK Two 50 "
This is how I get the array using xpath:
var iterator = document.evaluate('//xpath/li[*]', document, null, XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
try {
var thisNode = iterator.iterateNext();
var arrayList = [];
while (thisNode) {
arrayList.push(thisNode.textContent);
thisNode = iterator.iterateNext();
}
for (var i = 0; i < arrayList.length; i++) {
console.log(arrayList[i]);
}
} catch (e) {
dump('Error' + e);
}
arrayList
What I would like to do with this array is to sort out and return only the matches. E.g. I would like for it to return only UK and China, so the array would look like this.
0 " UK One 150 "
1 " China Two 120 "
2 " China One 90 "
3 " UK Two 50 "
You can do it like this with help of sort() filter() and regex
What i did is first filter all the elements which contains either UK or China.
Now on this filtered array i need to capture the number using regex and sorted them in descending order.
let arr =[
"UK One 150 ",
"Switzerland Two 70 ",
"China Two 120 ",
"Switzerland One 45 ",
"China One 90 ",
"UK Two 50 ",
];
let op = arr.filter(e=>
/(UK|China)/gi.test(e))
.sort((a,b)=>{a.match(/\d+/g) - b.match(/\d+/g)}
);
console.log(op);
You can filter your array using the regular expression and then sort the result on the numeric value.
let data =["UK One 150 ","Switzerland Two 70 ","China Two 120 ","Switzerland One 45 ","China One 90 ","UK Two 50 "],
result = ((arr) => data.filter(s => new RegExp(arr.join('|'), 'ig').test(s)))(['UK', 'China'])
.sort((a,b)=> +a - +b);
console.log(result);
You can use a form of Schwartzian transform to "decorate" the data by extracting the name of the country, and the number using a array.map() and regex.
Now you can filter by the country, sort by the number, and extract the str using another map.
const arr =[
"UK One 150 ",
"Switzerland Two 70 ",
"China Two 120 ",
"Switzerland One 45 ",
"China One 90 ",
"UK Two 50 ",
];
const pattern = /^(\S+)\D+(\d+)/;
const requestedCounteries = new Set(['UK', 'China']);
const result = arr
.map(str => str.match(pattern)) // ['UK One 150 ', 'UK', '150']
.filter(([,country]) => requestedCounteries.has(country))
.sort(([,,a], [,,b]) => +b - +a)
.map(([str]) => str);
console.log(result);
Hello I was having issue with this function. I wanted to create a function that takes a number, a starting point and a final point, and writes the multiplication table of the number from the starting point to the ending point. For example, tabmul(10,2,4) returns
10.2 = 20
10.3 = 30
10.4 = 40
This is all good but it doesn't work for negative numbers. For example,
tabmul(10,-4,-1) should generate
10.-4 = -40
10.-3 = -30
10.-2 = -20
10.-1 = -10
but it doesn't return anything. This is my code:
function tabmul(a,b,c){ \\function that generates the multiplication table
var myarray = new Array();
var x
for(x=b; x<=c; x++){
myarray[x - b] = a*x;
document.write(a + "." + x + "=" + myarray[x - b] + "<br>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
tabmul(a,b,c);
} else {
alert("The starting point is bigger than the ending point");
}
You are comparing strings. This is because prompt returns strings. you need to convert a,b,c to numbers. Also you are using wrong symbols for comments, you need to correct those.
function tabmul(a,b,c){ //function that generates the multiplication table
a = Number(a);
b = Number(b);
c = Number(c);
var myarray = new Array();
var x
for(x=b;x<=c;x++){
myarray[x-b] = a*x;
document.write(a+"."+x+"="+myarray[x-b]+"<br/>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
if(0 <= c-b){ //this checks if the starting point is smaller or equal than the ending point of the table
tabmul(a,b,c);
}
else{
alert("The starting point is bigger than the ending point");
}
1)Make normal names for function arguments.
2)Use indentation and 'let' in 'for' loop instead of 'var' right before:
for(let x = b; x <= c; x++){}
3)Don't forget semicolons.
function multiplication(val, start, end) {
if(end - start <= 0) return;
for(let i = start; i <= end; i++) {
console.log(val + ' * ' + i + ' = ' + val * i);
}
}
multiplication(10, -4, -1);
10 * -4 = -40
10 * -3 = -30
10 * -2 = -20
10 * -1 = -10
You should also convert your input to a number using Number or parseInt to make sure it is numeric.
After that you can run into problems referring to an array by index using a negative number.
myarray[x-b] // can fail if x-b<0. Also for a large number n it will insert empty elements in your array up to N.
For example take the following:
var myarray= new Array();
myarray[-4]=1;
console.log(JSON.stringify(myarray));
// result "[]"
myarray= new Array();
myarray[10]=1;
console.log(JSON.stringify(myarray));
// result "[null,null,null,null,null,null,null,null,null,null,1]"
You could convert it to a string:
myarray['"' + (x-b) + '"'] = a*x;
Or you could just use push() and your indexes will start with zero.:
for(x=b;x<=c;x++){
myarray.push(a*x);
document.write(a+"."+x+"="+myarray(myarray.length-1)+"<br/>")
}
I get back
Nan ,
what does this mean?
In the distinctPlayer variable are two values 110 and 115. I want to have for this two Player the name and the sum of Note.
The first query of finalTotal gives for 110 the sum of Note 8 + 2 = 10 and for 115 the sum of Note 4 + 3 = 7 back.
The second query ... name of 110 is Dave and for 115 is Tom.
The while loop have an execution of 2 times. Then I try to safe each line of while in a variable. First line is Dave: 10 and second line is Tom: 7. But I don't get this back. At the moment the result is NaN ,
In the html the function is defined as
<p>
<pre>{{otherHelperFunction}}</pre>
</p>
And here is the function
var d = 0;
while(distinctPlayer[d]) {
var finalTotal = Spieltag.find({SpielerID: distinctPlayer[d]}).map(function (doc) {
total =+ doc.Note;
});
var finalName = Spieltag.find({SpielerID: distinctPlayer[d]}).map(function (doc) {
return doc.Name;
});
var finalReturn =+ finalName +" "+ finalTotal;
d++;
}
return finalReturn;
NaN means Not a Number. Try the following:
var finalReturn = finalName + " " + finalTotal;
The addition assignment operator is += which can be used as follows:
var a = 1;
a += 1 // a now has a value of 2
The += operator in this case represents a = a + 1.
You're using =+, the correct syntax is +=
Let's go,
NaN is Not a Number, you are trying treat as number what not Number.
You are using =+, you should use +=.
Probabily the doc.Note not is number.
JavaScript have function isNaN, this return a boolean.
i have a sting with a byte in it ("00001011") and now id like to get a array with all possible combinations of the 1 (acitve) "bits" in it also as a "byte string"
so from
var bString = "00001011"; //outgoing string
to a array with all string in it with all possible combinations of this "byte string" like - "00000001", "00000011", "00000010" and so on
is that possible?
thank you in advance
function combinations( input ){
var number = parseInt( input, 2 );
var combinations = [];
var zeroes = (new Array(input.length)).join(0);
for(var i=1;i<=number;i++){
if((i&number) == i){ combinations.push( i ) }
}
return combinations.map( function(dec){
return (zeroes + dec.toString(2)).substr( -zeroes.length-1 );
});
}
http://jsfiddle.net/jkf7pfxn/3/
console.log( combinations("00001011") );
// ["00000001", "00000010", "00000011", "00001000", "00001001", "00001010", "00001011"]
The idea goes as follows: iterate all numbers from 1 to the input number. If current number AND input number return the current number then both have 1 bits in the same place.
On a smaller number, "0101" (which is 5) it works as follows:
1 & 5 == 1, (0001 & 0101) push 1 to the matches.
2 & 5 == 0, (0010 & 0101) no match.
3 & 5 == 1, (0011 & 0101) no match.
4 & 5 == 4, (0100 & 0101) push 4 to the matches.
5 & 5 == 5, (0101 & 0101) push 5 to the matches.
So the combinations for 0101 are 1 (0001), 2 (0010), 4 (0100) and 5 (0101).
Then there's this little trick to pad numbers with zeroes:
var zeroes = (new Array(input.length)).join(0); // gives a long enough string of zeroes
then
// convert to base 2, add the zeroas at the beginning,
// then return the last n characters using negative value for substring
return (zeroes + dec.toString(2)).substr( -1 * zeroes.length);
Since 11111111 is 255 so just loop all values and convert them to binary
$(document).ready(function() {
for (var i = 0; i < 256; i++) {
$('#core').append('<div>' + dec2bin(i) + '</div>');
}
function dec2bin(dec) {
return ('00000000' + (dec >>> 0).toString(2)).slice(-8);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='core'></div>
If you want to enumerate all combinations of binary numbers where 1 can only be in the place of your pattern, you can write a simple recursive function:
var input = "00010111";
var current = [];
function combinations()
{
if (input.length === current.length)
{
var output = current.join('');
if (parseInt(output, 2) !== 0) // exclude all-zeroes case
document.body.innerHTML += output + "<br/>";
return;
}
current.push('0');
combinations();
current.pop();
if (input[current.length - 1] === '1')
{
current.push('1');
combinations();
current.pop();
}
}
combinations();
This algorithm works well for input of any length.
Although it is a recursion, it has a linear time complexity.
How can I do the following in JavaScript?
Concatenate "1", "2", "3" into "123"
Convert "123" into 123
Add 123 + 100 = 223
Covert 223 into "223"
You want to become familiar with parseInt() and toString().
And useful in your toolkit will be to look at a variable to find out what type it is—typeof:
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
Step (1) Concatenate "1", "2", "3" into "123"
"1" + "2" + "3"
or
["1", "2", "3"].join("")
The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").
Step (2) Convert "123" into 123
parseInt("123")
Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)
Step (3) Add 123 + 100 = 223
123 + 100
Step (4) Covert 223 into "223"
(223).toString()
or
String(223)
Put It All Togther
(parseInt("1" + "2" + "3") + 100).toString()
or
(parseInt(["1", "2", "3"].join("")) + 100).toString()
r = ("1"+"2"+"3") // step1 | build string ==> "123"
r = +r // step2 | to number ==> 123
r = r+100 // step3 | +100 ==> 223
r = ""+r // step4 | to string ==> "223"
//in one line
r = ""+(+("1"+"2"+"3")+100);
These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.
Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.
Step (1) Concatenate "1", "2", "3" into "123"
result = "1" + "2" + "3";
Step (2) Convert "123" into 123
result = +"123";
Step (3) Add 123 + 100 = 223
result = 123 + 100;
Step (4) Convert 223 into "223"
result = "" + 223;
If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.
You can do it like this:
// step 1
var one = "1" + "2" + "3"; // string value "123"
// step 2
var two = parseInt(one); // integer value 123
// step 3
var three = 123 + 100; // integer value 223
// step 4
var four = three.toString(); // string value "223"
To convert a string to a number, subtract 0.
To convert a number to a string, add "" (the empty string).
5 + 1 will give you 6
(5 + "") + 1 will give you "51"
("5" - 0) + 1 will give you 6
parseInt is misfeatured like scanf:
parseInt("12 monkeys", 10) is a number with value '12'
+"12 monkeys" is a number with value 'NaN'
Number("12 monkeys") is a number with value 'NaN'
Below is a very irritating example of how JavaScript can get you into trouble:
If you just try to use parseInt() to convert to number and then add another number to the result it will concatenate two strings.
However, you can solve the problem by placing the sum expression in parentheses as shown in the example below.
Result: Their age sum is: 98; Their age sum is NOT: 5048
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
var myFather = new Person("John", "Doe", "50", "blue");
var myMother = new Person("Sally", "Rally", 48, "green");
document.getElementById("demo").innerHTML = "Their age sum is: "+
(parseInt(myFather.age)+myMother.age)+"; Their age sum is NOT: " +
parseInt(myFather.age)+myMother.age;
</script>
</body>
</html>
Simplest is
when you want to make a integer a string do
var a,b, c;
a = 1;
b = a.toString(); // This will give you string
Now, from the variable b which is of type string we can get the integer
c = b *1; //This will give you integer value of number :-)
If you want to check above is a number. If you are not sure if b contains integer
then you can use
if(isNaN(c*1)) {
//NOt a number
}
else //number
We can do this by using unary plus operator to convert them to numbers first and simply add. see below:-
var a = "4";
var b = "7";
var sum = +a + +b;