I have this snippet that is is getting 3 numbers and its working distinguing them. If one of 3 numbers is diferent than the others it must return its correspondend.
An input example:
1 1 0
0 0 0
1 0 0
output must be:
C
*
A
The approach i had was that one:
var input = require('fs').readFileSync('stdin', 'utf8')
var lines = input.split('\n')
for (let i = 0; i < lines.length; i++) {
var round = lines[i].split(' ').map(i => parseInt(i))
// console.log(round); [1, 1, 0]
var A = round[0]
var B = round[1]
var C = round[2]
if(A === B && A === C){
console.log("*");
} else if (A === B && A !== C) {
console.log("C");
} else if (A !== B && A === C) {
console.log("B");
} else if (A !== B && A !== C) {
console.log("A");
}
}
I'm not sure what the problem is exactly but if it is to try to minimize the code in some way one thing to notice is that we don't care whether the the values are 0 or 1 only whether the players have chosen the same or not so once we have the values of A, B and C for a round we can just do:
(UPDATE: thanks to a comment from #Samathingamajig a redundant != comparison has been removed)
console.log( ((A==B)&&(B==C)) ? '*' : (A==B) ? 'C' : (A==C) ? 'B' : 'A' );
Like #Samathingamajig said:
function _0or1(arr) {
[A,B,C] = arr
if (A === B && A === C) {
console.log("*");
} else if (A === B) {
console.log("C");
} else if (A === C) {
console.log("B");
} else {
console.log("A");
}
}
_0or1([0,0,0])
_0or1([1,0,0])
_0or1([0,1,0])
_0or1([0,0,1])
_0or1([1,1,0])
_0or1([0,1,1])
_0or1([1,0,1])
_0or1([1,1,1])
Related
Hi I am trying to create a function in JS that takes a string and checks if there are an equal number of "x"s and "o"s in the string.
My code so far (not working):
const checkXo = (str) => {
const y = 0;
const z = 0;
for (let x = 0, x < str.length, x++) {
if (str.charAt(x) == "o") {
y++;
} else if (str.charAt(x) == "x") {
z++;
}
}
if (y === z) {
return true;
} else {
return false;
}
}
checkXo("xxoo");
const defines a constant, so you won't be able to change values of y and z. Instead, you should use var or let:
let y = 0;
let z = 0;
Consider to do it in a `functional' way:
const checkXo = (str, a, b) =>
str.split('').filter(s => s === a).length ===
str.split('').filter(s => s === b).length
test it with
checkXo('xxoo', 'x', 'o') // return true
checkXo('stackoverflow', 'x', 'o') // return false
Please note a single line of code can check for equal quantity of any characters of your choice 'a, 'b'.
Doing a survey where a user picks :
A B or C
I then need to know if the user has picked Mostly A's, B's or C's.
I'm trying a few jQuery logics' but not having much luck, Due to expression expected error.
Is there a neater / better way to show purely which variable is the highest?
My current jQuery :
var count = 0;
var count_a = 0;
var count_b = 0;
var count_c = 0;
$('.radio-select').click(function()
{
var chosen_option = $(this).val();
if(chosen_option == 'a')
{
count++;
count_a ++;
}
if(chosen_option == 'b')
{
count++;
count_b ++;
}
if(chosen_option == 'c')
{
count++;
count_c ++;
}
check_numbers(count, count_a, count_b, count_c);
})
function check_numbers(count, a, b, c)
{
parseInt(a);
parseInt(b);
parseInt(c);
if(count == '8')
{
if ((a > b ) && (a > c))
{
alert("A is Highest");
}
if ((b > a ) && (b > c))
{
alert("B is Highest");
}
if(c > b) && (c > a))
{
alert("C is highest!");
}
}
}
jsFiddle Example
If you wanted a smaller way of doing it you could use inline if statements. Up to you if this is a better way, I like it though.
a = 5
b = 11
c = 6
console.log((a > b && a > c? a : (b > c ? b : c)))
Firstly you do not need to use parseInt() on a, b, c as they are already integers. And again count is an integer while you are comparing it to a string. This should work.
if(count == 8)
{
if ((a > b ) && (a > c))
{
alert("A is Highest");
}
else if ((b > a ) && (b > c))
{
alert("B is Highest");
}
else
{
alert("C is highest!");
}
You need to fetch the value returned by parseInt. Use it like: a = parseInt(a); and same for the other variables before comparing them in the if...else.
function check_numbers(count, a, b, c)
{
var x = parseInt(a),
y = parseInt(b),
z = parseInt(c);
if(count == 8)
{
var result = (x > y ? (x > z ? x : z) : (y > z ? y : z));
}
}
#StuBlackett you can consider adding the values and labels to an array then sorting Descending and returning the lable at the top.
function CompareIndexZero(a, b) {
if (a[0] < b[0]) return 1;
if (a[0] > b[0]) return -1;
return 0;
}
function myFunction() {
var count_a = 2;
var count_b = 5;
var count_c = 4;
var arrHighest = [];
arrHighest.push([count_a, "A"]);
arrHighest.push([count_b, "B"]);
arrHighest.push([count_c, "C"]);
arrHighest.sort(CompareIndexZero);
alert(arrHighest[0][1] + " is the highest");
}
Here is a modified version of check_numbers() that works as intended if I got you right. The point I want to make is the use of Math.max() to find the highest number from a selection of numbers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
function check_numbers(count, a, b, c) {
if(count === 8) {
var numArray = [a, b, c];
var highest = Math.max.apply(null, numArray);
console.log(highest);
if (highest === a) {
console.log('a is highest');
} else if (highest === b) {
console.log('b is highest');
} else if (highest === c) {
console.log('c is highest');
}
}
}
check_numbers(8, 1 , 2, 5);
check_numbers(8, 5, 2, 1);
check_numbers(8, 1 , 5, 2);
Have you also taken into account that multiple answers could share the highest count?
My 2 cents on that:
var count = count_a = count_b = count_c = 0;
$('.radio-select').on('click', function() {
var chosen_option = $(this).val();
if (chosen_option == 'a') {
count_a++;
}
else if (chosen_option == 'b') {
count_b++;
}
else if (chosen_option == 'c') {
count_c++;
}
if (++count == 8) {
check_numbers(count_a, count_b, count_c);
}
});
function check_numbers(a, b, c) {
var highest = ((a > b && a > c) ? a : (b > c)? b : c),
multiple = false,
alertText = '';
if (a == highest) {
alertText += 'A';
}
if (b == highest) {
if (alertText != '') {
multiple = true;
alertText += ' and ';
}
alertText += 'B';
}
if (c == highest) {
if (alertText != '') {
multiple = true;
alertText += ' and ';
}
alertText += 'C';
}
alert(alertText + ' ' + (multiple ? 'are' : 'is') + ' highest!');
}
I only want to show unique variables. Is there an easier or cleaner way to compare three js variables?
if (a==b) {
if (a==c) {
//show only a
} else {
//show a and c
}
} else {
if (a==c) {
//show a and b
} else {
//show a and b and c
}
}
Not really, no:
if (a == b && a == c) {
// show a
} else if (a == b) {
// show a and c
} else if (a == c) {
// show a and b
} else {
// show a, b, and c
}
I know you have not specified to use jQuery, but this is another way you could do it (should you choose to use Jquery)
var array1 = [];
var a = 2, b = 3, c= 2;
array1.push(a);
array1.push(b);
array1.push(c);
console.log(array1);
var unique = $.unique(array1);
console.log(unique);
P.S. - I have considered the variables to be numbers.
I have an Array that I need to sort exactly like using order by in Oracle SQl.
If I have following Array:
var array = ['Ba12nes','Apfel','Banane','banane','abc','ABC','123','2', null,'ba998ne']
var.sort(compare);
I would like to have the following result
var array = ['abc','ABC','Apfel','banane','Banane','Ba12nes','ba998ne','123','2', null]
If the null values are somewhere else, I don't have a Problem with it.
My current solution, which does not help me ^^
function compare(a,b) {
if(a == null)
return -1;
if (b == null)
return 1;
if (a.toLowerCase() < b.toLowerCase())
return -1;
if (a.toLowerCase() > b.toLowerCase())
return 1;
return 0;
}
I do understand that i need a custom sorting function. And at the moment I am thinking that only a regular expression can solve the problem of sorting the string values in front of the numbers. But I am still not sure how to solve the Problem with lowercase letters in bevor Uppercase letters.
Iirc, Oracle implements a 3-tiered lexicographic sorting (but heed the advice of Alex Poole and check the NLS settings first):
First sort by base characters ignoring case and diacritics, digits come after letters in the collation sequence.
Second, on ties sort respecting diacritics, ignoring case.
Third, on ties sort by case.
You can emulate the behavior using javascript locale apis by mimicking each step in turn in a custom compare function, with the exception of the letter-digit inversion in the collation sequence.
Tackle the latter by identifying 10 contiguous code points that do not represent digits and that lie beyond the set of code points that may occur in the strings you are sorting. Map digits onto the the chosen code point range preserving order. When you sort, specify the Unicode collating extension 'direct' which means 'sorting by code point'. Remap after sorting.
In the PoC code below I have chosen some cyrillic characters.
function cmptiered(a,b) {
//
// aka oracle sort
//
return lc_base.compare(a, b) || lc_accent.compare(a, b) || lc_case.compare(a, b);
} // cmptiered
var lc_accent = new Intl.Collator('de', { sensitivity: 'accent' });
var lc_base = new Intl.Collator('de-DE-u-co-direct', { sensitivity: 'base' });
var lc_case = new Intl.Collator('de', { caseFirst: 'lower', sensitivity: 'variant' });
var array = ['Ba12nes','Apfel','Banane','banane','abc','ABC','123','2', null, 'ba998ne' ];
// Map onto substitute code blocks
array = array.map ( function ( item ) { return (item === null) ? null : item.replace ( /[0-9]/g, function (c) { return String.fromCharCode(c.charCodeAt(0) - "0".charCodeAt(0) + "\u0430".charCodeAt(0)); } ); } );
array.sort(cmptiered);
// Remap substitute code point
array = array.map ( function ( item ) { return (item === null) ? null : item.replace ( /[\u0430-\u0439]/g, function (c) { return String.fromCharCode(c.charCodeAt(0) - "\u0430".charCodeAt(0) + "0".charCodeAt(0)); } ); } );
Edit
Function cmptiered streamlined following Nina Scholz' comment.
This proposals feature sorting without use of Intl.Collator. The first solution works with direct sort and comparing the given values.
var array = ['Ba12nes', 'Apfel', 'Banane', 'banane', 'abc', 'ABC', '123', '2', null, 'ba998ne'];
array.sort(function (a, b) {
var i = 0;
if (a === null && b === null) { return 0; }
if (a === null) { return 1; }
if (b === null) { return -1; }
while (i < a.length && i < b.length && a[i].toLocaleLowerCase() === b[i].toLocaleLowerCase()) {
i++;
}
if (isFinite(a[i]) && isFinite(b[i])) { return a[i] - b[i]; }
if (isFinite(a[i])) { return 1; }
if (isFinite(b[i])) { return -1; }
return a.localeCompare(b);
});
document.write(JSON.stringify(array));
The second solution features a different approach, based on Sorting with map and a custom sort scheme which takes a new string. The string is build by this rules:
If the value is null take the string 'null'.
If a character is a decimal, takes the character with space paddded around, eg. if it is 9 take the string ' 9 '.
Otherwise for every other character take two spaces and the character itself, like ' o'.
The new build string is used with a a.value.localeCompare(b.value).
Here are the strings with the mapped values:
' B a 1 2 n e s'
' A p f e l'
' B a n a n e'
' b a n a n e'
' a b c'
' A B C'
' 1 2 3 '
' 2 '
'null'
' b a 9 9 8 n e'
sorted, it became
' a b c'
' A B C'
' A p f e l'
' b a n a n e'
' B a n a n e'
' B a 1 2 n e s'
' b a 9 9 8 n e'
' 1 2 3 '
' 2 '
'null'
var array = ['Ba12nes', 'Apfel', 'Banane', 'banane', 'abc', 'ABC', '123', '2', null, 'ba998ne'],
mapped = array.map(function (el, i) {
var j, o = { index: i, value: '' };
if (el === null) {
o.value = 'null';
return o;
}
for (j = 0; j < el.length; j++) {
o.value += /\d/.test(el[j]) ? ' ' + el[j] + ' ' : ' ' + el[j];
}
return o;
});
mapped.sort(function (a, b) {
return a.value.localeCompare(b.value);
});
var result = mapped.map(function (el) {
return array[el.index];
});
document.write(JSON.stringify(result));
A simple head on solution that works at least for english & russian (mimicking NLS_SORT=RUSSIAN) and doesn't rely on fancy things like Intl.Collator, locales and options that don't exist for IE<11.
function compareStringOracle(str1, str2) {
if (str1 == null && str2 != null)
return 1;
else if (str1 != null && str2 == null)
return -1;
else if (str1 == null && str2 == null)
return 0;
else {
return compareStringCaseInsensitiveDigitsLast(str1, str2) ||
/* upper case wins between otherwise equal values, which can be checked with
a simple binary comparison (at least for eng & rus) */
((str1 < str2) ? -1 : (str1 > str2) ? 1 : 0);
}
}
function compareStringCaseInsensitiveDigitsLast(str1, str2) {
for (var i = 0; i < str1.length; ++i) {
if (i === str2.length)
return 1;
// toLocaleLowerCase is unnecessary for eng & rus
var c1 = str1.charAt(i).toLowerCase();
var c2 = str2.charAt(i).toLowerCase();
var d1 = "0" <= c1 && c1 <= "9";
var d2 = "0" <= c2 && c2 <= "9";
if (!d1 && d2)
return -1;
else if (d1 && !d2)
return 1;
else if (c1 !== c2)
return (c1 < c2) ? -1 : (c1 > c2) ? 1 : 0;
}
if (str1.length < str2.length)
return -1;
else
return 0;
}
I am putting an interactive java script form whereas the the out put is getting confused with switch case. Kindly help me: It is pipe weight calculation.
Pipe sizes: 100mm, 150 mm, 200 mm, 250mm up to 1000mm
For each pipe the pressure class varies: PN3, PN6 and PN9
For each pressure class the stiffness varies: SN124 and SN256
For given Pipes size, pressure class and stiffness class - the weight will be different. To arrive the out put - I am using the switch case, which is very lengthy and time consuming. Any body can help me in solving the java script so that same will be put in the HTML file.
This is the code I have, but I think there must be a better way to do it.
What's a better way?
<SCRIPT LANGUAGE="JavaScript">
function CalculateSum(Atext, Btext, Ctext,form)
{
var A = parseFloat(Atext);
var B = parseFloat(Btext);
var C = parseFloat(Ctext);
switch (true){
case (A == 100 && B == 3 && C == 124): K =21.4; L=102; M =55; break ;
case (A == 100 && B == 3 && C == 256): K =21.9; L=125; M=49; break ;
case (A == 100 && B == 3 && C == 512): K =22.2; L=133; M=45; break ;
case (A == 100 && B == 6 && C == 124): K =42.9; L=139; M=41; break ;
case (A == 100 && B == 6 && C == 256): K =42.78;L=141; M=39; break ;
case (A == 100 && B == 6 && C == 512): K =43.01;L=144; M=37; break ;
case (A == 100 && B == 9 && C == 124): K =54.84;L=148; M=34; break ;
case (A == 100 && B == 9 && C == 256): K =55.02;L=152; M=31; break ;
case (A == 100 && B == 9 && C == 512): K =56.90;L=157; M=29; break ;
case (A == 150 && B == 3 && C == 124): K =39.4; L=164; M=25; break ;
....
......
.......
break ;
}
form.Ans1.value = K + " Kg/Rmt";
form.Ans1.value = L + " Rmt";
form.Ans1.value = M + " Nos";
}
</SCRIPT>
I assume you can't calculate K from A, B, and C, which would of course be best. Assuming that's the case:
Your way works. It's an unusual way of using switch, but it's valid in JavaScript. (Not in most other languages.)
The other way to do it would be to have a table as a nested bunch of objects, and look the values up in the table:
var Values = {
// Values for A
100: {
// Values for B when A = 100
3: {
// Values for C when A == 100 and B == 3
124: 21.4,
256: 21.9,
512: 22.2
},
6: {
// Values for C when A == 100 and B == 6
124: 42.9,
256: 42.78,
512: 43.01
},
9: {
// Values for C when A == 100 and B == 9
124: 54.84,
256: 55.02,
512:39.4
}
},
150: {
// Values for B when A = 150
3: {
// Values for C when A == 150 and B == 3
124: 39.4
}
}
};
I'm not sure that makes the data more readable/maintainable, but it's quite quick to use, and you can write it a bit more concisely (see the end of the answer); I wanted to include the comments above.
CalculateSum ends up looking like this:
function CalculateSum(Atext, Btext, Ctext,form)
{
var A = parseFloat(Atext);
var B = parseFloat(Btext);
var C = parseFloat(Ctext);
var entry;
// Get the top-level entry for A
entry = Values[A];
if (entry) {
// We have one, get its entry for this value of B
entry = entry[B];
if (entry) {
// We have one, get _its_ entry for C
entry = entry[C];
}
}
if (typeof entry === "number") {
form.Ans.value = entry + " Kg/Rmt";
}
else {
// Didn't find it
}
}
Or as Deestan points out in the comments, you can shorten that a bit if you're not doing this in a hyper-tight loop you run hundreds of thousands of times (which I'm guessing you're not):
function CalculateSum(Atext, Btext, Ctext,form)
{
var A = parseFloat(Atext);
var B = parseFloat(Btext);
var C = parseFloat(Ctext);
var K;
// Get the entry from our tables
K = Values[A] && Values[A][B] && Values[A][B][C];
if (typeof K === "number") {
form.Ans.value = K + " Kg/Rmt";
}
else {
// Didn't find it
}
}
(There I changed entry to K because we never store anything but the final value in it.)
And here's the more concise Values:
var Values = {
100: {
3: { 124: 21.4, 256: 21.9, 512: 22.2 },
6: { 124: 42.9, 256: 42.78, 512: 43.01 },
9: { 124: 54.84, 256: 55.02, 512: 39.4 }
},
150: {
3: { 124: 39.4 }
}
};