Javascript replacing numbers 10-15 with a-f - javascript

I'm new to coding and I've been searching for hours and haven't really found a definitive answer to my problem. A few suggestions have been close to what I want to achieve which I think has helped a little but still not getting the outcome I want.
I've been using codepen.io a lot for seeing an instant output to my code as opposed to jsfiddle, just because I prefer how it works.
This is the code in question:
var x;
var y;
var z;
var arrayFiller;
var betaArray = new Object(256);
betaArray[0] = 0 + " " + 0;
for(var i=1; i<256; i++)
{
x = i;
y = x % 16;
x = x / 16;
x = Math.floor(x);
z = x % 16;
x = i;
arrayFiller = z + "" + y + " ";
$(
function()
{
var hexDerp =
{
'0' : "0",
'1' : "1",
'2' : "2",
'3' : "3",
'4' : "4",
'5' : "5",
'6' : "6",
'7' : "7",
'8' : "8",
'9' : "9",
'10': "A",
'11': "B",
'12': "C",
'13': "D",
'14': "E",
'15': "F"
};
var hexDerp1 = /(0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15)/g;
var arrayFillerHex = arrayFiller.replace
(
hexDerp1,
function(s)
{
if(s in hexDerp)
{
return hexDerp[s];
}
}
);
}
);
betaArray[i] = arrayFiller;
document.write(betaArray[i]);
}
My apologies if it is poorly formatted, I find this to be the clearest method for myself.
The bit that currently doesn't work is the function part which is an amalgamation of what I've found in order to replace the 10-15 with a-f.
There may be other ways of getting this inputted and outputted, but I want to keep this for what I am going to end up using this for.
tl;dr: what I wanted to do with this code, is get an array that is 256 elements large, and populate the elements with the hexadecimal version of the element number, to later be used in a unique alphabet that I am making.

You can convert decimal numbers to hexadecimal numbers using this:
(anyNumber).toString(16);

Related

How to populate array with numbers based on odds?

I recently saw a roulette wheel of sorts which contained the following possible numbers. 1, 2, 9, 16, 24, 49j and 49f. Each number has odds of itself over 1. So the odds of rolling a 2 are 2/1 and a 9 is 9/1. I thought it would be a fun (and simple) exercise to populate an array with the right amount of each type of number but it's proved anything but. My first idea was to build a name/value array to hold each numbers odds and then a second one to hold a counter value.
let numbers = {
"1": "1",
"2": "2",
"9": "9",
"16": "16",
"24": "24",
"49f": "49",
"49j": "49"
};
let counter = {
"1": "0",
"2": "0",
"9": "0",
"16": "0",
"24": "0",
"49f": "0",
"49j": "0"
};
let tc = {
"1": "0",
"2": "0",
"9": "0",
"16": "0",
"24": "0",
"49f": "0",
"49j": "0"
};
That last one tc is just to tally how many of each number is in the final array and confirm my mathematical genius. So from here it should be a simple matter of looping 50 times and looping through each number, incrementing its counter by 1 and when the counter value equals the odds value, push that number into the array and reset its counter to 0. So each iteration I should get a 1 and every 3rd iteration I should get a 2 and so on.
var wheel = [];
function load_numbers( ) {
for(let number in numbers) {
var count = parseInt(counter[number], 10);
var odd = parseInt(numbers[number], 10);
var t = parseInt(tc[number], 10);
count++;
if (count == odd) {
wheel.push(number);
count = 0;
t++; tc[number] = t;
}
counter[number] = count;
}
}
function load_wheel( ) {
for (i = 0; i < 50; i++) {
load_numbers();
}
for(let mc in tc) {
document.write(mc + ": " + tc[mc] + " of " + wheel.length + " <br>");
}
}
However that code produces the following
1: 50 of 87
2: 25 of 87
9: 5 of 87
16: 3 of 87
24: 2 of 87
49f: 1 of 87
49j: 1 of 87
These odds are clearly wrong but I can't see what's wrong with the method, I've tried doubling the odds and looping 100 times, still wrong. Setting a breakpoint after 49j == 1 also gives me these odds. In desperation I tried calculating the percentage of each numbers odds and adding them together (ie 1 = 50%, 2 = 33%) and that procedure keeps giving me 108%! So at this point I have to conclude I've been wrong about math my whole life or the Casino is pulling a fast one! Or is there something I'm overlooking?

