JavaScript How to run variables in if and for? - javascript

I want to use FOR loop instead, please.
let int1, int1, int3;//... (int4 to int999)
let op1, op;//... (op2 to op999)
if(int1 < 200) {
op1 = int1;
}
else {
op1 = '';
}
if(int2 < 200) {... (same IF statement for int2 to int999)
Instead, I want this.
for(i = 1; i < 5; i++) {
let int = [int1, int2, int3, int4];
let op = [op1, op2, op3, op4];
if(int[i] < 200) {
op[i] = int[i];
}
else {
op[i] = '';
}
}
alert(op1 + op2 + op3 + op4);
But that doesn't work somebody help.

Your code should be as follows with an example:
let int = [1, 2, 3, 4];
let op = [999, 999, 999, 999];
for(i = 0; i < 4; i++) {
if(int[i] < 200) {
op[i] = int[i];
}
else {
op[i] = '';
}
}
alert(op[0] + op[1] + op[2] + op[3]);
Out:
285
Or in your kind of "symbolic form":
let int = [int1, int2, int3, int4];
let op = [op1, op2, op3, op4];
for(i = 0; i < 4; i++) {
if(int[i] < 200) {
op[i] = int[i];
}
else {
op[i] = 0;
}
}
alert(op[0] + op[1] + op[2] + op[3]);

Instead of a set of variables, You should use an array instead.
Then, Your code would look something like this:
let input = [input1, input2 ... input999];
let output = [];
for(let i = 0; i < input.length; i++){
if(input[i]) {
output[i] = input[i];
} else {
alert("error")
}
})

Related

problem using .split() method in a function but it works on console.log

the problem is only in the bottom function objectPutter
specifically the line with wowza.split(' '); labelled with the comment
let eq
let x = null
let bracketNum = 0
let k = 0
let pre = 0
class subEqCreator { //subEq object
constructor() {
this.precede = 0;
this.text = '';
}
parser() {
this.text += eq[k]
}
ma() {
this.text.split(' ')
}
};
function trigger() { //used for HTML onClick method
show();
brackets();
subEqDynamic()
parseEquation();
objectPutter()
};
function show() {
const recent = document.querySelector("ol");
const txt = document.getElementById('input');
eq = txt.value;
li = document.createElement('li');
li.innerText = eq;
recent.appendChild(li);
txt.value = '';
};
function brackets() { //counts how many brackets appear
for (let i = 0; i < eq.length; i++) {
if (eq[i] == "(") {
bracketNum++;
};
};
};
let subEqDynamic = function() { // creates a new object for each bracket
for (let count = 0; count <= bracketNum; count++) {
this['subEq' + count] = x = new subEqCreator()
};
};
function parseEquation() { // assign characters to SubEq object
let nextIndex = 0;
let currentIndex = 0;
let lastIndex = [0];
let eqLen = eq.length;
let nex = this['subEq' + nextIndex]
for (k; k < eqLen; k++) {
if (eq[k] == "(") {
nextIndex++;
pre++
this['subEq' + currentIndex].text += '( )';
this['subEq' + nextIndex].precede = pre;
lastIndex.push(currentIndex);
currentIndex = nextIndex;
} else if (eq[k] == ")") {
pre--
currentIndex = lastIndex.pop();
} else {
this['subEq' + currentIndex].parser()
}
}
}
function objectPutter() {
for (let i = 0; i < bracketNum; i++) {
let wowza = this['subEq' + i].text
wowza.split(' '); // 🚩 why isnt it working here
console.log(subEq0);
for (let j = 1; j <= wowza.length; j += 2) { // for loop generates only odds
let ni = i++
wowza.splice(j, 0, this['subEq' + ni])
console.log(i)
}
}
}
to fix this i tried;
making a method for it ma() in the constructor.
putting in the function parseEquation above in case it was a scope issue.
also, i noticed subEq0.split(' ') worked in browser console even replicating it to the way i done it using this['subEq' + i].text.split(' ') where i = 0.
After it runs the it says .splice is not a function and console.log(subEq0) shows subEq0.text is still a string
.split() does not change the variable it returns the splitted variable

A* Algorithm - Javascript: Why does my algorithm not find the shortest path

