public void PrintPascalTriangle(int inNumberOfLines)
{
int noOfLines = inNumberOfLines;
int number = 1;
for(int i=0;i<noOfLines;i++)
{
number = 1;
for(int j=0;j<=i;j++)
{
Console.Write(number + " ");
number = number * (i - j) / (j + 1);
}
}
}
how can convert this method into single loop and print values in single row?
I just need Pascal triangle values in a row (no need to worry about spaces or visual rep) upto n.
Rows of Pascal's Triangle are all values of "the combinatorial function", n!/[k!( n-k)!], for a fixed n. The combinatorial function can be computed efficiently as below, see the Choose function, which I ripped from this answer:
class Program
{
static int Choose(int n, int k)
{
if (k > n)
return 0;
if (k * 2 > n)
k = n - k;
if (k == 0)
return 1;
int result = n;
for (int i = 2; i <= k; ++i)
{
result *= (n - i + 1);
result /= i;
}
return result;
}
static List<int> RowOfPascalsTriangle(int n)
{
return Enumerable.Range(0, n).Select(k => Choose(n-1, k)).ToList();
}
static void Main(string[] args)
{
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(1)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(2)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(3)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(4)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(5)));
}
}
Related
I am trying to sort the neighborhoods by their populations. I used heap sorting algorithm in C#. I created an Array which keeps the population of the neighborhoods named "arr". And created an array which keeps the name of the hoods . It works good but how can I get output of sorting with name of the neighborhoods?
My code is here:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace HoodSorting
{
public class example
{
static void heapSort(int[] arr, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--)
{
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
static void heapify(int[] arr, int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
heapify(arr, n, largest);
}
}
public static void Main()
{// arr REPRESENTS THE POUPLATION OF THE NEIGHBORHOODS
string[] neighborhoods = { "Bornova" ,"Westriver","Paradise","Goodman","McMountain","Rocker","Summerlin","Northcity","Greenhill","Sevenwaves"};
int[] arr = { 55, 25, 89, 34, 12, 19, 78, 95, 1, 100 };
int n = 10, i;
Console.WriteLine("Heap Sort");
Console.Write("Initial array is: ");
for (i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
heapSort(arr, 10);
Console.Write("\nSorted Array is: ");
for (i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
}
}
}
How can I get output like this:
Sorted Array is: Greenhill, McMountain,....,........, Northcity, Sevenwaves
Thanks a lot for the help
From an OOP perspective you would keep the two properties (name and population of a neighborhood) together in one object. Then when you sort the objects, you'll still have the associated data right there.
There are several ways to do this. For instance, you could create tuples.
Here is how that is applied to your code:
static void heapSort(Tuple<int, string>[] arr)
{
int n = arr.Length;
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--)
{
(arr[0], arr[i]) = (arr[i], arr[0]);
heapify(arr, i, 0);
}
}
static void heapify(Tuple<int, string>[] arr, int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left].Item1 > arr[largest].Item1)
largest = left;
if (right < n && arr[right].Item1 > arr[largest].Item1)
largest = right;
if (largest != i)
{
(arr[i], arr[largest]) = (arr[largest], arr[i]);
heapify(arr, n, largest);
}
}
public static void Main()
{
Tuple<int, string>[] arr = {
Tuple.Create(55, "Bornova"),
Tuple.Create(25, "Westriver"),
Tuple.Create(89, "Paradise"),
Tuple.Create(34, "Goodman"),
Tuple.Create(12, "McMountain"),
Tuple.Create(19, "Rocker"),
Tuple.Create(78, "Summerlin"),
Tuple.Create(95, "Northcity"),
Tuple.Create(1, "Greenhill"),
Tuple.Create(100, "Sevenwaves")
};
Console.WriteLine("Initial array is: ");
foreach (var pair in arr)
{
Console.Write(pair.Item2 + " ");
}
Console.WriteLine();
heapSort(arr);
Console.WriteLine("Sorted Array is: ");
foreach (var pair in arr)
{
Console.Write(pair.Item2 + " ");
}
Console.WriteLine();
}
The number n is entered from the keyboard (in this case, n = 7), you need to output such a figure
How to beautifully combine these 2 functions into one?
static void printD(int N, int k)
{
for (int i = 1; i <= k / 2; i++)
Console.Write(" ");
for (int i = 1; i <= N - k + 1; i++)
Console.Write("*");
Console.WriteLine();
if (k < N)
printD(N, k + 2);
}
static void printU(int N, int k)
{
for (int c = 1; c <= N / 2 + 1 - k; c++)
Console.Write(" ");
for (int c = 1; c <= k * 2 - 1; c++)
Console.Write("*");
Console.WriteLine();
if (k < N / 2 + 1)
printD(N, k + 1);
}
I suggest extracting a method which prints a single line:
static bool printLine(int N, int k) {
if (k <= 0 || k > N)
return false;
Console.Write(new string(' ', (N - k) / 2));
Console.Write(new string('*', k));
return true;
}
Then we can easily implement recursive printing for down and up triangles:
static void printD(int N, int k) {
if (printLine(N, k)) {
Console.WriteLine();
printD(N, k - 2);
}
}
static void printU(int N, int k) {
if (printLine(N, k)) {
Console.WriteLine();
printU(N, k + 2);
}
}
Finally, to draw a diamond shape figure we have to print up and then down triangles. So in order to combine triangles all we have to do is to call printU and printD:
static void print(int N) {
printU(N, N % 2 == 0 ? 2 : 1);
printD(N, N);
}
Demo:
print(6);
Console.WriteLine();
print(5);
Outcome:
**
****
******
******
****
**
*
***
*****
*****
***
*
Please, fiddle with the code.
When running this program, my first line has 62 digits while the other lines only have 60. How can I place 2 spaces in front of the first line so each line of the array is no more then 60 characters? So basically it would look like ( with two spaces in the beginning)
9999999999999999999999999999999999999999999999999999999999
999999999999999999999999999999999999999999999999999999999999
999999999999999999999999999999999999999999999999999999999999
using System;
namespace BigFactorial
{
class Program
{
static int MAX = 5000;
//This is telling the program what to multiply.
private static void mult(int[] x, int n)
{
int y = 0, i, m;
for (i = 0; i < MAX; i++)
{
m = y + x[i] * n;
x[i] = m % 10000;
y = m / 10000;
}
}
//This is telling the program how to calculate factorial of n.
public static void Factorial(int[] a, int n)
{
a[0] = 1;
for (int i = n; i > 1; i--)
{
mult(a, i);
}
}
//This is displaing the factorial after the calculation.
public static void Display(int[] a)
{
int i;
for (i = MAX - 1; a[i] == 0; i--) ;
Console.Write(a[i]);
for (int j = i - 1, c = 1; j >= 0; j--, c++)
{
string s = "" + a[j];
Console.Write(s.PadLeft(4, '0'));
if (c % 15 == 0)
Console.WriteLine();
}
Console.WriteLine();
}
public static void Main(string[] args)
{
while (true)
{
//Telling user to enter a number.
Console.Write("Enter a number to factor or a negative number to quit: ");
int n = int.Parse(Console.ReadLine());
//Quit function
if (n < 0) break;
int[] arr = new int[MAX];
Factorial(arr, n);
Display(arr);
}
//100000 is the max number it can calculate
}
}
}
You have already demonstrated that you know how to use String.PadLeft(), so cache the strings that you are writing in memory so you can inspect them rather than writing directly out to the console.
using System.Linq;
using System.Text;
public static void Display(int[] a)
{
int i = 0;
// build the string in memory, so we can inspect the length of the lines
StringBuilder output = new StringBuilder();
output.Append(a[i]);
for (int j = i - 1, c = 1; j >= 0; j--, c++)
{
output.Append($"{a[j]}".PadLeft(4, '0'));
if (c % 15 == 0)
output.AppendLine();
}
// get the lines into an array so we can normalise the length,
// although we know the length today, calculating it expresses the intent better
var lines = output.ToString().Split(new string [] { Environment.NewLine }, StringSplitOptions.None);
var maxLength = lines.Max(x => x.Length);
// now write the output to the console
foreach(var line in lines)
Console.WriteLine(line.PadLeft(maxLength, ' '));
}
It is not necessary to use StringBuilder like this, you could have used a List<string> and that would simplify the code further. It is however useful to identify that code written targeting the Console can easily be refactored to write to memory via StringBuilder as the syntax is very similar.
You could also have used a StringWriter instance called Console and the syntax would be identical... But that was a step too far for a logic block as simple as this.
I am looking for a output below with the input n and with number of loops less than (n*(n+1))/2 ,
Example N = 4,
1
2 3
4 5 6
7 8 9 10
Number of loops should be less than 10.
Is this possible???
There's also a solution with only one loop.
Print numbers in order, followed by a space, and if the last number was triangular, then print a newline. Keep track of how many newlines you have, and that's it.
Here's the code:
public static void PrintPyramid(int n)
{
var i = 0;
while (n > 0)
{
Console.Write(++i);
if (IsTriangularNumber(i))
{
Console.Write(Environment.NewLine);
n--;
}
else
{
Console.Write(" ");
}
}
}
public static bool IsTriangularNumber(int i)
{
var n = (int)Math.Sqrt(i*2);
return n*(n + 1) / 2 == i;
}
And here's how it works: http://ideone.com/Mx7Cel
For faster triangular number tests, see the answers to this question.
By cheating it is easy:
public static void PrintPyramid(int n)
{
int i = 1;
int row = 1;
int maxNumberInRow = 1;
int cycles = 0;
while (row <= n)
{
cycles++;
if (i == maxNumberInRow)
{
Console.Write(i);
Console.Write(" ");
i++;
}
else
{
Console.Write(i);
Console.Write(" ");
i++;
Console.Write(i);
Console.Write(" ");
i++;
}
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
}
}
Console.WriteLine();
Console.WriteLine("Cycles: {0}", cycles);
}
I did a little loop unrolling, doing up to two numbers in the same cycle. For n == 4, it is 6 full cycles.
Note that if we want to play the semantic game, a partial loop unrolling is enough:
public static void PrintPyramid3(int n)
{
if (n >= 1)
{
Console.Write("1");
Console.Write(" ");
Console.WriteLine();
}
int i = 2;
int row = 2;
int maxNumberInRow = 3;
int cycles = 0;
while (row <= n)
{
cycles++;
Console.Write(i);
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.WriteLine("Cycles: {0}", cycles);
}
The first row is "outside" the loop, so for n == 4, only 9 cycles are necessary.
Based on this code, it is easy to partially loop unroll the first x cases and do the remaining cases in a loop.
Ok... I was kidding... It is possible to do it in a totally loopless way...
public static void PrintPyramid(int n)
{
PrintPyramidRecursive(n, 1, 1, 1);
}
private static void PrintPyramidRecursive(int n, int i = 1, int row = 1, int maxNumberInRow = 1)
{
Console.Write(i);
Console.Write(" ");
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
if (row > n)
{
return;
}
}
PrintPyramidRecursive(n, i, row, maxNumberInRow);
}
You only need to use recursion! :-) :-) :-)
This one is a little more devious: no (apparent) cycles and no recursion:
public static void PrintPyramid5(int n)
{
int i = 1;
int row = 1;
int maxNumberInRow = 1;
ManualResetEvent mre = new ManualResetEvent(false);
Timer t = null;
TimerCallback tc = x =>
{
Console.Write(i);
Console.Write(" ");
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
if (row > n)
{
t.Dispose();
mre.Set();
}
}
};
t = new Timer(tc, null, 0, 1);
mre.WaitOne();
}
Simply put, the printing method is called by a Timer :-) So the loop is in the operating system. The printing method (tc) will clearly be called 10 times for n == 4.
You could pretend that string.Join() and Enumerable.Range() don't do any looping internally, and do it like this:
int n = 4;
for (int i = 1, j = 1; i <= n; ++i, j += i-1)
Console.WriteLine(string.Join(" ", Enumerable.Range(j, i).Select(x => x.ToString("00"))));
The for loop therefore only loops once per line rather than once per output number. But it's a cheat, because string.Join() and Enumerable.Range() do loop internally.
As per xanatos's suggestion, here's a version with no explicit loops at all:
Console.WriteLine(
string.Join("\n", Enumerable.Range(1, n).Select(i =>
string.Join(" ", Enumerable.Range((i*(i-1))/2+1, i).Select(x =>
x.ToString("00"))))));
This is a curiosity only, of course. ;)
Finally, here's a variant of xanatos's recursive solution:
private static string Triangular(int max, int row, int rowEnd, int number)
{
if (row == max)
return "";
else if (number <= rowEnd)
return number.ToString("00") + " " + Triangular(max, row, rowEnd, number + 1);
else
return "\n" + Triangular(max, row + 1, rowEnd + row + 1, number);
}
Which you'd use like this:
Console.WriteLine(Triangular(n, 1, 1, 1));
here i did your homework
public static void PrintPyramid(int n)
{
int t = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write(t);
t++;
}
Console.WriteLine();
}
}
I need to find the number of zeroes at the end of a factorial number. So here is my code, but it doesn't quite work :/
using System;
class Sum
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
long factoriel = 1;
for (int i = 1; i <= n; i++)
{
factoriel *= i;
}
Console.WriteLine(factoriel);
int timesZero = 0;
while(factoriel % 10 != 0)
{
timesZero++;
}
Console.WriteLine(timesZero);
}
}
I know I can use a for loop and divide by 5, but I don't want to. Where is the problem in my code and why isn't it working?
There's problem with your algorithm: integer overflow. Imagine, that you are given
n = 1000
and so n! = 4.0238...e2567; you should not compute n! but count its terms that are in form of (5**p)*m where p and m are some integers:
5 * m gives you one zero
25 * m gives you two zeros
625 * m gives you three zeros etc
The simplest code (which is slow on big n) is
static void Main(string[] args) {
...
int timesZero = 0;
for (int i = 5; i <= n; i += 5) {
int term = i;
while ((term % 5) == 0) {
timesZero += 1;
term /= 5;
}
}
...
}
Much faster implementation is
static void Main(string[] args) {
...
int timesZero = 0;
for (int power5 = 5; power5 <= n; power5 *= 5)
timesZero += n / power5;
...
}
Counting Trailing zeros in Factorial
static int countZerosInFactOf(int n)##
{
int result = 0;
int start = 1;
while (n >= start)
{
start *= 5;
result += (int)n/start;
}
return result;
}
Make sure to add inbuilt Reference System.Numeric
using System.Text;
using System.Threading.Tasks;
using System.Numeric
namespace TrailingZeroFromFact
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a no");
int no = int.Parse(Console.ReadLine());
BigInterger fact = 1;
if (no > 0)
{
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
Console.WriteLine("{0}!={1}", no, fact);
string str = fact.ToString();
string[] ss = str.Split('0');
int count = 0;
for (int i = ss.Length - 1; i >= 0; i--)
{
if (ss[i] == "")
count = count + 1;
else
break;
}
Console.WriteLine("No of trailing zeroes are = {0}", count);
}
else
{
Console.WriteLine("Can't calculate factorial of negative no");
}
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter the number:");
int n = int.Parse(Console.ReadLine());
int zero = 0;
long fac=1;
for (int i = 1; i <= n; i++)
{
fac *= i;
}
Console.WriteLine("Factorial is:" + fac);
ab:
if (fac % 10 == 0)
{
fac = fac / 10;
zero++;
goto ab;
}
else
{
Console.WriteLine("Zeros are:" + zero);
}
Console.ReadLine();
}
Your code seems fine, just a little correction in the while-condition:
public static int CalculateTrailingZeroes(BigInteger bigNum)
{
int zeroesCounter = 0;
while (bigNum % 10 == 0)
{
zeroesCounter++;
bigNum /=10;
}
return zeroesCounter;
}
That works, I just tested it.