I have over 170000 entries of data in data file in this format:
1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:
1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:
Now each data array starts with a unique id and i was wondering is there a convenient way to push each entry 1479661 then 1479662 every second to an array and assign the values within the unique id into 6 fields that update.
Now I ask if there is a more convenient way as currently I am using this method:
Data comprises of three chunks in a single line
Split the link into chunks
var chunkOne = [1479661];
var chunkTwo = [-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00];
var chunkThree = [117,-1397,7,7.00,"A","Dead"];
Then get length of each array:
var chunkOneLength = chunkOne.length;
var chunkTwoLength = chunkTwo.length;
var chunkThreeLength = chunkThree.length;
Pick out the nth value in the array depending on the data chunk:
//uniqueID set as first
for (var i = 0; i < chunkOneLength; i = i + 1) {
// useful code would go here
alert("This is the unique ID " + chunkOne[i]);
}
//teamval
for (var i = 0; i < chunkTwoLength; i = i + 6) {
// useful code would go here
alert("This is the teamVal " + chunkTwo[i]);
}
Now the only problem I see with this method, is that the original data array will need to be formatted and separated into chunks every time.
As you have a separator on each section i.e. : you can actually use split to split them up like below and push them into a array and only have to do 2 loops - firstly pushing the split data in a new array and then looping through them and populating the structure.
Please note as long as each chunk of data is separated with : this will work with anything even if you expand the data later. obviously it will not work if you remove the : separator.
example below:
var splitChucks = [];
var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"];
for (var i = 0; i < chucks.length; i++){
splitChucks.push(chucks[i].split(':'))
}
for (var h = 0; h < splitChucks.length; h++) {
alert("This is the unique ID " + splitChucks[h][0]);
alert("This is the teamVal " + splitChucks[h][1]);
}
Hope this helps, this is a much more efficient way to do your task :)
var splitChucks = [];
var chucks = [ "1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:", "1479662:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1392,0.00;-1,4,-1,-6,-2419,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1392,7,7.07,A,Dead;:"];
for (var i = 0; i < chucks.length; i++){
splitChucks.push(chucks[i].split(':'))
}
for (var h = 0; h < splitChucks.length; h++) {
alert("This is the unique ID " + splitChucks[h][0]);
alert("This is the teamVal " + splitChucks[h][1]);
}
One of the best purposes of an unique ID is to act as an index. So, instead of iterating over your index array (chunkOne), use ID as an Object key!
// 1479661:-1,1,-1,-898,-769,0.00;-1,2,-1,-96,-1402,0.00;-1,3,-1,117,-1397,0.00;-1,4,-1,-4,-2420,0.00;4,5,-1,5570,4395,0.00;4,6,-1,5570,4395,0.00;4,7,-1,5570,4395,0.00;4,8,-1,5570,4395,0.00;4,9,-1,5570,4395,0.00;4,10,-1,5570,4395,0.00;4,11,-1,5570,4395,0.00;4,12,-1,5570,4395,0.00;4,13,-1,5570,4395,0.00;4,14,-1,5570,4395,0.00;-1,15,-1,913,-3533,0.00;4,16,-1,5570,4395,0.00;4,17,-1,5570,4395,0.00;4,18,-1,5570,4395,0.00;4,19,-1,5570,4395,0.00;4,20,-1,5570,4395,0.00;4,21,-1,5570,4395,0.00;4,22,-1,5570,4395,0.00;4,23,-1,5570,4395,0.00;4,24,-1,5570,4395,0.00;4,25,-1,5570,4395,0.00;4,26,-1,5570,4395,0.00;4,27,-1,5570,4395,0.00;4,28,-1,5570,4395,0.00;4,29,-1,5570,4395,0.00;:117,-1397,7,7.00,A,Dead;:
var data =
{
1479661:
[
-1,1,-1,-898,-769,0.00,-1,2,-1,-96,-1402,0.00,-1,3,-1,117,-1397,0.00,-1,4,-1,-4,-2420,0.00,4,5,-1,5570,4395,0.00,4,6,-1,5570,4395,0.00,4,7,-1,5570,4395,0.00,4,8,-1,5570,4395,0.00,4,9,-1,5570,4395,0.00,4,10,-1,5570,4395,0.00,4,11,-1,5570,4395,0.00,4,12,-1,5570,4395,0.00,4,13,-1,5570,4395,0.00,4,14,-1,5570,4395,0.00,-1,15,-1,913,-3533,0.00,4,16,-1,5570,4395,0.00,4,17,-1,5570,4395,0.00,4,18,-1,5570,4395,0.00,4,19,-1,5570,4395,0.00,4,20,-1,5570,4395,0.00,4,21,-1,5570,4395,0.00,4,22,-1,5570,4395,0.00,4,23,-1,5570,4395,0.00,4,24,-1,5570,4395,0.00,4,25,-1,5570,4395,0.00,4,26,-1,5570,4395,0.00,4,27,-1,5570,4395,0.00,4,28,-1,5570,4395,0.00,4,29,-1,5570,4395,0.00,117,-1397,7,7.00,"A","Dead"
]
// More data...
};
Object.keys(data).forEach(function(key)
{
console.log('This is ID ' + key);
data[key].forEach(function(value,index,array)
{
console.log('Index ' + index + ' of data key ' + key + ':');
console.log(data[key][index]);
});
});
Test this on any modern browser's console or node.js instance to see results.
Related
I'm trying to make a simple 'bad words' filter with javascript. It's meant to listen to any submit events on the page, then iterate through all input fields of the text type, check them for bad stuff by comparing the entered text with the word list, and finally return an according console.log/alert (for now).
I have two files: word-list.js with the critical words (loads first) and filter.js which pulls an array with all words from word-list.js.
My problems is, swear_words_arr[1] is 'undefined' and I don't understand why. I've been looking around for solutions, but still I can't seem to determine the reason for this. Help is much appreciated.
// get all inputs type = text and turn html collection into array
var getInputs = document.querySelectorAll("input[type=text]")
var inputs = Array.from(getInputs);
//var swear_alert_arr -> from in word-list.js
var swear_alert_arr = new Array();
var swear_alert_count = 0;
function reset_alert_count() {
swear_alert_count = 0;
}
function validate_text() {
reset_alert_count();
inputs.forEach(function(input) {
var compare_text = input.value;
console.log(compare_text);
for (var i = 0; i < swear_words_arr.length; i++) {
for (var j = 0; j < compare_text.length; i++) {
if (
swear_words_arr[i] ==
compare_text.substring(j, j + swear_words_arr[i].length).toLowerCase()
) {
swear_alert_arr[swear_alert_count] =
compare_text.substring(
j,
j + swear_words_arr[i].length
);
swear_alert_count++;
}
}
}
var alert_text = "";
for (var k = 1; k <= swear_alert_count; k++) {
alert_text += "\n" + "(" + k + ") " + swear_alert_arr[k - 1];
if (swear_alert_count > 0) {
alert("No!");
console.log('omg no bad stuff! D:');
} else {
console.log('no bad stuff found :)');
}
}
});
}
window.onload = reset_alert_count;
window.addEventListener('submit', function() {
validate_text();
});
It doesn't look like you've declared the array you're trying to access.
But, instead of loops with nested loops and keeping track of loop counters, just get a new array that contains any bad words in the submitted array. You can do this a number of ways, but the Array.prototype.filter() method works nicely:
let badWords = ["worse", "terrible", "horrible", "bad"];
let submittedWords = ["Good", "Terrible", "Great", "Fabulous", "Bad", "OK"];
// Loop over the submitted words and return an array of all the bad words found within it
let bad = submittedWords.filter(function(word){
// Do a case-insensitive match test. Return the word from the submitted words
// if it's on the bad word list.
return badWords.indexOf(word.toLowerCase()) > -1 ? word: null;
});
console.log("Bad words found in submitted data: " + bad.join(", "));
So I was asked to create an algorithm that when given a basic input of an array of counts and sites, it will output the accumulated visits to each TLD and Subdomain represented in a JSON object that will yield data like:
1120 com
800 google.com
310 reddit.com
60 mail.yahoo.com
10 mobile.sports.yahoo.com
50 sports.yahoo.com
10 stackoverflow.com
3 org
3 wikipedia.org
2 en.wikipedia.org
2 es.wikipedia.org
1 mobile.sports
1 sports
The input is something like:
// visits = [ "800,google.com",
// "60,mail.yahoo.com",
// "10,mobile.sports.yahoo.com",
// "40,sports.yahoo.com",
// "310,reddit.com",
// "10,stackoverflow.com",
// "2,en.wikipedia.org",
// "1,es.wikipedia.org",
// "1,mobile.sports" ]
My code looks like this so far and I know its wrong, but my brain is melted at the moment and I am not sure how to proceed. I am not necessarily looking for you to write the algorithm for me, but I do want to understand logically how I could break this down.
function getDomainHits(arr){
var splitCount = [];
var splitDomains = [];
var domainCountDict = {"Domains" : [],"Count" : 0};
for (var i = 0; i < arr.length; i++){
splitCount = arr[i].split(",");
splitDomains = splitCount[1].split(".");
for (var j = 0; j < splitDomains.length; j++){
if (!domainCountDict.Domain.includes(splitDomains[j])){
domainCountDict.Domain.push(splitDomains[j]);
}
}
}
console.log(domainCountDict);
}
As you can see I stopped here because I couldn't think of the best way to split these into different key, value pairs - one being domains and the other being the counts. Also my algorithm doesn't exactly follow the requirements.
So I figured out the algorithm. Define a variable - initialize it as an Array, and a dictionary to store the processed array data.
var splitCount = [];
var domainCountDict = {};
Then you need to take the Array of strings (arr - the function parameter) and iterate through it. On each iteration you need to split the string element into another Array to further process it.
for (var i = 0; i < arr.length; i++){
splitCount = arr[i].split(",");
...
}
So for the example input data of
// visits = [ "800,google.com",
// "60,mail.yahoo.com",
// "10,mobile.sports.yahoo.com",
// "40,sports.yahoo.com",
// "310,reddit.com",
// "10,stackoverflow.com",
// "2,en.wikipedia.org",
// "1,es.wikipedia.org",
// "1,mobile.sports" ]
Iteration 0 would be split into an Array of ["800","google.com"] and assigned to Var splitCount. You would then need to access splitCount and because of the input formatting you don't need to create a for loop. I created a variable to store the current count of the site - which will always be element 0 because of the format of the input data.
I didn't bother with input sanitation here because I didn't have time to create a map function that will turn the number elements into - well... numbers. I relied on the assumption that the input data will always have a number in the 0th index - which is terrible. Don't do this.
var curCnt = 0;
if (splitCount[0]){
curCnt = splitCount[0];
}
This next chunk of logic hurt my brain a little bit because I needed to find a way to store each domain component and its count in the dict and determine if the other domains contained components that already existed and if so increment those. Lets make some more Arrays!
var domain = [];
var currentDom = [];
if (splitCount[1] != undefined && splitCount[1]){
domain = splitCount[1].split(".");
for (var j = domain.length - 1; j >= 0; j--){
...
}
}
Above you will see that created an Array to hold the domain components called domain and another called currentDom to hold the components that are being worked and have already been worked, because we want to make sure that we count com and google.com. Lets look inside of the for loop.
for (var j = domain.length - 1; j >= 0; j--){
currentDom.unshift(domain.pop());
/*console.log("current iter: " + k + "\n"
+ "currentDom: " + currentDom.join(".") + "\n"
+ "current count: " + curCnt + "\n");*/
if (currentDom.join(".") in domainCountDict){
/*console.log("currentDom2: " + currentDom.join("."));
console.log("increment existing");*/
domainCountDict[currentDom.join(".")] += parseInt(curCnt);
}
if (!(currentDom.join(".") in domainCountDict)){
/*console.log("currentDom3: " + currentDom.join("."));
console.log("increment new");*/
domainCountDict[currentDom.join(".")] = parseInt(curCnt);
//console.log(domainCountDict);
}
}
Above you will see that I am iterating backwards in this loop to work the TLD first and then the domains/subdomains. I chose to pop the last element off the end of the current array and unshift it to the beginning of the new Array, currentDom. This will effectively let me work on a portion of the entire FQDN to determine if it has been included in the dictionary.
I have a few if statements to determine if the currentDom is included in the array. I had to use Array.join() to accurately check if the string of the current domain components have been included in the dictionary. If not then the string of currentDom would be added as a key and the curCnt would be the value assigned. If so, then the value would be incremented. Because of my lazy input sanitation in the curCnt assignment I had to parse these as Int because JS dynamic types. I am sure there is a better way, but my brain hurts now.
Finally make sure that you return the created dictionary on the outside of all of these for loops.
The full algorithm is below
// Sample output (in any order/format):
// getTotalsByDomain(counts)
// 1320 com
// 900 google.com
// 410 yahoo.com
// 60 mail.yahoo.com
// 10 mobile.sports.yahoo.com
// 50 sports.yahoo.com
// 10 stackoverflow.com
// 3 org
// 3 wikipedia.org
// 2 en.wikipedia.org
// 1 es.wikipedia.org
// 1 mobile.sports
// 1 sports
let counts = [ "900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"2,en.wikipedia.org",
"1,es.wikipedia.org",
"1,mobile.sports" ];
console.log(getDomainHits(counts));
function getDomainHits(arr){
var splitCount = [];
var domainCountDict = {};
for (var i = 0; i < arr.length; i++){
splitCount = arr[i].split(",");
var curCnt = 0;
if (splitCount[0]){
curCnt = splitCount[0];
}
var domain = [];
var currentDom = [];
if (splitCount[1] != undefined && splitCount[1]){
domain = splitCount[1].split(".");
for (var j = domain.length - 1; j >= 0; j--){
currentDom.unshift(domain.pop());
/*console.log("current iter: " + k + "\n"
+ "currentDom: " + currentDom.join(".") + "\n"
+ "current count: " + curCnt + "\n");*/
if (currentDom.join(".") in domainCountDict){
/*console.log("currentDom2: " + currentDom.join("."));
console.log("increment existing");*/
domainCountDict[currentDom.join(".")] += parseInt(curCnt);
}
if (!(currentDom.join(".") in domainCountDict)){
/*console.log("currentDom3: " + currentDom.join("."));
console.log("increment new");*/
domainCountDict[currentDom.join(".")] = parseInt(curCnt);
//console.log(domainCountDict);
}
}
}
}
return domainCountDict;
}
Problem: I am creating an array, or multiple arrays, to write values, and continue doing so until a certain value is drawn. The long view for this code is to, using these values to match one letter to another. (i.e. The Bombe used in WWII.) Except this will be completely digital. The Bombe was a decrypter that find that one letter is able to get mapped to another. (Enigma example will be posted in comments.) I am trying to decrpyt any message using this.
Understanding: I don't remember a lot of code especially since I have never used google-apps-script before. I no basic ideas, but some of the syntax's are different I am getting lost. (i.e.: instead of System.out.print(); it would be Logger.log(data);. That's really all I have gotten from it so far. I have some code worked out which can be found here.
Background: This is quite a lot of text to read I understand, but hear me out before you just flag me and move on. The hyperlink posted in the above comment under the words "Enigma example" shows the mapping that I am trying to do in reverse. I however need to create loops and variables that I do not remember how to create. I have information on the Enigma and Bombe: Enigma & Bombe info. I have done some searches on Google and the like, however nothing that I understand or benefit my end goal. All I have gotten is another link, which I will post in the comments, that shows me a basic loop as they put it.
What I need help with: I am asking for help in the following: Looping, variables and arrays. Suggestions will be the most valuable to me, because I am here to learn, not get my stuff done done by asking.
Ideas: Some ideas I have are, Garbage collectors, multi-dimensional array and/or just a sequence of possibilities. (See the "Enigma & Bombe info" link above.
For easy Copy/Pasting:
function bombeCode1() {
var fastRotor = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var mediumRotor = fastRotor;
var slowRotor = fastRotor;
var rows = 26;
var columns = 26;
for (var i=0; i < rows ; i++) {
Logger.log('Outer Loop: value of i : ' + i);
// Logger.log("Partition for Outer Loop");
// Logger.log(" ");
var fastRotorValue = fastRotor[i];
for (var j=0; j < columns ; j++) {
Logger.log('-Inner Loop value of j : ' +j);
//var fastRotorValue = fastRotor[i];
var medRotorValue = mediumRotor[j];
// Logger.log("---- " + fastRotorValue + " " + medRotorValue);
for (var k=0; k < 26 ; k++) {
// Logger.log('---- XXXX Third Loop value of k : ' + k);
//var fastRotorValue = fastRotor[i];
//var medRotorValue = mediumRotor[j];
var slowRotorValue = slowRotor[k];
Logger.log("---- XXXX " + fastRotorValue + " " + medRotorValue + " " + slowRotorValue);
}; //var objectNumberValuePair = {"0":"A", "1":"B", "2":"C","3":"D","4":"E","5":"F","6":"G","7":"H","8":"I",
// "9":"J","10":"K","11":"L","12":"M","13":"N","14":"O","15":"P","16":"Q","17":"R",
// "18":"S","19":"T","20":"U","21":"V","22":"W","23":"X","24":"Y","25":"Z"}
// Logger.log(slowRotorValue = objectNumberValuePair);
// Logger.log(medRoterValue = objectNumberValuePair);
// Logger.log(fastRoterValue = objectNumberValuePair);
}
}
}
Here is the code I modified a little bit, just to show the Loop values in the Logger print out.
function bombeCode1() {
var fastRotor = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N",
"O","P","Q","R","S","T","U","V","W","X","Y","Z"];
var mediumRotor = fastRotor;
var slowRotor = fastRotor;
var rows = 3;
var columns = 6;
for (var i=0; i < rows ; i++) {
Logger.log('Outer Loop: value of i : ' + i);
Logger.log("Partition for Outer Loop");
Logger.log(" ");
for (var j=0; j < columns ; j++) {
Logger.log('----Inner Loop value of j : ' + j);
var fastRoterValue = fastRotor[i];
var medRoterValue = mediumRotor[j];
Logger.log("---- " + fastRoterValue + " " + medRoterValue);
for (var k=0; k < 6 ; k++) {
Logger.log('---- XXXX Third Loop value of k : ' + k);
var fastRoterValue = fastRotor[i];
var medRoterValue = mediumRotor[j];
var slowRotorValue = slowRotor[k];
Logger.log("---- XXXX " + fastRoterValue + " " + medRoterValue + " " + slowRotorValue);
};
}
}
}
Run it and see what you think. I'm sure it's not what you need, but got to start somewhere.
So i am having issues coming up with an undefined array element.
1) cant get my undefined array to work
2) i want it to output the array as an occurrence of the word and number of times.
var wordCount =[];
splitAT.sort();
alert(splitAT);
for (var i = 0; i < splitAT.length; i++)
{
if(splitAT[i] in wordCount)
{
wordCount.push(1);
}
else
{
wordCount[splitAT[i]] = 1;
}
document.write('[' + splitAT[i] + '][' + wordCount[i] + ']<br>')
alert("your next wordcount is");
alert(wordCount); // this is just so i know where i am in the program.
alert("END");
First up, use the right tool for the job: wordCount should be an object rather than an array:
var wordCount = {}; // note, curly brackets
...because you plan to access it using strings as keys, not numeric array indices. (Yes, an array will work for this purpose, but it's not an array's intended purpose.)
Then in your loop, if the current word is already in wordCount you want to add 1 to the existing value, not use .push(1) which will insert a new array element at the end of the numerically indexed elements.
// WRONG:
wordCount.push(1); // inserts a new element
// RIGHT:
wordCount[splitAT[i]]++; // increments the current value
Putting that together, you would count the words like this:
var wordCount = {};
splitAT.sort();
for (var i = 0; i < splitAT.length; i++) {
if(splitAT[i] in wordCount) {
wordCount[splitAT[i]]++;
} else {
wordCount[splitAT[i]] = 1;
}
}
"i want it to output the array as an occurrence of the word and number of times."
To output the results you could do something like this:
var output = [];
for (var k in wordCount)
output.push("'" + k + "' appears " + wordCount[k] + " time(s).");
document.getElementById("NumCount").value = output.join("\n");
(Assuming you want to output to a textarea element with id="NumCount", which is what you had in your fiddle.)
I have a string that has been converted into an 2D Array in js.
board = "...|.X.|...|"
It is used to represent a game board
each . represents a space
each | represents a row
each X represents a wall
EDIT: code below for the 2d array creation
var src= "...|.X.|...|";
board = src.split(/\|/g);
for (var i = 0; i < board.length; i++) {
var cells = board[i].split('');
for (var j = 0; j < cells.length; j++) {
cells[j] = parseInt(cells[j]);
}
board[i][j] = cells;
console.log(board[1][1])
//returns 'X'
when i access board[i][j] it returns correctly:
[0][0] = "."
[1][1] = "X"
[1][2] = "."
etc etc
I want to update the specific element with a string representing a piece.
However when i insert into an element like so:
board[0][0] = "piece4"
The array returns in firebug as so:
board = "piece4|.X.|...|"
When it should look like:
board = ".piece4.|.X.|...|"
Why are elements [0][1] and [0][2] being overwritten? Am I not understanding arrays of array index access correctly in js?
I just had the same problem, but it had a more complex reason and I want to add it, in case someone finds this page searching for the same problem I had:
I had created and filled a 2-dimensional array like this:
var foo = Array(n).fill(Array(n).fill(0));
which creates a 2-dimensional n*n array filled with zeroes.
Now when I tried to overwrite a cell like this
foo[1][1] = 1;
I ended up with these values:
[[0,1,0],
[0,1,0],
[0,1,0]]
which is really surprising IMHO.
The reason for this was, that there has only been one row, which had internally been referenced three times. So when I changed the first index in "the second" row, it effectively changed all rows.
Bottom line: don't use Array.fill to create multi-dimensional arrays!
PROBLEM:
I'm betting that you have a one-dimensional array with strings stored in each. So your array actually looks like:
array (
[0] => '...',
[1] => '.X.',
[2] => '...'
)
When this is what you want:
array (
[0] => array (
[0] => '.',
[1] => '.',
[2] => '.'
),
[1] => array (
[0] => '.',
[1] => 'X',
[2] => '.'
),
[2] => array (
[0] => '.',
[1] => '.',
[2] => '.'
)
)
SOLUTION:
When constructing your 2D array, make sure you explicitly declare each entry in board as an array. So to construct it, your code might look something like this:
board = new Array();
rows = 3;
for (var i = 0; i < rows; i++)
board[i] = new Array('.', '.', '.');
An other way to create a 2D array in javascript is to use Array.from function
var 2Darr = Array.from(Array(5), () => {
return new Array(5).fill(0)
})
This will create a 5 x 5 array completely filled with 0. Array.from takes two parameters, the first one is an javascript iterable Object to extract the array from, the second one is an optional callback where we can specify something to apply to the array elements.
Accessing the element can be done simply like in other languages.
I ran into a similar problem. So after reading a lot... this finally suited my needs.
myArr = [1,1,1];
var arr = new Array();
for (var i = 0; i < 10; i++) {
arr[i] = Array.from(myArr);
}
//lets edit 3 positions
arr[0][1]= -1;
arr[3][2]= 100;
arr[8][0] = 8080;
for(var i=0; i<10; i++){
console.log(i + " === " + arr[i]);
}
OUTPUT:
if you noticed only the edited index values changed... nothing else
0 === 1,-1,1 <---
1 === 1,1,1
2 === 1,1,1
3 === 1,1,100 <---
4 === 1,1,1
5 === 1,1,1
6 === 1,1,1
7 === 1,1,1
8 === 8080,1,1 <---
9 === 1,1,1
Two remarks here:
Arrays start with index 0 in every dimension.
If you access a string as a 2D array, every element is a char rather than a string.
So if you write board[0][0] = 'X'; then you get the right behavior (and that changes the first character of the string, not the second).
The situation and solution given above is pretty simple. The issue of updating specific values in a list of objects (often referred to as an array, but that's a discussion for a different time) has more practical and industrial application. The problem you tend to run into is thinking that looking at a value in a specific cell, e.g. my_array[0][0] returns 'some value' will also let you change that value through an assignment e.g. my_array[0][0] = 'new value'. You will find that depending on how you defined your array, the change shows in the same row across the columns, not what you are needing.
Look at the example code as an illustration of creating, and managing a multidimensional list of objects (array).
<html>
<head>
<title>JavaScript Object List/Array</title>
<script>
//Make a JavaScript array that can manage data of inventory between different locations over time.
var list_of_brands = ["BMW","Harley Davidson","Honda","Kawasaki"];
var list_of_locations = ["Dayton","Cincinnati"];
//a month of data
var DAYS_IN_A_MONTH = 30;
var calendar = [];
for(day_of_sales = 1; day_of_sales <= DAYS_IN_A_MONTH; day_of_sales++){
//hold your locations
var shop_location = [];//You need to create a new array for each day - that's part of the trick!
for(location_index = 0;location_index < list_of_locations.length;location_index++){
//set up some starting inventory
var inventory = [];//You need to create a new array for each location - that's part of the trick!
for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){
inventory[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0};
};//end inventory loop
shop_location[list_of_locations[location_index]] = {"city":list_of_locations[location_index],inventory};
}//end location loop
calendar[day_of_sales] = {"Day": day_of_sales, shop_location};
}//end calendar loop
//check your work
console.log('calendar:'); console.log(calendar);
console.log('shop_location:'); console.log(shop_location);
console.log('specific information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//returns 'BMW'
console.log('change Dayton.BMW information: '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand="Triumph");//change value
console.log('check work (Dayton.BMW): '); console.log(calendar[1].shop_location["Dayton"].inventory['BMW'].brand);//check work - PASS
console.log('check work (Cincinnati.BMW): '); console.log(calendar[1].shop_location["Cincinnati"].inventory["BMW"].brand);//check work other location - PASS!!
//Make some lasting and specific changes
console.log("Now make a change in the month's value over showing a sale on the 13th");
var sale_date = 13;
console.log("date of sale " + sale_date + "th");
var original_number_on_hand = calendar[sale_date].shop_location["Dayton"].inventory["BMW"].on_hand;
console.log("original_number_on_hand on that date: " + original_number_on_hand);
var number_of_units_sold = 3;
console.log("number_of_units_sold on that date: " + number_of_units_sold);
var new_inventory_level = original_number_on_hand - number_of_units_sold;
console.log("new_inventory_level: " + new_inventory_level);
for(date_index = sale_date; date_index <= DAYS_IN_A_MONTH; date_index ++){
calendar[date_index].shop_location["Dayton"].inventory["BMW"].sold = number_of_units_sold;
calendar[date_index].shop_location["Dayton"].inventory["BMW"].on_hand = new_inventory_level;
}
console.log("Show change in inventory");
console.log(list_of_locations[0]+" has " + calendar[10].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[10].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[11].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[11].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[12].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[12].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[13].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[13].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[14].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[14].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[15].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[15].shop_location["Cincinnati"].inventory["BMW"].on_hand);
console.log(list_of_locations[0]+" has " + calendar[16].shop_location["Dayton"].inventory["BMW"].on_hand + " " + list_of_locations[1]+" has " + calendar[16].shop_location["Cincinnati"].inventory["BMW"].on_hand);
//add new items to a shop's inventory
var inventory_2 =[];
for(brand_index = 0; brand_index < list_of_brands.length; brand_index++){
inventory_2[list_of_brands[brand_index]] = {"brand": list_of_brands[brand_index], "on_hand": 10,"sold": 0};
};//end inventory loop
console.log("show inventory_2");console.log(inventory_2);
console.log("add inventory");inventory_2["Indian"] = {"brand": "Indian", "on_hand": 10,"sold": 0};
console.log("show updated inventory_2");console.log(inventory_2);
</script>
</head>
<body>
<p>look in the JavaScript console for output</p>
</body>
</html>