I am working on visualizing A*. I have a problem where the algorithm finds a path, but it is not the shortest. If I remove the part of the A* function code which is commented as 'tie-breaking', the algorithm finds the shortest path, but it searches the whole grid just like Dijkstra's algorithm, which I don't think A* is supposed to do. These are the pictures of the results with and without tie-breaking:
With Tie-Breaking
Without Tie-Breaking
What is wrong? Here is my A* function:
async a_star_search() {
this.clearSearchNotWalls();
let openSet = [];
let closedSet = [];
let start, end;
let path = [];
this.findNeighbors();
//shapes is a 2d array of squares... a grid
for (let i = 0; i < this.shapes.length; i++) {
for (let j = 0; j < this.shapes[0].length; j++) {
if (this.shapes[i][j].type == "Start") {
start = this.shapes[i][j];
}
if (this.shapes[i][j].type == "End") {
end = this.shapes[i][j];
}
}
}
openSet.push(start);
while (openSet.length > 0) {
let lowestIndex = 0;
//find lowest index
for (let i = 0; i < openSet.length; i++) {
if (openSet[i].F < openSet[lowestIndex].F)
lowestIndex = i;
}
//current node
let current = openSet[lowestIndex];
//if reached the end
if (openSet[lowestIndex] === end) {
path = [];
let temp = current;
path.push(temp);
while (temp.cameFrom) {
path.push(temp.cameFrom);
temp = temp.cameFrom;
}
console.log("Done!");
for (let i = path.length - 1; i >= 0; i--) {
this.ctxGrid.fillStyle = "#ffff00";
this.ctxGrid.fillRect(path[i].x, path[i].y, 14, 14);
await new Promise(resolve =>
setTimeout(() => {
resolve();
}, this.animDelay / 2)
);
}
break;
}
this.removeFromArray(openSet, current);
closedSet.push(current);
let my_neighbors = current.neighbors;
for (let i = 0; i < my_neighbors.length; i++) {
var neighbor = my_neighbors[i];
if (!closedSet.includes(neighbor) && neighbor.type != "Wall") {
let tempG = current.G + 1;
let newPath = false;
if (openSet.includes(neighbor)) {
if (tempG < neighbor.G) {
neighbor.G = tempG;
newPath = true;
}
} else {
neighbor.G = tempG;
newPath = true;
openSet.push(neighbor);
}
if (newPath) {
neighbor.H = this.heuristic(neighbor, end);
neighbor.G = neighbor.F + neighbor.H;
neighbor.cameFrom = current;
}
}
}
//draw
for (let i = 0; i < closedSet.length; i++) { //BLUE
this.ctxGrid.fillStyle = "#4287f5";
this.ctxGrid.fillRect(closedSet[i].x, closedSet[i].y, 14, 14);
}
for (let i = 0; i < openSet.length; i++) { //GREEN
this.ctxGrid.fillStyle = "#00ff00";
this.ctxGrid.fillRect(openSet[i].x, openSet[i].y, 14, 14);
}
await new Promise(resolve =>
setTimeout(() => {
resolve();
}, 10)
);
}
if (openSet.length <= 0) {
//no solution
}
}
Here is my heuristic function:
heuristic(a, b) {
//let d = Math.sqrt(Math.pow(b.I - a.I, 2) + Math.pow(b.J - a.J, 2));
let d = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));
return d;
}

How can I make this Index script show more than 150 results in Blogger?

I have been using this script which was great but unfortunately it will only show the most recent 150 results even if I change the parameter and I have more that many posts.
I guess the best result would be to break it up with results A-M , N-Z but I don't know how to do that. Any help would be much appreciated.
<div>
<ul id="postList12"></ul>
</div>
<script type="text/javascript">
var startIndex = 1;
var maxResults = 999;
var allResults = [];
function sendQuery12()
{
var scpt = document.createElement("script");
scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults;
document.body.appendChild(scpt);
}
function printArrayResults(root)
{
//Sort Alphebetically
allResults.sort(function(a, b){
var a_string = a.children[0].textContent ;
var b_string = b.children[0].textContent ;
if(a_string < b_string) return -1;
if(a_string > b_string) return 1;
return 0;
})
var elmt = document.getElementById("postList12");
for (index = 0; index < allResults.length; index++) {
elmt.appendChild(allResults[index]);
}
}
function processPostList12(root)
{
var elmt = document.getElementById("postList12");
if (!elmt)
return;
var feed = root.feed;
if (feed.entry.length > 0)
{
for (var i = 0; i < feed.entry.length; i++)
{
var entry = feed.entry[i];
var title = entry.title.$t
for (var j = 0; j < entry.link.length; j++)
{
if (entry.link[j].rel == "alternate")
{
var url = entry.link[j].href;
if (url && url.length > 0 && title && title.length > 0)
{
var liE = document.createElement("li");
var a1E = document.createElement("a");
a1E.href = url;
a1E.textContent = title;
liE.appendChild(a1E);
//elmt.appendChild(liE);
allResults.push(liE);
}
break;
}
}
}
if (feed.entry.length >= maxResults)
{
startIndex += maxResults;
sendQuery12();
} else {
printArrayResults();
}
}
}
sendQuery12();
</script>

