How do you align matrices with a negative sign in mathjax? - mathjax

If you just use something like this:
\(
\left[
\begin{matrix}
0 & 1 & 5 & 2 \\
1 & -7 & 1 & 0 \\
0 & 0 & 1 & 3
\end{matrix}
\right]
\)
the negative signs don't line up.
so what I've been doing is going through and adding in a \phantom{-} to offset the difference:
\(
\left[
\begin{matrix}
0 & \phantom{-}1 & 5 & 2 \\
1 & -7 & 1 & 0 \\
0 & \phantom{-}0 & 1 & 3
\end{matrix}
\right]
\)
That works for that one column but now the widths between the columns is different unless every column after the first one has at least one number with a negative sign. So I'm fixing that by giving them all a \phantom{-}:
\(
\left[
\begin{matrix}
0 & \phantom{-}1 & \phantom{-}5 & \phantom{-}2 \\
1 & -7 & \phantom{-}1 & \phantom{-}0 \\
0 & \phantom{-}0 & \phantom{-}1 & \phantom{-}3
\end{matrix}
\right]
\)
And that looks right to me but the way I'm doing it is extremely tedious. Is there a better way of doing this?
Maybe I should write my own script to automate doing all that. This seems ideal to me:
<matrix>
0 1 5 2;
1 -7 1 0;
0 0 1 3
</matrix>

This might be more like what you are looking for:
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS_HTML"></script>
\(
\left[
\begin{matrix}
0 & \hfil 1 & 5 & 2 \\
1 & \ \llap{-}7 & 1 & 0 \\
0 & \hfil 0 & 1 & 3
\end{matrix}
\right]
\)

