Comparing double-digit values within an array [duplicate] - javascript

This question already has answers here:
Using Javascript to compare two input numbers in HTML?
(4 answers)
issue with comparing two numbers in javascript
(5 answers)
compare two input values in input validation html javascript?
(3 answers)
Closed 3 years ago.
I'm writing my first javascript/html code to collect football results and then produce a league table. My code copes with single digit scores fine but not double digit scores.
Three arrays are used for results, league and players as below:
Results=[];
var Results=[
["Home","F","A","Away"],
["Si",,,"Ste"],
["Si",,,"Gaz"],
["Ste",,,"Gaz"],
["Ste",,,"Si"],
["Gaz",,,"Si"],
["Gaz",,,"Ste"],
["Si",,,"Ste"],
["Si",,,"Gaz"],
["Ste",,,"Gaz"],
["Ste",,,"Si"],
["Gaz",,,"Si"],
["Gaz",,,"Ste"],
];
League=[];
var League=[
["Team","P","W","D","L","F","A","GD","Pts"],
["Si",,,,,,,,],
["Ste",,,,,,,,],
["Gaz",,,,,,,,]
];
players=[];
var players=["Si","Ste","Gaz"];
I believe the faulty code is where wins are calculated:
if (Results[i][1]>Results[i][2])
{ wins++;
pts= +pts + 3;
}
This is taken from two 'for' loops that iterate through the results array for each player and populate the league array accordingly:
for (p = 0; p < players.length; p++)
{
for (i = 1; i < Results.length; i++)
{
if (Results[i][1]!= "")
{
if (Results[i][0]==players[p])
{
pld++;
goalsF=+goalsF + +Results[i][1];
goalsA=+goalsA + +Results[i][2];
gd=(goalsF - goalsA);
if (Results[i][1]>Results[i][2])
{
wins++;
pts= +pts + 3;
}
else if (Results[i][1]<Results[i][2])
{
loses++;
}
else
{
draws++;
pts++
}
}
}
if (Results[i][1]!= "")
{
if (Results[i][3]==players[p])
{
pld++;
goalsF=+goalsF + +Results[i][2];
goalsA=+goalsA + +Results[i][1];
gd=(goalsF - goalsA);
if (Results[i][1]<Results[i][2])
{
wins++;
pts= +pts + 3;
}
else if (Results[i][1]>Results[i][2])
{
loses++;
}
else
{
draws++;
pts++
}
}
}
}
r=p+1;
League[r][1]=pld;
League[r][2]=wins;
League[r][3]=draws;
League[r][4]=loses;
League[r][5]=goalsF;
League[r][6]=goalsA;
League[r][7]=gd;
League[r][8]=pts;
var pld=0;
var wins=0;
var draws=0;
var loses=0;
var goalsF=0;
var goalsA=0;
var gd=0;
var pts=0;
var r=0;
}
For a 10-1 score it works correctly:
For 10-2 (or 10-3) the result gets reversed and the player with the lower score is deemed the winner!?
It's as if the comparison is only working on the first digit of the scoreline. How do I fix this?

Related

find the number of unique numerical elements in any array [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Count unique elements in array without sorting
(9 answers)
Closed 14 days ago.
have made some code but it is broken and gives errors. the code is supposed to find the number of unique numerical elements in any array. So far, i created the following code snippet which contains a uniqueLength() function to return the number of unique elements.
function uniqueLength(nums) => {
if(nums.length === 0) {
return 0;
}
let i=0;
while(j>nums.lengths) {
if(nums[j]] ==! nums[i]) {
i++;
nums[i] = nums[j];
j++;
} else {
j++;
}
}
give i+1;
}
// Should return 5
const result = uniqueLength([1,1,2,3,4,5,5]);
console.log(result);
// Should return 1
const result2 = uniqueLength([1,1,1,1]);
console.log(result2);
where there is dashes one of these hints should go there
return
nums[j]
!=
nums[j] == nums[i]
nums[i]
give
j > nums.length
returns
let j=1;
=
**!==
j < nums.length**

How to optimize the code? (reverse string) [duplicate]

