Are any of the existing solvers equivalent to this TriangularSolver from the Java ejml library?
In particular I need a function that solves the lower triangular matrix using forward substitution.
I ended up implementing a lower triangular matrix solver myself:
public static Vector<double> SolveLower(this Matrix<double> a, Vector<double> b)
{
if (a.RowCount != a.ColumnCount)
{
throw new ArgumentException("Matrix must be square.");
}
if (a.RowCount != b.Count)
{
throw new ArgumentException("Matrix row and Vector must be the same length.");
}
var x = b.Clone();
double sum;
for (int row = 0; row < a.ColumnCount; row++)
{
sum = x.At(row);
for (int col = 0; col < row; col++)
{
sum -= a.At(row, col) * x.At(col);
}
x[row] = sum / a.At(row, row);
}
return x;
}
Test method:
[TestMethod]
public void TestSolveLowerMatrix()
{
var a = Matrix<double>.Build.DenseOfArray(new double[,] { { 3, 0, 0, 0},
{ -1, 1, 0, 0 },
{ 3, -2, -1, 0 },
{ 1, -2, 6, 2}});
var b = Vector<double>.Build.DenseOfArray(new double[] { 5, 6, 4, 2 });
var x = a.SolveLower(b);
// Verify results are valid
var expected = Vector<double>.Build.Dense(new double[] { 5 / 3.0, 23 / 3.0, -43 / 3.0, 305 / 6.0 });
Assert.AreEqual(expected.ToString(), x.ToString());
// Double check that A*x = b
Assert.AreEqual(b.ToString(), (a * x).ToString());
}
Related
In the problem description, we were told to take outer pixels as having a value of "0".
I discriminate de outer pixels so as to do nothing with them, they won´t add a value, because multiplying by 0 gets 0.
I can´t seem to find where i went wrong. Can somebody give me a clue. Thanks a lot.
here is my code
// Detect edges
void edges(int height, int width, RGBTRIPLE image[height][width])
{
// Make copy
RGBTRIPLE copy[height][width];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
copy[i][j] = image[i][j];
}
}
double gxB, gxR, gxG, gyR, gyB, gyG;
int GX[3][3] = {{-1, 0, 1}, {-2, 0, 2}, {-1, 0, 1}};
int GY[3][3] = {{-1, -2, -1}, {0, 0, 0}, {1, 2, 1}};
// Loop through pixels
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
gxB = 0;
gxR = 0;
gxG = 0;
gyR = 0;
gyB = 0;
gyG = 0;
// Loop through 3x3 box
for (int row = (i - 1); row < (i + 2); row++)
{
for (int col = (j - 1); col < (j +2); col++)
{
// Discriminate border pixels
if (exists(row, col, height, width))
{
gxR += copy[row][col].rgbtRed * GX[row][col];
gxG += copy[row][col].rgbtGreen * GX[row][col];
gxB += copy[row][col].rgbtBlue * GX[row][col];
gyR += copy[row][col].rgbtRed * GY[row][col];
gyG += copy[row][col].rgbtGreen * GY[row][col];
gyB += copy[row][col].rgbtBlue * GY[row][col];
}
else
{
gxR += 0.0;
gxG += 0.0;
gxB += 0.0;
gyR += 0.0;
gyG += 0.0;
gyB += 0.0;
}
}
}
image[i][j].rgbtRed = trimm(round(sqrt((gxR * gxR) + (gyR * gyR))));
image[i][j].rgbtGreen = trimm(round(sqrt((gxG * gxG) + (gyG * gyG))));
image[i][j].rgbtBlue = trimm(round(sqrt((gxB * gxB) + (gyB * gyB))));
}
}
return;
}
bool exists(int ROW, int COL, int H, int W)
{
if (((ROW >= 0) && (ROW < H)) && ((COL >= 0) && (COL < W)))
{
return true;
}
else
{
return false;
}
}
int trimm(int x)
{
if (x < 256)
{
return x;
}
else
{
return 255;
}
}
When dealing with a string of numbers let's say '12345', I would do something like this
String number = '12345';
List<String> listnumber = number.split("");
List<int> output = [];
for (int i = 0; i < listnumber.length; i++) {
if (i != listnumber.length - 1) {
output.add(int.parse(listnumber[i]));
}
List<String> temp = [listnumber[i]];
for (int j = i + 1; j < listnumber.length; j++) {
temp.add(listnumber[j]);
output.add(int.parse(temp.join()));
}
}
print(output.toString());
result:
[1, 12, 123, 1234, 12345, 2, 23, 234, 2345, 3, 34, 345, 4, 45]
Perfect! that's exactly what I want. But now I can't get the same result for a string of letters.
Can someone help me achieve the same result with a string such as 'abcde'.
Thanks in advance
void main(){
String number = 'abcde';
List<String> listnumber = number.split("");
List<String> output = []; // int -> String
for (int i = 0; i < listnumber.length; i++) {
if (i != listnumber.length - 1 ) {
output.add(listnumber[i]); //
}
List<String> temp = [listnumber[i]];
for (int j = i + 1; j < listnumber.length; j++) {
temp.add(listnumber[j]); //
output.add((temp.join()));
}
}
print(output.toString());
}
Output:
[a, ab, abc, abcd, abcde, b, bc, bcd, bcde, c, cd, cde, d, de]
I am trying remove 3mm bleed size from pdf. by using below criteria
My source file is Source file
I am using below code to trim left and right
public void TrimLeftandRight(string sourceFilePath, string outputFilePath)
{
PdfReader pdfReader = new PdfReader(sourceFilePath);
float width = (float)GetPDFwidth(sourceFilePath);
float height = (float)GetPDFHeight(sourceFilePath);
float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(3);
PdfRectangle rectrightside = new PdfRectangle(0, 0, width - widthTo_Trim, height);
PdfRectangle rectLeftside = new PdfRectangle(widthTo_Trim, 0, width, height);
// int[] pagealignment = new int[] { 8, 1, 2, 7, 6, 3, 4, 5 };
int[] pagealignment = new int[] { 6, 1, 2, 5, 4, 3 };
using (var output = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write))
{
// Create a new document
Document doc = new Document();
// Make a copy of the document
PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);
// Open the newly created document
doc.Open();
// Loop through all pages of the source document
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
// Get a page
var page = pdfReader.GetPageN(i);
// Apply the rectangle filter we created
switch (i)
{
case 6:
page.Put(PdfName.CROPBOX, rectLeftside);
page.Put(PdfName.MEDIABOX, rectrightside);
break;
case 2:
page.Put(PdfName.MEDIABOX, rectrightside);
break;
case 4:
page.Put(PdfName.MEDIABOX, rectLeftside);
break;
case 1:
page.Put(PdfName.MEDIABOX, rectLeftside);
break;
case 5:
page.Put(PdfName.MEDIABOX, rectrightside);
// page.Put(PdfName.CROPBOX, rectLeftside);
break;
case 3:
page.Put(PdfName.CROPBOX, rectLeftside);
page.Put(PdfName.MEDIABOX, rectrightside);
break;
}
// Copy the content and insert into the new document
var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
smartCopy.AddPage(copiedPage);
}
// Close the output document
smartCopy.Close();
doc.Close();
doc.Dispose();
}
}
the output of above code produces
Trimmed left and right file
and I used below code to merge trimmed files
public void CreategateFinalOutput(string inputfile)
{
double widthinpoints = iTextSharp.text.Utilities.MillimetersToPoints(897);
string onlyfilename = Path.GetFileName(inputfile);
// string originalfilename = Server.MapPath("~/Uploads/" + onlyfilename);
int Noofpagesinpdf = GetNoofpagesofpdf(inputfile);
// var a3doc = new Document(PageSize.A3.Rotate(), 0, 0, 0, 0);
double originalwidth = GetPDFwidth(inputfile);
float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(3);
double width = (GetPDFwidth(inputfile) * 3);
width = widthinpoints;
double height = GetPDFHeight(inputfile);
var a3reader = new PdfReader(inputfile);
var a3doc = new Document(new Rectangle((float)width, (float)height));
var a3writer = PdfWriter.GetInstance(a3doc, new FileStream(Server.MapPath("~/RP/" + onlyfilename), FileMode.Create));
a3doc.Open();
var a3cb = a3writer.DirectContent;
PdfImportedPage page;
int totalPages = a3reader.NumberOfPages;
// int[] pagealignment = new int[] { 8, 1, 2, 7, 6, 3, 4, 5 };
int[] pagealignment = new int[] { 5, 6, 1, 2, 3, 4 };
int iteration = 1;
for (int i = 1; i <= totalPages; i++)
{
a3doc.NewPage();
var a3size = new Document(new Rectangle((float)width, (float)height));
//new code
int fistpage = 0;
int secpage = 0;
int thirdpage = 0;
switch (iteration)
{
case 1:
fistpage = 5;
secpage = 6;
thirdpage = 1;
break;
case 2:
fistpage = 2;
secpage = 3;
thirdpage = 4;
break;
}
double trimwidth = iTextSharp.text.Utilities.MillimetersToPoints(3);
page = a3writer.GetImportedPage(a3reader, fistpage);
double pagewidth = page.Width;
a3cb.AddTemplate(page, 0, 0);
i++;
page = a3writer.GetImportedPage(a3reader, secpage);
double pagewidtha = page.Width;
a3cb.AddTemplate(page, (float)(pagewidtha), 0);
i++;
page = a3writer.GetImportedPage(a3reader, thirdpage);
double pagewidthaThird = page.Width;
// a3cb.AddTemplate(page, (int)(a3size.Width / 2), 0); //commented
a3cb.AddTemplate(page, (float)(pagewidthaThird + pagewidth), 0);
iteration++;
a3doc.Close();
}
}
When i merged pdf by using above code the out put is not as per desire
Final output
Here we have removed borders of page 5 and 6 but when we merged there is border appearing .
You can see it downloading pdfs.. apologies for a such a big code. the help will be highly appreciated
I request to download pdfs and check pdfs for better views
I need to find the rank/index of a lottery combination and be able to reverse the process (Find the lottery combination given its rank).
Consider a lottery game with 5 balls from 1 to 45 and 1 powerball from 1 to 20. Duplication is not allowed and the order does not matter. The number of combinations is:
(45 * 44 * 43 * 42 * 41 / 5!) * 20 = 24,435,180
The first combination (index 0) is:
1, 2, 3, 4, 5, 1
The last combination (index 24,435,179) is:
41, 42, 43, 44, 45, 20
How can I convert a combination into its index and vice versa without exhaustively enumerating all combinations?
I came across this MSDN article, which shows how to get the combination of a given index. However, I don't know how to get the index from a combination. I've tried:
Choose(c1,k) + Choose(c2,k-1) + Choose(c3,k-2) + Choose(c4,k-3) ...
Where ci is the number at position i in the ordered combination set and k is the size of the set. Since the index of a combination depends on the range of the elements, this does not work. Additionally, I'm not sure if it is going to work with elements of different sizes in the set (e.g. main pool's range is 1-45, powerball's range is 1-20)
I was able to figure it out. I created a new Combination class, based on the MSDN example, which can convert a combination to an index and vice versa. A separate index is retrieved for each pool of numbers. All the indices are then combined to represent a combination with elements of different sizes.
A Pool class was also created to represent the settings of a pool (Range of elements, size etc). The Pool class:
public class Pool {
public int From { get; set; }
public int To { get; set; }
public int Size { get; set; }
public int Numbers { get { return (To - From + 1); } }
public Pool(int From, int To, int Size) {
this.From = From;
this.To = To;
this.Size = Size ;
}
}
The Combination class:
class Combination {
public Pool[] Pools { get; set; }
public long[][] Data { get; set; } //First index represents pool index, second represents the numbers
public Combination(Pool[] Pools, long[][] Data) {
this.Pools = Pools;
this.Data = Data;
if (Data.GetLength(0) != Pools.Length) {
throw (new ArgumentException("Invalid data length"));
}
for (int i = 0; i < Data.GetLength(0); i++) {
if (Data[i].Length != Pools[i].Size) {
throw (new ArgumentException("Invalid data length"));
}
}
}
public static Combination FromIndex(long Index, Pool[] Pools) {
long[][] elements = new long[Pools.Length][];
long[] c = new long[Pools.Length - 1];
long cumulative = 1;
for (int i = 0; i < Pools.Length - 1; i++) {
c[i] = Combination.Choose(Pools[i].Numbers, Pools[i].Size);
checked {
cumulative *= c[i];
}
}
for (int i = Pools.Length - 1; i >= 1; i--) {
long ind = Index / cumulative;
Index -= ind * cumulative;
cumulative /= c[i - 1];
elements[i] = Combination.FromIndex(ind, Pools[i]);
}
elements[0] = Combination.FromIndex(Index, Pools[0]);
return (new Combination(Pools, elements));
}
public static long[] FromIndex(long Index, Pool Pool) {
long[] ans = new long[Pool.Size];
long a = (long)Pool.Numbers;
long b = (long)Pool.Size;
long x = GetDual((long)Pool.Numbers, (long)Pool.Size, Index);
for (int k = 0; k < Pool.Size; k++) {
ans[k] = LargestV(a, b, x);
x -= Choose(ans[k], b);
a = ans[k];
b--;
}
for (int k = 0; k < Pool.Size; k++) {
ans[k] = ((long)Pool.Numbers - 1) - ans[k];
}
//Transform to relative
for (int i = 0; i < ans.Length; i++) {
ans[i] += Pool.From;
}
return (ans);
}
private static long GetDual(long To, long Size, long m) {
return (Choose(To, Size) - 1) - m;
}
public static long Choose(long To, long Size) {
if (To < 0 || Size < 0)
throw new Exception("Invalid negative parameter in Choose()");
if (To < Size)
return 0; // special case
if (To == Size)
return 1;
long delta, iMax;
if (Size < To - Size) {
delta = To - Size;
iMax = Size;
} else {
delta = Size;
iMax = To - Size;
}
long ans = delta + 1;
for (long i = 2; i <= iMax; ++i) {
checked {
ans = (ans * (delta + i)) / i;
}
}
return ans;
}
private static long LargestV(long a, long b, long x) {
long v = a - 1;
while (Choose(v, b) > x)
--v;
return v;
}
public long ToIndex() {
long Index = 0;
long cumulative = 1;
for (int i = 0; i < Pools.Length; i++) {
checked {
Index += ToIndex(i) * cumulative;
cumulative *= Combination.Choose(Pools[i].Numbers, Pools[i].Size);
}
}
return (Index);
}
public long ToIndex(int PoolIndex) {
long ind = 0;
for (int i = 0; i < Pools[PoolIndex].Size; i++) {
long d = (Pools[PoolIndex].Numbers - 1) - (Data[PoolIndex][i] - Pools[PoolIndex].From);
ind += Choose(d, Pools[PoolIndex].Size - i);
}
ind = GetDual(Pools[PoolIndex].Numbers, Pools[PoolIndex].Size, ind);
return (ind);
}
public override string ToString() {
string s = "{ ";
for (int i = 0; i < Data.Length; ++i) {
for (int k = 0; k < Data[i].Length; k++) {
s += Data[i][k] + " ";
}
if (i != Data.Length - 1) {
s += "| ";
}
}
s += "}";
return s;
}
}
To see this in action:
//Create pools
Pool[] pools = new Pool[2];
pools[0] = new Pool(1, 45, 5);
pools[1] = new Pool(1, 20, 1);
//Create a combination
long[][] data = new long[][] { new long[] { 41, 42, 43, 44, 45 }, new long[] { 20 } };
Combination combination = new Combination(pools, data);
//Get index from combination:
long index = combination.ToIndex();
Console.WriteLine("Index: " + index);
//Get combination from index:
Combination combFromIndex = Combination.FromIndex(index, pools);
Console.WriteLine("Combination: " + combFromIndex);
Output:
Index: 24435179
Combination: { 41 42 43 44 45 | 20 }
I found a project description on a course website for computer graphics. I am trying to complete the project for fun.
Here is the link to the problem description:
http://www.pdfhost.net/index.php?Action=Download&File=901bc7785bef41364b3a40f6f4493926
Below is my code. The problem I am running in to is that the terms of the series grow so fast I can't map the points to the screen correctly. From the problem description it says the points will be mappable within a -2 - 2 square but the difference in value between the points is so huge that normalizing by the largest would collapse most of the points to a single pixel.
I assume I have a fundamental misunderstanding that I can't identify. Any help or insight would be appreciated!
int w = 800, h = 600;
int numTimes = 10, cSize = 5;
float xr = 2, yr = 2;
void setup() {
size(w,h);
}
void draw() {
background(255);
Complex v = new Complex(mouseX*(xr/w) - (xr/2), mouseY*(yr/h) - (yr/2));
Complex[] exps = new Complex[numTimes];
for (int i = 0; i < numTimes; i++) {
exps[i] = complexExp(v,i);
}
ellipse(w/2, h/2, cSize, cSize);
for (int i = 0; i < numTimes; i++) {
drawSeries(new Complex(0,0), exps, i, i);
}
}
void drawSeries(Complex vToDraw, Complex[] exps, int count, int clrTrunc) {
if (count == 0) {
Complex v = exps[0];
float progress = float(clrTrunc) / float(numTimes);
fill(255*progress, 180, 255 - 255*progress);
vToDraw.add(v);
ellipse(vToDraw.r*(w/xr) + (w/2), vToDraw.i*(h/xr) + h/2, cSize, cSize);
vToDraw.sub(v);
vToDraw.sub(v);
ellipse(vToDraw.r*(w/xr) + (w/2), vToDraw.i*(h/xr) + h/2, cSize, cSize);
} else {
Complex v = exps[count];
vToDraw.add(v);
drawSeries(vToDraw, exps, count - 1, clrTrunc );
vToDraw.sub(v);
vToDraw.sub(v);
drawSeries(vToDraw, exps, count - 1,clrTrunc );
}
}
Complex complexExp(Complex v, int times) {
if (times == 0) {
return new Complex(1, 1);
} else if ( times == 1) {
return new Complex( v.r*v.r - v.i*v.i, 2*v.r*v.i );
} else {
return complexExp( new Complex( v.r*v.r - v.i*v.i, 2*v.r*v.i ), times - 1 );
}
}
class Complex {
float r, i;
Complex() {
this.r = 0;
this.i = 0;
}
Complex(float r, float i) {
this.r = r;
this.i = i;
}
void add(Complex nv) {
this.r += nv.r;
this.i += nv.i;
}
void sub(Complex nv) {
this.r -= nv.r;
this.i -= nv.i;
}
}
I think you can make the code cleaner if you write a more complete Complex class.
int w = 800, h = 600;
int numTimes = 10, cSize = 5;
float xr = 3, yr = 3;
void setup() {
size(w,h);
noLoop();
}
void mousePressed() {
redraw();
}
void draw() {
background(255);
Complex v = new Complex(mouseX*(xr/w) - (xr/2), mouseY*(yr/h) - (yr/2));
Complex[] exps = new Complex[numTimes];
for (int i = 0; i < numTimes; i++) {
exps[i] = v.raisedTo(i);
print(exps[i]);
}
ellipse(w/2, h/2, cSize, cSize);
print(exps);
drawSerie(exps, numTimes);
}
void drawSerie(Complex[] exps, int total)
{
Complex partial = new Complex(0, 0);
drawPartial(exps, total -1, partial);
}
void drawFinal(Complex toDraw)
{
point(toDraw.r*(w/xr) + (w/2), toDraw.i*(h/xr) + h/2);
}
void drawPartial(Complex [] exps, int depth, Complex partial)
{
if (depth == -1)
{
drawFinal(partial);
return;
}
int nextDepth = depth -1;
drawPartial(exps, nextDepth, partial);
Complex element = exps[depth];
drawPartial(exps, nextDepth, partial.add(element));
drawPartial(exps, nextDepth, partial.sub(element));
}
class Complex {
float r, i;
Complex() {
this.r = 0;
this.i = 0;
}
Complex(float r, float i) {
this.r = r;
this.i = i;
}
Complex(Complex other)
{
this.r = other.r;
this.i = other.i;
}
Complex mult(Complex other)
{
return new Complex(this.r*other.r - this.i*other.i, this.r*other.i + this.i*other.r);
}
Complex add(Complex nv) {
return new Complex(this.r + nv.r, this.i + nv.i);
}
Complex sub(Complex nv) {
return new Complex(this.r - nv.r, this.i - nv.i);
}
Complex raisedTo(int n) {
if (n == 0) {
return new Complex(1, 0);
}
else if (n % 2 == 0)
{
return (this.mult(this)).raisedTo(n/2);
}
else
{
return this.mult(this.raisedTo(n - 1 ));
}
}
String toString()
{
return "real: " + this.r + " imaginary: " + this.i;
}
}
The computation of the series is not efficient but, I think, it is clear