Javascript shif left or right bidirectional

Thanks to this great site using excellent code from Nope i get this code:
var myStringArray = ["1","2","3","4","5","6","7","8","9","10"];
var loopByX = function(x){
var y = myStringArray.splice(0,x);
myStringArray = myStringArray.concat(y);
return y;
}
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
console.log(loopByX(3));
That works great...i added it to HTML5 application and see that i have a little wrong describe example of output so i need to get this output:
1
2
3
2
3
4
3
4
5
4
5
6
5
6
7
6
7
8
7
8
9
8
9
10
9
10
1
10
1
2
1
2
3
so to get value minus one or plus one (pressing up or down buttons so it is called bidirection) using above code i get 3 items up or down and it works..but i see when i copy paste the code i need to get one item up or down in loop...if can be done to modify code to do that...i try to do x-1 in function and y-1 but it is not going to give me above example output...
So i need function that i can call loopByX(3) and multiple calling function it will be shifting left by one place in loop and calling multiple function loopByX(-3) shifting right by one place in loop...what needs to be modified to archieve above output?
Many Thanks.
You could take the double array and the adjusted index.
function take(direction) {
index += direction + array.length;
index %= array.length;
console.log(array.concat(array).slice(index, index + 3).join(' '));
}
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
index = 0;
<button onclick="take(-1)">-</button>
<button onclick="take(1)">+</button>
With <div> ... </div>
function take(direction) {
index += direction + array.length;
index %= array.length;
console.log(
array
.concat(array)
.slice(index, index + 3)
.map(v => `<div>${ v }</div>`)
.join('')
);
}
var array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"],
index = 0;
<button onclick="take(-1)">-</button>
<button onclick="take(1)">+</button>

How to Extract Numbers From a Polynomial String (including the + and - signs)

I'm trying to figure out how to extract e.g. -13, as a negative value out of a polynomial, e.g. -13x^2+2-12x^4. So far, I've successfully take out the powers. Additionally, my solution came up to this:
/\(+)(-)\d{1,4}/g
I know it's wrong syntax, but I'm not sure how to represent the + or - which goes with the following number.
It would be good if you can show me how to count the next x like the end of an common/searched phrase, I'm not sure about the term. You know, if it is -3x^ and the point is to extract -3, then it should be like /\ + or - \/d{1,4} x_here/g
var formula = '-13x^2+2-12x^4';
formula.match(/[+-]?\d{1,4}/g);
Returns:
["-13", "2", "+2", "-12", "4"]
If you wish to organize the numbers into coefficients and powers, here's an approach that works:
var formula = '-13x^2+2-12x^4';
function processMatch(matched){
var arr = [];
matched.forEach(function(match){
var vals = match.split('^');
arr.push({
coeff: parseInt(vals[0]),
power: vals[1] != null ? parseInt(vals[1]) : 0
})
})
console.log(arr);
}
processMatch(formula.match(/[+-]?\d+x\^\d+|[+-\s]\d[+-\s]/g))
/* console output:
var arr = [
{ coeff: -13, power: 2 },
{ coeff: 2, power: 0 },
{ coeff: -12, power: 4 }
];*/
I think you want:
var str = '2x^2-14x+5';
var re = /([+-]?\d{1,4})/g;
var result = str.match(re);

What is the faster way to convert an object with property value: "HH:MM:SS" to string "N Minutes"?