This question already has answers here:
Reversing string without affecting any special characters
(7 answers)
Reverse string without reversing special characters using Javascript
(3 answers)
Closed 1 year ago.
The task says : Change the order of words in a sentence but let non-alphanumerical characters stay in the same place e.g: 'Hello, it is world here.' -> "here, world is it Hello."
So far i have created something like this, but i need to optimize it (there are too many loops).
var text = 'Hello, it is world here.';
function reverseFunc(text){
let alpha = text.match(/[a-z0-9]+/gi).reverse();
let nonAlpha = text.match(/[\W_]+/gi);
let result = [];
console.log("Alpha : " + alpha)
console.log("Non alpha : " +nonAlpha)
if(alpha == null || nonAlpha == null) console.log(text)
else if((/[a-z0-9]/i).test(text.split("")[0])){
if (alpha.length == nonAlpha.length) {
for (let i = 0; i < nonAlpha.length; i++) {
result.push(alpha[i], nonAlpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}else{
for (let i = 0; i < alpha.length; i++) {
result.push(alpha[i], nonAlpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}
}else{
if (nonAlpha.length == alpha.length) {
for (let i = 0; i < alpha.length; i++) {
result.push(nonAlpha[i], alpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}else{
for (let i = 0; i < nonAlpha.length; i++) {
result.push(nonAlpha[i], alpha[i]);
}
console.log(result.join(""))
return(result.join(""))
}
}
}
reverseFunc(text)
I also have a problem when the text is only 1 char long e.g ".", or " ". I tried this:
if(alpha == null || nonAlpha == null) console.log(text)
but it seems like it is working only for alphanumeric chars.How could this algorithm be corrected?

How to generate random numbers without including a set number? [duplicate]

This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 4 years ago.
I'm just trying to generate 8 random numbers from 1 to 25. My issue is that I already have a variable and its value is 14, with that being said my question is how to generate random numbers from 1 to 25 and if one them is equal to 14 then replace it with another random number? at the end, I want to have 8 random numbers in my array and I don't want to include 14 in it. Can anyone tell me what I'm missing or how to make this more accurate? and sometimes I only end up with 7 elements in my array, does anyone knows why?
Here's my code:
var arr = [];
var currentvar = 14;
for(var i = 0 ; i < 9; i++){
var num = Math.floor(Math.random()*25) + 1;
if(num === currentvar){
num = Math.floor(Math.random()*25) + 1;
}else{
arr.push(num);
}
}
console.log(arr);
Study the logic you've implemented more closely. You go through the loop exactly 9 times (not 8), and you have mutually exclusive outcomes for each iteration due to an if...else control flow.
Either you reassign num if it's equal to currentvar (which you should do correctly by removing var from the second assignment), or you add it to the array, never both in one iteration. That's what else means, and you probably want a do...while loop to assign num until it is not equal to currentvar.
var arr = [];
var currentvar = 14;
var num;
for (var i = 0; i < 8; i++) {
do {
num = Math.floor(Math.random() * 25) + 1;
} while (num === currentvar);
arr.push(num);
}
console.log(arr);
Alternatively, if you want to keep your if...else statement, you can decrement the loop counter i instead to repeat the loop an extra time when num === currentvar:
var arr = [];
var currentvar = 14;
for (var i = 0; i < 8; i++) {
var num = Math.floor(Math.random() * 25) + 1;
if (num === currentvar) {
i--;
} else {
arr.push(num);
}
}
console.log(arr);

javascript generating random characters [duplicate]

This question already has answers here:
Generate random string/characters in JavaScript
(93 answers)
Closed 6 years ago.
I am trying to program a password generator. However, I find that my code is unreliable. I want each run of my function to return 20 random characters. This works most times, however if I spam the function enough times then I sometimes get a result that's below my criteria (eg: 2 strings, none, etc).
var longth = 20,
allc = "!##$%^&*()_+~`|}{[]\:;?><,./-=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
passgen = '';
for (var i = 0; i < longth; i++) {
passgen += allc.charAt(Math.floor(Math.random() * allc.length));
}
Not sure if the problem is with logic in my code, or if there's a break in one of the characters in my allc variable that's causing problems. Maybe I'm not expressing the variable correctly.
I don't see any problem with your code. I have modified it slightly to take a direct index out of the array, rather than using charAt but that shouldn't matter.
This code is tested by creating 1,000,000 strings and logs how many failed the creation criteria. It doesn't seem to fail.
function makePassword(){
var longth = 20,
allc = "!##$%^&*()_+~`|}{[]\:;?><,./-=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
passgen = '';
for (var i = 0; i < longth; i++) {
passgen += allc[Math.floor(Math.random() * allc.length)];
}
return passgen;
}
// Test
var failed = [];
var result = "";
for(var x = 0; x < 1000000; ++x){
result = makePassword();
if(result.length !== 20){
failed.push(result);
}
}
console.log("Incorrect strings generated: " + failed.length, failed);

Separating every 3 numbers with commas [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 6 years ago.
The first thing i want to ask is if there is a more efficient way of writing this programm of mine. The second question is why on earth after a specific number of characters the programm does not function well and prints zeros.
function toCurrency(price) {
var currencyToString = price.toString();
var finalPrice = "";
var counterComma = 0;
for (var i = 0; i < currencyToString.length; i++) {
counterComma++;
finalPrice += currencyToString[i];
if(counterComma == 3){
counterComma = 0;
finalPrice += ",";
}
}
return finalPrice;
}
console.log(toCurrency(123456253635423197874));
https://jsfiddle.net/DimitriXd4/68epen4n/

Categories

Resources