how do i get non-repeated character and its count in JavaScript?

Here is my code. What should I modify of this code to get the output as
"T-1
r-1
a-1
e-1 "
(other characters are repeating. So no need to print the others)
function different() {
var retureArr = [];
var count = 0;
var complete_name = "Trammell";
var stringLength = complete_name.length;
for (var t = 0; t < stringLength; t++) {
for (var s = 0; s < stringLength; s++) {
var com1 = complete_name.charAt(t);
var com2 = complete_name.charAt(s);
if (com1 != com2) {
retureArr[count] = com1;
count++;
}
}
count = 0;
}
}
I think this is what you want. You need to count the number of occurrences of each character in a dictionary. Then you can print them based on the count being equal to 1.
var retureArr = [];
var complete_name = "Trammell";
for (var i = 0; i < complete_name.length; i++)
{
var key = complete_name[i];
if (!(key in retureArr))
{
retureArr[key] = 1;
}
else
{
retureArr[key] = retureArr[key] + 1;
}
}
var output = "";
for (var key in retureArr)
{
if (retureArr[key] == 1)
{
output += key + "-" + retureArr[key] + " ";
}
}
alert(output);
This alerts the following string:
T-1 r-1 a-1 e-1
This works. but perhaps isn't the most efficient!
var string = "input string";
var stringList = [];
var outputString = "";
for (var i=0; i < string.length; i++){
var charObject = {"Char": string.charAt(i), "Passed": false};
stringList.push(charObject);
}
for (var i=0; i < stringList.length; i++){
if(!stringList[i].Passed && stringList[i].Char != " "){
var currentCount = countOccurrences(string, stringList[i].Char);
if(currentCount == 1){
outputString += stringList[i].Char+"-"+currentCount + " ";
}
stringList[i].Passed = true;
}
}
console.log(outputString);
function countOccurrences(string, char){
var count = 0;
for (var i=0; i < string.length; i++){
if(string.charAt(i) == char){
count++;
}
}
return count;
}

Why is the final output "B-D"

Keep in mind this is unfinished, the only question I have is why does the console.log produce this output?
/>B /* This is what I expected */
/>B-D /* The second output I expected to be just ">/D" I am conused as to how it is coming up with >/"B-D" */
graphArray = ["4","A","B","C","D","A-B","B-D","B-C","C-D"];
pointsArray = [];
linesArray = [];
nodes = graphArray[0];
for (i = 1; i < graphArray.length; i++) {
if (i <= nodes) {
pointsArray.push(graphArray[i]);
}
if (i > nodes) {
linesArray.push(graphArray[i]);
}
}
nextpoint = pointsArray[0];
patt = new RegExp(/-.*/);
patt2 = new RegExp(nextpoint + "-");
for (i = 0; i < linesArray.length; i++) {
x = 0;
while (x < linesArray.length) {
if (linesArray[x].replace(patt,"") === nextpoint) {
nextpoint = linesArray[x].replace(patt2,"");
console.log(nextpoint);
}
x++;
}
}
Edit: Smacks forehead it must be getting too late for me I can't believe I missed that. Thank you for point that out. Solved.
Your patt2 = new RegExp(nextpoint + "-"); should be inside the loop
for (i = 0; i < linesArray.length; i++) {
x = 0;
while (x < linesArray.length) {
patt2 = new RegExp(nextpoint + "-");
if (linesArray[x].replace(patt,"") === nextpoint) {
nextpoint = linesArray[x].replace(patt2,"");
console.log(nextpoint);
}
x++;
}
}

Categories

Resources