From a83c683e724a5085dfaa54b6b2f8ec1d90644290 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:24:31 +0000 Subject: [PATCH 01/15] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D0=B8=D0=BB(=D0=B0)=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2?= =?UTF-8?q?=20'flutter/lib'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/curve_painter.dart | 288 ++++++-------- flutter/lib/drawing_page.dart | 507 ++++++++++++++++++++++++ flutter/lib/graph.dart | 679 +++++++++++++++++++++++++++++++++ 3 files changed, 1295 insertions(+), 179 deletions(-) create mode 100644 flutter/lib/drawing_page.dart create mode 100644 flutter/lib/graph.dart diff --git a/flutter/lib/curve_painter.dart b/flutter/lib/curve_painter.dart index 0a334e5..4363d0b 100644 --- a/flutter/lib/curve_painter.dart +++ b/flutter/lib/curve_painter.dart @@ -8,71 +8,85 @@ class CurvePainter extends CustomPainter { Key? key, required this.graphData, required this.bfsPath, - required this.dfsStart, + required this.start, + required this.end, required this.dfsAccessTable, }); List? bfsPath; List? dfsAccessTable; - int? dfsStart; + int? start; + int? end; Graphs graphData; - final double dotRad = 6; - final double lineWidth = 2; - final Color lineColor = Colors.black; - final double aboveHeight = 5; - double circleRad = 100; - final TextStyle textStyle = TextStyle( - color: Colors.green.shade900, + final double _dotRad = 6; + final double _lineWidth = 1.5; + final Color _lineColor = Colors.black; + final double _aboveHeight = 5; + double _circleRad = 100; + final TextStyle _textStyle = TextStyle( + color: Colors.red.shade900, + decorationColor: Colors.green.shade900, + decorationThickness: 10, + decorationStyle: TextDecorationStyle.dashed, fontSize: 20, ); - - void drawLine(Canvas canvas, Offset p1, Offset p2) { + Map _off = {}; + void _drawLine(Canvas canvas, Offset p1, Offset p2) { Paint p = Paint(); - p.color = lineColor; - p.strokeWidth = lineWidth; + p.color = _lineColor; + p.strokeWidth = _lineWidth; canvas.drawLine(p1, p2, p); } - void drawDot(Canvas canvas, Offset p1) { + void _drawDot(Canvas canvas, Offset p1, [double plusRad = 0, Color? col]) { + col ??= Colors.yellow.shade900; var p = Paint(); - p.color = Colors.yellow.shade900; - p.strokeWidth = lineWidth + 2; - canvas.drawCircle(p1, dotRad, p); + p.color = col; + p.strokeWidth = _lineWidth + 2; + canvas.drawCircle(p1, _dotRad + plusRad, p); } - void drawSelfConnect(Canvas canvas, Offset p1) { + void _drawSelfConnect(Canvas canvas, Offset p1) { var p = Paint(); - p.color = lineColor; - p.strokeWidth = lineWidth; + p.color = _lineColor; + p.strokeWidth = _lineWidth; p.style = PaintingStyle.stroke; - canvas.drawCircle(Offset(p1.dx + dotRad + 20, p1.dy), dotRad + 20, p); + canvas.drawCircle(Offset(p1.dx + _dotRad + 20, p1.dy), _dotRad + 20, p); } - TextSpan _getTextSpan(String s) => TextSpan(text: s, style: textStyle); + TextSpan _getTextSpan(String s) => TextSpan(text: s, style: _textStyle); TextPainter _getTextPainter(String s) => TextPainter( text: _getTextSpan(s), textDirection: TextDirection.ltr, textAlign: TextAlign.center); - void drawDotNames(Canvas canvas, Offset place, String s) { + void _drawDotNames(Canvas canvas, Offset place, String s) { var textPainter = _getTextPainter(s); textPainter.layout(); textPainter.paint( canvas, Offset((place.dx - textPainter.width), - (place.dy - textPainter.height) - aboveHeight)); + (place.dy - textPainter.height) - _aboveHeight)); } - void drawAboveText(Canvas canvas, Offset size, String s) { - var textPainter = _getTextPainter(s); + void _drawDotNum(Canvas canvas, Offset size, String s) { + var textPainter = TextPainter( + text: TextSpan( + text: s, + style: const TextStyle( + color: Colors.black, + fontSize: 17, + )), + textDirection: TextDirection.ltr, + textAlign: TextAlign.center); textPainter.layout(); textPainter.paint( canvas, - Offset((size.dx - textPainter.width), - (size.dy - textPainter.height) - aboveHeight)); + Offset((size.dx - textPainter.width) + 25, + (size.dy - textPainter.height) + _aboveHeight + 30)); } - int getHighInputConnections() { + int _getHighInputConnections() { if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) { return -1; } @@ -83,17 +97,18 @@ class CurvePainter extends CustomPainter { return higest; } - Map getDotPos(int dotsAm, Size size, [int? exclude]) { + Map _getDotPos(int dotsAm, Size size) { Map off = {}; var width = size.width / 2; var height = size.height / 2; int add = 0; - int h = getHighInputConnections(); + int h = _getHighInputConnections(); for (int i = 0; i < dotsAm; i++) { if ((i + 1) != h) { - double x = cos(2 * pi * (i - add) / (dotsAm - add)) * circleRad + width; + double x = + cos(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + width; double y = - sin(2 * pi * (i - add) / (dotsAm - add)) * circleRad + height; + sin(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + height; off[i + 1] = Offset(x, y); } else if ((i + 1) == h) { @@ -110,7 +125,7 @@ class CurvePainter extends CustomPainter { return off; } - void drawHArrow(Canvas canvas, Size size, Offset from, Offset to, + void _drawHArrow(Canvas canvas, Size size, Offset from, Offset to, [bool doubleSided = false]) { Path path; @@ -120,7 +135,7 @@ class CurvePainter extends CustomPainter { ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round - ..strokeWidth = lineWidth; + ..strokeWidth = _lineWidth; var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + (to.dy - from.dy) * (to.dy - from.dy)); @@ -131,8 +146,8 @@ class CurvePainter extends CustomPainter { path.relativeCubicTo( 0, 0, - -(from.dx + to.dx) / (length * 2) - 40, - -(from.dy + to.dy) / (length * 2) - 40, + -(from.dx + to.dx + length) / (length) - 40, + -(from.dy + to.dy + length) / (length) - 40, to.dx - from.dx, to.dy - from.dy); path = @@ -140,7 +155,7 @@ class CurvePainter extends CustomPainter { canvas.drawPath(path, paint); } - void drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, + void _drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, [bool doubleSided = false]) { Path path; @@ -150,7 +165,7 @@ class CurvePainter extends CustomPainter { ..style = PaintingStyle.stroke ..strokeCap = StrokeCap.round ..strokeJoin = StrokeJoin.round - ..strokeWidth = lineWidth; + ..strokeWidth = _lineWidth; var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + (to.dy - from.dy) * (to.dy - from.dy)); @@ -161,7 +176,7 @@ class CurvePainter extends CustomPainter { path.relativeCubicTo( 0, 0, - (from.dx + to.dx) / (length * 3) + 40, + (from.dx + to.dx) / (length * 2) + 40, (from.dy + to.dy) / (length * 2) + 40, to.dx - from.dx, to.dy - from.dy); @@ -173,29 +188,29 @@ class CurvePainter extends CustomPainter { canvas.drawPath(path, paint); } - void drawConnections( + void _drawConnections( Canvas canvas, Size size, List dots, Map off) { for (var i in dots) { var list = i.getL(); var beg = off[i.num]; for (var d in list.keys) { if (d == i.num) { - drawSelfConnect(canvas, off[d]!); + _drawSelfConnect(canvas, off[d]!); } else { if (graphData.getDoubleSidedBool()) { if (d > i.num) { - drawHArrow(canvas, size, beg!, off[d]!, false); + _drawHArrow(canvas, size, beg!, off[d]!, false); if (graphData.getUseLengthBool()) { - drawDotNames( + _drawDotNames( canvas, Offset((off[d]!.dx + beg.dx) / 2 - 18, (off[d]!.dy + beg.dy) / 2 - 18), i.getL()[d].toString()); } } else { - drawHighArrow(canvas, size, beg!, off[d]!, false); + _drawHighArrow(canvas, size, beg!, off[d]!, false); if (graphData.getUseLengthBool()) { - drawDotNames( + _drawDotNames( canvas, Offset((off[d]!.dx + beg.dx) / 2 + 30, (off[d]!.dy + beg.dy) / 2 + 30), @@ -203,9 +218,9 @@ class CurvePainter extends CustomPainter { } } } else { - drawLine(canvas, beg!, off[d]!); + _drawLine(canvas, beg!, off[d]!); if (graphData.getUseLengthBool()) { - drawDotNames( + _drawDotNames( canvas, Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2), i.getL()[d].toString()); @@ -216,52 +231,71 @@ class CurvePainter extends CustomPainter { } } + void _drawBFS(Canvas canvas) { + if (bfsPath != null) { + for (int i = 0; i < bfsPath!.length; i++) { + _drawDot(canvas, _off[bfsPath![i]]!, 8, Colors.yellow); + } + _drawDot(canvas, _off[start]!, 9, Colors.green); + _drawDot(canvas, _off[end]!, 7, Colors.red.shade200); + for (int i = 0; i < bfsPath!.length; i++) { + _drawDotNum(canvas, _off[bfsPath![i]]!, "bfs: №${i + 1}"); + } + } + } + + void _drawDFS(Canvas canvas) { + if (dfsAccessTable != null) { + for (int i = 0; i < dfsAccessTable!.length; i++) { + if (dfsAccessTable![i]) { + _drawDot(canvas, _off[i + 1]!, 8, Colors.green.shade500); + _drawDotNum(canvas, _off[i + 1]!, "dfs: visible"); + } else { + _drawDot(canvas, _off[i + 1]!, 7, Colors.red.shade500); + _drawDotNum(canvas, _off[i + 1]!, "dfs: not visible"); + } + } + _drawDot(canvas, _off[start]!, 9, Colors.green.shade900); + } + } + @override void paint(Canvas canvas, Size size) { if (size.width > size.height) { - circleRad = size.height / 3; + _circleRad = size.height / 3; } else { - circleRad = size.width / 3; + _circleRad = size.width / 3; } - //var paint = Paint(); - //drawLine(canvas, Offset(0, size.height / 2), - //Offset(size.width, size.height / 2)); - //gr = getGraph(); - //int higest = getHighConnections(); - //if (higest > -1) { - var off = getDotPos(graphData.getDotAmount(), size); //, higest); - //off[higest] = Offset(size.width / 2, size.height / 2); - for (int i in off.keys) { - drawDot(canvas, off[i]!); - drawDotNames( - canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); + _off = _getDotPos(graphData.getDotAmount(), size); //, higest); + for (int i in _off.keys) { + _drawDot(canvas, _off[i]!); + //drawDotNames(canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); } - //var g = gr.getNoRepeatDots(); - //print(g); + var g = graphData.getDots(); - drawConnections(canvas, size, g, off); + _drawBFS(canvas); + _drawDFS(canvas); + _drawConnections(canvas, size, g, _off); //pringArr(canvas, size); //drawArrow(canvas, Offset(size.width / 2, size.height / 2), // Offset(size.width / 2 + 50, size.height / 2 + 200)); //} + + for (int i in _off.keys) { + //drawDot(canvas, off[i]!); + _drawDotNames( + canvas, _off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); + } } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } - - /*void _drawTextAt(String txt, Offset position, Canvas canvas) { - final textPainter = getTextPainter(txt); - textPainter.layout(minWidth: 0, maxWidth: 0); - Offset drawPosition = - Offset(position.dx, position.dy - (textPainter.height / 2)); - textPainter.paint(canvas, drawPosition); - }*/ } -void pringArr(Canvas canvas, Size size) { +/*void _pringArr(Canvas canvas, Size size) { TextSpan textSpan; TextPainter textPainter; Path path; @@ -292,108 +326,4 @@ void pringArr(Canvas canvas, Size size) { ); textPainter.layout(minWidth: size.width); textPainter.paint(canvas, Offset(0, size.height * 0.06)); -/* - /// Draw a double sided arrow. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.2); - path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0); - path = ArrowPath.make(path: path, isDoubleSided: true); - canvas.drawPath(path, paint..color = Colors.cyan); - - textSpan = const TextSpan( - text: 'Double sided arrow', - style: TextStyle(color: Colors.cyan), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.16)); - - /// Use complex path. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.3); - path.relativeCubicTo(0, 0, size.width * 0.25, 0, size.width * 0.5, 50); - path.relativeCubicTo(0, 0, -size.width * 0.25, 50, -size.width * 0.5, 50); - //path.relativeCubicTo(0, 0, size.width * 0.125, 10, size.width * 0.25, -10); - path = ArrowPath.make(path: path, isDoubleSided: true); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Complex path', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.28)); - - /// Draw several arrows on the same path. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.53); - path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 50); - path = ArrowPath.make(path: path); - path.relativeCubicTo(0, 0, -size.width * 0.25, 0, -size.width * 0.5, 50); - path = ArrowPath.make(path: path); - Path subPath = Path(); - subPath.moveTo(size.width * 0.375, size.height * 0.53 + 100); - subPath.relativeCubicTo(0, 0, size.width * 0.125, 10, size.width * 0.25, -10); - subPath = ArrowPath.make(path: subPath, isDoubleSided: true); - path.addPath(subPath, Offset.zero); - canvas.drawPath(path, paint..color = Colors.cyan); - - textSpan = const TextSpan( - text: 'Several arrows on the same path', - style: TextStyle(color: Colors.cyan), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.49)); - - /// Adjusted - path = Path(); - path.moveTo(size.width * 0.1, size.height * 0.8); - path.relativeCubicTo(0, 0, size.width * 0.3, 50, size.width * 0.25, 75); - path = ArrowPath.make(path: path, isAdjusted: true); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Adjusted', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.left, - textDirection: TextDirection.ltr, - ); - textPainter.layout(); - textPainter.paint(canvas, Offset(size.width * 0.2, size.height * 0.77)); - - /// Non adjusted. - path = Path(); - path.moveTo(size.width * 0.6, size.height * 0.8); - path.relativeCubicTo(0, 0, size.width * 0.3, 50, size.width * 0.25, 75); - path = ArrowPath.make(path: path, isAdjusted: false); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Non adjusted', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.left, - textDirection: TextDirection.ltr, - ); - textPainter.layout(); - textPainter.paint(canvas, Offset(size.width * 0.65, size.height * 0.77));*/ -} +}*/ diff --git a/flutter/lib/drawing_page.dart b/flutter/lib/drawing_page.dart new file mode 100644 index 0000000..426256d --- /dev/null +++ b/flutter/lib/drawing_page.dart @@ -0,0 +1,507 @@ +import 'package:graphs/src/graph.dart'; +import 'package:graphs/curve_painter.dart'; + +import 'package:file_picker/file_picker.dart'; +import 'package:flutter/material.dart'; + +Graphs getGraph() { + List d = []; + d.add(Dot.fromTwoLists("1", [2, 3], [5, 1])); + d.add(Dot.fromTwoLists("2", [1, 3], [1, 1])); + d.add(Dot.fromTwoLists("3", [1, 2], [1, 2])); + //d.add(Dot.fromTwoLists("Name1", [], [])); + //d.add(Dot.fromTwoLists("Name2", [], [])); + return Graphs.fromList("Имя", d, true, true); +} + +class DrawingPage extends StatefulWidget { + const DrawingPage({Key? key}) : super(key: key); + + @override + State createState() => _DrawingPageState(); +} + +class _DrawingPageState extends State { + double screenSize = 0; + Graphs graphData = getGraph(); + List? bfsPath; + List? dfsAccessTable; + int? startDot; + int? endDot; + String? dropdownValue1; + String? dropdownValue2; + + final _textNameController = TextEditingController(); + final _textNumbController = TextEditingController(); + final _textDestController = TextEditingController(); + final _textLnthController = TextEditingController(); + final _textGrNmController = TextEditingController(); + + void clearInputData() { + setState(() { + _textDestController.clear(); + _textNumbController.clear(); + _textLnthController.clear(); + _textNameController.clear(); + dropdownValue1 = null; + dropdownValue2 = null; + /*startDot = null; + bfsPath = null; + dfsAccessTable = null; + endDot = null;*/ + }); + } + + @override + Widget build(BuildContext context) { + screenSize = MediaQuery.of(context).size.width; + _textGrNmController.text = graphData.getName(); + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Align( + alignment: Alignment.topLeft, + child: Text("Graph name:\n", + style: TextStyle( + fontSize: 18, + color: Colors.white, + ))), + toolbarHeight: 110, + flexibleSpace: Container( + color: Colors.green.shade900, + child: Column(children: [ + const SizedBox(height: 5), + Row(children: [ + addSpaceW(screenSize / 8 + 19), + createButton("\nAdd dot\n", addDotPushed), + createInputBox("Dot name", screenSize / 4 - 25, Icons.label, + _textNameController), + addSpaceW(8), + createButton("\nAdd path\n", addPathPushed), + createInputBox("Input length", screenSize / 4 - 25, + Icons.arrow_right_alt_outlined, _textLnthController), + ]), + addSpaceH(3), + Row(children: [ + addSpaceW(6), + createInputBox( + "Name", screenSize / 8 - 25, null, _textGrNmController), + //addSpaceW(screenSize / 8 - 4), + createButton("\nDel dot \n", delDotPushed), + //createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController), + addSpaceW(54), + dropList1(screenSize / 4 - 80), + addSpaceW(54), + createButton("\nDel path\n", delPathPushed), + addSpaceW(54), + dropList2(screenSize / 4 - 80), + //createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController), + ]), + ]), + ), + actions: [ + IconButton( + onPressed: () => graphData.flushData(), + icon: const Icon(Icons.delete_sweep), + iconSize: 60, + ), + ]), + body: CustomPaint( + painter: CurvePainter( + graphData: graphData, + bfsPath: bfsPath, + dfsAccessTable: dfsAccessTable, + start: startDot, + end: endDot), + child: Align( + alignment: Alignment.topRight, + child: ButtonBar( + mainAxisSize: MainAxisSize.min, + children: [ + createButton("Bfs", bfsPushed), + createButton("Dfs", dfsPushed), + createButton("Clear dfs or bfs", () { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + }); + }), + createButton(graphData.getUseLengthStr(), changeLength), + createButton(graphData.getDoubleSidedStr(), changeOriented), + /*Text(_textGrNmController.text, + style: + TextStyle(fontSize: 15, color: Colors.blueGrey.shade900)),*/ + createButton("Save to file", fileSaver), + createButton("Load from file", fileOpener), + createButton("Help", () { + String out = + " В поле \"Graph name\" можно сменить имя графу.\n"; + out += + " Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n"; + out += + " Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n"; + out += + " Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" "; + out += + "и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n"; + out += + " Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n"; + out += + " Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n"; + out += + " Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n"; + out += + " Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n"; + out += + " Кнопка \"Help\" описывает работу с интерфейсом программы."; + showPopUp("Help:", out); + }) + ], + ), + ), + ), + )); + } + + // ignore: avoid_types_as_parameter_names, non_constant_identifier_names, use_function_type_syntax_for_parameters + ElevatedButton createButton(String txt, void onPressing()) { + return ElevatedButton( + onPressed: onPressing, + style: ButtonStyle( + backgroundColor: MaterialStateProperty.resolveWith( + (states) => Colors.green.shade700)), + child: Text(txt, + style: const TextStyle( + fontSize: 15, + color: Colors.white70, + height: 1, + )), + ); + } + + Container createInputBox(String text, double wid, IconData? icon, + TextEditingController? controller) { + if (icon == null) { + return Container( + width: wid, + height: 40, + margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), + child: TextField( + controller: controller, + textAlign: TextAlign.center, + onChanged: (name) => graphData.setName(name), + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(vertical: 10, horizontal: 10), + filled: true, + fillColor: Colors.white, + //prefixIcon: Icon(icon, color: Colors.black), + border: const OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(40))), + hintStyle: const TextStyle(color: Colors.black38), + hintText: text), + )); + } + return Container( + width: wid, + height: 40, + margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), + child: TextField( + controller: controller, + textAlign: TextAlign.center, + decoration: InputDecoration( + contentPadding: + const EdgeInsets.symmetric(vertical: 10, horizontal: 10), + filled: true, + fillColor: Colors.white, + prefixIcon: Icon(icon, color: Colors.black), + border: const OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(40))), + hintStyle: const TextStyle(color: Colors.black38), + hintText: text), + )); + } + + SizedBox addSpaceH(double h) { + return SizedBox(height: h); + } + + SizedBox addSpaceW(double w) { + return SizedBox(width: w); + } + + void showPopUp(String alertTitle, String err) => showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: Text(alertTitle), + content: Text(err), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + +//*********ButtonsFunctions********* + void addDotPushed() { + //showPopUp("Test", "Test message"); + //var inp = int.tryParse(_textNameController.text); + setState(() { + if (_textNameController.text == "") { + showPopUp("Error", "No name in \"Dot name\" box"); + } else { + String? res = graphData.addIsolated(_textNameController.text); + if (res != null) { + showPopUp("Error", res); + } + } + clearInputData(); + }); + } + + void addPathPushed() { + setState(() { + if (dropdownValue1 == null) { + showPopUp("Error", "Select output dot"); + } else if (dropdownValue2 == null) { + showPopUp("Error", "select input dot"); + } else if (_textLnthController.text == "" && + graphData.getUseLengthBool()) { + showPopUp("Error", "No length in \"Input length\" box"); + } else { + int? from = int.parse(dropdownValue1!); + int? to = int.parse(dropdownValue2!); + int? len = int.tryParse(_textLnthController.text); + if (len == null && graphData.getUseLengthBool()) { + showPopUp("Error", + "Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\""); + } else { + len ??= 0; + String? res = graphData.addPath(from, to, len); + if (res != null) { + showPopUp("Error", res); + } + } + } + clearInputData(); + }); + } + + void changeOriented() { + setState(() { + String? res = graphData.flipUseOrientation(); + if (res != null) showPopUp("Error", res); + }); + } + + void changeLength() { + setState(() { + String? res = graphData.flipUseLength(); + if (res != null) showPopUp("Error", res); + }); + } + + void delPathPushed() { + setState(() { + if (_textNumbController.text == "") { + showPopUp("Error", "No number in \"Dot number\" box"); + } else if (_textDestController.text == "") { + showPopUp("Error", "No name in \"Dot name\" box"); + } else { + int? from = int.tryParse(_textNumbController.text); + int? to = int.tryParse(_textDestController.text); + if (from == null || to == null) { + showPopUp("Error", + "Can't parse input.\nInts only allowed in \"Dot number\" and \"Destination number\""); + } else { + String? res = graphData.delPath(from, to); + if (res != null) { + showPopUp("Error", res); + } + } + } + clearInputData(); + }); + } + + void delDotPushed() { + setState(() { + /*if (_textNumbController.text == "") { + showPopUp("Error", "No number in \"Dot number\" box"); + } else { + int? dot = int.tryParse(_textNumbController.text); + if (dot == null) { + showPopUp("Error", "Can't parse input.\nInts only allowed"); + } else { + String? res = graphData.delDot(dot); + if (res != null) { + showPopUp("Error", res); + } + } + }*/ + if (dropdownValue1 != null) { + graphData.delDot(int.parse(dropdownValue1!)); + } else { + showPopUp("Error", "Nothing in input"); + } + clearInputData(); + }); + } + + void fileOpener() async { + FilePickerResult? result = + await FilePicker.platform.pickFiles(allowedExtensions: ["txt"]); + setState(() { + if (result != null) { + if (!result.files.single.path!.endsWith(".txt")) { + showPopUp("Error", "Can open only \".txt\" files"); + } else { + //print(result.files.single.path!); + String? res = + graphData.replaceDataFromFile(result.files.single.path!); + if (res != null) showPopUp("Error", res); + } + } else { + showPopUp("Error", "No file selected"); + // User canceled the picker + } + }); + } + + void fileSaver() async { + String? outputFile = await FilePicker.platform.saveFile( + dialogTitle: 'Please select an output file:', + fileName: 'output-file.txt', + allowedExtensions: ["txt"]); + if (outputFile == null) { + showPopUp("Error", "Save cancelled"); + // User canceled the picker + } else { + if (!outputFile.endsWith(".txt")) { + outputFile += ".txt"; + } + graphData.printToFile(outputFile); + } + } + + void bfsPushed() { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + if (dropdownValue1 == null) { + showPopUp("Error", "No number in \"Dot number\" box"); + } else if (dropdownValue2 == null) { + showPopUp("Error", "No number in \"Destination number\" box"); + } else { + startDot = int.parse(dropdownValue1!); + endDot = int.parse(dropdownValue2!); + + bfsPath = graphData.bfsPath(startDot!, endDot!); + if (bfsPath == null) { + showPopUp("Info", "There is no path"); + } + print(bfsPath); + } + }); + clearInputData(); + } + + void dfsPushed() { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + if (dropdownValue1 == null) { + showPopUp("Error", "No number in \"Dot number\" box"); + } else { + startDot = int.parse(dropdownValue1!); + dfsAccessTable = graphData.dfsIterative(startDot!); + if (dfsAccessTable == null) { + showPopUp("Err", "report this error."); + } + print(dfsAccessTable); + } + clearInputData(); + }); + } + //*********ButtonsFunctions********* + + SizedBox dropList1(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), // Not necessary for Option 1 + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue1, + + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + //background: Paint()..color = Colors.white, + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue1 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); + } + + SizedBox dropList2(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), // Not necessary for Option 1 + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue2, + + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + //background: Paint()..color = Colors.white, + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue2 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); + } +} diff --git a/flutter/lib/graph.dart b/flutter/lib/graph.dart new file mode 100644 index 0000000..cd8707b --- /dev/null +++ b/flutter/lib/graph.dart @@ -0,0 +1,679 @@ +import 'dart:io'; + +class Separators { + static const String dotToConnections = ": "; + static const String dotToLength = "|"; + static const String space = " "; + static const String hasLength = "Взвешенный"; + static const String hasNoLength = "НеВзвешенный"; + static const String isOriented = "Ориентированный"; + static const String isNotOriented = "НеОриентированный"; + static const String nL = "\n"; + static const String end = "END"; + + Separators(); +} + +class Dot { + //Data + // ignore: prefer_final_fields + String _name = ""; + int num = -1; + Map _ln = {}; + + //****Get**** + String getName() => _name; + bool hasConnection(int n) => _ln.containsKey(n); + Map getL() => _ln; + + int getLength(int x) { + if (hasConnection(x)) { + return _ln[x]!; + } + return -1; + } + //****Get**** + + //Set + void setName(String n) => _name = n; + + //Add + void addPath(int inp, int length) => _ln[inp] = length; + + //Del + void delPath(int n) => _ln.removeWhere((key, value) => + key == n); // удалить обратный путь если не ориентированный + + //Print + void printD() { + stdout.write("$_name: №$num => "); + for (var i in _ln.keys) { + stdout.write("$i|${_ln[i]} "); + } + stdout.write("\n"); + } + + //******Constructor****** + Dot([String name = "Undefined", int n = -1]) { + _name = name; + num = n; + _ln = {}; + } + Dot.fromTwoLists(String name, List num0, List length, + [int n = -1]) { + _name = name; + num = n; + Map nw = {}; + if (num0.length != length.length) { + print("Error in lists"); + } else { + for (var i = 0; i < num0.length; i++) { + nw[num0[i]] = length[i]; + _ln = nw; + } + } + } + Dot.fromMap(String name, Map l, [int n = -1]) { + _name = name; + num = n; + _ln = l; + } + //******Constructor****** + + //Copy + Dot.clone(Dot a) { + _name = a.getName(); + num = a.num; + _ln = a.getL(); + } +} + +class Graphs { + //Data + String _name = "Undefined"; //Имя + int _amount = 0; //Количество вершин + List _dots = []; //Список смежности вершин + Map _nameTable = {}; //Список вершин по именам + bool _useLength = false; //Взвешенность + bool _oriented = false; //Ориентированность + + //*********************Add************************ + String? addDot(Dot a) { + if (getNumByName(a.getName()) != null) { + return ("Dot name \"${a.getName()}\" already in use. Change name or use addPath"); + } + _amount++; + a.num = _amount; + _dots.add(a); + _syncNameTable(); + checkDots(false); + if (!_oriented) _fullFix(); + return null; + } + + bool addDotFromToLists(String name, List num0, List length, + [int n = -1]) { + var a = Dot.fromTwoLists(name, num0, length, n); + if (getNumByName(a.getName()) != null) { + print( + "Dot name ${a.getName()} already in use. Change name or use addPath"); + return false; + } + _amount++; + a.num = _amount; + _dots.add(a); + _syncNameTable(); + checkDots(false); + if (!_oriented) _fixPathAfterInsert(a); + return true; + } + + String? addIsolated(String name) { + var res = addDot(Dot.fromTwoLists(name, [], [])); + _syncNameTable(); + return res; + } + + String? addPath(int from, int to, [int len = 0]) { + if (from <= 0 || from > _amount || to <= 0 && to > _amount) { + return "Index out of range. Have dots 1..$_amount"; + } + _dots[from - 1].addPath(to, len); + if (!_oriented) { + _dots[to - 1].addPath(from, len); + } + return null; + } + //*********************Add************************ + + //*********Delete********* + String? delPath(int from, int to) { + if (from <= 0 || from > _amount || to <= 0 && to > _amount) { + return "Can't find specified path"; + } + _dots[from - 1].delPath(to); + if (!_oriented) { + _dots[to - 1].delPath(from); + } + return null; + } + + String? delDot(int inn) { + if (inn > _amount || inn < 1) { + return "Index out of range. Allowed 1..$_amount"; + } + List toDel = []; + for (int i in _dots[inn - 1].getL().keys) { + toDel.add(i); + } + for (int i in toDel) { + delPath(i, inn); + } + _dots.removeAt(inn - 1); + _syncNum(); + _syncNameTable(); + _fixAfterDel(inn); + return null; + } + + void flushData() { + _dots = []; + _amount = 0; + _nameTable = {}; + } + //*********Delete********* + + //******Helper******* + bool checkDots([bool verbose = false]) { + for (var a in _dots) { + for (var i in a.getL().keys) { + try { + if (!_dots[i - 1].getL().containsKey(a.num)) { + if (verbose) print("Can't find ${a.num}"); + return false; + } + } catch (e) { + if (verbose) { + print("Can't find Dot $i for path ${a.num}->$i. Exception $e"); + } + _dots[a.num - 1].getL().remove(i); + return false; + } + } + } + return true; + } + + void _fixAfterDel(int inn) { + for (int i = 0; i < _dots.length; i++) { + Map l = {}; + for (int j in _dots[i].getL().keys) { + if (j >= inn) { + l[j - 1] = _dots[i].getL()[j]!; + } else { + l[j] = _dots[i].getL()[j]!; + } + } + _dots[i] = Dot.fromMap(_dots[i].getName(), l, _dots[i].num); + } + } + + void _fixPathAfterInsert(Dot a) { + //Для неориентированного + for (var i in a.getL().keys) { + if (!_dots[i - 1].getL().containsKey(a.num)) { + addPath(i, a.num, a.getL()[i]!); + } + } + } + + void _fullFix() { + for (var i in _dots) { + _fixPathAfterInsert(i); + } + } + + void _syncNameTable() { + _nameTable = {}; + for (var i in _dots) { + _nameTable[i.num] = i.getName(); + } + } + + void _syncNum() { + _amount = 0; + for (var i in _dots) { + i.num = ++_amount; + } + _syncNameTable(); + } + //******Helper******* + + //*****Setters******* + void setName(String name) => _name = name; + String? flipUseOrientation() { + if (_amount != 0) { + return "Can change use of orientation only in empty graph"; + } + _oriented = !_oriented; + return null; + } + + String? flipUseLength() { + if (_amount != 0) { + return "Can change use of length only in empty graph"; + } + _useLength = !_useLength; + return null; + } + + String? replaceDataFromFile(String path) { + File file = File(path); + List lines = file.readAsLinesSync(); + if (lines.length < 3) { + return "Not enough lines in file"; + } + String name = lines.removeAt(0); + bool oriented; + switch (lines.removeAt(0)) { + case Separators.isOriented: + oriented = true; + break; + case Separators.isNotOriented: + oriented = false; + break; + default: + return "Error on parsing \"IsOriented\""; + } + bool useLength; + switch (lines.removeAt(0).trim()) { + case Separators.hasLength: + useLength = true; + break; + case Separators.hasNoLength: + useLength = false; + break; + default: + return "Error on parsing \"HasLength\""; + } + List dots = []; + for (var l in lines) { + l = l.trimRight(); + if (l != Separators.end) { + var spl = l.split(Separators.space); + List dot = []; + List len = []; + String name = spl.removeAt(0); + name = name.substring(0, name.length - 1); + for (var splitted in spl) { + if (splitted != "") { + var dt = splitted.split(Separators.dotToLength); + if (dt.length == 2) { + int? parsed = int.tryParse(dt[0]); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"${dt[0]}\""; + } + dot.add(parsed); + if (useLength) { + parsed = int.tryParse(dt[1]); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"${dt[1]}\""; + } + len.add(parsed); + } else { + len.add(0); + } + } else if (dt.length == 1) { + int? parsed = int.tryParse(splitted); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"$splitted\""; + } + dot.add(parsed); + len.add(0); + } + } + } + dots.add(Dot.fromTwoLists(name, dot, len)); + } + } + _name = name; + _oriented = oriented; + _useLength = useLength; + _dots = dots; + _syncNum(); + _syncNameTable(); + if (!_oriented) _fullFix(); + return null; + } + //*****Setters******* + + //*****Getters******* + bool getDoubleSidedBool() => _oriented; + String getDoubleSidedStr() { + if (_oriented) return Separators.isOriented; + return Separators.isNotOriented; + } + + bool getUseLengthBool() => _useLength; + String getUseLengthStr() { + if (_useLength) return Separators.hasLength; + return Separators.hasNoLength; + } + + List getDots() => _dots; + String getName() => _name; + String? getNameByNum(int n) => _nameTable[n]; + Map getNameTable() => _nameTable; + int getDotAmount() => _dots.length; + int? getNumByName(String n) { + for (var i in _nameTable.keys) { + if (_nameTable[i] == n) return i; + } + return null; + } + + List>? getLenTable() { + List>? out = >[]; + for (int i = 0; i < _amount; i++) { + List xx = []; + for (int j = 1; j <= _amount; j++) { + xx.add(_dots[i].getLength(j)); + } + out.add(xx); + } + return out; + } + + List>? getPathTable() { + List>? out = >[]; + for (int i = 0; i < _amount; i++) { + List xx = []; + for (int j = 1; j <= _amount; j++) { + if (_dots[i].getLength(j) != -1) { + xx.add(i); + } else { + xx.add(-1); + } + } + out.add(xx); + } + return out; + } + + /*List getNoRepeatDots() { + List ret = []; + for (int i = 0; i < _amount; i++) { + ret.add(Dot(_dots[i].getName(), _dots[i].num)); + } + for (int i = 0; i < _amount; i++) { + for (int j in _dots[i].getL().keys) { + if (!ret[j - 1].hasConnection(i + 1) && !ret[i].hasConnection(j) || + i == j) { + var len = _dots[i].getLength(j); + ret[i].addPath(j, len); + } + } + } + return ret; + }*/ + //*****Getters******* + + //******Print****** + void printG() { + stdout.write("$_name: "); + if (_oriented) { + stdout.write("Ориентированный, "); + } else { + stdout.write("Не ориентированный, "); + } + if (_useLength) { + print("Взвешенный"); + } else { + print("Не взвешенный"); + } + for (var i in _dots) { + i.printD(); + } + } + + void printToFile(String name) { + var file = File(name); + file.writeAsStringSync("$_name\n"); + if (_oriented) { + file.writeAsStringSync("${Separators.isOriented}\n", + mode: FileMode.append); + } else { + file.writeAsStringSync("${Separators.isNotOriented}\n", + mode: FileMode.append); + } + if (_useLength) { + file.writeAsStringSync("${Separators.hasLength}\n", + mode: FileMode.append); + } else { + file.writeAsStringSync("${Separators.hasNoLength}\n", + mode: FileMode.append); + } + for (int i = 0; i < _amount; i++) { + file.writeAsStringSync((i + 1).toString() + Separators.dotToConnections, + mode: FileMode.append); + var d = _dots[i].getL(); + for (var j in d.keys) { + file.writeAsStringSync( + j.toString() + Separators.dotToLength + d[j].toString() + " ", + mode: FileMode.append); + } + file.writeAsStringSync(Separators.nL, mode: FileMode.append); + } + file.writeAsStringSync(Separators.end, mode: FileMode.append); + } + //******Print****** + + //*******Constructor******** + Graphs( + [String name = "Undefined", + bool hasLen = false, + bool isOriented = false]) { + _name = name; + _dots = []; + _useLength = hasLen; + _oriented = isOriented; + _amount = 0; + _nameTable = {}; + } + Graphs.fromList(String name, List dots, bool hasLen, bool oriented) { + _name = name; + _dots = dots; + _useLength = hasLen; + _amount = _dots.length; + _oriented = oriented; + _syncNum(); + if (!_oriented) _fullFix(); + } + Graphs.fromFile(String path) { + replaceDataFromFile(path); + /*File file = File(path); + List lines = file.readAsLinesSync(); + _name = lines.removeAt(0); + _oriented = lines.removeAt(0) == Separators.isOriented.trim(); + _useLength = lines.removeAt(0) == Separators.hasLength.trim(); + _dots = []; + for (var l in lines) { + if (l != Separators.end) { + var spl = l.split(Separators.space); + List dot = []; + List len = []; + String name = spl.removeAt(0); + name = name.substring(0, name.length - 1); + for (var splitted in spl) { + var dt = splitted.split(Separators.dotToLength); + if (dt.length == 2) { + dot.add(int.parse(dt[0])); + if (_useLength) { + len.add(int.parse(dt[1])); + } else { + len.add(0); + } + } else if (dt.length == 1) { + dot.add(int.parse(splitted)); + len.add(0); + } + } + _dots.add(Dot.fromTwoLists(name, dot, len)); + } + } + _syncNum(); + _syncNameTable(); + if (!_oriented) _fullFix();*/ + } + //*******Constructor******** + + //Copy + Graphs.clone(Graphs a) { + _name = a.getName(); + _dots = a.getDots(); + _oriented = a.getDoubleSidedBool(); + _useLength = a.getUseLengthBool(); + _amount = _dots.length; + _syncNameTable(); + } + + //************Алгоритмы************ + /* bool bfsHasPath(int startDot, int goalDot) { + // обход в ширину + startDot--; + goalDot--; + List visited = []; + List queue = []; + for (int i = 0; i < _amount; i++) { + visited.add(false); + } // изначально список посещённых узлов пуст + queue.add(startDot); // начиная с узла-источника + visited[startDot] = true; + while (queue.isNotEmpty) { + // пока очередь не пуста + int node = queue.removeAt(0); // извлечь первый элемент в очереди + if (node == goalDot) { + return true; // проверить, не является ли текущий узел целевым + } + for (int child in _dots[node].getL().keys) { + // все преемники текущего узла, ... + if (!visited[child - 1]) { + // ... которые ещё не были посещены ... + queue.add(child - 1); // ... добавить в конец очереди... + visited[child - 1] = true; // ... и пометить как посещённые + } + } + } + return false; // Целевой узел недостижим + }*/ + + List? bfsPath(int startDot, int goalDot) { + if (startDot == goalDot) return [startDot]; + //if (!bfsHasPath(startDot, goalDot)) return null; + startDot--; + goalDot--; + List>? graph = getLenTable(); + List used = []; + List dst = []; + List pr = []; + + for (int i = 0; i < _amount; i++) { + dst.add(-1); + used.add(false); + pr.add(0); + } + + List q = []; + q.add(startDot); + used[startDot] = true; + dst[startDot] = 0; + pr[startDot] = + -1; //Пометка, означающая, что у вершины startDot нет предыдущей. + + while (q.isNotEmpty) { + int cur = q.removeAt(0); + int x = 0; + for (int neighbor in graph![cur]) { + if (neighbor != -1) { + if (!used[x]) { + q.add(x); + used[x] = true; + dst[x] = dst[cur] + 1; + pr[x] = cur; //сохранение предыдущей вершины + } + } + x++; + } + } + + //Восстановим кратчайший путь + //Для восстановления пути пройдём его в обратном порядке, и развернём. + List path = []; + + int cur = goalDot; //текущая вершина пути + path.add(cur + 1); + + while (pr[cur] != -1) { + //пока существует предыдущая вершина + cur = pr[cur]; //переходим в неё + path.add(cur + 1); //и дописываем к пути + } + + path = path.reversed.toList(); + + //print("Shortest path between vertices ${startDot+1} and ${goalDot+1} is: $path"); + if (path[0] == (startDot + 1) && + path[1] == (goalDot + 1) && + !_dots[startDot].hasConnection(goalDot + 1)) return null; + return path; + } + + List? dfsIterative(int v) { + v--; + //List? pos = []; + List label = []; + for (int i = 0; i < _amount; i++) { + label.add(false); + } + List stack = []; + stack.add(v); + //pos.add(v); + while (stack.isNotEmpty) { + v = stack.removeLast(); + if (!label[v]) { + label[v] = true; + for (int i in _dots[v].getL().keys) { + stack.add(i - 1); + //pos.add(i); + } + } + } + //print(pos); + return label; + } + + void dijkstra(int source) { + /* + create vertex set Q; + + for each vertex v in Graph{ + dist[v] ← INFINITY ; + prev[v] ← UNDEFINED ; + add v to Q;} + dist[source] ← 0; + + while Q is not empty{ + u ← vertex in Q with min dist[u] + + remove u from Q + + for each neighbor v of u still in Q{ + alt ← dist[u] + length(u, v); + if alt < dist[v]: { + dist[v] ← alt; + prev[v] ← u;} + }} + return dist[], prev[]*/ + } + //************Алгоритмы************ +} From 3e0be6b7db7318374ebbe4783ee32fb72813d0d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:25:17 +0000 Subject: [PATCH 02/15] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20'flutter/lib/curve=5Fpainter.dart'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/curve_painter.dart | 329 --------------------------------- 1 file changed, 329 deletions(-) delete mode 100644 flutter/lib/curve_painter.dart diff --git a/flutter/lib/curve_painter.dart b/flutter/lib/curve_painter.dart deleted file mode 100644 index 4363d0b..0000000 --- a/flutter/lib/curve_painter.dart +++ /dev/null @@ -1,329 +0,0 @@ -import 'package:arrow_path/arrow_path.dart'; -import 'package:graphs/src/graph.dart'; -import 'package:flutter/material.dart'; -import 'dart:math'; - -class CurvePainter extends CustomPainter { - CurvePainter({ - Key? key, - required this.graphData, - required this.bfsPath, - required this.start, - required this.end, - required this.dfsAccessTable, - }); - - List? bfsPath; - List? dfsAccessTable; - int? start; - int? end; - Graphs graphData; - final double _dotRad = 6; - final double _lineWidth = 1.5; - final Color _lineColor = Colors.black; - final double _aboveHeight = 5; - double _circleRad = 100; - final TextStyle _textStyle = TextStyle( - color: Colors.red.shade900, - decorationColor: Colors.green.shade900, - decorationThickness: 10, - decorationStyle: TextDecorationStyle.dashed, - fontSize: 20, - ); - Map _off = {}; - void _drawLine(Canvas canvas, Offset p1, Offset p2) { - Paint p = Paint(); - p.color = _lineColor; - p.strokeWidth = _lineWidth; - canvas.drawLine(p1, p2, p); - } - - void _drawDot(Canvas canvas, Offset p1, [double plusRad = 0, Color? col]) { - col ??= Colors.yellow.shade900; - var p = Paint(); - p.color = col; - p.strokeWidth = _lineWidth + 2; - canvas.drawCircle(p1, _dotRad + plusRad, p); - } - - void _drawSelfConnect(Canvas canvas, Offset p1) { - var p = Paint(); - p.color = _lineColor; - p.strokeWidth = _lineWidth; - p.style = PaintingStyle.stroke; - canvas.drawCircle(Offset(p1.dx + _dotRad + 20, p1.dy), _dotRad + 20, p); - } - - TextSpan _getTextSpan(String s) => TextSpan(text: s, style: _textStyle); - TextPainter _getTextPainter(String s) => TextPainter( - text: _getTextSpan(s), - textDirection: TextDirection.ltr, - textAlign: TextAlign.center); - - void _drawDotNames(Canvas canvas, Offset place, String s) { - var textPainter = _getTextPainter(s); - textPainter.layout(); - textPainter.paint( - canvas, - Offset((place.dx - textPainter.width), - (place.dy - textPainter.height) - _aboveHeight)); - } - - void _drawDotNum(Canvas canvas, Offset size, String s) { - var textPainter = TextPainter( - text: TextSpan( - text: s, - style: const TextStyle( - color: Colors.black, - fontSize: 17, - )), - textDirection: TextDirection.ltr, - textAlign: TextAlign.center); - textPainter.layout(); - textPainter.paint( - canvas, - Offset((size.dx - textPainter.width) + 25, - (size.dy - textPainter.height) + _aboveHeight + 30)); - } - - int _getHighInputConnections() { - if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) { - return -1; - } - int higest = -1; - for (var i in graphData.getDots()) { - if (i.getL().length > higest) higest = i.num; - } - return higest; - } - - Map _getDotPos(int dotsAm, Size size) { - Map off = {}; - var width = size.width / 2; - var height = size.height / 2; - int add = 0; - int h = _getHighInputConnections(); - for (int i = 0; i < dotsAm; i++) { - if ((i + 1) != h) { - double x = - cos(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + width; - double y = - sin(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + height; - - off[i + 1] = Offset(x, y); - } else if ((i + 1) == h) { - off[i + 1] = Offset(width + 2, height - 2); - add = 1; - h = 0; - } else { - print("GetDotPos error"); - } - //print(off.length); - } - - //print(off); - return off; - } - - void _drawHArrow(Canvas canvas, Size size, Offset from, Offset to, - [bool doubleSided = false]) { - Path path; - - // The arrows usually looks better with rounded caps. - Paint paint = Paint() - ..color = Colors.black - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round - ..strokeJoin = StrokeJoin.round - ..strokeWidth = _lineWidth; - - var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + - (to.dy - from.dy) * (to.dy - from.dy)); - - /// Draw a single arrow. - path = Path(); - path.moveTo(from.dx, from.dy); - path.relativeCubicTo( - 0, - 0, - -(from.dx + to.dx + length) / (length) - 40, - -(from.dy + to.dy + length) / (length) - 40, - to.dx - from.dx, - to.dy - from.dy); - path = - ArrowPath.make(path: path, isDoubleSided: doubleSided, tipLength: 16); - canvas.drawPath(path, paint); - } - - void _drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, - [bool doubleSided = false]) { - Path path; - - // The arrows usually looks better with rounded caps. - Paint paint = Paint() - ..color = Colors.black - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round - ..strokeJoin = StrokeJoin.round - ..strokeWidth = _lineWidth; - - var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + - (to.dy - from.dy) * (to.dy - from.dy)); - - /// Draw a single arrow. - path = Path(); - path.moveTo(from.dx, from.dy); - path.relativeCubicTo( - 0, - 0, - (from.dx + to.dx) / (length * 2) + 40, - (from.dy + to.dy) / (length * 2) + 40, - to.dx - from.dx, - to.dy - from.dy); - path = ArrowPath.make( - path: path, - isDoubleSided: doubleSided, - tipLength: 13, - isAdjusted: false); - canvas.drawPath(path, paint); - } - - void _drawConnections( - Canvas canvas, Size size, List dots, Map off) { - for (var i in dots) { - var list = i.getL(); - var beg = off[i.num]; - for (var d in list.keys) { - if (d == i.num) { - _drawSelfConnect(canvas, off[d]!); - } else { - if (graphData.getDoubleSidedBool()) { - if (d > i.num) { - _drawHArrow(canvas, size, beg!, off[d]!, false); - if (graphData.getUseLengthBool()) { - _drawDotNames( - canvas, - Offset((off[d]!.dx + beg.dx) / 2 - 18, - (off[d]!.dy + beg.dy) / 2 - 18), - i.getL()[d].toString()); - } - } else { - _drawHighArrow(canvas, size, beg!, off[d]!, false); - if (graphData.getUseLengthBool()) { - _drawDotNames( - canvas, - Offset((off[d]!.dx + beg.dx) / 2 + 30, - (off[d]!.dy + beg.dy) / 2 + 30), - i.getL()[d].toString()); - } - } - } else { - _drawLine(canvas, beg!, off[d]!); - if (graphData.getUseLengthBool()) { - _drawDotNames( - canvas, - Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2), - i.getL()[d].toString()); - } - } - } - } - } - } - - void _drawBFS(Canvas canvas) { - if (bfsPath != null) { - for (int i = 0; i < bfsPath!.length; i++) { - _drawDot(canvas, _off[bfsPath![i]]!, 8, Colors.yellow); - } - _drawDot(canvas, _off[start]!, 9, Colors.green); - _drawDot(canvas, _off[end]!, 7, Colors.red.shade200); - for (int i = 0; i < bfsPath!.length; i++) { - _drawDotNum(canvas, _off[bfsPath![i]]!, "bfs: №${i + 1}"); - } - } - } - - void _drawDFS(Canvas canvas) { - if (dfsAccessTable != null) { - for (int i = 0; i < dfsAccessTable!.length; i++) { - if (dfsAccessTable![i]) { - _drawDot(canvas, _off[i + 1]!, 8, Colors.green.shade500); - _drawDotNum(canvas, _off[i + 1]!, "dfs: visible"); - } else { - _drawDot(canvas, _off[i + 1]!, 7, Colors.red.shade500); - _drawDotNum(canvas, _off[i + 1]!, "dfs: not visible"); - } - } - _drawDot(canvas, _off[start]!, 9, Colors.green.shade900); - } - } - - @override - void paint(Canvas canvas, Size size) { - if (size.width > size.height) { - _circleRad = size.height / 3; - } else { - _circleRad = size.width / 3; - } - - _off = _getDotPos(graphData.getDotAmount(), size); //, higest); - for (int i in _off.keys) { - _drawDot(canvas, _off[i]!); - //drawDotNames(canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); - } - - var g = graphData.getDots(); - _drawBFS(canvas); - _drawDFS(canvas); - _drawConnections(canvas, size, g, _off); - //pringArr(canvas, size); - //drawArrow(canvas, Offset(size.width / 2, size.height / 2), - // Offset(size.width / 2 + 50, size.height / 2 + 200)); - //} - - for (int i in _off.keys) { - //drawDot(canvas, off[i]!); - _drawDotNames( - canvas, _off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); - } - } - - @override - bool shouldRepaint(CustomPainter oldDelegate) { - return true; - } -} - -/*void _pringArr(Canvas canvas, Size size) { - TextSpan textSpan; - TextPainter textPainter; - Path path; - - // The arrows usually looks better with rounded caps. - Paint paint = Paint() - ..color = Colors.black - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round - ..strokeJoin = StrokeJoin.round - ..strokeWidth = 3.0; - - /// Draw a single arrow. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.10); - path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0); - path = ArrowPath.make(path: path); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Single arrow', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.06)); -}*/ From 364495be658be50b57b58cb05093068b5570c6ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:25:47 +0000 Subject: [PATCH 03/15] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20'flutter/lib/drawing=5Fpage.dart'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/drawing_page.dart | 507 ---------------------------------- 1 file changed, 507 deletions(-) delete mode 100644 flutter/lib/drawing_page.dart diff --git a/flutter/lib/drawing_page.dart b/flutter/lib/drawing_page.dart deleted file mode 100644 index 426256d..0000000 --- a/flutter/lib/drawing_page.dart +++ /dev/null @@ -1,507 +0,0 @@ -import 'package:graphs/src/graph.dart'; -import 'package:graphs/curve_painter.dart'; - -import 'package:file_picker/file_picker.dart'; -import 'package:flutter/material.dart'; - -Graphs getGraph() { - List d = []; - d.add(Dot.fromTwoLists("1", [2, 3], [5, 1])); - d.add(Dot.fromTwoLists("2", [1, 3], [1, 1])); - d.add(Dot.fromTwoLists("3", [1, 2], [1, 2])); - //d.add(Dot.fromTwoLists("Name1", [], [])); - //d.add(Dot.fromTwoLists("Name2", [], [])); - return Graphs.fromList("Имя", d, true, true); -} - -class DrawingPage extends StatefulWidget { - const DrawingPage({Key? key}) : super(key: key); - - @override - State createState() => _DrawingPageState(); -} - -class _DrawingPageState extends State { - double screenSize = 0; - Graphs graphData = getGraph(); - List? bfsPath; - List? dfsAccessTable; - int? startDot; - int? endDot; - String? dropdownValue1; - String? dropdownValue2; - - final _textNameController = TextEditingController(); - final _textNumbController = TextEditingController(); - final _textDestController = TextEditingController(); - final _textLnthController = TextEditingController(); - final _textGrNmController = TextEditingController(); - - void clearInputData() { - setState(() { - _textDestController.clear(); - _textNumbController.clear(); - _textLnthController.clear(); - _textNameController.clear(); - dropdownValue1 = null; - dropdownValue2 = null; - /*startDot = null; - bfsPath = null; - dfsAccessTable = null; - endDot = null;*/ - }); - } - - @override - Widget build(BuildContext context) { - screenSize = MediaQuery.of(context).size.width; - _textGrNmController.text = graphData.getName(); - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Align( - alignment: Alignment.topLeft, - child: Text("Graph name:\n", - style: TextStyle( - fontSize: 18, - color: Colors.white, - ))), - toolbarHeight: 110, - flexibleSpace: Container( - color: Colors.green.shade900, - child: Column(children: [ - const SizedBox(height: 5), - Row(children: [ - addSpaceW(screenSize / 8 + 19), - createButton("\nAdd dot\n", addDotPushed), - createInputBox("Dot name", screenSize / 4 - 25, Icons.label, - _textNameController), - addSpaceW(8), - createButton("\nAdd path\n", addPathPushed), - createInputBox("Input length", screenSize / 4 - 25, - Icons.arrow_right_alt_outlined, _textLnthController), - ]), - addSpaceH(3), - Row(children: [ - addSpaceW(6), - createInputBox( - "Name", screenSize / 8 - 25, null, _textGrNmController), - //addSpaceW(screenSize / 8 - 4), - createButton("\nDel dot \n", delDotPushed), - //createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController), - addSpaceW(54), - dropList1(screenSize / 4 - 80), - addSpaceW(54), - createButton("\nDel path\n", delPathPushed), - addSpaceW(54), - dropList2(screenSize / 4 - 80), - //createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController), - ]), - ]), - ), - actions: [ - IconButton( - onPressed: () => graphData.flushData(), - icon: const Icon(Icons.delete_sweep), - iconSize: 60, - ), - ]), - body: CustomPaint( - painter: CurvePainter( - graphData: graphData, - bfsPath: bfsPath, - dfsAccessTable: dfsAccessTable, - start: startDot, - end: endDot), - child: Align( - alignment: Alignment.topRight, - child: ButtonBar( - mainAxisSize: MainAxisSize.min, - children: [ - createButton("Bfs", bfsPushed), - createButton("Dfs", dfsPushed), - createButton("Clear dfs or bfs", () { - setState(() { - bfsPath = null; - dfsAccessTable = null; - startDot = null; - endDot = null; - }); - }), - createButton(graphData.getUseLengthStr(), changeLength), - createButton(graphData.getDoubleSidedStr(), changeOriented), - /*Text(_textGrNmController.text, - style: - TextStyle(fontSize: 15, color: Colors.blueGrey.shade900)),*/ - createButton("Save to file", fileSaver), - createButton("Load from file", fileOpener), - createButton("Help", () { - String out = - " В поле \"Graph name\" можно сменить имя графу.\n"; - out += - " Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n"; - out += - " Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n"; - out += - " Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" "; - out += - "и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n"; - out += - " Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n"; - out += - " Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n"; - out += - " Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n"; - out += - " Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n"; - out += - " Кнопка \"Help\" описывает работу с интерфейсом программы."; - showPopUp("Help:", out); - }) - ], - ), - ), - ), - )); - } - - // ignore: avoid_types_as_parameter_names, non_constant_identifier_names, use_function_type_syntax_for_parameters - ElevatedButton createButton(String txt, void onPressing()) { - return ElevatedButton( - onPressed: onPressing, - style: ButtonStyle( - backgroundColor: MaterialStateProperty.resolveWith( - (states) => Colors.green.shade700)), - child: Text(txt, - style: const TextStyle( - fontSize: 15, - color: Colors.white70, - height: 1, - )), - ); - } - - Container createInputBox(String text, double wid, IconData? icon, - TextEditingController? controller) { - if (icon == null) { - return Container( - width: wid, - height: 40, - margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), - child: TextField( - controller: controller, - textAlign: TextAlign.center, - onChanged: (name) => graphData.setName(name), - decoration: InputDecoration( - contentPadding: - const EdgeInsets.symmetric(vertical: 10, horizontal: 10), - filled: true, - fillColor: Colors.white, - //prefixIcon: Icon(icon, color: Colors.black), - border: const OutlineInputBorder( - borderRadius: BorderRadius.all(Radius.circular(40))), - hintStyle: const TextStyle(color: Colors.black38), - hintText: text), - )); - } - return Container( - width: wid, - height: 40, - margin: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), - child: TextField( - controller: controller, - textAlign: TextAlign.center, - decoration: InputDecoration( - contentPadding: - const EdgeInsets.symmetric(vertical: 10, horizontal: 10), - filled: true, - fillColor: Colors.white, - prefixIcon: Icon(icon, color: Colors.black), - border: const OutlineInputBorder( - borderRadius: BorderRadius.all(Radius.circular(40))), - hintStyle: const TextStyle(color: Colors.black38), - hintText: text), - )); - } - - SizedBox addSpaceH(double h) { - return SizedBox(height: h); - } - - SizedBox addSpaceW(double w) { - return SizedBox(width: w); - } - - void showPopUp(String alertTitle, String err) => showDialog( - context: context, - builder: (BuildContext context) => AlertDialog( - title: Text(alertTitle), - content: Text(err), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context, 'OK'), - child: const Text('OK'), - ), - ], - ), - ); - -//*********ButtonsFunctions********* - void addDotPushed() { - //showPopUp("Test", "Test message"); - //var inp = int.tryParse(_textNameController.text); - setState(() { - if (_textNameController.text == "") { - showPopUp("Error", "No name in \"Dot name\" box"); - } else { - String? res = graphData.addIsolated(_textNameController.text); - if (res != null) { - showPopUp("Error", res); - } - } - clearInputData(); - }); - } - - void addPathPushed() { - setState(() { - if (dropdownValue1 == null) { - showPopUp("Error", "Select output dot"); - } else if (dropdownValue2 == null) { - showPopUp("Error", "select input dot"); - } else if (_textLnthController.text == "" && - graphData.getUseLengthBool()) { - showPopUp("Error", "No length in \"Input length\" box"); - } else { - int? from = int.parse(dropdownValue1!); - int? to = int.parse(dropdownValue2!); - int? len = int.tryParse(_textLnthController.text); - if (len == null && graphData.getUseLengthBool()) { - showPopUp("Error", - "Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\""); - } else { - len ??= 0; - String? res = graphData.addPath(from, to, len); - if (res != null) { - showPopUp("Error", res); - } - } - } - clearInputData(); - }); - } - - void changeOriented() { - setState(() { - String? res = graphData.flipUseOrientation(); - if (res != null) showPopUp("Error", res); - }); - } - - void changeLength() { - setState(() { - String? res = graphData.flipUseLength(); - if (res != null) showPopUp("Error", res); - }); - } - - void delPathPushed() { - setState(() { - if (_textNumbController.text == "") { - showPopUp("Error", "No number in \"Dot number\" box"); - } else if (_textDestController.text == "") { - showPopUp("Error", "No name in \"Dot name\" box"); - } else { - int? from = int.tryParse(_textNumbController.text); - int? to = int.tryParse(_textDestController.text); - if (from == null || to == null) { - showPopUp("Error", - "Can't parse input.\nInts only allowed in \"Dot number\" and \"Destination number\""); - } else { - String? res = graphData.delPath(from, to); - if (res != null) { - showPopUp("Error", res); - } - } - } - clearInputData(); - }); - } - - void delDotPushed() { - setState(() { - /*if (_textNumbController.text == "") { - showPopUp("Error", "No number in \"Dot number\" box"); - } else { - int? dot = int.tryParse(_textNumbController.text); - if (dot == null) { - showPopUp("Error", "Can't parse input.\nInts only allowed"); - } else { - String? res = graphData.delDot(dot); - if (res != null) { - showPopUp("Error", res); - } - } - }*/ - if (dropdownValue1 != null) { - graphData.delDot(int.parse(dropdownValue1!)); - } else { - showPopUp("Error", "Nothing in input"); - } - clearInputData(); - }); - } - - void fileOpener() async { - FilePickerResult? result = - await FilePicker.platform.pickFiles(allowedExtensions: ["txt"]); - setState(() { - if (result != null) { - if (!result.files.single.path!.endsWith(".txt")) { - showPopUp("Error", "Can open only \".txt\" files"); - } else { - //print(result.files.single.path!); - String? res = - graphData.replaceDataFromFile(result.files.single.path!); - if (res != null) showPopUp("Error", res); - } - } else { - showPopUp("Error", "No file selected"); - // User canceled the picker - } - }); - } - - void fileSaver() async { - String? outputFile = await FilePicker.platform.saveFile( - dialogTitle: 'Please select an output file:', - fileName: 'output-file.txt', - allowedExtensions: ["txt"]); - if (outputFile == null) { - showPopUp("Error", "Save cancelled"); - // User canceled the picker - } else { - if (!outputFile.endsWith(".txt")) { - outputFile += ".txt"; - } - graphData.printToFile(outputFile); - } - } - - void bfsPushed() { - setState(() { - bfsPath = null; - dfsAccessTable = null; - startDot = null; - endDot = null; - if (dropdownValue1 == null) { - showPopUp("Error", "No number in \"Dot number\" box"); - } else if (dropdownValue2 == null) { - showPopUp("Error", "No number in \"Destination number\" box"); - } else { - startDot = int.parse(dropdownValue1!); - endDot = int.parse(dropdownValue2!); - - bfsPath = graphData.bfsPath(startDot!, endDot!); - if (bfsPath == null) { - showPopUp("Info", "There is no path"); - } - print(bfsPath); - } - }); - clearInputData(); - } - - void dfsPushed() { - setState(() { - bfsPath = null; - dfsAccessTable = null; - startDot = null; - endDot = null; - if (dropdownValue1 == null) { - showPopUp("Error", "No number in \"Dot number\" box"); - } else { - startDot = int.parse(dropdownValue1!); - dfsAccessTable = graphData.dfsIterative(startDot!); - if (dfsAccessTable == null) { - showPopUp("Err", "report this error."); - } - print(dfsAccessTable); - } - clearInputData(); - }); - } - //*********ButtonsFunctions********* - - SizedBox dropList1(double width) { - var button = DropdownButton( - hint: const Text( - 'Select Dot', - style: TextStyle(color: Colors.white, fontSize: 13), - ), // Not necessary for Option 1 - alignment: AlignmentDirectional.centerEnd, - value: dropdownValue1, - - isDense: true, - borderRadius: const BorderRadius.all(Radius.circular(20)), - dropdownColor: Colors.green.shade800, - style: const TextStyle( - //background: Paint()..color = Colors.white, - color: Colors.white, - fontSize: 18, - ), - onChanged: (String? newValue) { - setState(() { - dropdownValue1 = newValue; - }); - }, - items: graphData.getDots().map((location) { - return DropdownMenuItem( - child: Text(location.getName()), - value: location.num.toString(), - ); - }).toList(), - ); - - return SizedBox( - child: button, - width: width, - ); - } - - SizedBox dropList2(double width) { - var button = DropdownButton( - hint: const Text( - 'Select Dot', - style: TextStyle(color: Colors.white, fontSize: 13), - ), // Not necessary for Option 1 - alignment: AlignmentDirectional.centerEnd, - value: dropdownValue2, - - isDense: true, - borderRadius: const BorderRadius.all(Radius.circular(20)), - dropdownColor: Colors.green.shade800, - style: const TextStyle( - //background: Paint()..color = Colors.white, - color: Colors.white, - fontSize: 18, - ), - onChanged: (String? newValue) { - setState(() { - dropdownValue2 = newValue; - }); - }, - items: graphData.getDots().map((location) { - return DropdownMenuItem( - child: Text(location.getName()), - value: location.num.toString(), - ); - }).toList(), - ); - - return SizedBox( - child: button, - width: width, - ); - } -} From 7bbb41421284a5dde4f7a4af056ba7e614c94aad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:25:57 +0000 Subject: [PATCH 04/15] =?UTF-8?q?=D0=A3=D0=B4=D0=B0=D0=BB=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20'flutter/lib/graph.dart'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/graph.dart | 679 ----------------------------------------- 1 file changed, 679 deletions(-) delete mode 100644 flutter/lib/graph.dart diff --git a/flutter/lib/graph.dart b/flutter/lib/graph.dart deleted file mode 100644 index cd8707b..0000000 --- a/flutter/lib/graph.dart +++ /dev/null @@ -1,679 +0,0 @@ -import 'dart:io'; - -class Separators { - static const String dotToConnections = ": "; - static const String dotToLength = "|"; - static const String space = " "; - static const String hasLength = "Взвешенный"; - static const String hasNoLength = "НеВзвешенный"; - static const String isOriented = "Ориентированный"; - static const String isNotOriented = "НеОриентированный"; - static const String nL = "\n"; - static const String end = "END"; - - Separators(); -} - -class Dot { - //Data - // ignore: prefer_final_fields - String _name = ""; - int num = -1; - Map _ln = {}; - - //****Get**** - String getName() => _name; - bool hasConnection(int n) => _ln.containsKey(n); - Map getL() => _ln; - - int getLength(int x) { - if (hasConnection(x)) { - return _ln[x]!; - } - return -1; - } - //****Get**** - - //Set - void setName(String n) => _name = n; - - //Add - void addPath(int inp, int length) => _ln[inp] = length; - - //Del - void delPath(int n) => _ln.removeWhere((key, value) => - key == n); // удалить обратный путь если не ориентированный - - //Print - void printD() { - stdout.write("$_name: №$num => "); - for (var i in _ln.keys) { - stdout.write("$i|${_ln[i]} "); - } - stdout.write("\n"); - } - - //******Constructor****** - Dot([String name = "Undefined", int n = -1]) { - _name = name; - num = n; - _ln = {}; - } - Dot.fromTwoLists(String name, List num0, List length, - [int n = -1]) { - _name = name; - num = n; - Map nw = {}; - if (num0.length != length.length) { - print("Error in lists"); - } else { - for (var i = 0; i < num0.length; i++) { - nw[num0[i]] = length[i]; - _ln = nw; - } - } - } - Dot.fromMap(String name, Map l, [int n = -1]) { - _name = name; - num = n; - _ln = l; - } - //******Constructor****** - - //Copy - Dot.clone(Dot a) { - _name = a.getName(); - num = a.num; - _ln = a.getL(); - } -} - -class Graphs { - //Data - String _name = "Undefined"; //Имя - int _amount = 0; //Количество вершин - List _dots = []; //Список смежности вершин - Map _nameTable = {}; //Список вершин по именам - bool _useLength = false; //Взвешенность - bool _oriented = false; //Ориентированность - - //*********************Add************************ - String? addDot(Dot a) { - if (getNumByName(a.getName()) != null) { - return ("Dot name \"${a.getName()}\" already in use. Change name or use addPath"); - } - _amount++; - a.num = _amount; - _dots.add(a); - _syncNameTable(); - checkDots(false); - if (!_oriented) _fullFix(); - return null; - } - - bool addDotFromToLists(String name, List num0, List length, - [int n = -1]) { - var a = Dot.fromTwoLists(name, num0, length, n); - if (getNumByName(a.getName()) != null) { - print( - "Dot name ${a.getName()} already in use. Change name or use addPath"); - return false; - } - _amount++; - a.num = _amount; - _dots.add(a); - _syncNameTable(); - checkDots(false); - if (!_oriented) _fixPathAfterInsert(a); - return true; - } - - String? addIsolated(String name) { - var res = addDot(Dot.fromTwoLists(name, [], [])); - _syncNameTable(); - return res; - } - - String? addPath(int from, int to, [int len = 0]) { - if (from <= 0 || from > _amount || to <= 0 && to > _amount) { - return "Index out of range. Have dots 1..$_amount"; - } - _dots[from - 1].addPath(to, len); - if (!_oriented) { - _dots[to - 1].addPath(from, len); - } - return null; - } - //*********************Add************************ - - //*********Delete********* - String? delPath(int from, int to) { - if (from <= 0 || from > _amount || to <= 0 && to > _amount) { - return "Can't find specified path"; - } - _dots[from - 1].delPath(to); - if (!_oriented) { - _dots[to - 1].delPath(from); - } - return null; - } - - String? delDot(int inn) { - if (inn > _amount || inn < 1) { - return "Index out of range. Allowed 1..$_amount"; - } - List toDel = []; - for (int i in _dots[inn - 1].getL().keys) { - toDel.add(i); - } - for (int i in toDel) { - delPath(i, inn); - } - _dots.removeAt(inn - 1); - _syncNum(); - _syncNameTable(); - _fixAfterDel(inn); - return null; - } - - void flushData() { - _dots = []; - _amount = 0; - _nameTable = {}; - } - //*********Delete********* - - //******Helper******* - bool checkDots([bool verbose = false]) { - for (var a in _dots) { - for (var i in a.getL().keys) { - try { - if (!_dots[i - 1].getL().containsKey(a.num)) { - if (verbose) print("Can't find ${a.num}"); - return false; - } - } catch (e) { - if (verbose) { - print("Can't find Dot $i for path ${a.num}->$i. Exception $e"); - } - _dots[a.num - 1].getL().remove(i); - return false; - } - } - } - return true; - } - - void _fixAfterDel(int inn) { - for (int i = 0; i < _dots.length; i++) { - Map l = {}; - for (int j in _dots[i].getL().keys) { - if (j >= inn) { - l[j - 1] = _dots[i].getL()[j]!; - } else { - l[j] = _dots[i].getL()[j]!; - } - } - _dots[i] = Dot.fromMap(_dots[i].getName(), l, _dots[i].num); - } - } - - void _fixPathAfterInsert(Dot a) { - //Для неориентированного - for (var i in a.getL().keys) { - if (!_dots[i - 1].getL().containsKey(a.num)) { - addPath(i, a.num, a.getL()[i]!); - } - } - } - - void _fullFix() { - for (var i in _dots) { - _fixPathAfterInsert(i); - } - } - - void _syncNameTable() { - _nameTable = {}; - for (var i in _dots) { - _nameTable[i.num] = i.getName(); - } - } - - void _syncNum() { - _amount = 0; - for (var i in _dots) { - i.num = ++_amount; - } - _syncNameTable(); - } - //******Helper******* - - //*****Setters******* - void setName(String name) => _name = name; - String? flipUseOrientation() { - if (_amount != 0) { - return "Can change use of orientation only in empty graph"; - } - _oriented = !_oriented; - return null; - } - - String? flipUseLength() { - if (_amount != 0) { - return "Can change use of length only in empty graph"; - } - _useLength = !_useLength; - return null; - } - - String? replaceDataFromFile(String path) { - File file = File(path); - List lines = file.readAsLinesSync(); - if (lines.length < 3) { - return "Not enough lines in file"; - } - String name = lines.removeAt(0); - bool oriented; - switch (lines.removeAt(0)) { - case Separators.isOriented: - oriented = true; - break; - case Separators.isNotOriented: - oriented = false; - break; - default: - return "Error on parsing \"IsOriented\""; - } - bool useLength; - switch (lines.removeAt(0).trim()) { - case Separators.hasLength: - useLength = true; - break; - case Separators.hasNoLength: - useLength = false; - break; - default: - return "Error on parsing \"HasLength\""; - } - List dots = []; - for (var l in lines) { - l = l.trimRight(); - if (l != Separators.end) { - var spl = l.split(Separators.space); - List dot = []; - List len = []; - String name = spl.removeAt(0); - name = name.substring(0, name.length - 1); - for (var splitted in spl) { - if (splitted != "") { - var dt = splitted.split(Separators.dotToLength); - if (dt.length == 2) { - int? parsed = int.tryParse(dt[0]); - if (parsed == null) { - return "Error while parsing file\nin parsing int in \"${dt[0]}\""; - } - dot.add(parsed); - if (useLength) { - parsed = int.tryParse(dt[1]); - if (parsed == null) { - return "Error while parsing file\nin parsing int in \"${dt[1]}\""; - } - len.add(parsed); - } else { - len.add(0); - } - } else if (dt.length == 1) { - int? parsed = int.tryParse(splitted); - if (parsed == null) { - return "Error while parsing file\nin parsing int in \"$splitted\""; - } - dot.add(parsed); - len.add(0); - } - } - } - dots.add(Dot.fromTwoLists(name, dot, len)); - } - } - _name = name; - _oriented = oriented; - _useLength = useLength; - _dots = dots; - _syncNum(); - _syncNameTable(); - if (!_oriented) _fullFix(); - return null; - } - //*****Setters******* - - //*****Getters******* - bool getDoubleSidedBool() => _oriented; - String getDoubleSidedStr() { - if (_oriented) return Separators.isOriented; - return Separators.isNotOriented; - } - - bool getUseLengthBool() => _useLength; - String getUseLengthStr() { - if (_useLength) return Separators.hasLength; - return Separators.hasNoLength; - } - - List getDots() => _dots; - String getName() => _name; - String? getNameByNum(int n) => _nameTable[n]; - Map getNameTable() => _nameTable; - int getDotAmount() => _dots.length; - int? getNumByName(String n) { - for (var i in _nameTable.keys) { - if (_nameTable[i] == n) return i; - } - return null; - } - - List>? getLenTable() { - List>? out = >[]; - for (int i = 0; i < _amount; i++) { - List xx = []; - for (int j = 1; j <= _amount; j++) { - xx.add(_dots[i].getLength(j)); - } - out.add(xx); - } - return out; - } - - List>? getPathTable() { - List>? out = >[]; - for (int i = 0; i < _amount; i++) { - List xx = []; - for (int j = 1; j <= _amount; j++) { - if (_dots[i].getLength(j) != -1) { - xx.add(i); - } else { - xx.add(-1); - } - } - out.add(xx); - } - return out; - } - - /*List getNoRepeatDots() { - List ret = []; - for (int i = 0; i < _amount; i++) { - ret.add(Dot(_dots[i].getName(), _dots[i].num)); - } - for (int i = 0; i < _amount; i++) { - for (int j in _dots[i].getL().keys) { - if (!ret[j - 1].hasConnection(i + 1) && !ret[i].hasConnection(j) || - i == j) { - var len = _dots[i].getLength(j); - ret[i].addPath(j, len); - } - } - } - return ret; - }*/ - //*****Getters******* - - //******Print****** - void printG() { - stdout.write("$_name: "); - if (_oriented) { - stdout.write("Ориентированный, "); - } else { - stdout.write("Не ориентированный, "); - } - if (_useLength) { - print("Взвешенный"); - } else { - print("Не взвешенный"); - } - for (var i in _dots) { - i.printD(); - } - } - - void printToFile(String name) { - var file = File(name); - file.writeAsStringSync("$_name\n"); - if (_oriented) { - file.writeAsStringSync("${Separators.isOriented}\n", - mode: FileMode.append); - } else { - file.writeAsStringSync("${Separators.isNotOriented}\n", - mode: FileMode.append); - } - if (_useLength) { - file.writeAsStringSync("${Separators.hasLength}\n", - mode: FileMode.append); - } else { - file.writeAsStringSync("${Separators.hasNoLength}\n", - mode: FileMode.append); - } - for (int i = 0; i < _amount; i++) { - file.writeAsStringSync((i + 1).toString() + Separators.dotToConnections, - mode: FileMode.append); - var d = _dots[i].getL(); - for (var j in d.keys) { - file.writeAsStringSync( - j.toString() + Separators.dotToLength + d[j].toString() + " ", - mode: FileMode.append); - } - file.writeAsStringSync(Separators.nL, mode: FileMode.append); - } - file.writeAsStringSync(Separators.end, mode: FileMode.append); - } - //******Print****** - - //*******Constructor******** - Graphs( - [String name = "Undefined", - bool hasLen = false, - bool isOriented = false]) { - _name = name; - _dots = []; - _useLength = hasLen; - _oriented = isOriented; - _amount = 0; - _nameTable = {}; - } - Graphs.fromList(String name, List dots, bool hasLen, bool oriented) { - _name = name; - _dots = dots; - _useLength = hasLen; - _amount = _dots.length; - _oriented = oriented; - _syncNum(); - if (!_oriented) _fullFix(); - } - Graphs.fromFile(String path) { - replaceDataFromFile(path); - /*File file = File(path); - List lines = file.readAsLinesSync(); - _name = lines.removeAt(0); - _oriented = lines.removeAt(0) == Separators.isOriented.trim(); - _useLength = lines.removeAt(0) == Separators.hasLength.trim(); - _dots = []; - for (var l in lines) { - if (l != Separators.end) { - var spl = l.split(Separators.space); - List dot = []; - List len = []; - String name = spl.removeAt(0); - name = name.substring(0, name.length - 1); - for (var splitted in spl) { - var dt = splitted.split(Separators.dotToLength); - if (dt.length == 2) { - dot.add(int.parse(dt[0])); - if (_useLength) { - len.add(int.parse(dt[1])); - } else { - len.add(0); - } - } else if (dt.length == 1) { - dot.add(int.parse(splitted)); - len.add(0); - } - } - _dots.add(Dot.fromTwoLists(name, dot, len)); - } - } - _syncNum(); - _syncNameTable(); - if (!_oriented) _fullFix();*/ - } - //*******Constructor******** - - //Copy - Graphs.clone(Graphs a) { - _name = a.getName(); - _dots = a.getDots(); - _oriented = a.getDoubleSidedBool(); - _useLength = a.getUseLengthBool(); - _amount = _dots.length; - _syncNameTable(); - } - - //************Алгоритмы************ - /* bool bfsHasPath(int startDot, int goalDot) { - // обход в ширину - startDot--; - goalDot--; - List visited = []; - List queue = []; - for (int i = 0; i < _amount; i++) { - visited.add(false); - } // изначально список посещённых узлов пуст - queue.add(startDot); // начиная с узла-источника - visited[startDot] = true; - while (queue.isNotEmpty) { - // пока очередь не пуста - int node = queue.removeAt(0); // извлечь первый элемент в очереди - if (node == goalDot) { - return true; // проверить, не является ли текущий узел целевым - } - for (int child in _dots[node].getL().keys) { - // все преемники текущего узла, ... - if (!visited[child - 1]) { - // ... которые ещё не были посещены ... - queue.add(child - 1); // ... добавить в конец очереди... - visited[child - 1] = true; // ... и пометить как посещённые - } - } - } - return false; // Целевой узел недостижим - }*/ - - List? bfsPath(int startDot, int goalDot) { - if (startDot == goalDot) return [startDot]; - //if (!bfsHasPath(startDot, goalDot)) return null; - startDot--; - goalDot--; - List>? graph = getLenTable(); - List used = []; - List dst = []; - List pr = []; - - for (int i = 0; i < _amount; i++) { - dst.add(-1); - used.add(false); - pr.add(0); - } - - List q = []; - q.add(startDot); - used[startDot] = true; - dst[startDot] = 0; - pr[startDot] = - -1; //Пометка, означающая, что у вершины startDot нет предыдущей. - - while (q.isNotEmpty) { - int cur = q.removeAt(0); - int x = 0; - for (int neighbor in graph![cur]) { - if (neighbor != -1) { - if (!used[x]) { - q.add(x); - used[x] = true; - dst[x] = dst[cur] + 1; - pr[x] = cur; //сохранение предыдущей вершины - } - } - x++; - } - } - - //Восстановим кратчайший путь - //Для восстановления пути пройдём его в обратном порядке, и развернём. - List path = []; - - int cur = goalDot; //текущая вершина пути - path.add(cur + 1); - - while (pr[cur] != -1) { - //пока существует предыдущая вершина - cur = pr[cur]; //переходим в неё - path.add(cur + 1); //и дописываем к пути - } - - path = path.reversed.toList(); - - //print("Shortest path between vertices ${startDot+1} and ${goalDot+1} is: $path"); - if (path[0] == (startDot + 1) && - path[1] == (goalDot + 1) && - !_dots[startDot].hasConnection(goalDot + 1)) return null; - return path; - } - - List? dfsIterative(int v) { - v--; - //List? pos = []; - List label = []; - for (int i = 0; i < _amount; i++) { - label.add(false); - } - List stack = []; - stack.add(v); - //pos.add(v); - while (stack.isNotEmpty) { - v = stack.removeLast(); - if (!label[v]) { - label[v] = true; - for (int i in _dots[v].getL().keys) { - stack.add(i - 1); - //pos.add(i); - } - } - } - //print(pos); - return label; - } - - void dijkstra(int source) { - /* - create vertex set Q; - - for each vertex v in Graph{ - dist[v] ← INFINITY ; - prev[v] ← UNDEFINED ; - add v to Q;} - dist[source] ← 0; - - while Q is not empty{ - u ← vertex in Q with min dist[u] - - remove u from Q - - for each neighbor v of u still in Q{ - alt ← dist[u] + length(u, v); - if alt < dist[v]: { - dist[v] ← alt; - prev[v] ← u;} - }} - return dist[], prev[]*/ - } - //************Алгоритмы************ -} From 3950fabb86e67895604424d740a74baf17f3ac58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:26:10 +0000 Subject: [PATCH 05/15] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D0=B8=D0=BB(=D0=B0)=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2?= =?UTF-8?q?=20'flutter/lib'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/curve_painter.dart | 329 +++++++++++++++++++++++++++++++++ 1 file changed, 329 insertions(+) create mode 100644 flutter/lib/curve_painter.dart diff --git a/flutter/lib/curve_painter.dart b/flutter/lib/curve_painter.dart new file mode 100644 index 0000000..4363d0b --- /dev/null +++ b/flutter/lib/curve_painter.dart @@ -0,0 +1,329 @@ +import 'package:arrow_path/arrow_path.dart'; +import 'package:graphs/src/graph.dart'; +import 'package:flutter/material.dart'; +import 'dart:math'; + +class CurvePainter extends CustomPainter { + CurvePainter({ + Key? key, + required this.graphData, + required this.bfsPath, + required this.start, + required this.end, + required this.dfsAccessTable, + }); + + List? bfsPath; + List? dfsAccessTable; + int? start; + int? end; + Graphs graphData; + final double _dotRad = 6; + final double _lineWidth = 1.5; + final Color _lineColor = Colors.black; + final double _aboveHeight = 5; + double _circleRad = 100; + final TextStyle _textStyle = TextStyle( + color: Colors.red.shade900, + decorationColor: Colors.green.shade900, + decorationThickness: 10, + decorationStyle: TextDecorationStyle.dashed, + fontSize: 20, + ); + Map _off = {}; + void _drawLine(Canvas canvas, Offset p1, Offset p2) { + Paint p = Paint(); + p.color = _lineColor; + p.strokeWidth = _lineWidth; + canvas.drawLine(p1, p2, p); + } + + void _drawDot(Canvas canvas, Offset p1, [double plusRad = 0, Color? col]) { + col ??= Colors.yellow.shade900; + var p = Paint(); + p.color = col; + p.strokeWidth = _lineWidth + 2; + canvas.drawCircle(p1, _dotRad + plusRad, p); + } + + void _drawSelfConnect(Canvas canvas, Offset p1) { + var p = Paint(); + p.color = _lineColor; + p.strokeWidth = _lineWidth; + p.style = PaintingStyle.stroke; + canvas.drawCircle(Offset(p1.dx + _dotRad + 20, p1.dy), _dotRad + 20, p); + } + + TextSpan _getTextSpan(String s) => TextSpan(text: s, style: _textStyle); + TextPainter _getTextPainter(String s) => TextPainter( + text: _getTextSpan(s), + textDirection: TextDirection.ltr, + textAlign: TextAlign.center); + + void _drawDotNames(Canvas canvas, Offset place, String s) { + var textPainter = _getTextPainter(s); + textPainter.layout(); + textPainter.paint( + canvas, + Offset((place.dx - textPainter.width), + (place.dy - textPainter.height) - _aboveHeight)); + } + + void _drawDotNum(Canvas canvas, Offset size, String s) { + var textPainter = TextPainter( + text: TextSpan( + text: s, + style: const TextStyle( + color: Colors.black, + fontSize: 17, + )), + textDirection: TextDirection.ltr, + textAlign: TextAlign.center); + textPainter.layout(); + textPainter.paint( + canvas, + Offset((size.dx - textPainter.width) + 25, + (size.dy - textPainter.height) + _aboveHeight + 30)); + } + + int _getHighInputConnections() { + if (graphData.getDots().length != 1 && graphData.getDots().length <= 3) { + return -1; + } + int higest = -1; + for (var i in graphData.getDots()) { + if (i.getL().length > higest) higest = i.num; + } + return higest; + } + + Map _getDotPos(int dotsAm, Size size) { + Map off = {}; + var width = size.width / 2; + var height = size.height / 2; + int add = 0; + int h = _getHighInputConnections(); + for (int i = 0; i < dotsAm; i++) { + if ((i + 1) != h) { + double x = + cos(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + width; + double y = + sin(2 * pi * (i - add) / (dotsAm - add)) * _circleRad + height; + + off[i + 1] = Offset(x, y); + } else if ((i + 1) == h) { + off[i + 1] = Offset(width + 2, height - 2); + add = 1; + h = 0; + } else { + print("GetDotPos error"); + } + //print(off.length); + } + + //print(off); + return off; + } + + void _drawHArrow(Canvas canvas, Size size, Offset from, Offset to, + [bool doubleSided = false]) { + Path path; + + // The arrows usually looks better with rounded caps. + Paint paint = Paint() + ..color = Colors.black + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = _lineWidth; + + var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + + (to.dy - from.dy) * (to.dy - from.dy)); + + /// Draw a single arrow. + path = Path(); + path.moveTo(from.dx, from.dy); + path.relativeCubicTo( + 0, + 0, + -(from.dx + to.dx + length) / (length) - 40, + -(from.dy + to.dy + length) / (length) - 40, + to.dx - from.dx, + to.dy - from.dy); + path = + ArrowPath.make(path: path, isDoubleSided: doubleSided, tipLength: 16); + canvas.drawPath(path, paint); + } + + void _drawHighArrow(Canvas canvas, Size size, Offset from, Offset to, + [bool doubleSided = false]) { + Path path; + + // The arrows usually looks better with rounded caps. + Paint paint = Paint() + ..color = Colors.black + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = _lineWidth; + + var length = sqrt((to.dx - from.dx) * (to.dx - from.dx) + + (to.dy - from.dy) * (to.dy - from.dy)); + + /// Draw a single arrow. + path = Path(); + path.moveTo(from.dx, from.dy); + path.relativeCubicTo( + 0, + 0, + (from.dx + to.dx) / (length * 2) + 40, + (from.dy + to.dy) / (length * 2) + 40, + to.dx - from.dx, + to.dy - from.dy); + path = ArrowPath.make( + path: path, + isDoubleSided: doubleSided, + tipLength: 13, + isAdjusted: false); + canvas.drawPath(path, paint); + } + + void _drawConnections( + Canvas canvas, Size size, List dots, Map off) { + for (var i in dots) { + var list = i.getL(); + var beg = off[i.num]; + for (var d in list.keys) { + if (d == i.num) { + _drawSelfConnect(canvas, off[d]!); + } else { + if (graphData.getDoubleSidedBool()) { + if (d > i.num) { + _drawHArrow(canvas, size, beg!, off[d]!, false); + if (graphData.getUseLengthBool()) { + _drawDotNames( + canvas, + Offset((off[d]!.dx + beg.dx) / 2 - 18, + (off[d]!.dy + beg.dy) / 2 - 18), + i.getL()[d].toString()); + } + } else { + _drawHighArrow(canvas, size, beg!, off[d]!, false); + if (graphData.getUseLengthBool()) { + _drawDotNames( + canvas, + Offset((off[d]!.dx + beg.dx) / 2 + 30, + (off[d]!.dy + beg.dy) / 2 + 30), + i.getL()[d].toString()); + } + } + } else { + _drawLine(canvas, beg!, off[d]!); + if (graphData.getUseLengthBool()) { + _drawDotNames( + canvas, + Offset((off[d]!.dx + beg.dx) / 2, (off[d]!.dy + beg.dy) / 2), + i.getL()[d].toString()); + } + } + } + } + } + } + + void _drawBFS(Canvas canvas) { + if (bfsPath != null) { + for (int i = 0; i < bfsPath!.length; i++) { + _drawDot(canvas, _off[bfsPath![i]]!, 8, Colors.yellow); + } + _drawDot(canvas, _off[start]!, 9, Colors.green); + _drawDot(canvas, _off[end]!, 7, Colors.red.shade200); + for (int i = 0; i < bfsPath!.length; i++) { + _drawDotNum(canvas, _off[bfsPath![i]]!, "bfs: №${i + 1}"); + } + } + } + + void _drawDFS(Canvas canvas) { + if (dfsAccessTable != null) { + for (int i = 0; i < dfsAccessTable!.length; i++) { + if (dfsAccessTable![i]) { + _drawDot(canvas, _off[i + 1]!, 8, Colors.green.shade500); + _drawDotNum(canvas, _off[i + 1]!, "dfs: visible"); + } else { + _drawDot(canvas, _off[i + 1]!, 7, Colors.red.shade500); + _drawDotNum(canvas, _off[i + 1]!, "dfs: not visible"); + } + } + _drawDot(canvas, _off[start]!, 9, Colors.green.shade900); + } + } + + @override + void paint(Canvas canvas, Size size) { + if (size.width > size.height) { + _circleRad = size.height / 3; + } else { + _circleRad = size.width / 3; + } + + _off = _getDotPos(graphData.getDotAmount(), size); //, higest); + for (int i in _off.keys) { + _drawDot(canvas, _off[i]!); + //drawDotNames(canvas, off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); + } + + var g = graphData.getDots(); + _drawBFS(canvas); + _drawDFS(canvas); + _drawConnections(canvas, size, g, _off); + //pringArr(canvas, size); + //drawArrow(canvas, Offset(size.width / 2, size.height / 2), + // Offset(size.width / 2 + 50, size.height / 2 + 200)); + //} + + for (int i in _off.keys) { + //drawDot(canvas, off[i]!); + _drawDotNames( + canvas, _off[i]!, "${graphData.getDots()[i - 1].getName()}:[$i]"); + } + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) { + return true; + } +} + +/*void _pringArr(Canvas canvas, Size size) { + TextSpan textSpan; + TextPainter textPainter; + Path path; + + // The arrows usually looks better with rounded caps. + Paint paint = Paint() + ..color = Colors.black + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round + ..strokeJoin = StrokeJoin.round + ..strokeWidth = 3.0; + + /// Draw a single arrow. + path = Path(); + path.moveTo(size.width * 0.25, size.height * 0.10); + path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0); + path = ArrowPath.make(path: path); + canvas.drawPath(path, paint..color = Colors.blue); + + textSpan = const TextSpan( + text: 'Single arrow', + style: TextStyle(color: Colors.blue), + ); + textPainter = TextPainter( + text: textSpan, + textAlign: TextAlign.center, + textDirection: TextDirection.ltr, + ); + textPainter.layout(minWidth: size.width); + textPainter.paint(canvas, Offset(0, size.height * 0.06)); +}*/ From 276e7d36ed991e5103082793f12c6bbf2e7b2924 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:26:25 +0000 Subject: [PATCH 06/15] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D0=B8=D0=BB(=D0=B0)=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2?= =?UTF-8?q?=20'flutter/lib/pages'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/pages/drawing_page.dart | 205 ++++++++++++++++++++-------- 1 file changed, 148 insertions(+), 57 deletions(-) diff --git a/flutter/lib/pages/drawing_page.dart b/flutter/lib/pages/drawing_page.dart index c98e583..426256d 100644 --- a/flutter/lib/pages/drawing_page.dart +++ b/flutter/lib/pages/drawing_page.dart @@ -26,7 +26,10 @@ class _DrawingPageState extends State { Graphs graphData = getGraph(); List? bfsPath; List? dfsAccessTable; - int? dfsStartDot; + int? startDot; + int? endDot; + String? dropdownValue1; + String? dropdownValue2; final _textNameController = TextEditingController(); final _textNumbController = TextEditingController(); @@ -34,11 +37,19 @@ class _DrawingPageState extends State { final _textLnthController = TextEditingController(); final _textGrNmController = TextEditingController(); - void clearTextControllers() { - _textDestController.clear(); - _textNumbController.clear(); - _textLnthController.clear(); - _textNameController.clear(); + void clearInputData() { + setState(() { + _textDestController.clear(); + _textNumbController.clear(); + _textLnthController.clear(); + _textNameController.clear(); + dropdownValue1 = null; + dropdownValue2 = null; + /*startDot = null; + bfsPath = null; + dfsAccessTable = null; + endDot = null;*/ + }); } @override @@ -72,17 +83,19 @@ class _DrawingPageState extends State { ]), addSpaceH(3), Row(children: [ - addSpaceW(5), + addSpaceW(6), createInputBox( "Name", screenSize / 8 - 25, null, _textGrNmController), //addSpaceW(screenSize / 8 - 4), createButton("\nDel dot \n", delDotPushed), - createInputBox("Dot number", screenSize / 4 - 25, - Icons.fiber_manual_record, _textNumbController), - addSpaceW(13), + //createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController), + addSpaceW(54), + dropList1(screenSize / 4 - 80), + addSpaceW(54), createButton("\nDel path\n", delPathPushed), - createInputBox("Destination number", screenSize / 4 - 25, - Icons.fiber_manual_record, _textDestController), + addSpaceW(54), + dropList2(screenSize / 4 - 80), + //createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController), ]), ]), ), @@ -97,8 +110,9 @@ class _DrawingPageState extends State { painter: CurvePainter( graphData: graphData, bfsPath: bfsPath, - dfsStart: dfsStartDot, - dfsAccessTable: dfsAccessTable), + dfsAccessTable: dfsAccessTable, + start: startDot, + end: endDot), child: Align( alignment: Alignment.topRight, child: ButtonBar( @@ -106,7 +120,14 @@ class _DrawingPageState extends State { children: [ createButton("Bfs", bfsPushed), createButton("Dfs", dfsPushed), - createButton("Clear dfs or bfs", () => bfsPath = null), + createButton("Clear dfs or bfs", () { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + }); + }), createButton(graphData.getUseLengthStr(), changeLength), createButton(graphData.getDoubleSidedStr(), changeOriented), /*Text(_textGrNmController.text, @@ -238,26 +259,24 @@ class _DrawingPageState extends State { showPopUp("Error", res); } } - clearTextControllers(); + clearInputData(); }); } void addPathPushed() { setState(() { - if (_textNumbController.text == "") { - showPopUp("Error", "No number in \"Dot number\" box"); - } else if (_textDestController.text == "") { - showPopUp("Error", "No number in \"Destination number\" box"); + if (dropdownValue1 == null) { + showPopUp("Error", "Select output dot"); + } else if (dropdownValue2 == null) { + showPopUp("Error", "select input dot"); } else if (_textLnthController.text == "" && graphData.getUseLengthBool()) { showPopUp("Error", "No length in \"Input length\" box"); } else { - int? from = int.tryParse(_textNumbController.text); - int? to = int.tryParse(_textDestController.text); + int? from = int.parse(dropdownValue1!); + int? to = int.parse(dropdownValue2!); int? len = int.tryParse(_textLnthController.text); - if (from == null || - to == null || - (len == null && graphData.getUseLengthBool())) { + if (len == null && graphData.getUseLengthBool()) { showPopUp("Error", "Can't parse input.\nInts only allowed in \"Dot number\", \"Destination number\" and \"Input length\""); } else { @@ -268,7 +287,7 @@ class _DrawingPageState extends State { } } } - clearTextControllers(); + clearInputData(); }); } @@ -305,13 +324,13 @@ class _DrawingPageState extends State { } } } - clearTextControllers(); + clearInputData(); }); } void delDotPushed() { setState(() { - if (_textNumbController.text == "") { + /*if (_textNumbController.text == "") { showPopUp("Error", "No number in \"Dot number\" box"); } else { int? dot = int.tryParse(_textNumbController.text); @@ -323,8 +342,13 @@ class _DrawingPageState extends State { showPopUp("Error", res); } } + }*/ + if (dropdownValue1 != null) { + graphData.delDot(int.parse(dropdownValue1!)); + } else { + showPopUp("Error", "Nothing in input"); } - clearTextControllers(); + clearInputData(); }); } @@ -366,51 +390,118 @@ class _DrawingPageState extends State { void bfsPushed() { setState(() { - dfsAccessTable = null; bfsPath = null; - if (_textNumbController.text == "") { + dfsAccessTable = null; + startDot = null; + endDot = null; + if (dropdownValue1 == null) { showPopUp("Error", "No number in \"Dot number\" box"); - } else if (_textDestController.text == "") { + } else if (dropdownValue2 == null) { showPopUp("Error", "No number in \"Destination number\" box"); } else { - int? from = int.tryParse(_textNumbController.text); - int? to = int.tryParse(_textDestController.text); - if (from == null || to == null) { - showPopUp("Error", - "Can't parse input.\nInts only allowed in \"Dot number\" and \"Destination number\""); - } else { - bfsPath = graphData.bfsPath(from, to); - if (bfsPath == null) { - showPopUp("Info", "There is no path"); - } - print(bfsPath); + startDot = int.parse(dropdownValue1!); + endDot = int.parse(dropdownValue2!); + + bfsPath = graphData.bfsPath(startDot!, endDot!); + if (bfsPath == null) { + showPopUp("Info", "There is no path"); } + print(bfsPath); } - clearTextControllers(); }); + clearInputData(); } void dfsPushed() { setState(() { bfsPath = null; - bfsPath = null; - if (_textNumbController.text == "") { + dfsAccessTable = null; + startDot = null; + endDot = null; + if (dropdownValue1 == null) { showPopUp("Error", "No number in \"Dot number\" box"); } else { - int? from = int.tryParse(_textNumbController.text); - if (from == null) { - showPopUp("Error", - "Can't parse input.\nInts only allowed in \"Dot number\"."); - } else { - dfsAccessTable = graphData.dfsIterative(from); - if (dfsAccessTable == null) { - showPopUp("Err", "report this error."); - } - print(dfsAccessTable); + startDot = int.parse(dropdownValue1!); + dfsAccessTable = graphData.dfsIterative(startDot!); + if (dfsAccessTable == null) { + showPopUp("Err", "report this error."); } + print(dfsAccessTable); } - clearTextControllers(); + clearInputData(); }); } //*********ButtonsFunctions********* + + SizedBox dropList1(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), // Not necessary for Option 1 + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue1, + + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + //background: Paint()..color = Colors.white, + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue1 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); + } + + SizedBox dropList2(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), // Not necessary for Option 1 + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue2, + + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + //background: Paint()..color = Colors.white, + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue2 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); + } } From 41de1ba314a850feebb680feff1aa6342eb199d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:26:41 +0000 Subject: [PATCH 07/15] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D0=B8=D0=BB(=D0=B0)=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2?= =?UTF-8?q?=20'flutter/lib/src'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/src/graph.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/flutter/lib/src/graph.dart b/flutter/lib/src/graph.dart index 2d90efd..cd8707b 100644 --- a/flutter/lib/src/graph.dart +++ b/flutter/lib/src/graph.dart @@ -363,6 +363,7 @@ class Graphs { List getDots() => _dots; String getName() => _name; String? getNameByNum(int n) => _nameTable[n]; + Map getNameTable() => _nameTable; int getDotAmount() => _dots.length; int? getNumByName(String n) { for (var i in _nameTable.keys) { @@ -567,6 +568,7 @@ class Graphs { }*/ List? bfsPath(int startDot, int goalDot) { + if (startDot == goalDot) return [startDot]; //if (!bfsHasPath(startDot, goalDot)) return null; startDot--; goalDot--; @@ -606,7 +608,6 @@ class Graphs { //Восстановим кратчайший путь //Для восстановления пути пройдём его в обратном порядке, и развернём. - List path = []; int cur = goalDot; //текущая вершина пути From f20cb1fef05976c09f18cbd53cb2b5f4acdd09c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 11:37:25 +0000 Subject: [PATCH 08/15] fix null check --- flutter/lib/pages/drawing_page.dart | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/flutter/lib/pages/drawing_page.dart b/flutter/lib/pages/drawing_page.dart index 426256d..7b87a0b 100644 --- a/flutter/lib/pages/drawing_page.dart +++ b/flutter/lib/pages/drawing_page.dart @@ -101,7 +101,15 @@ class _DrawingPageState extends State { ), actions: [ IconButton( - onPressed: () => graphData.flushData(), + onPressed: () { + setState(() { + startDot = null; + endDot = null; + bfsPath = null; + dfsAccessTable = null; + graphData.flushData(); + }); + }, icon: const Icon(Icons.delete_sweep), iconSize: 60, ), @@ -126,6 +134,7 @@ class _DrawingPageState extends State { dfsAccessTable = null; startDot = null; endDot = null; + clearInputData(); }); }), createButton(graphData.getUseLengthStr(), changeLength), From 77c2f02a962910ef638b4cafdb8a33670eb69e75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 12:03:49 +0000 Subject: [PATCH 09/15] src from flutter --- cmd/bin/graphs0.dart | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/cmd/bin/graphs0.dart b/cmd/bin/graphs0.dart index 01f1114..f00af38 100644 --- a/cmd/bin/graphs0.dart +++ b/cmd/bin/graphs0.dart @@ -51,7 +51,6 @@ void main(List arguments) { List graphs = []; String name; String str = ""; - Separators sep = Separators(); while (deistvie != 0) { stdout.write( "1 - создать граф, 2 - удалить граф, 3 - добавить в граф вершину,\n4 - удалить вершину, 5 - добавить ребро/дугу, 6 - удалить ребро/дугу,\n7 - вывести граф на экран, 8 - вывести граф в файл, 0 - выход\nDeistvie: "); @@ -112,9 +111,9 @@ void main(List arguments) { List inn = []; List len = []; - List a = str.split(sep.space); + List a = str.split(Separators.space); for (var splitted in a) { - var dt = splitted.split(sep.dotToLength); + var dt = splitted.split(Separators.dotToLength); if (dt.length == 2) { inn.add(int.parse(dt[0])); len.add(int.parse(dt[1])); @@ -161,9 +160,9 @@ void main(List arguments) { "Ввод: *куда*|*вес* через пробел. Если граф не взвешенный, то *вес* можно не указывать.\nВершина cмежна с: "); str = getStrLine(); - List a = str.split(sep.space); + List a = str.split(Separators.space); for (var splitted in a) { - var dt = splitted.split(sep.dotToLength); + var dt = splitted.split(Separators.dotToLength); if (dt.length == 2) { inn.add(int.parse(dt[0])); len.add(int.parse(dt[1])); @@ -244,7 +243,7 @@ void main(List arguments) { num = graphs[y].getDotAmount(); stdout.write( "Количество вершин: $num. Введите через пробел 2 вершины, между которыми удалить ребро: "); - List x = getStrLine().split(sep.space); + List x = getStrLine().split(Separators.space); x1 = int.parse(x[0]); x2 = int.parse(x[1]); if (x1 >= 0 && x1 < num && x2 >= 0 && x2 < num) { From 4b3542edadfc88713bc18d75f8d08cd355583a50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 12:04:06 +0000 Subject: [PATCH 10/15] src from flutter --- cmd/bin/src/graph.dart | 245 ++++++++++++++++++++++++++++++++--------- 1 file changed, 193 insertions(+), 52 deletions(-) diff --git a/cmd/bin/src/graph.dart b/cmd/bin/src/graph.dart index 74df1c3..cd8707b 100644 --- a/cmd/bin/src/graph.dart +++ b/cmd/bin/src/graph.dart @@ -1,15 +1,15 @@ import 'dart:io'; class Separators { - final String dotToConnections = ": "; - final String dotToLength = "|"; - final String space = " "; - final String hasLength = "Взвешенный\n"; - final String hasNoLength = "НеВзвешенный\n"; - final String isOriented = "Ориентированный\n"; - final String isNotOriented = "НеОриентированный\n"; - final String nL = "\n"; - final String end = "END"; + static const String dotToConnections = ": "; + static const String dotToLength = "|"; + static const String space = " "; + static const String hasLength = "Взвешенный"; + static const String hasNoLength = "НеВзвешенный"; + static const String isOriented = "Ориентированный"; + static const String isNotOriented = "НеОриентированный"; + static const String nL = "\n"; + static const String end = "END"; Separators(); } @@ -25,6 +25,7 @@ class Dot { String getName() => _name; bool hasConnection(int n) => _ln.containsKey(n); Map getL() => _ln; + int getLength(int x) { if (hasConnection(x)) { return _ln[x]!; @@ -53,9 +54,9 @@ class Dot { } //******Constructor****** - Dot() { - _name = "Undefined"; - num = -1; + Dot([String name = "Undefined", int n = -1]) { + _name = name; + num = n; _ln = {}; } Dot.fromTwoLists(String name, List num0, List length, @@ -97,11 +98,9 @@ class Graphs { bool _oriented = false; //Ориентированность //*********************Add************************ - bool addDot(Dot a) { + String? addDot(Dot a) { if (getNumByName(a.getName()) != null) { - print( - "Dot name ${a.getName()} already in use. Change name or use addPath"); - return false; + return ("Dot name \"${a.getName()}\" already in use. Change name or use addPath"); } _amount++; a.num = _amount; @@ -109,7 +108,7 @@ class Graphs { _syncNameTable(); checkDots(false); if (!_oriented) _fullFix(); - return true; + return null; } bool addDotFromToLists(String name, List num0, List length, @@ -129,37 +128,40 @@ class Graphs { return true; } - bool addIsolated(String name) { - var o = addDot(Dot.fromTwoLists(name, [], [])); + String? addIsolated(String name) { + var res = addDot(Dot.fromTwoLists(name, [], [])); _syncNameTable(); - return o; + return res; } - bool addPath(int from, int to, [int len = 0]) { + String? addPath(int from, int to, [int len = 0]) { if (from <= 0 || from > _amount || to <= 0 && to > _amount) { - return false; + return "Index out of range. Have dots 1..$_amount"; } _dots[from - 1].addPath(to, len); if (!_oriented) { _dots[to - 1].addPath(from, len); } - return true; + return null; } //*********************Add************************ //*********Delete********* - bool delPath(int from, int to) { + String? delPath(int from, int to) { if (from <= 0 || from > _amount || to <= 0 && to > _amount) { - return false; + return "Can't find specified path"; } _dots[from - 1].delPath(to); if (!_oriented) { _dots[to - 1].delPath(from); } - return true; + return null; } - bool delDot(int inn) { + String? delDot(int inn) { + if (inn > _amount || inn < 1) { + return "Index out of range. Allowed 1..$_amount"; + } List toDel = []; for (int i in _dots[inn - 1].getL().keys) { toDel.add(i); @@ -171,7 +173,13 @@ class Graphs { _syncNum(); _syncNameTable(); _fixAfterDel(inn); - return true; + return null; + } + + void flushData() { + _dots = []; + _amount = 0; + _nameTable = {}; } //*********Delete********* @@ -241,12 +249,121 @@ class Graphs { } //******Helper******* + //*****Setters******* + void setName(String name) => _name = name; + String? flipUseOrientation() { + if (_amount != 0) { + return "Can change use of orientation only in empty graph"; + } + _oriented = !_oriented; + return null; + } + + String? flipUseLength() { + if (_amount != 0) { + return "Can change use of length only in empty graph"; + } + _useLength = !_useLength; + return null; + } + + String? replaceDataFromFile(String path) { + File file = File(path); + List lines = file.readAsLinesSync(); + if (lines.length < 3) { + return "Not enough lines in file"; + } + String name = lines.removeAt(0); + bool oriented; + switch (lines.removeAt(0)) { + case Separators.isOriented: + oriented = true; + break; + case Separators.isNotOriented: + oriented = false; + break; + default: + return "Error on parsing \"IsOriented\""; + } + bool useLength; + switch (lines.removeAt(0).trim()) { + case Separators.hasLength: + useLength = true; + break; + case Separators.hasNoLength: + useLength = false; + break; + default: + return "Error on parsing \"HasLength\""; + } + List dots = []; + for (var l in lines) { + l = l.trimRight(); + if (l != Separators.end) { + var spl = l.split(Separators.space); + List dot = []; + List len = []; + String name = spl.removeAt(0); + name = name.substring(0, name.length - 1); + for (var splitted in spl) { + if (splitted != "") { + var dt = splitted.split(Separators.dotToLength); + if (dt.length == 2) { + int? parsed = int.tryParse(dt[0]); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"${dt[0]}\""; + } + dot.add(parsed); + if (useLength) { + parsed = int.tryParse(dt[1]); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"${dt[1]}\""; + } + len.add(parsed); + } else { + len.add(0); + } + } else if (dt.length == 1) { + int? parsed = int.tryParse(splitted); + if (parsed == null) { + return "Error while parsing file\nin parsing int in \"$splitted\""; + } + dot.add(parsed); + len.add(0); + } + } + } + dots.add(Dot.fromTwoLists(name, dot, len)); + } + } + _name = name; + _oriented = oriented; + _useLength = useLength; + _dots = dots; + _syncNum(); + _syncNameTable(); + if (!_oriented) _fullFix(); + return null; + } + //*****Setters******* + //*****Getters******* - bool getDoubleSided() => _oriented; - bool getUseLength() => _useLength; + bool getDoubleSidedBool() => _oriented; + String getDoubleSidedStr() { + if (_oriented) return Separators.isOriented; + return Separators.isNotOriented; + } + + bool getUseLengthBool() => _useLength; + String getUseLengthStr() { + if (_useLength) return Separators.hasLength; + return Separators.hasNoLength; + } + List getDots() => _dots; String getName() => _name; String? getNameByNum(int n) => _nameTable[n]; + Map getNameTable() => _nameTable; int getDotAmount() => _dots.length; int? getNumByName(String n) { for (var i in _nameTable.keys) { @@ -282,6 +399,23 @@ class Graphs { } return out; } + + /*List getNoRepeatDots() { + List ret = []; + for (int i = 0; i < _amount; i++) { + ret.add(Dot(_dots[i].getName(), _dots[i].num)); + } + for (int i = 0; i < _amount; i++) { + for (int j in _dots[i].getL().keys) { + if (!ret[j - 1].hasConnection(i + 1) && !ret[i].hasConnection(j) || + i == j) { + var len = _dots[i].getLength(j); + ret[i].addPath(j, len); + } + } + } + return ret; + }*/ //*****Getters******* //******Print****** @@ -303,31 +437,34 @@ class Graphs { } void printToFile(String name) { - Separators sep = Separators(); var file = File(name); file.writeAsStringSync("$_name\n"); if (_oriented) { - file.writeAsStringSync(sep.isOriented, mode: FileMode.append); + file.writeAsStringSync("${Separators.isOriented}\n", + mode: FileMode.append); } else { - file.writeAsStringSync(sep.isNotOriented, mode: FileMode.append); + file.writeAsStringSync("${Separators.isNotOriented}\n", + mode: FileMode.append); } if (_useLength) { - file.writeAsStringSync(sep.hasLength, mode: FileMode.append); + file.writeAsStringSync("${Separators.hasLength}\n", + mode: FileMode.append); } else { - file.writeAsStringSync(sep.hasNoLength, mode: FileMode.append); + file.writeAsStringSync("${Separators.hasNoLength}\n", + mode: FileMode.append); } for (int i = 0; i < _amount; i++) { - file.writeAsStringSync((i + 1).toString() + sep.dotToConnections, + file.writeAsStringSync((i + 1).toString() + Separators.dotToConnections, mode: FileMode.append); var d = _dots[i].getL(); for (var j in d.keys) { file.writeAsStringSync( - j.toString() + sep.dotToLength + d[j].toString() + " ", + j.toString() + Separators.dotToLength + d[j].toString() + " ", mode: FileMode.append); } - file.writeAsStringSync(sep.nL, mode: FileMode.append); + file.writeAsStringSync(Separators.nL, mode: FileMode.append); } - file.writeAsStringSync(sep.end, mode: FileMode.append); + file.writeAsStringSync(Separators.end, mode: FileMode.append); } //******Print****** @@ -353,22 +490,22 @@ class Graphs { if (!_oriented) _fullFix(); } Graphs.fromFile(String path) { - Separators sep = Separators(); - File file = File(path); + replaceDataFromFile(path); + /*File file = File(path); List lines = file.readAsLinesSync(); _name = lines.removeAt(0); - _oriented = lines.removeAt(0) == sep.isOriented.trim(); - _useLength = lines.removeAt(0) == sep.hasLength.trim(); + _oriented = lines.removeAt(0) == Separators.isOriented.trim(); + _useLength = lines.removeAt(0) == Separators.hasLength.trim(); _dots = []; for (var l in lines) { - if (l != sep.end) { - var spl = l.split(sep.space); + if (l != Separators.end) { + var spl = l.split(Separators.space); List dot = []; List len = []; String name = spl.removeAt(0); name = name.substring(0, name.length - 1); for (var splitted in spl) { - var dt = splitted.split(sep.dotToLength); + var dt = splitted.split(Separators.dotToLength); if (dt.length == 2) { dot.add(int.parse(dt[0])); if (_useLength) { @@ -386,7 +523,7 @@ class Graphs { } _syncNum(); _syncNameTable(); - if (!_oriented) _fullFix(); + if (!_oriented) _fullFix();*/ } //*******Constructor******** @@ -394,14 +531,14 @@ class Graphs { Graphs.clone(Graphs a) { _name = a.getName(); _dots = a.getDots(); - _oriented = a.getDoubleSided(); - _useLength = a.getUseLength(); + _oriented = a.getDoubleSidedBool(); + _useLength = a.getUseLengthBool(); _amount = _dots.length; _syncNameTable(); } //************Алгоритмы************ - bool bfsHasPath(int startDot, int goalDot) { + /* bool bfsHasPath(int startDot, int goalDot) { // обход в ширину startDot--; goalDot--; @@ -428,9 +565,10 @@ class Graphs { } } return false; // Целевой узел недостижим - } + }*/ List? bfsPath(int startDot, int goalDot) { + if (startDot == goalDot) return [startDot]; //if (!bfsHasPath(startDot, goalDot)) return null; startDot--; goalDot--; @@ -470,7 +608,6 @@ class Graphs { //Восстановим кратчайший путь //Для восстановления пути пройдём его в обратном порядке, и развернём. - List path = []; int cur = goalDot; //текущая вершина пути @@ -493,21 +630,25 @@ class Graphs { List? dfsIterative(int v) { v--; + //List? pos = []; List label = []; for (int i = 0; i < _amount; i++) { label.add(false); } List stack = []; stack.add(v); + //pos.add(v); while (stack.isNotEmpty) { v = stack.removeLast(); if (!label[v]) { label[v] = true; for (int i in _dots[v].getL().keys) { stack.add(i - 1); + //pos.add(i); } } } + //print(pos); return label; } From 442288141db82938274bb6dfa8272474d1612f1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 12:05:16 +0000 Subject: [PATCH 11/15] function reordering --- flutter/lib/pages/drawing_page.dart | 441 +++++++++++++--------------- 1 file changed, 212 insertions(+), 229 deletions(-) diff --git a/flutter/lib/pages/drawing_page.dart b/flutter/lib/pages/drawing_page.dart index 7b87a0b..d87907d 100644 --- a/flutter/lib/pages/drawing_page.dart +++ b/flutter/lib/pages/drawing_page.dart @@ -52,130 +52,8 @@ class _DrawingPageState extends State { }); } - @override - Widget build(BuildContext context) { - screenSize = MediaQuery.of(context).size.width; - _textGrNmController.text = graphData.getName(); - return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Align( - alignment: Alignment.topLeft, - child: Text("Graph name:\n", - style: TextStyle( - fontSize: 18, - color: Colors.white, - ))), - toolbarHeight: 110, - flexibleSpace: Container( - color: Colors.green.shade900, - child: Column(children: [ - const SizedBox(height: 5), - Row(children: [ - addSpaceW(screenSize / 8 + 19), - createButton("\nAdd dot\n", addDotPushed), - createInputBox("Dot name", screenSize / 4 - 25, Icons.label, - _textNameController), - addSpaceW(8), - createButton("\nAdd path\n", addPathPushed), - createInputBox("Input length", screenSize / 4 - 25, - Icons.arrow_right_alt_outlined, _textLnthController), - ]), - addSpaceH(3), - Row(children: [ - addSpaceW(6), - createInputBox( - "Name", screenSize / 8 - 25, null, _textGrNmController), - //addSpaceW(screenSize / 8 - 4), - createButton("\nDel dot \n", delDotPushed), - //createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController), - addSpaceW(54), - dropList1(screenSize / 4 - 80), - addSpaceW(54), - createButton("\nDel path\n", delPathPushed), - addSpaceW(54), - dropList2(screenSize / 4 - 80), - //createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController), - ]), - ]), - ), - actions: [ - IconButton( - onPressed: () { - setState(() { - startDot = null; - endDot = null; - bfsPath = null; - dfsAccessTable = null; - graphData.flushData(); - }); - }, - icon: const Icon(Icons.delete_sweep), - iconSize: 60, - ), - ]), - body: CustomPaint( - painter: CurvePainter( - graphData: graphData, - bfsPath: bfsPath, - dfsAccessTable: dfsAccessTable, - start: startDot, - end: endDot), - child: Align( - alignment: Alignment.topRight, - child: ButtonBar( - mainAxisSize: MainAxisSize.min, - children: [ - createButton("Bfs", bfsPushed), - createButton("Dfs", dfsPushed), - createButton("Clear dfs or bfs", () { - setState(() { - bfsPath = null; - dfsAccessTable = null; - startDot = null; - endDot = null; - clearInputData(); - }); - }), - createButton(graphData.getUseLengthStr(), changeLength), - createButton(graphData.getDoubleSidedStr(), changeOriented), - /*Text(_textGrNmController.text, - style: - TextStyle(fontSize: 15, color: Colors.blueGrey.shade900)),*/ - createButton("Save to file", fileSaver), - createButton("Load from file", fileOpener), - createButton("Help", () { - String out = - " В поле \"Graph name\" можно сменить имя графу.\n"; - out += - " Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n"; - out += - " Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n"; - out += - " Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" "; - out += - "и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n"; - out += - " Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n"; - out += - " Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n"; - out += - " Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n"; - out += - " Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n"; - out += - " Кнопка \"Help\" описывает работу с интерфейсом программы."; - showPopUp("Help:", out); - }) - ], - ), - ), - ), - )); - } - - // ignore: avoid_types_as_parameter_names, non_constant_identifier_names, use_function_type_syntax_for_parameters - ElevatedButton createButton(String txt, void onPressing()) { + // *************buttons************* + ElevatedButton createButton(String txt, void Function() onPressing) { return ElevatedButton( onPressed: onPressing, style: ButtonStyle( @@ -190,6 +68,32 @@ class _DrawingPageState extends State { ); } + void showPopUp(String alertTitle, String err) => showDialog( + context: context, + builder: (BuildContext context) => AlertDialog( + title: Text(alertTitle), + content: Text(err), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, 'OK'), + child: const Text('OK'), + ), + ], + ), + ); + // *************buttons************* + + // ***addSpace*** + SizedBox addSpaceH(double h) { + return SizedBox(height: h); + } + + SizedBox addSpaceW(double w) { + return SizedBox(width: w); + } + // ***addSpace*** + + // *************inputs************* Container createInputBox(String text, double wid, IconData? icon, TextEditingController? controller) { if (icon == null) { @@ -233,32 +137,78 @@ class _DrawingPageState extends State { )); } - SizedBox addSpaceH(double h) { - return SizedBox(height: h); + SizedBox dropList1(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), + //icon: const Icon(Icons.fiber_manual_record, color: Colors.white), + alignment: AlignmentDirectional.bottomEnd, + value: dropdownValue1, + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue1 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); + + return SizedBox( + child: button, + width: width, + ); } - SizedBox addSpaceW(double w) { - return SizedBox(width: w); - } + SizedBox dropList2(double width) { + var button = DropdownButton( + hint: const Text( + 'Select Dot', + style: TextStyle(color: Colors.white, fontSize: 13), + ), + alignment: AlignmentDirectional.centerEnd, + value: dropdownValue2, + isDense: true, + borderRadius: const BorderRadius.all(Radius.circular(20)), + dropdownColor: Colors.green.shade800, + style: const TextStyle( + color: Colors.white, + fontSize: 18, + ), + onChanged: (String? newValue) { + setState(() { + dropdownValue2 = newValue; + }); + }, + items: graphData.getDots().map((location) { + return DropdownMenuItem( + child: Text(location.getName()), + value: location.num.toString(), + ); + }).toList(), + ); - void showPopUp(String alertTitle, String err) => showDialog( - context: context, - builder: (BuildContext context) => AlertDialog( - title: Text(alertTitle), - content: Text(err), - actions: [ - TextButton( - onPressed: () => Navigator.pop(context, 'OK'), - child: const Text('OK'), - ), - ], - ), - ); + return SizedBox( + child: button, + width: width, + ); + } + // *************inputs************* //*********ButtonsFunctions********* void addDotPushed() { - //showPopUp("Test", "Test message"); - //var inp = int.tryParse(_textNameController.text); setState(() { if (_textNameController.text == "") { showPopUp("Error", "No name in \"Dot name\" box"); @@ -339,19 +289,6 @@ class _DrawingPageState extends State { void delDotPushed() { setState(() { - /*if (_textNumbController.text == "") { - showPopUp("Error", "No number in \"Dot number\" box"); - } else { - int? dot = int.tryParse(_textNumbController.text); - if (dot == null) { - showPopUp("Error", "Can't parse input.\nInts only allowed"); - } else { - String? res = graphData.delDot(dot); - if (res != null) { - showPopUp("Error", res); - } - } - }*/ if (dropdownValue1 != null) { graphData.delDot(int.parse(dropdownValue1!)); } else { @@ -369,14 +306,12 @@ class _DrawingPageState extends State { if (!result.files.single.path!.endsWith(".txt")) { showPopUp("Error", "Can open only \".txt\" files"); } else { - //print(result.files.single.path!); String? res = graphData.replaceDataFromFile(result.files.single.path!); if (res != null) showPopUp("Error", res); } } else { showPopUp("Error", "No file selected"); - // User canceled the picker } }); } @@ -388,7 +323,6 @@ class _DrawingPageState extends State { allowedExtensions: ["txt"]); if (outputFile == null) { showPopUp("Error", "Save cancelled"); - // User canceled the picker } else { if (!outputFile.endsWith(".txt")) { outputFile += ".txt"; @@ -442,75 +376,124 @@ class _DrawingPageState extends State { } //*********ButtonsFunctions********* - SizedBox dropList1(double width) { - var button = DropdownButton( - hint: const Text( - 'Select Dot', - style: TextStyle(color: Colors.white, fontSize: 13), - ), // Not necessary for Option 1 - alignment: AlignmentDirectional.centerEnd, - value: dropdownValue1, - - isDense: true, - borderRadius: const BorderRadius.all(Radius.circular(20)), - dropdownColor: Colors.green.shade800, - style: const TextStyle( - //background: Paint()..color = Colors.white, - color: Colors.white, - fontSize: 18, + // build + @override + Widget build(BuildContext context) { + screenSize = MediaQuery.of(context).size.width; + _textGrNmController.text = graphData.getName(); + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: const Align( + alignment: Alignment.topLeft, + child: Text("Graph name:\n", + style: TextStyle( + fontSize: 18, + color: Colors.white, + ))), + toolbarHeight: 110, + flexibleSpace: Container( + color: Colors.green.shade900, + child: Column(children: [ + const SizedBox(height: 5), + Row(children: [ + addSpaceW(screenSize / 8 + 19), + createButton("\nAdd dot\n", addDotPushed), + createInputBox("Dot name", screenSize / 4 - 25, Icons.label, + _textNameController), + addSpaceW(8), + createButton("\nAdd path\n", addPathPushed), + createInputBox("Input length", screenSize / 4 - 25, + Icons.arrow_right_alt_outlined, _textLnthController), + ]), + addSpaceH(3), + Row(children: [ + addSpaceW(6), + createInputBox( + "Name", screenSize / 8 - 25, null, _textGrNmController), + //addSpaceW(screenSize / 8 - 4), + createButton("\nDel dot \n", delDotPushed), + //createInputBox("Dot number", screenSize / 4 - 25, Icons.fiber_manual_record, _textNumbController), + addSpaceW(54), + dropList1(screenSize / 4 - 80), + addSpaceW(54), + createButton("\nDel path\n", delPathPushed), + addSpaceW(54), + dropList2(screenSize / 4 - 80), + //createInputBox("Destination number", screenSize / 4 - 25, Icons.fiber_manual_record, _textDestController), + ]), + ]), + ), + actions: [ + IconButton( + onPressed: () { + setState(() { + startDot = null; + endDot = null; + bfsPath = null; + dfsAccessTable = null; + graphData.flushData(); + clearInputData(); + }); + }, + icon: const Icon(Icons.delete_sweep), + iconSize: 60, + ), + ]), + body: CustomPaint( + painter: CurvePainter( + graphData: graphData, + bfsPath: bfsPath, + dfsAccessTable: dfsAccessTable, + start: startDot, + end: endDot), + child: Align( + alignment: Alignment.topRight, + child: ButtonBar( + mainAxisSize: MainAxisSize.min, + children: [ + createButton("Bfs", bfsPushed), + createButton("Dfs", dfsPushed), + createButton("Clear dfs or bfs", () { + setState(() { + bfsPath = null; + dfsAccessTable = null; + startDot = null; + endDot = null; + clearInputData(); + }); + }), + createButton(graphData.getUseLengthStr(), changeLength), + createButton(graphData.getDoubleSidedStr(), changeOriented), + createButton("Save to file", fileSaver), + createButton("Load from file", fileOpener), + createButton("Help", () { + String out = + " В поле \"Graph name\" можно сменить имя графу.\n"; + out += + " Для добавления точки необходимо ввести имя в \"Dot name\" и нажать на \"Add dot\".\n"; + out += + " Для удаления точки необходимо ввести номер в \"Dot number\" и нажать на \"Del dot\".\n"; + out += + " Для добавления пути необходимо ввести: номер выходной вершины в \"Dot number\", номер входной вершины в \"Destination number\" "; + out += + "и, если граф взвешенный, то ввести длину пути в \"Input length\". Затем нажать \"Add path\".\n"; + out += + " Для удаления пути необходимо ввести номер выходной вершины в \"Dot number\" и номер входной вершины в \"Destination number\". Затем нажать \"Del path\".\n\n"; + out += + " Кнопки \"Bfs\" и \"Dfs\" нумеруют точки в зависимости от послежовательности, в которой они будут пройдены.\n"; + out += + " Кнопки \"Взвешенный\" и \"Ориентированный\" позволяют сменить эти значения перед построением графа (т.е. для их работы граф должен быть пустым).\n"; + out += + " Кнопки \"Save to file\" и \"Load from file\" позволяют вывести информацию в файл и загрузить информацию из файла соответственно.\n"; + out += + " Кнопка \"Help\" описывает работу с интерфейсом программы."; + showPopUp("Help:", out); + }) + ], + ), + ), ), - onChanged: (String? newValue) { - setState(() { - dropdownValue1 = newValue; - }); - }, - items: graphData.getDots().map((location) { - return DropdownMenuItem( - child: Text(location.getName()), - value: location.num.toString(), - ); - }).toList(), - ); - - return SizedBox( - child: button, - width: width, - ); - } - - SizedBox dropList2(double width) { - var button = DropdownButton( - hint: const Text( - 'Select Dot', - style: TextStyle(color: Colors.white, fontSize: 13), - ), // Not necessary for Option 1 - alignment: AlignmentDirectional.centerEnd, - value: dropdownValue2, - - isDense: true, - borderRadius: const BorderRadius.all(Radius.circular(20)), - dropdownColor: Colors.green.shade800, - style: const TextStyle( - //background: Paint()..color = Colors.white, - color: Colors.white, - fontSize: 18, - ), - onChanged: (String? newValue) { - setState(() { - dropdownValue2 = newValue; - }); - }, - items: graphData.getDots().map((location) { - return DropdownMenuItem( - child: Text(location.getName()), - value: location.num.toString(), - ); - }).toList(), - ); - - return SizedBox( - child: button, - width: width, - ); + )); } } From 749afe3e6e4bd9726117333bfcea3c0ff8aa485c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 12:26:46 +0000 Subject: [PATCH 12/15] option for bfs --- cmd/bin/graphs0.dart | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/cmd/bin/graphs0.dart b/cmd/bin/graphs0.dart index f00af38..05db1dc 100644 --- a/cmd/bin/graphs0.dart +++ b/cmd/bin/graphs0.dart @@ -53,7 +53,7 @@ void main(List arguments) { String str = ""; while (deistvie != 0) { stdout.write( - "1 - создать граф, 2 - удалить граф, 3 - добавить в граф вершину,\n4 - удалить вершину, 5 - добавить ребро/дугу, 6 - удалить ребро/дугу,\n7 - вывести граф на экран, 8 - вывести граф в файл, 0 - выход\nDeistvie: "); + "1 - создать граф, 2 - удалить граф, 3 - добавить в граф вершину,\n4 - удалить вершину, 5 - добавить ребро/дугу, 6 - удалить ребро/дугу,\n7 - вывести граф на экран, 8 - вывести граф в файл, 9 - обход в ширину,\n0 - выход\nDeistvie: "); deistvie = getIntLine(); switch (deistvie) { case 1: @@ -156,7 +156,7 @@ void main(List arguments) { stdout.write("Имя вершины: "); String dotName = getStrLine(); - stdout.write( + /*stdout.write( "Ввод: *куда*|*вес* через пробел. Если граф не взвешенный, то *вес* можно не указывать.\nВершина cмежна с: "); str = getStrLine(); @@ -170,12 +170,12 @@ void main(List arguments) { inn.add(int.parse(splitted)); len.add(0); } - } + }*/ printGraphsName(graphs); stdout.write("Вставка в графа с номером: "); int y = getIntLine(); if (y >= 0 && y < graphs.length) { - graphs[y].addDotFromToLists(dotName, inn, len); + graphs[y].addIsolated(dotName); } else { print("Не найден граф с таким номером"); } @@ -285,6 +285,29 @@ void main(List arguments) { } break; } + case 9: + { + int num = graphs.length; + printGraphsName(graphs); + stdout.write("Работаем в графе с номером: "); + int y = getIntLine(); + if (y >= 0 && y < num) { + graphs[y].printG(); + num = graphs[y].getDotAmount(); + stdout.write("Вершина, из которой выходят: "); + int x1 = getIntLine(); + stdout.write("Вершина, в которую идут: "); + int x2 = getIntLine(); + if (x1 >= 0 && x1 <= num && x2 >= 0 && x2 <= num) { + print("BFS: ${graphs[y].bfsPath(x1, x2)}"); + } else { + print("Не найдены введеные вершины в графе\n"); + } + } else { + print("Не найден граф с таким номером"); + } + break; + } case 0: getStrLine(); exit(0); From 0a0698bd013bb3dbe1611c94045aedc5b79df8b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=BE=D1=80=D0=BE=D0=B7=D0=BE=D0=B2=20=D0=90=D0=BD?= =?UTF-8?q?=D0=B4=D1=80=D0=B5=D0=B9?= Date: Wed, 10 Nov 2021 12:28:24 +0000 Subject: [PATCH 13/15] =?UTF-8?q?=D0=97=D0=B0=D0=B3=D1=80=D1=83=D0=B7?= =?UTF-8?q?=D0=B8=D0=BB(=D0=B0)=20=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20=D0=B2?= =?UTF-8?q?=20'flutter/lib'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- flutter/lib/curve_painter.dart | 34 +--------------------------------- 1 file changed, 1 insertion(+), 33 deletions(-) diff --git a/flutter/lib/curve_painter.dart b/flutter/lib/curve_painter.dart index 4363d0b..2680cc7 100644 --- a/flutter/lib/curve_painter.dart +++ b/flutter/lib/curve_painter.dart @@ -246,6 +246,7 @@ class CurvePainter extends CustomPainter { void _drawDFS(Canvas canvas) { if (dfsAccessTable != null) { + print("nn"); for (int i = 0; i < dfsAccessTable!.length; i++) { if (dfsAccessTable![i]) { _drawDot(canvas, _off[i + 1]!, 8, Colors.green.shade500); @@ -294,36 +295,3 @@ class CurvePainter extends CustomPainter { return true; } } - -/*void _pringArr(Canvas canvas, Size size) { - TextSpan textSpan; - TextPainter textPainter; - Path path; - - // The arrows usually looks better with rounded caps. - Paint paint = Paint() - ..color = Colors.black - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round - ..strokeJoin = StrokeJoin.round - ..strokeWidth = 3.0; - - /// Draw a single arrow. - path = Path(); - path.moveTo(size.width * 0.25, size.height * 0.10); - path.relativeCubicTo(0, 0, size.width * 0.25, 50, size.width * 0.5, 0); - path = ArrowPath.make(path: path); - canvas.drawPath(path, paint..color = Colors.blue); - - textSpan = const TextSpan( - text: 'Single arrow', - style: TextStyle(color: Colors.blue), - ); - textPainter = TextPainter( - text: textSpan, - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - ); - textPainter.layout(minWidth: size.width); - textPainter.paint(canvas, Offset(0, size.height * 0.06)); -}*/