I have hundred of objects with structure like
{
movieName: 'xyz',
time: '02:15:50'
timeAsText: null
}
I need to set timeAsText with a text as "136 minutes" based on property 'time'.
Seconds should be rounded up.
Could you point me out what could be the faster approach?
I tried this with two methods (DEMO); the first using map, and the second using a plain for...loop. As you can see from the demo the plain loop is considerably faster:
var out = [];
for (var i = 0, l = arr.length; i < l; i++) {
var obj = arr[i];
var time = obj.time.split(':').map(Number);
if (time[2] > 0) { time[1]++; }
obj.timeAsText = (time[0] * 60) + time[1] + ' minutes';
out.push(obj);
}
the best to do is probably that, and, seeing the numbers of similar answers, probably the only one.
-first, you use split(':') to make your string become a array of parseable string;
-then, parse the value to int. Use parseInt
at this time, you should have a array like that
[number_of_hours, number_of_minutes,number_of_second]
-then you just have to add the different values like
obj.timeAsText = array[0]*60+array[1]+Math.round(array[2]/60)+' minutes';
The full answer :
var arr=obj.time.split(':').forEach(function(entry){
entry=parseInt(entry);
});
obj.timeAsText= arr[0]*60+arr[1]+Math.round(array[2]/60)+" minutes";
Try this
var obj = {
movieName: 'xyz',
time: '02:15:50'
timeAsText: null
}
var a = obj.time.split(':'); // split it at the colons
var minutes = parseInt(+a[0]) * 60 + parseInt(+a[1]) + Math.round(parseInt(+a[2])/60);
obj.timeAsText = minutes + " minutes";
I don't know if it's the fastest, but it's the most easily readable one:
var test = {
movieName: 'xyz',
time: '02:15:50',
timeAsText: null
};
test.time.replace(/^(\d{2}):(\d{2}):(\d{2})$/, function(m, p1, p2, p3) {
// Multiplication and division implicitly converts p1 and p3 to numbers
return p1*60 + parseInt(p2) + Math.ceil(p3/60);
});

How to keep leading zero in a timetable

I've got a selection of times, but I want to keep the leading zero:
var fastTrainReading = [0943, 0957, 1006, 1013 , 1027, 1036, 1043, 1057, 1106, 1113, 1127, 1136, 1213, 1227, 1236, 1243, 1257, 1306, 1313, 1327, 1336, 1343, 1357, 1406, 1413, 1427, 1436, 1443, 1457, 1506, 1513, 1527, 1537, 1543, 1559, 1606, 1613, 1627, 1636, 1643, 1657, 1704, 1718, 1728, 1735, 1749, 1758, 1816, 1830, 1847, 1859, 1906, 1911, 1930, 1936, 1941, 1959, 2006, 2017, 2027];
This is the math performed:
var currentTime = hour*100 + mins;
if ((day == 0) || (day == 6)) {
document.write ("There are no buses today");
} else {
var displayCount = 0;
var TrainStr1 = "";
for (var i=0, len=fastTrainReading.length; i<len; ++i) {
if ((fastTrainReading[i] > currentTime) && (displayCount < 2)) {
displayCount = displayCount+1;
TrainStr1=TrainStr1 + fastTrainReading[i] + "<br/>";
}
}
}
document.write (TrainStr1)
I had a pretty good search through, if I missed something feel free to abuse me (but point me in the right direction).
Simplest solution is to store your time data as strings e.g. var fastTrainReading = ['0943', .... JavaScript will cast to integer for you in your calculation routines.
For a comprehensive string formatting solution that adheres to conventional principles, try sprintf() for javascript: http://www.diveintojavascript.com/projects/javascript-sprintf
You can try to use .toString() like: TrainStr1=TrainStr1 +fastTrainReading[i].toString()+ "<br/>"; alt to save your times as strings.
By default you won't get the leading zeroes.
As you know the length of TrainStr1 is 4, you can use the following function to get zeroes.
function formatted(time) {
var s = "0000" + time;
return s.substr(s.length-4); }
You can call the function 'formatted' before using document.write
You need to zero pad your numbers.
Number.prototype.zf = function _zeroFormat(digits)
{
var n = this.toString(), pLen = digits - n.length;
for ( var i = 0; i < pLen; i++)
{
n = '0' + n;
}
return n;
}
if ((fastTrainReading[i] > currentTime.zf(4)) && (displayCount < 2)) {
displayCount = displayCount+1;
TrainStr1=TrainStr1 + fastTrainReading[i] + "<br/>";
}
Once you've normalized all of your numbers to be 0-padded to 4 digits, string comparison is possible. Otherwise, you'll have issues. As things stand, it looks like your code was trying to compare a string (like an element from fastTrainReading) and a number (currentTime).
Just declare your array as strings:
var fastTrainReading = ['0943', '0957', '1006', '1013'];
And don't worry fastTrainReading[i] > currentTime will still work.
'100' > 99 == true

Categories

Resources