Double Parse into an 2D array or jagged array - string

I have a text file that consist of
name,definition;
name1,definition;
name2, definition;
i know how to split the the string that is being taken into the script from the text file but i dont know how to get it all into a 2darray or jagged array.
it should look like this after words
array[0][0] = name;
array[0][1] = definition;
SORRY, i forgot to say what language, its in C#

Here's your solution in JavaScript. note If your row values can contain quotes, new lines, or escaped delimiters more parsing is necessary.
http://jsfiddle.net/N4YYA/
var result = [];
var txt = document.getElementById("test").value;
// get lines
var lines = txt.split(";");
for(var i=0; i<lines.length; i++) {
// get and trim whitespace off the line
var line = lines[i].replace(/(^[\s\r\n]*|[\s\r\n]*$)/g, "");
var values = line.split(",");
var row = [];
for(var j=0; j<values.length; j++) {
// get and trim whitespace off each value
var value = values[j].replace(/(^[\s\r\n]*|[\s\r\n]*$)/g, "");
// add it to your row array
row.push(value);
}
// add row to results
result.push(row);
}
// debug show result
var o = document.getElementById("outp");
for(var x=0; x<result.length; x++)
o.innerHTML += result[x].toString() + "<br/>";

In C#:
string[][] array = inputString.Split(';').Select(x => x.Split(',')).ToArray();
and if you want to include the trim for some reason:
string[][] array = inputString.Split(';').Select(x => x.Split(',').Select(y=>y.Trim()).ToArray()).ToArray();

Related

Node - Test if string contain element of array replace him by random element of same array (synonym)

I want to change each word that matches the synonym list randomly by another synonym or itself (to randomly keep this keyword).
I test if a string (input) contains one element of an array (words). If it's true, I want to randomly replace this with the element of this same list.
var input = "This is an amazing text blob where this word amazing is replaced by a random word from list_of_words. Isn't this amazing!";
words_synonym = ["amazing", "formidable", "great", "smart"];
// first condition --> true if "input" contain one element of "words_synonym"
input = input.toLowerCase();
console.log(words_synonym.some(word => input.includes(word)));
after, I want to replace the "element" that validated the condition with a random element of the same array (words_synonym).
But I can't select this element. I have just true or false
var random_word = words_synonym[Math.floor(Math.random() * (words_synonym.length))]
input = input.replace(element, random_word, 0)
thanks
The way you have it right now, you're checking if any of the synonyms match any of the words (via words_synonym.some(word => input.includes(word))). In order to do what you want, you'll need both the position of the target word and the new word, neither of which you have now. To do this, you'll want to break apart your nested loops.
The code words_synonym.some(word => input.includes(word)) is equivalent to:
let has_synonym = false;
for (word of words_synonym) { // this is a loop
if (input.includes(word)) { // this is also a loop
has_synonym = true;
break;
}
}
console.log(has_synonym);
So to fix your main issue, just replace includes with indexOf.
To handle the case of replacing all of the tokens, I would suggest keeping track of the token you have replaced outside of the loop, otherwise you end up replacing each token many times which may become very expensive. To do this, just keep track of your starting position outside of the loop and increment it with the end index of the replacement word. indexOf already takes a start argument for exactly this use case!
const input = "This is an amazing text blob where this word amazing is replaced by a random word from list_of_words. Isn't this amazing!";
const words_synonym = ["amazing", "formidable", "great", "smart"];
let output = input;
let start = 0; // index of the end of the last replaced token
for (word of words_synonym) {
let index = output.indexOf(word, start);
while (index >= 0) {
const new_word = words_synonym[Math.floor(Math.random() * (words_synonym.length))];
output = output.substr(0, index) + new_word + output.substr(index + word.length, output.length);
start = index + new_word.length + 1; // increment the start
index = output.indexOf(word, start);
}
}
console.log("input: ", input);
console.log("output: ", output);
You can use method find:
words_synonym.find(word => input.includes(word))
Which returns
The value of the first element in the array that satisfies the
provided testing function. Otherwise, undefined is returned.
from docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
i have modify answer of dantiston and i have include a loop in order to change all the word match "words_synonym".
But there is a problem. The program don't check all the word of "words_synonym" but only the first with indexof.
var input = "This is an amazing text blob where this word amazing is replaced by a random word from list_of_words. Isn't this amazing!";
words_synonym = ["amazing", "formidable", "great", "smart"];
let output = input;
for (word of words_synonym) {
let index = output.indexOf(word);
if (index >= 0) {
console.log(word);
var indexes = [], i = -1;
while ((i = output.indexOf(word, i+1)) != -1){
index=output.indexOf(word, i);
var new_word = words_synonym[Math.floor(Math.random() * (words_synonym.length))];
output = output.substr(0, index) + new_word + output.substr(index + word.length, output.length);
}
}
}
console.log("input: ", input);
console.log("output: ", output);

print random amount of words from a text file

