Printing number sequence in C# with less loops - c#

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();
}
}

Related

Sorting Neighborhoods by Population Using Heap

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();
}

print pascal triangle values in a single loop

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)));
}
}

pyramid pattern in while loop c#

I have to create a program to print pyramid pattern (1 2 33 44 555 666...) and sum the numbers.
Here is my solution:
static void Main(string[] args)
{
int i, j;
i = 1;
int sum = 0;
while (i < 9)
{
for (j = 1; j <= i; j+=2)
{
Console.Write(i);
}
Console.Write("\n");
sum += i;
i++;
}
Console.WriteLine("Summary: " + sum);
Console.ReadLine();
}
And my output:
What am I doing wrong here (wrong summary)?
Here is an optimized and working version of your code:
int sum = 0;
for (int i = 1; i < 9; i++)
{
int current = 0;
for (int j = 1; j <= i; j += 2)
{
Console.Write(i);
current = 10 * current + i;
}
Console.WriteLine();
sum += current;
}
Console.WriteLine("Summary: " + sum);
The main issue is that you were only capturing the value of i (integer being printed) and using that to calculate the summary. As seen here, the current value is captured (for the entire line) within the nested loop and then added to the summary to give you the result you expect.
HTH
Only made small adjustments to your code.
static void Main(string[] args)
{
int i, j;
i = 1;
int sum = 0;
while (i <= 9)
{
for (j = 0; j <= i - 1; j++)
{
Console.Write(i);
sum += i * (int)Math.Pow(10, j);
}
Console.WriteLine();
i++;
}
Console.WriteLine("Sum: " + sum);
Console.ReadLine();
}
If you like to extend your code to let the user pick a number you can do this:
Instead of this line:
while (i <= 9)
You can do this:
Console.WriteLine("Please enter a number between 1 and 9:");
int maxValue = 1;
while (true)
{
if (!int.TryParse(Console.ReadLine(), out maxValue) || maxValue < 1 || maxValue > 9)
{
Console.WriteLine("Wrong input! Try again:");
continue;
}
break;
}
while (i <= maxValue)
Please find not optimized but quick solution
int i, j;
i = 1;
int sum = 0;
while (i < 9)
{
int current = 0;
for (j = 1; j <= i; j += 2)
{
current = 10 * current + i;
Console.Write(i);
}
Console.Write("\n");
sum += current;
i++;
}
Console.WriteLine("Summary: " + sum);
Console.ReadLine();

How to print a triangle of Binary numbers in c#

I need to add binary number logic into this snippet. I just cannot wrap my head around how to implement binary numbers, I could just add 0s and 1s but that does not seem to be right
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
Console.Write("*");
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
}
}
}
you can use modulo (%)
c = star % 2; // will print first the '1'
c = (star + 1) % 2; // will print first the '0'
int num;
Console.WriteLine("enter level");
num = Int32.Parse(Console.ReadLine());
int count = 1;
int c = 0;
for (int lines = num; lines >= 1; lines--)
{
for (int spaces = lines - 1; spaces >= 1; spaces--)
{
Console.Write(" ");
}
for (int star = 1; star <= count; star++)
{
c = star % 2; //this will return 1 if the value of star is odd then 0 if even
Console.Write(c);
Console.Write(" ");
}
count++;
Console.WriteLine();
}
Console.ReadLine();
VIEW DEMO

Number of zeroes at the end of factorial

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.

Categories

Resources