Library to read numbers from a string in JS [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
I'm asking if there is a method or library that reads easily numbers this type of input strings (like competitive programming):
2 3
0 1 20
1 2 2
0 2 17
I'm finding something like Scanner class of Java because it has methods to detect whether there is next number, it jumps to the next line,...
Thanks in advance!

Try with parseInt for reading numbers. Also you can get the array of numbers with strings like the ones you have provided with somehting like this:
var numbers = str.split(" ").map(function(item) { return parseInt(item); });

The best thing you can do is use functional programming to implement a set of methods you can use together in the way you see fit.
const byLine = (input) => input.split('\n');
const toInt = (el) => Number(el);
const getDigits = (el) => el.split(' ').map(toInt);
const flatten = (arr) => arr.reduce((p, c) => p.concat(c));
function scanner(input) {
return flatten(byLine(input).map(getDigits));
}
DEMO

If you have access to the lines, you could use the following:
var i, lines = [ /* your lines goes here */], row;
// get lines
for (i = 0; i < lines.length; i++) {
row = lines[i].split(' ').map(Number);
// do something with row
}

Related

Function with maximum possible sum of some of its k consecutive numbers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
As title, can anyone help me write a function return maximum possible sum of some of its k consecutive numbers
(numbers that follow each other in order.) of a given array of positive integers. Thank you!
I have read the answer but can anyone show me how its work? i just dont understand those code about?
There are several ways to do this, you can do this with the help of traditional for, Math.max(), indexOf() and Array#reduce.
First of all, you need to find the maximum value of your input array, then you should pop it and according to the iteration count, iterate to find the next maximum value. Then after you find all the maximum values you need to sum them up at last.
function maxOfSumChain(arr, length) {
const maxArr = [];
for (let i = 0; i < length; i++) {
const max = Math.max(...arr);
maxArr.push(max);
arr.splice(arr.indexOf(max), 1);
}
return maxArr.reduce((a, b) => a + b, 0);
}
console.log(maxOfSumChain([1, 3, 2, 6, 2], 3));
console.log(maxOfSumChain([1, 3, 2], 2));

Need help extracting string from a text file via regex [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to extract a certain js object from a text/js file via regex.
The whole file contains a lot of code, but I'm only interested in getting a variable called cfg.
The file could look like this:
function A(){
}
var cfg = {
setting:1,
setting2: 5,
setting3:[],
setting4:{
setting5:"test"
}
};
function B(){
}
Could anyone help me to figure out the regex for this ? I'm terrible at regex and I've tried plenty of available solutions but some of them don't seem to be valid in C#.
Right now my solution is using:
string[] split = input.Split(new string[] { "var cfg = " }, StringSplitOptions.None);
if(split.Length > 2)
{
string[] split2 = split[1].Split(new string[] { ";" }, StringSplitOptions.None);
return JObject.Parse(split2[0]);
}
Which obviously doesn't cover different writings of the cfg object. Like var cfg={};
Thanks in advance!
I would recoment you use a JS parser such as Jint if your code is more complex or will change. But for your example this should work:
var r = new Regex(#"var cfg = (?<Content>\{[^;]*});");
var content = r.Match(text).Groups["Content"];
Note: If the cfg literal contains ; the regex will not work as expected.

Javascript - Sum solution [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am getting below line in my source file and I would like to sum those values separated by pipe ("|")
There is no limit for the values coming in the line (might be 100 values)
10|20|30|40|[no limit for values] - Separator is pipe "|"
The ouptput would be 100
Please help to write a javascript function for the above query.
Regards
Jay
You should take a look at JavaScript's built-in functions: With split you can split your string into an array, with reduce you can 'reduce' your array to a single value, in that case via summation. These two links should provide you enough information for building your code.
You could try something like below:
function sum(value){
var total = 0;
var array = value.split(",").map(Number);
for( var i = 0; i < array.length; i++) {
total += array[i];
}
alert(total);
}
var value = "10|20|30|40".replace(/\|/g, ',');
console.log(sum(value));
https://jsfiddle.net/f7uqw7cL/

Creating mathematical charts using chart.js jQuery [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Have you got any ideas how to create user-interactive line math charts with chart.js library, something like in wolframalpha? I know that i need to calculate x and y to draw chart correctly and range. It should look like myExample I can do line charts with static data, put in a code but need to know how to draw it after user provide function e.g 2x+5. All ideas and tricks will be very useful :) Thanks
Use math.js to parse the string input into a function.
// If "input" is a variable representing the string input for y
var f = math.eval('f(x) = ' + input');
Then compute a range of values for f to pass into chart.js:
// If "min" and "max" are values representing the minimum and max values
var values = [],
var x = min;
var increment = (max - min) / 10000;
for (var i = 0; i < 10000; i++)
values[i] = f(x + increment * i);

How do I rearrange an array with similar items so that similar items will never neighbor each other? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
So for example if I have this array:
var input = [1,1,2,4,6,7,7,1];
I want the output to be something like:
[1,2,1,4,6,7,1,7]
The order of the new array does not matter, as long as similar items will never (or at least as seldom as possible) neighbor each other.
I can use plain JavaScript as well as underscore.js.
Try the following:
var input = [1,1,2,4,6,7,7,1];
input.sort()
var output = [];
var len = input.length;
for (var i = 0; i < Math.floor((len / 2)); i++) {
output.push(input[i]);
output.push(input[len - i - 1]);
}
if (len % 2) {
var left_over = input[Math.floor(len / 2)];
if (left_over == output[0]) {
output.push(left_over);
} else {
output.unshift(left_over);
}
}
Or see http://jsfiddle.net/d0j3Lfa3/1.
The solution sorts the numbers then alternates high and low. It deals with an odd number of elements, including corner cases such as [1,1,2] and [1,2,2] where it needs to push the middle element differently to pass. Since the input is sorted, input order doesn't affect the output.
This answer may help simplify things a bit.

Categories

Resources