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
Related
I would like to know if there will be a way to transform a csv to the JSON format suitable for the Tabulator library?
The idea would be to have a format as seen on excel :
- the first cell on the top left, empty
- columns A, B, C... AA, AB... according to the number of cells on the longest row
- the line number automatically on the first cell of each line)
I had the idea of doing it directly with loops, but it takes a lot of time I find. I don't see any other way.
Thank you for the help.
Check the following function, I hope this is what you are looking for...
let csvfile = 'title1,title2,title3,title4\n1,2,3,4\n11,22,33,44' //YOUR CSV FILE
let capLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' // ALPHABET SET
let finalJson = [];
let headers;
let line =[];
convertCSV2JSON(csvfile)
function convertCSV2JSON(csv) {
line = csv.split("\n"); //PARSE ALL AVAILABLE LINES INTO ARRAY
result = [];
headers = line[0].split(","); //PARSE ALL AVAILABLE STRING NAMES INTO ARRAY AND KEEP ONLY THE FIRST ONE (HEADER)
line.slice(1).forEach(function(item,i){ //RUN EACH ITEM EXCLUDING COLUMN NAMES
var obj = {};
if(line[i] === null || line[i] === undefined) {
}else{
var entries = line[i+1].split(","); // SEPARATE FOUND ENTRIES EXCLUDING COLUMN NAMES (i+1)
for(var j = 0; j < entries.length; j++) { // PARSE ENTRIES
obj[convert2Letters(j)] = entries[j]; // ASSIGN A LETTER AS COLUMN NAME
}
}
finalJson.push(obj);
})
console.log(finalJson);
}
function convert2Letters(iteration) {
let readyLetter = ''
while (iteration >= 0) {
readyLetter += capLetters[iteration % 26]
iteration = Math.floor(iteration / 26) - 1
}
return readyLetter
}
The fuzzy part was at foreach() function, because you cannot initiate index at your preference... slice() did the trick!
Moreover convert2Letters() function takes an array of letters and on each iteration finds the modulus of 26 letters, removing by one shows you the next combination...
Example:
If you have 30 columns it will give 30 % 26 = 4
4 corresponds to capLetters[4] which is 'E'
calculate next: iteration = Math.floor(iteration / 26) - 1 which means on every 26 increment (0,26,52,78...) it will give (-1,0,1,2...) corresponding. So a 30 columns iteration will have 0 as result which corresponds to capLetters[0] = 'A'
Resulting: 30 columns will give letters 'EA'
Have to pick unique random numbers from a given array of numbers. We have a list of numbers from that system has to pick unique random numbers.
Should have an option to input count, like if we give 3 system should pick 3 numbers from the given list.
Is there any available library?
const crypto = require('crypto');
const yourNumbers = [1,2,5,3,4,5,67,34,5345,6623,4234];
let selectedNumbers = [];
let i = 0;
const numbersRequired = 4;
while (i < numbersRequired){
const pos = crypto.randomBytes(4).readUInt32BE()%yourNumbers.length;
if (selectedNumbers.includes(yourNumbers[pos])) {
continue;
}
i++;
selectedNumbers.push(yourNumbers[pos]);
}
console.log(selectedNumbers)
I won't describe the code as it's self explanatory. Also handle the scenario where you cannot pick the required amount of numbers when the yourNumbers is too short. Also change the byte size if your number list is huge
const count = 8
pickedNumbers = [];
randomNumberList = [5,7,22,45,77,33,7,33,11,22,53,46,86,57,88];
for (i =0; i< count ; i++){
const randArrayIndex = Math.floor(Math.random() * randomNumberList.length);
pickedNumbers.push(randomNumberList[randArrayIndex]);
}
console.log(pickedNumbers);
It's a simple calculation. no need for an external library. You can use the random function of the Math object to generate a random number in js. It will return a number between 0 and 1. multiply it with the length of your array list. then it will give you a random index value from the range 0 - your array length. you can use push method of array object to push the numbers you are generating into an empty array.
control how many times you want this to happen with a loop setting the count value by users' input.
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();
On the webpage
http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463
It lists prices for a particular item in a game, I wanted to grab the "Current guide price:" of said item, and store it as a variable so I could output it in a google spreadsheet. I only want the number, currently it is "643.8k", but I am not sure how to grab specific text like that.
Since the number is in "k" form, that means I can't graph it, It would have to be something like 643,800 to make it graphable. I have a formula for it, and my second question would be to know if it's possible to use a formula on the number pulled, then store that as the final output?
-EDIT-
This is what I have so far and it's not working not sure why.
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var number = page.match(/Current guide price:<\/th>\n(\d*)/)[1];
SpreadsheetApp.getActive().getSheetByName('RuneScape').appendRow([new Date(), number]);
}
Your regex is wrong. I tested this one successfully:
var number = page.match(/Current guide price:<\/th>\s*<td>([^<]*)<\/td>/m)[1];
What it does:
Current guide price:<\/th> find Current guide price: and closing td tag
\s*<td> allow whitespace between tags, find opening td tag
([^<]*) build a group and match everything except this char <
<\/td> match the closing td tag
/m match multiline
Use UrlFetch to get the page [1]. That'll return an HTTPResponse that you can read with GetBlob [2]. Once you have the text you can use regular expressions. In this case just search for 'Current guide price:' and then read the next row. As to remove the 'k' you can just replace with reg ex like this:
'123k'.replace(/k/g,'')
Will return just '123'.
https://developers.google.com/apps-script/reference/url-fetch/
https://developers.google.com/apps-script/reference/url-fetch/http-response
Obviously, you are not getting anything because the regexp is wrong. I'm no regexp expert but I was able to extract the number using basic string manipulation
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
Then, I wrote a function to convert k,m etc. to the corresponding multiplying factors.
function getMultiplyingFactor(symbol){
switch(symbol){
case 'k':
case 'K':
return 1000;
case 'm':
case 'M':
return 1000 * 1000;
case 'g':
case 'G':
return 1000 * 1000 * 1000;
default:
return 1;
}
}
Finally, tie the two together
function pullRuneScape() {
var page = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var TD = "<td>";
var start = page.indexOf('Current guide price');
start = page.indexOf(TD, start);
var end = page.indexOf('</td>',start);
var number = page.substring (start + TD.length , end);
Logger.log(number);
var numericPart = number.substring(0, number.length -1);
var multiplierSymbol = number.substring(number.length -1 , number.length);
var multiplier = getMultiplyingFactor(multiplierSymbol);
var fullNumber = multiplier == 1 ? number : numericPart * multiplier;
Logger.log(fullNumber);
}
Certainly, not the optimal way of doing things but it works.
Basically I parse the html page as you did (with corrected regex) and split the string into number part and multiplicator (k = 1000). Finally I return the extracted number. This function can be used in Google Docs.
function pullRuneScape() {
var pageContent = UrlFetchApp.fetch("http://services.runescape.com/m=itemdb_rs/Armadyl_chaps/viewitem.ws?obj=19463").getContentText();
var matched = pageContent.match(/Current guide price:<.th>\n<td>(\d+\.*\d*)([k]{0,1})/);
var numberAsString = matched[1];
var multiplier = "";
if (matched.length == 3) {
multiplier = matched[2];
}
number = convertNumber(numberAsString, multiplier);
return number;
}
function convertNumber(numberAsString, multiplier) {
var number = Number(numberAsString);
if (multiplier == 'k') {
number *= 1000;
}
return number;
}
I'm building an ActionScript program in which I need to insert text into another string at random positions.
I have the text which strings will be inserted into; and I have the strings which will be inserted as an array.
However, I don't know how to go about inserting the elements of this array into the other string at random positions.
Any help will be highly appreciated.
The answer to your modified question:
var stringsToInsert:Array = ["abc", "def", "ghi"];
var text:String = "here is some text"
var textArr:Array = text.split(" ");
while(stringsToInsert.length)
{
var randomPosition:uint = Math.round( Math.random() * textArr.length );
textArr.splice(randomPosition, 0, stringsToInsert.pop());
}
text = textArr.join(" ");
trace(text);
while(arrayOftringsToInsert.length)
{
var randomPosition:uint = Math.round( Math.random() * text.length )
text = text.slice(0, randomPosition) + arrayOftringsToInsert.pop() + text.slice(randomPosition + 1, text.length)
}