Using loop print the following output on console.
        1
      121
    12321
  1234321
123454321
  1234321
    12321
      121
        1

Have you attempted it all? This seems a lot like a Homework question, which is not what this site is for.

I'll give you a hint though, you could use an array for this (to store the numbers, with only 1 occurance of each)

Well I've just done it for fun, was interesting. My code is probably messy but oh well!

Show us what you have done and we can help.

Edited 2 Years Ago by Mike Askew

Comments
naughty! ;)

I think that this guy aint comming back, so it would be nice for Mike Askew to post his code, i m really interested on how he did it. I would definitly use here three loops one for normal concatenation second for reverse concatenation and third for removing digits. I ll give it a try in the evening.

I must admit that i to google to find out about square and square root are possible for such a thing, i didn t notice that in the rising and falling sequence. But again tnx Ketsuekiame for letting me think a little bit more XD.

You really did it that small?

Remember look at the empty line space he has to, so he pads the left. I think we should both post the code we have (well mine might be more pseudocode)

Haha god damn my method is looking extremely bad now xD

Mine is based off a loop and identifying the last number added to the sequence, was bored and had nothing to do at work :p

static void Main(string[] args)
        {
            // Works up to 10
            int NumberOfNumbersToAdd = 5;

            #region Don't need to change these
            string Output = "";
            int Padding = (NumberOfNumbersToAdd * 2) - 1;
            #endregion

            if (NumberOfNumbersToAdd * 2 >= 20)
                Padding++;

            for (int i = 1; i != NumberOfNumbersToAdd; i++)
            {
                if (Output.Length == 0)
                {
                    Output = "1";
                    Console.WriteLine(Output.PadLeft(Padding, ' '));
                }

                if (Output.Length > 0)
                {
                    int CurNum = Convert.ToInt32(Output[Output.Length / 2].ToString());
                    int NewNum = CurNum + 1;
                    Output = string.Concat(Output.Substring(0, Output.LastIndexOf(CurNum.ToString()) + 1), NewNum, Output.Substring(Output.LastIndexOf(CurNum.ToString())));
                    Console.WriteLine(Output.PadLeft(Padding, ' '));
                }
            }

            for (int i = 1; i != NumberOfNumbersToAdd; i++)
            {
                int CurNum = Convert.ToInt32(Output[Output.Length / 2].ToString());
                Output = string.Concat(Output.Substring(0, Output.LastIndexOf(CurNum.ToString()) - 1), Output.Substring(Output.LastIndexOf(CurNum.ToString()) + 1));
                Console.WriteLine(Output.PadLeft(Padding, ' '));
            }

            Console.ReadLine();
        }

Edited 2 Years Ago by Mike Askew

Well guys, here is my version in a mere 30 lines. Fun to do! Awaiting the other contestants. :)

using System;
using System.Collections.Generic;

namespace NumberPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            const string one = "1";
            const int len = 9;          
            List<string> Grid = new List<string>();           
            string Number = "1";
            int calc = 1;
            for (int i = 0; i < len-1; i++)
            {             
                Grid.Add(calc.ToString().PadLeft(len));
                Number = i < len / 2 ? Number += one : Number.Substring(0, Number.Length -1);
                calc = int.Parse(Number);
                calc *= calc;
            }
            Grid.Add(Grid[0]); //The first will be the last
            foreach (var item in Grid)
            {
                Console.WriteLine(item);
            }            
            Console.ReadKey();
        }
    }
}

Edited 2 Years Ago by ddanbe: addition

Comments
you are always neat with your code (reffering to the const)
 static void Main(string[] args)
        {
            string number = "12345";
            int counter = -1;
            string output="";
            int counter2 = 0;
            int pad = (2 * (number.Length-1)) + 1;
            List<string> list = new List<string>();

            for (int i = 0; i < number.Length; i++) // normal seqeuncial concatenation
            {
                output = output + number[i];
                if (i == 0)
                {
                    Console.WriteLine(output.PadLeft(pad));
                    list.Add(output);
                }

                for (int j = counter; j >=0 ; j--)//   reverse concatenation
                {
                    counter2 = output.Length;
                    output = output + number[j];

                    if (output[output.Length-1]==number[0])
                    {
                        Console.WriteLine(output.PadLeft(pad));
                        list.Add(output);
                        output=output.Remove(counter+2);
                    }
                }
                counter++;
            }
            list.RemoveAt(list.Count - 1);
            list.Reverse();
            foreach (var item in list)
            {
                Console.WriteLine(item.PadLeft(pad));
            }
            Console.ReadLine();
        }

