This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.
function convertToRoman(num) {
var romans = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
var result = '';
for (var key in romans) {
if (num >= romans[key]) {
result += key.repeat(Math.trunc(num / romans[key]));
num -= romans[key] * Math.trunc(num / romans[key]);
}
}
return result;
}
If you add a div element and give it an id like "output", you can do something like this.
document.getElementById("output").innerHTML = result;
You can use the trusty old alert function. Just do alert(convertToRoman(10)). Put this in a <script> tag or inside body onload attribute
For fancier more professional debugging, you can use console.log. Originating with an old Firefox addon called Firebug, it is now supported by all browsers. Simply type console.log(convertToRoman(10)); The result will be printed out to console, to see it, right click your browser, and open inspect document and move to Console tab, or alternatively, Ctrl+Shift+I in Chrome
You are missing the part where you attach the result to the html. See working code below as an example.
function convertToRoman(num) {
var romans = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
var result = '';
for (var key in romans) {
if (num >= romans[key]) {
result += key.repeat(Math.trunc(num / romans[key]));
num -= romans[key] * Math.trunc(num / romans[key]);
}
}
document.getElementById('output').innerHTML = result;
}
convertToRoman(12345);
<div> my result <span id="output"></span></div>
Related
i´m new to JavaScript and learning with the Help of the Website https://www.jshero.net/koans/roman1.html.
The exercise is to code a converter, that converts roman numbers from a string 'CDLXXXIII' to the arabic number.
I made a code with a "while loop" that works, but the website wants me to do it with a recursive function.
Heres my code:
function roman(roemische){
let romBuchstaben = ['I','IV','V','IX','X','XL','L','XC','C','CD','D','CM', 'M'];
let romZahlen = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];
let summe = 0;
while (roemische.length > 0){
let suchzeichen = roemische[0] + roemische[1];
if (romBuchstaben.indexOf(suchzeichen) !== -1){
summe += romZahlen[romBuchstaben.indexOf(suchzeichen)];
roemische = roemische.substr(2,roemische.length-2);
} else {
summe += romZahlen[romBuchstaben.indexOf(roemische[0])];
roemische = roemische.substr(1, roemische.length-1);
}
}
return summe;
}
(I´m sorry that the var's are in german).
I´m not that familiar with recursion, could some1 give me an example, how to do it with one?
Greetings Marcel
You could change the storage of the values a bit by taking an object with roman signs as keys and decimal values.
For crating a recursive function, you could add an exit condition which is here just a check for an empty string and return zero in this case.
Then check if two character are in the object and if so take the value and add the result of calling the function again with the rest of the string.
If not take only the first character and the value and call the function again for getting the rest of the string.
function roman(number) {
const
values = { I: 1, IV: 4, V: 5, IX: 9, X: 10, XL: 40, L: 50, XC: 90, C: 100, CD: 400, D: 500, CM: 900, M: 1000 },
two = number.slice(0, 2);
if (!number) return 0;
return two in values
? values[two] + roman(number.slice(2))
: values[number[0]] + roman(number.slice(1));
}
console.log(roman('CDLXXXIII')); // 483
So I'm using this function that's supposed to make a car change lanes. It will change lanes as long as I don't return the number plate return vehicleObject_list[i]. But when I return the number plate as the instructions ask, the car stops changing lanes return vehicleObject_list[i].Number_Plate. The details are below:
function moveLanes(target_car)
{
/*
This function should do the following:
- move target_car from one lane to the other.
- do the move in a single step without any extra animation.
- use Lane_Position_a and Lane_Position_b to effect the change.
- finally you should return target_car at the end of the function.
hint: You will need to modify the x property of target_car.
*/
if(checkCarInfront(target_car).x == Lane_Position_a ){
target_car.x = Lane_Position_b;
}
else {
target_car.x = Lane_Position_a;
}
}
function checkCarInfront( carObj )
{
/*
This function should do the following:
- determine if carObj is in the same lane and less than 200px behind any of the cars in vehicleObject_list.
- do this by traversing vehicleObject_list and comparing each car's Distance_Driven property to that of carObj.
- if you find a car that matches these requirements then return the Number_Plate property for the car. Otherwise return false.
*/
for (var i = 0; i < vehicleObject_list.length; i++)
{
if (carObj.x == vehicleObject_list[i].x && ((vehicleObject_list[i].Distance_Driven - carObj.Distance_Driven) < 200) && ((vehicleObject_list[i].Distance_Driven - carObj.Distance_Driven) > 0))
{
return vehicleObject_list[i].Number_Plate;
}
}
return false;
}
var vehicleObject_list = [
{ x: 500, y: 0, Distance_Driven: -200, Car_Type: 'greenCar', Number_Plate: 'MBH0WW', Gas_Amt: 2, exhaust: [ ]} , { x: 500, y: 0, Distance_Driven: 200, Car_Type: 'whiteCar', Number_Plate: 'RLDGCM', Gas_Amt: 2, exhaust: [ ]} , { x: 300, y: 0, Distance_Driven: 600, Car_Type: 'whiteCar', Number_Plate: '9WGXXI', Gas_Amt: 2, exhaust: [ ]} ]
Detective_CarObject =
{
x: roadLeftEdge + roadWidth/4,
y: 550,
Distance_Driven: 0,
Gas_Amt: 3,
EngineShudder_Value: 0,
Car_Type: 'detective',
Number_Plate: '5L3UTH',
exhaust: []
}
You could do something like:
if(checkCarInfront(target_car) && target_car.x == Lane_Position_a ){
target_car.x = Lane_Position_b;
} else {
target_car.x = Lane_Position_a;
}
because checkCarInfront(target_car) will return a number plate string if there is a match (which will evaluate to true as a non empty string). You can link the condition to the target_car object which has an .x property.
Be sure to manually test the data. (for example, with the current vehicleObject_list and Detective_CarObject values if you call checkCarInfront(Detective_CarObject) this will be false (due to Distance_Driven). You can however temporarily set Detective_CarObject's x to 500 and add an extra test car in the list to check your logic: { x: 500, y: 0, Distance_Driven: 199, Car_Type: 'rainbowCar', Number_Plate: 'R41NB0W', Gas_Amt: 2, exhaust: [ ]})
As a side note I recommend adhering to JS naming conventions. Here are a couple of examples: W3Schools, FreeCodeCamp, Google JavaScript Style Guide.
In the past I would've said choose one (e.g. underscores/snake_case (e.g. target_cat) or camelCase (e.g. checkCarInFront)) but not both and keep it consistent, but these days it seems the majority adhere to camelCase. Doing so will make it much easier to work in a team later and share/contribute to open source libraries and projects.
I'm using JustGage Javascript Plugin to create a dynamic gauge. I want to pass in an array to this gauge and have it display those values. So far, I'm only able to get it to display random integers using getRandomInt().
Here's the relevant js part of the code:
<script src="justgage-1.2.2/justgage.js"></script>
<script src="justgage-1.2.2/raphael-2.1.4.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var g1 = new JustGage({
id: 'g1',
value: getRandomInt(0, 100),
min: 0,
max: 100,
pointer: true,
gaugeWidthScale: 0.6,
customSectors: [{
color: '#ff0000',
lo: 50,
hi: 100
}, {
color: '#00ff00',
lo: 0,
hi: 50
}],
counter: true
});
setInterval(function() {
g1.refresh(getRandomInt(0, 100));
}, 2000)
});
</script>
I'm wondering why something like
var num= [1,2,3,4,5,6,7,8,9];
var i = 0;
setInterval(function() {
document.innerHTML = num[i++];
if (i == num.length) i = 0;
}, 1000);
Can't be used instead of the getRandomInt() function.
Since this can't be seen on jfiddle or codepen, here's the plugin's site that shows some demo charts: http://justgage.com/ Instead of having to hit a refresh button, it refreshes on it's own.
Thought it would be more productive to ask here while I still try to work things out too.
Man that plugin has lousy docs...
Seems like you're not far off with what you want to do - in your setInterval you're going to want to do something like this, with the key part being the g1.refresh(val) with the new value of your gauge.
var i = 0,
num = [1,2,3,4,5,6,7,8,9];
setInterval(function() {
if (i >= num.length) i = 0;
g1.refresh(num[i++]);
}, 2000);
In javascript what's the simplest way to find the next even 100 ("even 100" = 200, 400, etc.) that's closest to the given number. For ex: 1723 should return 1800, 1402 should return 1600, 21 should return 200, 17659 should return 17800 etc. I have the following that finds the nearest 100 next to the given_num but not the even 100
(parseInt(((given_num + 99) / 100 )) * 100 )
I can think of one way of getting the number without zeroes and checking if its odd/even to figure out next even number if its odd.But more curious to see if there's some simple/elegant way.
Based on bmb's comment, it sounds like you want granularity of 200, not 100. If so:
Divide by 200, round up, multiply by 200:
var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 200) * 200;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}
If you really want to work by rounding up to the "next 100," then the result for 1723 must be 1900 if the result for 1402 is 1600, and you do it by dividing by 100, rounding up, multplying by 100, and adding 100 (or dividing by 100, rounding up, adding 1, and multiplying by 100, which is the same thing):
var tests = [
{value: 1723, expect: 1800},
{value: 1402, expect: 1600},
{value: 21, expect: 200},
{value: 17659, expect: 17800}
];
tests.forEach(test);
function test(entry) {
var result = Math.ceil(entry.value / 100) * 100 + 100;
console.log({
value: entry.value,
expect: entry.expect,
result: result
});
}
Call recursively if not even, add 1 to go the next 100 etc
function closestEven(n) {
var x = Math.ceil(n / 100 ), y = x * 100;
return x % 2 === 0 ? y : closestEven(y+1);
}
console.log( closestEven(1723) ); // 1800
console.log( closestEven(1402) ); // 1600
console.log( closestEven(21) ); // 200
console.log( closestEven(17659)); // 17800
Try this:
var given_num = 1723;
var result = (given_num) + (100 - ((given_num + 100) % 100));
alert(result);
I am trying to subtract the value of object1's objectProperty from object2's object property and I keep getting NaN on the console. Here is example code:
object1.objectProperty - object2.object2Property
If this isn't enough to go off, I can post the full code from my project.
If there is another way to do this or some kind of function that can help, please let me know.
edit: Here is the code..
var myPokemon = {
health: 25,
defense: 5,
attack: 10,
speed: 5
};
var moves = {
Scratch: 5,
Bite: 5,
Slap: 5,
Growl: 1
};
var computerPokemon = {
health: 20,
defense: 5,
attack: 10,
speed: 7
};
function calcDamage(firstPokemon, secondPokemon, move) {
if(move == moves.Growl){
//starts here
var newDefense = moves.Growl - firstPokemon.defense;
console.log(newDefense);
//ends here
}else{
var newHealth = (firstPokemon.health + firstPokemon.defense) - (secondPokemon.attack + move);
console.log(newHealth);
}
}
edit: When I did
moves.Growl - firstPokemon.defense || 0; it returned -4 instead of NaN which is what I wanted it to do, but the person that answered that removed the answer so this has been answered by whoever that guy was.
The problem is that you are adding the object in the second argument. Also your if statement will never execute, I have fixed both as following
var myPokemon = {
health: 25,
defense: 5,
attack: 10,
speed: 5
};
var moves = {
Scratch: 5,
Bite: 5,
Slap: 5,
Growl: 1
};
var computerPokemon = {
health: 20,
defense: 5,
attack: 10,
speed: 7
};
function calcDamage(firstPokemon, secondPokemon, move) {
if(moves.Growl!=undefined){
//starts here
var newDefense = moves.Growl - firstPokemon.defense;
alert(newDefense);
//ends here
}else{
var newHealth = (Number(firstPokemon.health) + Number(firstPokemon.defense)) - (Number(secondPokemon.attack) + Number(move.Growl));
alert(newHealth);
}
}
calcDamage(myPokemon,computerPokemon,moves)
Usually, if you are getting NaN, you are probably working with other elements but numbers. Are you sure they both are numbers?
Just an example:
var x = {}, y = {};
x.r = 10;
y.r = 5;
x.r - y.r; // yields 5
Use parseInt to convert the values into integer and then do the math.
var value = parseInt(object1.objectProperty,10) - parseInt(object2.object2Property,10);
The Problem is here
var newHealth = (Number(firstPokemon.health) + Number(firstPokemon.defense)) - (Number(secondPokemon.attack) + Number(move.Growl));
The last one Number(move.Growl) it should be Number(moves.Growl) moves not move. In your case move is just a number and you are trying Number(move.Growl) which will be NaN and hence your getting NaN.