JulianJulianov

12. Pascal Triangle

Feb 10th, 2020
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.24 KB | None | 0 0
  1. 2. Pascal Triangle
  2. The triangle may be constructed in the following manner: In row 0 (the topmost row), there is a unique nonzero entry 1. Each entry of each subsequent row is constructed by adding the number above and to the left with the number above and to the right, treating blank entries as 0. For example, the initial number in the first (or any other) row is 1 (the sum of 0 and 1), whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row.
  3.  
  4. Print each row elements separated with whitespace.
  5.  
  6. using System;
  7. using System.Linq;
  8.  
  9. namespace _02PascalTriangle
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. int numberOfRows = int.Parse(Console.ReadLine());
  16.  
  17. int firstRow = 1;
  18. Console.WriteLine(firstRow);
  19.  
  20. if (numberOfRows == 1)
  21. {
  22. return;
  23. }
  24. int[] previousRow = new int[] {1, 1};
  25. Console.WriteLine(string.Join(" ", previousRow));
  26.  
  27. if (numberOfRows == 2)
  28. {
  29. return;
  30. }
  31. else
  32. {
  33. for (int i = 0; i < previousRow.Length + 1; i++)
  34. {
  35. int[] nextRow = new int[previousRow.Length + 1];
  36. nextRow[0] = 1;
  37. nextRow[nextRow.Length - 1] = 1;
  38.  
  39. for (int j = 1; j < nextRow.Length - 1; j++)
  40. {
  41. nextRow[j] = previousRow[j - 1] + previousRow[j];
  42. }
  43. Console.WriteLine(string.Join(" ", nextRow));
  44.  
  45. previousRow = nextRow;
  46.  
  47. if (previousRow.Length == numberOfRows)
  48. {
  49. break;
  50. }
  51. }
  52. }
  53. }
  54. }
  55. }
  56. /*namespace SandBox Друго решение с "Назъбен" масив!
  57. { /
  58. using System; //
  59. ///
  60. public class EntryPoint ////
  61. { /////
  62. public static void Main()//////
  63. { ///////
  64. ////////
  65. long triangleRows = long.Parse(Console.ReadLine());
  66.  
  67. long[][] jaggedArray = new long[triangleRows][];
  68.  
  69. jaggedArray[0] = new long[1];
  70. jaggedArray[0][0] = 1;
  71.  
  72.  
  73. for (long row = 1; row < jaggedArray.Length; row++)
  74. {
  75. jaggedArray[row] = new long[row + 1];
  76. jaggedArray[row][0] = 1;
  77. jaggedArray[row][jaggedArray[row].Length - 1] = 1;
  78.  
  79. for (long col = 1; col < jaggedArray[row].Length - 1; col++)
  80. {
  81. long leftDiagonal = jaggedArray[row - 1][col - 1];
  82. long rightDiagonal = jaggedArray[row - 1][col];
  83.  
  84. jaggedArray[row][col] = leftDiagonal + rightDiagonal;
  85. }
  86. }
  87.  
  88. for (long row = 0; row < triangleRows; row++)
  89. {
  90. Console.WriteLine(string.Join(" ", jaggedArray[row]));
  91. }
  92. }
  93. }
  94. }*/
Advertisement
Add Comment
Please, Sign In to add comment