I really wanted to avoid the list stuff but I was lazy to think how to reverse inside my loops.
By the way i would really want to see Ketsuekiame to post his code if ofcourse he s got the time for it. And i m also suprised that no one used recursion xd.

Edited 2 Years Ago by castajiz_2: none

Alright so I probably could have cleaned this up more, but here's what I got (note you can use numbers between 1 and 9)

class Program
{
    static void Main (string [] args)
    {
        int NumberRange = 5; //change how many (1 to 9)

        string temp = "";
        int [] NumRange = new int [NumberRange];
        string [] DisplayArray = new string [NumberRange];

        for(int i = 1; i <= NumberRange; i++)
        {
            NumRange [i - 1] = i;

            temp = String.Join("", NumRange.ToArray()).Replace("0", "");
            Array.Reverse(NumRange);
            temp += String.Join("", NumRange.ToArray()).Replace("0", "").Substring(1, i - 1);
            Array.Reverse(NumRange);

            DisplayArray [i - 1] = temp.PadLeft((NumberRange * 2) - 1);
            Console.WriteLine(DisplayArray [i - 1]);
        }
        for (int i = (NumberRange - 2); i >= 0; i--)
        {
            Console.WriteLine(DisplayArray [i]);
        }

        Console.ReadLine();
    }
}

(Hmm I could use a 2D array or list to save myself a few lines, and if I cared to look in the set cursor position more I might be able to trim some more)

Edited 2 Years Ago by JOSheaIV

Of course we cannot forget to thank the teacher or whomever of hxn xfir for providing us, bored at work, with this now fun little competition.

I need to tidy my code up a bit and rethink my logic clearly!

Edited 2 Years Ago by Mike Askew

How rich a human mind can be in coming up with solutions to a problem. Or is it also due to the richness of the C# language?
Still awaiting Ketsuekiame... Or is he still busy stuffing all the code into one line? :D
This is also an invitation to join this little fun "competion".

Comments
definitly agree

Man if only we could stuff it all into one line (as you see I tried).

I know that was my goal, to see how compact I could make it (as well as seeing what was possible). I must say it was actually enjoyable.

Also fun to see all the different styles (at my new job, yep finally got a SW development gig about a month ago, I can always tell one developers work because he's the only one to use enums)

Comments
Congrats!

I've had some success, 3 statements is my smallest but still not a single one. I will continue this afternoon, I can feel it wanting to escape my brain ;)

So far my method VERY closely matches ddanbe's (one of the best things about this is being able to calculate the next line based on the previous, it removes a lot of the looping you guys are doing)

I can't really get away with spending all day at work doing this and not getting any actual work done...So can't really work on it atm, but I think I should have the answer tonight :)

Comments
i can t wait to see your code, though i don t want to put any pressure, just post it when you r done with it
        static void Main(string[] args)
        {
            double powValue = 0;
            double sqrtvalue = 0;
            int NumberOfValues = 9;

            for (int i = 1; i < 100000; i = (i * 10 + 1))
            {

                powValue = (Math.Pow(i, 2));
                Console.WriteLine(powValue.ToString().PadLeft(NumberOfValues));
            }

            powValue = Math.Pow(((Math.Sqrt(powValue) - 1) / 10), 2);
            for (double i = Math.Sqrt(powValue); i > 0; i = (i - 1) / 10)
            {
                sqrtvalue = Math.Pow(i, 2);
                Console.WriteLine(sqrtvalue.ToString().PadLeft(NumberOfValues));
            }

            Console.ReadKey();
        }

I left alot of room for improvement but i figured i won't have any hair left.

logic : 1^2 = 1
        11^2 = 121

    etc

Edited 2 Years Ago by Fenrir()

Comments
NIce addition to this collection!

I cheated slightly...But here's a one liner :)

using System;
using System.Linq;

namespace OneLineTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Enumerable.Range(1,5).Select(x => new string('1', x)).Concat(Enumerable.Range(1,4).Reverse().Select(x => new string('1', x))).Select(int.Parse).ToList().ForEach(y => Console.WriteLine("{0,9}", y*y));
            Console.ReadKey();
        }
    }
}