I have a text file containing 100 words. I would like my programme to select a random number of words between 1 - 7 from the 100 words in the text file to print.
I know how to get a random number
var ranNum = Math.floor(Math.random() * 7) +1 ;
but not sure how to get my programme to select a random amount of words as determined by ranNum
function randomWord(){
var fs = require('fs');
var readME = fs.readFileSync('text.txt', 'utf8', function(err,data) {
//reads text file
console.log(data);
});
console.log(readME);
//returns a random num between 1-9
var ranNum = Math.floor(Math.random() * 7) + 1;
console.log(ranNum); //prints out that number
}
randomWord();
I want my programme to select a random amout of words from the text file each time it is run
If you want to get n random words from a text file and the text file consists of a string like this:
apple, orange, banana, pear, elephant, horse, dog, cow, brazil, england, france
You can use the following code:
// declare 'require()' imports at the top of your script
var fs = require('fs');
function randomWords(words){
// Since you use 'readFileSync', there is no callback function
var readME = fs.readFileSync('text.txt', 'utf8');
// Split the string into an array
var wordArr = readME.split(', ');
// Check if the specified amount of words is bigger than
// the actual array length (word count) so we don't end
// up in an infinite loop
words = words > wordArr.length ? wordArr.length : words;
// Create empty array
var randWords = [];
// push a random word to the new array n times
for (let i = 0; i < words; i++){
// new random number
let newRandom;
do {
// New random index based on the length of the array (word count)
let rand = Math.floor(Math.random() * wordArr.length);
newRandom = wordArr[rand];
}
// Make sure we don't have duplicates
while (randWords.includes(newRandom));
// Add the new word to the array
randWords.push(newRandom);
}
// Join the array to a string and return it
return randWords.join(', ');
}
// You can pass the amount of words you want to the function
console.log(randomWords(5));
I commented the code for clarification.
Working Repl.it Demo: Demo

c# beginner using stream reader to read in a txt file

i'm having trouble reading in a text file which contains 9 sets of three integer values separated by commas. This is what i have done so far, but how would i be able to read through the data going down row one to get a max value?
very stuck with a program the data text file looks like
21,7,11
20,10,12
17,7,18
these represent temperature, height and carbon%
i have read in the file as so
{
string s;
System.IO.StreamReader inputFile = new System.IO.StreamReader(DataFile);
s = inputFile.ReadLine();
int noDataLines = int.Parse(s);
double[,] data = new double[noDataLines, 3];
string[] ss;
is this right if the data is stored in the debug folder as a .txt file?
from here how would i go about getting a max temp(ie only reading the first vertical column of data)?
We can simply use mixture of System.IO File.ReadLines() method and LINQ .ToList() in order to read all text lines to List<string>. At this point we can just iterate through the collection parsing double values from text lines :
List<string> lines = File.ReadLines("filepath").ToList();
List<int[]> values = new List<int[]>();
int[] temp = new int[3];
for (int i = 0; i < lines.Count; i++)
{
string[] strValues = lines[i].Split(',');
for (int i2 = 0; i2 < strValues.Length; i2++)
temp[i2] = Convert.ToInt32(strValues[i2]);
values.Add(temp.ToArray());
}
Or we can use LINQ :
List<string> lines = File.ReadLines("filepath").ToList();
List<int[]> values = new List<int[]>();
int[] temp = new int[3];
for (int i = 0; i < lines.Count; i++)
values.Add(lines[i].Split(',')
.Select(l => Convert.ToInt32(l)).ToArray());

how to populate an array of type string[] using data table in C#

I'm having an issue populating
string double array using data table.
Please help.
string[][] export = function();
You'd want to do something like this:
(dt is your DataTable)
string[][] myArray = new string[dt.Rows.Count][dt.Columns.Count](); // Declare the new 2d array
for(i=0; i < dt.Rows.Count-1; i++) // Iterate through the rows
{
for(j=0; j < dt.Columns.Count-1; j++) // Iterate through the columns
{
myArray[i][j] = dt.Rows[i][j]; // Populate the array with the cell data.
}
}
return myArray

String comparison number of characters in same order

I have
Str A = "abcdef"
Str B = "abcdf"
I need a function(stA, stB) that returns 5 (ie. the number of characters matched), note that these characters need to be in same order.
For example:
Str A = "abcdef"
Str B = "fedcba",
function(stA, stB) would only return 1 for the 'a'
Pseudo code is good...
Oh btw given that all my strings will have <= 40 characters, O(n^2) might even be better than a O(41n) algorithm..
I haven't fully tested it, but this seems to be working (in JavaScript) for your test cases:
function compare(a, b)
{
var aChars = a.split('');
var bChars = b.split('');
var matches = [];
var bStart = 0;
for (var i=0; i < aChars.length; i++)
{
for (var j=bStart; j < bChars.length; j++)
{
if(aChars[i] == bChars[j])
{
matches.push(aChars[i]);
bStart = j;
break;
}
}
}
return matches.length;
}
compare('abcdef', 'abcdf'); // returns 5
compare('abcdef', 'fedcba'); // returns 1
Basically I'm starting at position 0 for string A and position 0 for string B. When a match is found, I change the start position for searching string B so that it skips the previous section.

Resources