I'm sure I might be a total fool because there is an easier way to do it but since I couldn't find how to do it the right way I automated my way of doing it.
My code is a little node.js script that converts this:
<matrix>
1 2 3;
-42 -5 -666;
7 \color{#a38f8c}{-8} 9
</matrix>
<br>
<br>
<matrix>
6 0 0 1;
0 -1 0 0;
0 0 0 0
</matrix>
<br>
<br>
<matrix>
6 0 -9 1;
0 1 \frac{1}{200} 0;
0 0 0 0
</matrix>
into this:
\(\left[ \begin{matrix} \phantom{-}1\phantom{0} & \phantom{-}2 & \phantom{-}3\phantom{00} \\ -42 & -5 & -666 \\ \phantom{-}7\phantom{0} & \color{#a38f8c}{-8} & \phantom{-}9\phantom{00} \end{matrix} \right] \)
<br>
<br>
\( \left[ \begin{matrix} 6 & \phantom{-}0 & \phantom{-}0 & \phantom{-}1 \\ 0 & -1 & \phantom{-}0 & \phantom{-}0 \\ 0 & \phantom{-}0 & \phantom{-}0 & \phantom{-}0 \end{matrix} \right] \)
<br>
<br>
\( \left[ \begin{matrix} 6 & \phantom{-}0 & -9 & \phantom{-}1 \\ 0 & \phantom{-}1 & \phantom{-}\frac{1}{200} & \phantom{-}0 \\ 0 & \phantom{-}0 & \phantom{-}0 & \phantom{-}0 \end{matrix} \right] \)
Which looks like this:
Well, more or less. It takes the innerHTML of each <matrix>. It's definitely not ideal but I didn't see anyone coming to save the day with an answer. It works for me:
let processMatrix = text => {
// parse a matrix template string into [['a','b'],['c','d']] format
let partitionText = text => {
let rows = text.split(";");
return rows.map(row => {
row = row.trim().replace( /\s\s+/g, ' ' );
return row.split(" ");
});
};
// iterate, column first, through the matrix
let iterateMatrix = (matrix, callback) => {
let numRows = matrix.length;
let numCols = matrix[0].length;
for(let c = 0; c < numCols; c++) {
for(let r = 0; r < numRows; r++) {
let value = matrix[r][c];
callback(value, r, c);
}
}
}
// does the text have \color{#a38f8c}{12345}?
let isColored = text => /color/.test(text);
// getter and setter for the actual value. e.g. 1 or \color{#ffffff}{1}
let valueRegex = /{-*\d+}/;
let getValue = text => {
if(isColored(text)) {
return valueRegex.exec(text)[0].replace("{", "").replace("}", "");
}
else {
return text;
}
}
let setValue = (text, newValue) => {
if(isColored(text)) {
return newValue; //text.replace(valueRegex, newValue)
}
else {
return newValue;
}
}
// how many digits does this number take? e.g. 456 takes 3 digits
let getDigitCount = text => {
let isFraction = /frac{/.test(text);
if(isFraction) {
/*let fractionParts = text.match(/{\d*}/g);
let numeratorLength = fractionParts[0].length - 2;
let denominatorLength = fractionParts[1].length - 2*/
return 1; // 1 seems to look about right
}
else {;
return text.match(/\d/g).length;
}
};
// create a string of n zeroes
let getDigitString = length => {
let digitString = "";
for(let i = 0 ; i < length; i++) {
digitString += "0";
}
return digitString;
};
// toString for the 2d array that is used to represent the matrix
let matrixToString = matix => {
matrix = matrix.map(row => {
return row.join(" & ");
});
return matrix.join(" \\\\ \n");
};
// ACTUALLY START WORKING...
// Step1: turn the input string into a 2d array
let matrix = partitionText(text);
// Step2: find and store the digit that is longest in length in each column
let digitCounts = [];
iterateMatrix(matrix, (value, r, c) => {
value = getValue(value);
let digitCount = getDigitCount(value);
if(digitCounts.length === c) {
digitCounts.push(0);
}
digitCounts[c] = digitCount > digitCounts[c] ? digitCount : digitCounts[c];
});
// Step3: normalize differences in length on a per column basis. e.g. [1;123;1234] => [1\phantom{000};123\phantom{0};1234]
iterateMatrix(matrix, (value, r, c) => {
let maxDigitsInColumn = digitCounts[c];
let digitDifference = maxDigitsInColumn - getValue(value).length;
if(digitDifference > 0) {
let valueWithNormalizedLength = value + "\\phantom{" + getDigitString(digitDifference) + "}";
matrix[r][c] = valueWithNormalizedLength;
}
});
// Step4: all numbers get a negative sign, even if it's just \phantom{-} so that spacing is consistent.
// the first column only gets a negative sign if other elements in that column have a negative sign
let anyNegatives = false;
iterateMatrix(matrix, (value, r, c) => {
let isNegative = getValue(value).startsWith('-');
anyNegatives = isNegative ? true : anyNegatives;
});
if(anyNegatives) {
iterateMatrix(matrix, (value, r, c) => {
let isFirstColumn = c === 0;
let addNegativeToFirstColumn = false;
if(isFirstColumn) {
let anyNegatives = matrix.filter(r => r[0].startsWith("-")).length > 0;
addNegativeToFirstColumn = anyNegatives;
}
if(isFirstColumn && addNegativeToFirstColumn === false) {
return;
}
let startsWithNegative = getValue(value).startsWith("-");
if(startsWithNegative === false) {
matrix[r][c] = setValue(value, "\\phantom{-}" + value);
}
});
}
// STEP5: call toString and wrap it in the required syntax for a latex matrix
let matrixWrapper = "\
\\( \n\
\\left[ \n\
\\begin{matrix} \n\
[MATRIX_LATEX] \n\
\\end{matrix} \n\
\\right] \n\
\\)";
return matrixWrapper.replace("[MATRIX_LATEX]", matrixToString(matrix));
}

Related

string split into all possible combination

for a given string "ABC", i wish to get all the possible character combination out of it ascendingly and without skip of character, the result should be:["A","B","C"],["AB","C"],["ABC"],["A","BC"]
Any idea how can i achieve this? I was thinking using a nested for loop to get all the component:
string input="ABCD";
List<string> component=new List<string>();
for(int i=0;i<=input.Length;i++){
for(int j=1;j<=(input.Length-i);j++){
component.Add(input.Substring(i,j));
}
}
But i have no idea how to put them into group as the above result. Any advice is appreciated.
You can go about this in several ways.
One way is recursion. Keep a current list of substrings and an overall results list. At the top level, iterate over all the possible gaps. Split the string into a substring and the rest. This should include the "gap" at the end, where you split the string into itself and the empty string as rest. Add the (non-empty) substring to the current list and recurse on the rest of the string. When the rest of the string is empty, add the current list to the overall results list. This will give you all 2ⁿ possibilities for a string with n + 1 letters.
Pseudocode:
// recursive function
function splits_r(str, current, res)
{
if (str.length == 0) {
res += [current]
} else {
for (i = 0; i < str.length; i++) {
splits_r(str.substr(i + 1, end),
current + [str.substr(0, i + 1)], res)
}
}
}
// wrapper to get the recursion going
function splits(str)
{
res = [];
splits_r(str, [], res);
return res;
}
Another way is enumeration of all possibilities. There are 2ⁿ possibilities for a string with n + 1 letters. You can consider one individual posibility as a combination of splits and non-splits. For example:
enum splits result
0 0 0 A B C D "ABCD"
0 0 1 A B C | D "ABC", "D"
0 1 0 A B | C D "AB", "CD"
0 1 1 A B | C | D "AB", "C", "D"
1 0 0 A | B C D "A", "BCD"
1 0 1 A | B C | D "A", "BC", "D"
1 1 0 A | B | C D "A", "B", "CD"
1 1 1 A | B | C | D "A", "B", "C", "D"
The enumeration uses 0 for no split and 1 for a split. It can be seen as a binary number. If you are familiar with bitwise operations, you can now enumerate all values from 0 to 2ⁿ and find out where the splits are.
Pseudocode:
function splits(str)
{
let m = str.length - 1; // possible gap positions
let n = (1 << m); // == pow(2, m)
let res = []
for (i = 0; i < n; i++) {
let last = 0
let current = []
for (j = 0; j < m; j++) { // loop over all gaps
if (i & (1 << j)) { // test for split
current.append(str.substr(last, j + 1));
last = j + 1;
}
}
current.append(s[last:])
res.append(current);
return res;
}

responce to multi numbers

im trying to make a specific responce for a set of numbers but i dont know the exact code for that for exemple i want the responce for only numbers in between 10 and 15 it doesnt interupt with the other 2 results
module.exports.run = async (bot, message, args) => {
var s, final;
var random = Math.floor(Math.random() *( 10000)) /500;
s = random + .005 + '',
final = s.substring(0, s.indexOf('.') + 3);
message.reply("Your BC Mark is " + final);
if (final + 16 > 16){
message.reply(`excellent mark !`)
}
if (final + 10 > 15 ){
message.reply(`good !`)
}
if (final + 1 < 10.5) {
message.reply(`not bad !`)
}
}
module.exports.help = {
name: "bac"
}
You could check if your number is greater than or equal to a value and also less than or equal to a value. This would create your intended ranges.
Test the code below and implement it as necessary.
const num = 8;
if (num >= 1 && num <= 5) console.log('Between 1 and 5.');
if (num >= 6 && num <= 10) console.log('Between 6 and 10.');
if (num >= 11 && num <= 15) console.log('Between 11 and 15.');
More about comparison operators.

CSV file parsing in C#

Wanted to check if there is any null value in column field in the csv file and also there shouldn't be null value after / in number column, if it is null the entire row should not be written to output file.
name,number,gender,country
iva 1/001 f Antartica
aaju 2/002 m russia
lax 3/ m brazil
ana 4/004 f Thailand
vis 5/005 m
for e.g. 3rd and 5th row should not be written to output file.
using (StreamWriter file = new StreamWriter(filepathop)) {
for (int i = 0; i < csv.Length; i++) {
{
if (i == 0) {
file.WriteLine(header + "," + "num" + "," + "serial" + "," + "date");
}
else {
var newline = new StringBuilder();
string[] words = csv[i].Split(',');
string[] no = words[1].Split('/');
string number = no[0];
string serial = no[1];
newline.Append(number + "," + serial + "," + tokens[0]);
file.WriteLine(csv[i] + "," + newline);
}
}
}
}
}
}
}
You can test for null columns with string.IsNullOrEmpty(column) or column.Length == 0 like so:
if (!string.IsNullOrEmpty(serial) && !string.IsNullOrEmpty(country))
file.WriteLine(csv[i] + "," + newline);
You might want to check and remove white space, too. Depends on your input.

How to multiply hex color codes?

I want to change color from 0x008000 (green) to 0x0000FF (blue).
If I multiply 0x008000 * 256 = 0x800000 (Google search acts as a calculator).
I need to find the correct multiplier so the result would be 0x0000FF.
To answer people below - I am doing this in order to make a color transition on a rectangle in pixi.js.
From what I've gathered, RGB color code is divided into 3 parts - red, green and blue in a scale of 0-FF expressed in hex, or 0-255 in decimal. But how to multiply correctly to get desired result?
If you want linear change from one color to another, i recommend something like this:
int startColor = 0x008000;
int endColor = 0x0000FF;
int startRed = (startColor >> 16) & 0xFF;
int startGreen = (startColor >> 8) & 0xFF;
int startBlue = startColor & 0xFF;
int endRed, endGreen, endBlue; //same code
int steps = 24;
int[] result = new int[steps];
for(int i=0; i<steps; i++) {
int newRed = ( (steps - 1 - i)*startRed + i*endRed ) / (steps - 1);
int newGreen, newBlue; //same code
result[i] = newRed << 16 | newGreen << 8 | newBlue;
}
This is for JavaScript:
var startColor = 0x008000;
var endColor = 0x0000FF;
var startRed = (startColor >> 16) & 0xFF;
var startGreen = (startColor >> 8) & 0xFF;
var startBlue = startColor & 0xFF;
var endRed = (endColor >> 16) & 0xFF;
var endGreen = (endColor >> 8) & 0xFF;
var endBlue = endColor & 0xFF;
var steps = 24;
var result = [];
for (var i = 0; i < steps; i++) {
var newRed = ((steps - 1 - i) * startRed + i * endRed) / (steps - 1);
var newGreen = ((steps - 1 - i) * startGreen + i * endGreen) / (steps - 1);
var newBlue = ((steps - 1 - i) * startBlue + i * endBlue) / (steps - 1);
var comb = newRed << 16 | newGreen << 8 | newBlue;
console.log(i + " -> " + comb.toString(16));
result.push(comb);
}
console.log(result);

Who owes who money algorithm in excel spreadsheet

I have a group of people who have different expenses during a period. Everybody has a balance after this period. It looks like this in excel:
Person A: 6
Person B: 10
Person C: -7,5
Person D: -8,5
After this period a settlement will take place. I currently do this by manually. This results in:
Person C pays 6 to person A.
Person C pays 1,5 to person B.
Person D pays 8,5 to person B.
Person A gets 6 from person C.
Person B gets 1,5 form person C.
Peron B gets 8,5 from person D.
(There are multiple solutions possible when more persons are involved.)
The problem is that I have to apply this procedure for a big group of people. So my question is: 'How to apply this 'who owes who'-procedure by using an excel spreadsheet algorithm or macro?'.
I made a excel version too but its in Open office. can you download that? The following macro might work on its own. If it does not should be something small. it works fine in OOO and is saved as a Excel 97/2000 workbook document.
'this might not be needed in Microsoft Excel, comment it out
Option VBASupport 1 'OWES
Option Explicit
'Cells(row, col),
Private Sub cmd1_Click()
'data is same sheet, from row 4, column 4
'row 4 has names in columns, so 4,4 has name 1, 4,5 has name 2
'row 5 has amounts spent like 6, -10
'output is in columns 3 and 5
dim i
dim j,s as String, sum1
s=""
'get number of cells used in row 4 and check if corresponding row 6 column has a number value too
i = 4
sum1=0
do while(cells(4,i).Value <> "" and i < 500)
j = CDbl(cells(5,i).Value)
sum1 = sum1 + j
if j <> cells(5,i).Value then
MsgBox "Col " & i & " not a number?"
End
end if
i=i+1
loop
if i > 499 then
Msgbox "too many cols"
End
end if
If sum1 > 0.3 or sum1 < -0.3 then
Msgbox "Sum is not near 0 :" & sum1
End
End if
Dim colCnt as Integer
colCnt = i - 4
cells (7,1).Value = "Col count = " & colCnt
Dim spent(colCnt) as Double
Dim owes1(colCnt ) as String
Dim owes2(colCnt ) as String
for i= 4 to colCnt + 3
spent(i - 3) = CDbl(cells(5,i).Value)
Next
Dim cnt,lastNeg, abs1,maxPay ' safety var for never ending loops, only if data bad like many cols and more than .1 diffs
lastNeg = 4
dim lastPay1
lastPay1 = 10
dim ii,jj,c1,c2,toPay
toPay = 0
On Local Error Goto errh
for i= 4 to colCnt + 3
cnt = 0
ii = i - 3
c1 = spent(ii)
'Cells(6,i) = "ok "
if spent(ii) > 0.1 and cnt < colCnt Then '//has to take
cnt = cnt + 1
for j = lastNeg to colCnt + 3 ' ; j < people.length && spent(ii) > 0.1; j++)
jj = j - 3
's = s & Me.Cells(ii,j) & " "
if spent(ii) > 0.1 then
if spent(jj) < -0.1 Then ' //has to give and has balance to give
c1 = spent(ii)
c2 = spent(jj)
lastNeg = j
abs1 = spent(jj) * -1'//can use absolute fn
maxPay = abs1
if(maxPay > spent(ii)) Then
toPay = spent(ii)'
else
toPay = abs1
End if
spent(ii) = spent(ii) - toPay
spent(jj) = spent(jj) + toPay
Cells(lastPay1, 3).Value = Cells(4 , j) & " pays " & toPay & " to " & Cells(4 , i )
Cells(lastPay1, 5).Value = Cells(4 , i) & " gets " & toPay & " from " & Cells(4 , j)
lastPay1 = lastPay1 + 1
End if
End if
Next
End if
Next
Msgbox "Done"
err.Clear
if err.Number <> 0 Then
errH:
dim yy
yy = msgBox("err " & err.Number & " " & err.Description & " Continue", 2)
if yy = vbYes Then
Resume Next
End IF
End IF
End Sub
Book at http://sel2in.com/prjs/vba/profile (owes)
Can see http://www.excel-vba.com/ , http://office.microsoft.com/en-in/training/get-in-the-loop-with-excel-macros-RZ001150634.aspx the help in excel was useful too (f1 inside macro editor, can select a keyword or type and get context sensitive help by pressing f1)
How important is the pairing of who owes what to who? The reason I ask - it's simple to figure out the total cost per person and then determine who owes money and who needs a refund. If one person can be the "banker", he can collect all the money due and disburse all the refunds.
Much simpler question, if you have somebody willing to be the banker.
Trying to pair everything up will quite possibly not result in an exact answer, or may require one or more people making payments to more than one person - as well as one or more people trying to collect from more than one other person.
See http://sel2in.com/pages/prog/html/owes.html
Javascript fn
<form>
Paste tab seperated list of people on first line, Second line has blanace - positive means they spent more than others, negative means other spent on them (they owe)
<br>
<textarea id=t1 rows=3 cols=70></textarea>
</form>
<button onclick=calcOwes() >Calc owes</button>
<br>
<b>Result:</b>
<div id=result>Will appear here if data is good</div>
<br>
<b>Parsed data for debug:</b>
<div id=data1>Will appear here if data is good</div>
<br>
<hr>
<script>
function calcOwes(){
/**
2013 Tushar Kapila
If Person A: 6
Person B: 10
Person C: -7,5
Person D: -8,5
Then Person C pays 6 to person A.
Person C pays 1,5 to person B.
Person D pays 8,5 to person B.
*/
s = document.getElementById("t1").value
var line = s.split("\n")
//v = confirm("Your Data looks okay?:\n" + s)
//if(!v){ return;}
if(s.length < 2 || s.indexOf("\n") < 0){
alert("No line sep ")
return
}
people = line[0].split("\t")
spent = line[1].split("\t")
spent2 = line[1].split("\t")
if(spent.length < 2){
alert("Bad data, no spent data " + spent.length + "; 0 " + spent[0] + "; 1 " + + spent[1])
return
}
if(people.length != spent.length){
alert("People and amounts do not tally. make sure no tabs inside names, spaces are okay")
return
}
sum = 0;
data1o = document.getElementById("data1")
data1o.innerHTML = "";
for(i = 0;i < people.length; i++){
spent[i] = spent[i].trim()
spent[i] = parseFloat(spent[i])
sum += spent[i]
s = (1 + i) + " \"" + people[i] + "\" :" + spent[i] + ";<br>"
data1o.innerHTML += s;
}
if(sum > 0.2 || sum < -0.2){
v = confirm("Sum (" + sum + ")is not zero continue?")
if(!v){return;}
}
lastNeg = 0;
payDetails = new Array();
getDetails = new Array();
lastPay = 0;
for(i = 0;i < people.length; i++){
cnt = 0;
if(spent[i] > 0.1 && cnt < people.length){//has to take
cnt++
for(j = lastNeg; j < people.length && spent[i] > 0.1; j++){
if(spent[j] < -0.1){//has to give and has balance to give
lastNeg = j;
abs1 = spent[j] * -1;//can use absolute fn
maxPay = abs1
if(maxPay > spent[i]){
toPay = spent[i];
}else{
toPay = abs1
}
spent[i] -= toPay
spent[j] += toPay
payDetails[lastPay] = people[j] + " pays " + toPay + " to " + people[i]
getDetails[lastPay] = people[i] + " gets " + toPay + " from " + people[j]
lastPay++;
}
}
}
}
s = ""
s2 = ""
for(i = 0;i < lastPay; i++){
s = s + payDetails[i] + "<br>"
s2 = s2 + getDetails[i] + "<br>"
}
document.getElementById("result").innerHTML = s + "<br>" + s2
}
</script>
<br>Sample input 1 (tabs there?)
<br><pre>
a b c d
6 10 -7.5 -8.5
</pre>
<br>Sample input 2
<pre>
Anna Dan Bobby Scareface Colly Doc Egg face
-6 10 -7.3 -8.33 11.67
</pre>

Resources