It could probably be optimised and I don't like the nesting but I can't recurse without defining a function so I picked the lesser of two evils.

I've been trying to find a way that I didn't have to do a mid level concat and parse but I think that my knowledge of LINQ is too limited.

Edited 2 Years Ago by Ketsuekiame

Comments
Knowledge of LINQ too limited? :)

Hey can we use the product we work on at work? Technically if I could use that I could save myself some code

And Ketsuekiame, I was linking of using some LINQ, but got lasy

Edited 2 Years Ago by JOSheaIV

@ Ketsuekiame: You win!
I understand for the most part how your super "oneliner" works, but could you please explain what the lambda expression( x => new string('1', x)) is doing? And why is the new keyword needed?

Okay, so the Enumerable.Range(start, count) generates a sequence of numbers. When you do the select on this it will perform the lambda of the select for each number in the sequence. I'm not really that interested in the number that the Enumerable outputs, that's a means to an end. This is because, as we know already, the sequence can be nicely calculated using a series of 1s squared.

The string constructor allows you to tell it to repeat a character x amount of times. The lambda, is essentially building the sequence of "1" for me. A common misconception with LINQ is that you have to get out what you put in, but this isn't true. So I put in an integer (3 for example) and get out a string (for 3 would be "111")

The Select method builds a new List of strings for me.

Unfortunately, you can't make Enumerable.Range count down, I tried experimenting with TakeWhile but simply using .Reverse().Select() gave better output, simpler. So to join the two currently non-existent lists together I had to use Concat. If you were to execute this query now, you'd get a list out that looked like

"1"
"11"
"111"
"1111"
"11111"
"1111"
"111"
"11"
"1"

So now we have the string of 1s that can be used for the calculation. As the easiest way to generate them was as strings, they needed to be parsed back to int so I could work on them mathematically, so input list of strings and select the integer back out (Select(int.Parse)). So my list of strings is now a list of ints, the last one is pretty self explanatory, for each of those ints, write out the value of that int squared.

Edited 2 Years Ago by Ketsuekiame

Here is an ugly but working entry

List<string> dothis(int level)
{
    string start = "";
    string middle = "";
    string end = "";
    List<string> line = new List<string>();

    for(int step = 1; step <= level; step++)
    {
        start += (step-1).ToString().Replace("0","");
        middle = step.ToString();
        end = new string(start.ToCharArray().Reverse().ToArray());
        line.Add(start + middle + end);
    }

    for (int step = level - 1; step >= 0; step--)
    {
        line.Add(line[step]);
    }

    return line;
}

@Venjense : your post is well appreciated but your outcome doesn't totaly resemble the OP's first post. :)

No way would I try a one-liner. I tested this on 5 and 50 and both worked properly.

        /// <summary>
        /// Goes from 1 to 99, lists on Console the number list forward and backword
        /// Right adjusting the values. All values except the last number are repeated in reverse order
        /// IE if 5 is passed 123454321
        /// </summary>
        /// <param name="num"></param>
        static void stringlist(int num)
        {
            if (num < 0) num = -num;
            else if (num <= 1)
            {
                Console.WriteLine("1");
                return;
            }
            if (num > 99)
            {
                Console.WriteLine("Passed number ({0}) exceeds 100, setting to 99", num);
                num = 99;
            }
            List<string> forward = new List<string>();
            StringBuilder left = new StringBuilder(), right = new StringBuilder(), pad = new StringBuilder();
            int len = 0;
            for (int i = 1; i <= num; i++)
            {
                pad.Append("    ");
                left.Append(i);
                string x = left.ToString() + right.ToString();
                forward.Add(x);
                len = x.Length;
                right.Insert(0, i);
            }
            foreach (string x in forward)
                if (x.Length == len) Console.WriteLine(x);
                else Console.WriteLine("{0}{1}", pad.ToString(0, len - x.Length), x);
            for (int i = forward.Count - 2; i > -1; i--)//-2 points to the next to last number
                Console.WriteLine("{0}{1}", pad.ToString(0, len - forward[i].Length), forward[i]);
        }
This article has been dead for over six months. Start a new discussion instead.