Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 4 of 6 FirstFirst ... 23456 LastLast
Results 76 to 100 of 133

Thread: 500 Ways to Print 1 to 10

  1. #76
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    #71: Fortran 90
    Last Fortran for a while. I mean, there are literally dozens of ways to make the program look different (indexed I/O versus formatted I/O, different kinds of loops, loops controlled by arithmetic if statements, assigned goto statements, programs that use an array instead of just writing the loop counter, etc., etc., etc.), but how much of this quaintness can anyone be expected to stand?


    !  Fortran 90 No explicit loop, use formatted I/O
    !
    !  Zaphod_b
    !
            Program PrintSequence
     
            write(*,'(1x,i0)') (i, i=1,10)
            Stop
     
            End Program PrintSequence


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 02:54 PM.

  2. #77
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    #72: TeX
    % File z.tex
    %
    % Print 1 through 10 with plain TeX.
    %
    % Just execute "pdftex z" from the
    % command line and look at z.pdf
    %
    %   Zaphod_b
    %
    \def\sequence#1
    {
      \count1=0
      \loop
         \ifnum\count1<#1
            \advance\count1 by 1
            \the\count1
            \vskip 2pt
      \repeat
    }
     
    \sequence {10}
    \end


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 02:55 PM.

  3. #78
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    #73: C
    (Believe it or not.)

    Perfectly standard C, compile with gcc -Wall -W -pedantic z.c -o z

    Or try it with your very own favorite standard C compiler.

    #define Beeblebrox void
    #define Curly int
    #define JustDoIt for
    #define Elroy int
    #define Larry int
    #define Moe int
    #define OO printf
    #define OOO "%d\n"
    #define Shagnasti main
    #define ThatsAllFolks return
    #define Whatever int
    #define really --_0
    /*
       Slightly Obfuscated C
     
    Reference:
    [url=http://www.dreamincode.net/forums/topic/38102-obfuscated-code-a-simple-introduction/]Obfuscated Code - A Simple Introduction - C++ Tutorials | Dream.In.Code[/url]
     
      Whimsically modified by Zaphod_b
     
    */
     
    #include <stdio.h>
     
    Beeblebrox _(Larry O, Curly _O, Moe _0)
    {
        JustDoIt(; O<_O; ++O) OO(OOO,_0++);
    }
     
    Elroy Shagnasti()
    {
        Whatever _0=1, O=013, _O=_0;
        _(_0,O,_O);
     
        ThatsAllFolks(really);
    }


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 02:56 PM.

  4. #79
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    #74: PostScript (Non-programming)

    Trivial postscript that doesn't use any programming language stuff like loops. Just lays 'em out there.
    %!PS-Adobe-2.0
    %
    % Trivial "brute-force" display of numbers 1--10
    %
    %  Zaphod_b
    %
    %%Creator: Zaphod_b (From scratch: With gvim)
    %%Title: SequenceBruteForce.ps
    %%Pages: 1
    %%PageOrder: Ascend
    %%BoundingBox: 0 0 612 792
    %%DocumentFonts: Times-Roman
    %%DocumentPaperSizes: Letter
    %%EndComments
     
    /inch {72 mul} def           % For my personal convience
    /Times-Roman findfont        % Just about as Plain Vanilla as you can get
    15 scalefont                 % I can read 15-point type without spectacles 
    setfont                      % Selects this font for writing
    newpath                      % Get ready to write
    1 inch 10 inch moveto        % Somewhere near the top of the page
    (1 2 3 4 5 6 7 8 9 10) show  % Put them all on the same line
    showpage                     % Taa-daa!

    If you have a PostScript printer attached to a port on your computer (or a PostScript driver for a port) just copy (use "echo" or "type" or whatever...) this file to that port.

    Or...

    If you have GhostView (or gsview or some other spin-off) or some other utility that can display PostScript, use that to view it (and print from there if you really want to).

    Or...

    Use ps2pdf (a shell script using gs or ghostscript) to create a pdf file and look at it with the acroread Acrobat Reader or some such thing.


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 05:46 PM.

  5. #80
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    75: PostScript with a "for" loop

    A little more "interesting" PostScript program. (You did know that PostScript is a full-fledged programming language, not just a page layout markup language, right?)

    Shows some macros that make text a little "easier." The actual program is the single line "for" loop near the bottom.
    %!PS-Adobe-2.0
    %
    %  Use a "for" loop to display numbers 1--10
    %
    %  Zaphod_b
    %
    %%Creator: Zaphod_b (From scratch: With gvim)
    %%Title: SequenceLoop.ps
    %%Pages: 1
    %%BoundingBox: 0 0 612 792
    %%DocumentPaperSizes: Letter
    %%EndComments
     
    %The above "official" %% comments are sometimes used by certain rendering
    % applications. They are, strictly speaking, not required for
    % most purposes.
     
    % A few macros to make text placement "easy." Mostly from
    % examples in the Blue Book.
     
    /inch {72 mul} def            % For my personal convience
     
    /LM 1 inch def                % Left margin is 1 inch from edge of paper
     
    /pointsize 15 def             % Can read 15 point type without my spectacles
     
    /leading
    {pointsize 1.2 mul} def       % Line spacing is 20% greater than point size
     
    /nstr
    {2 string} def                % Create a string long enough for two chars
     
    /newline
    {currentpoint leading sub     % Next line is below this one
     exch pop
     LM exch                      % Back to the left margin
     moveto} def
     
    /prt-n
    {nstr cvs show} def           % Convert number to string and print it
     
    /prtNum
    {dup prt-n newline} def       % Print number followed by newline
     
     
    % Experiment with different fonts by commenting out /Times-Roman
    % and uncommenting one of the others
     
    /Times-Roman findfont         % Just about as Plain Vanilla as you can get
    %/Chancery findfont           % Script.  Adds a little elegance if not overdone.
    %/Courier findfont            % Monospace like a typewriter.
    %/Bookman findfont            % A little different Roman font.
    %/Helvetica findfont          % Sans-serif.  My all-time least-favorite butt-ugly font.
    %/Avant-Garde findfont        % Sans-serif.  Try it with real text (not just numbers).
    %/Palatino findfont           % An alternative if you get bored with Times-Roman.
    %/Century-Schoolbook findfont % Another alternative to Times-Roman.
    %/Symbol findfont             % Guess what? Numbers still look like numbers (but try some text).
    %/Dingbats findfont           % Something really wild.
     
    pointsize scalefont           % Size defined above
    setfont                       % Selects this font for writing
    newpath                       % Get ready to write...
    LM 10 inch moveto             % Somewhere near the top of the page
     
    % The following is the only actual "programming" command
    1 1 10 {prtNum} for           % A "for" loop in "Reverse Polish"
     
    showpage                      % Taa-daa!


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 03:03 PM.

  6. #81
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    76: C with enums

    Notice that enums in C are are not exactly what a lot of people seem to think they are.
    #include <stdio.h>
     
    /* In C, an enum is an alias for an integer data type.
       There is practically no advantage to using them,
       and newcomers are surprised to find that you
       can't print out the name; just the integer value.
     
       Oh, well...
     
       Here's a way to print the integers 1-10.  I'm
       not sure that anyone on Planet Earth has ever
       done it exactly this way, but don't quote me on
       that.
     
       Zaphod_b
    */
     
    typedef enum
    {
        WinterDays, /* The 304-day Roman Calendar reserved 57 days between
                       December and January just for fun.  Ahhh.  Those were the days! */
     
        /* Now for the boring months of the English-language modern calendar */
         January, February, March    , April  , May     , June,
         July   , August  , September, October, November, December
    } months_t;
     
    int main()
    {
        months_t month;
     
        for (month = January; month <= October; month++)
        {
            printf("%d\n", month); /* The enum is really just an int, and that's what gets printed */
        }
        return 0;
    }

    Please note that this is a standard C program, but will not compile as a C++ program. For those ignorant people who are fond of spouting off the fallacy that claims "C++ is a superset of C," well, strictly speaking it is not. There are a handful of things that work in C that will not work in C++. This program and the next constitute my attempt to point out one of those things.


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 05:48 PM.

  7. #82
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    77: C++ with enums

    #include <iostream>
    using namespace std;
     
    /* In C++, unlike C, an enum is really a different data type.
     
       You can't increment an enum variable with a '++' operator,
       but if you use an enum in an arithmetic expression with
       an int variable, the enum is "promoted" to an int.
     
       The int result will NOT be automatically converted back
       to an enum, but you can use a simple cast.
     
     
       Anyhow...
     
       Here's a way to print the numbers 1--10 using C++
       enums.
     
       Zaphod_b
    */
     
    // Note that you can use the old-fashioned C-style typedef
    // if you want to, but I'll use the more modern C++
    // declaration:
    enum months_t
    {
        WinterDays, /* The 304-day Roman Calendar reserved 57 days between
                       December and January just for fun */
     
        /* Now for the boring months of the English-language modern calendar */
         January, February, March    , April  , May     , June,
         July   , August  , September, October, November, December
    };
     
    int main()
    {
        for (months_t month = January; month <= October; month = (months_t)(month+1))
        {
            cout << month << endl; // Note that the << operator is overloaded to print the int value
        }
        return 0;
    }


    In a C or C++ program like this, there is no way (really: no way) to print out the name of an enum as a string just from the enum definition. Really.

    Bottom line: I think Java enums make a lot more sense, and I think they can certainly be more useful, in general, than C enums or C++ enums.

    From interaction with new Javaites (including my own newbie self): It seems to me that enums often don't work out to be as easily useful as people thought they were going to when the topic was first introduced.


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 05:54 PM.

  8. #83
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    78: VHDL
    Writes to simulator console window. (Tested with Modelsim vsim)
    USE std.textio.ALL;
     
    ENTITY Sequence IS
    END ENTITY;
     
    ARCHITECTURE behavorial OF Sequence IS
    BEGIN
      counter : PROCESS
        VARIABLE count : INTEGER := 1;
        VARIABLE buf   : LINE;
      BEGIN
        WHILE count <= 10 LOOP
            WRITE(buf, count);
            WRITELINE(output, buf);
            count := count + 1;
        END LOOP;
        WAIT;
      END PROCESS counter;
    END ARCHITECTURE behavorial;


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 02:50 PM.

  9. #84
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    79: Java with enums---a little different from the previous Java enum example


    Man! Once enums begin dancing around in my head(s) it's like the theme from the Andy Griffith show---I just can't stop whistling. (R.I.P, Andy. We love ya, man!)

    Anyhow...

    //
    // Zaphod_b
    //
     
    public class Z
    {
        enum Month{
            January   (1),
            February  (2),
            March     (3), 
            April     (4),
            May       (5),
            June      (6),
            July      (7),
            August    (8),
            September (9),
            October   (10),
            November  (11),
            December  (12);
     
            private final int monthNum;
     
            public int num() {return monthNum;}
     
            Month(int n)
            {
                monthNum = n;
            }
     
        }
     
        public static void main(String [] args)
        {
            // It may look kind of silly to do it this way, but
            // I'll just print the numbers 1-10.  That's the
            // drill, right?
            //
            for (Month m : Month.values())
            {
                if (m.num() >= 1 && m.num() <= 10)
                System.out.println(m.num());
            }
     
            // If we wanted to print corresponding month names...
            //
            //System.out.println();
            //System.out.println("Month names for the first ten months:");
            //for (Month m : Month.values())
            //{
                //if (m.num() >= 1 && m.num() <= 10)
                //System.out.println(m);
            //}
        }
    }

    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 05:40 PM.

  10. #85
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    80: tcl

    #!/usr/bin/tclsh
     
    #
    #  Zaphod_b
    #
    for {set i 1} {$i <= 10} {incr i} {puts $i}

    Tested with tclsh8.4


    Cheers!

    Z
    Last edited by Zaphod_b; August 15th, 2012 at 04:20 PM.

  11. #86
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    81: perl
    #!/usr/bin/perl
    #
    #  Zaphod_b
    #
    for (my $i = 1; $i <= 10; $i++)
    {
        print $i, "\n";
    }

    Tested with perl 5.8.8

    By the way:
    Whatever happened to all of those perl guys anyhow? I mean, at one time you couldn't swing a dead cat without hitting several perl wonks, but I haven't heard much from them lately (the perl guys or the dead cats either).

    Are they all developing Java apps for Android devices now or what? (I can believe that some of the Android apps were written by dead cats. Not so sure about the perl guys. The unlearning curve for perl is steeper than the learning curve, I'm thinking.)


    Cheers!


    Z
    Last edited by Zaphod_b; July 17th, 2012 at 06:00 PM.

  12. #87
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    82: Korn shell script
    #!/user/bin/ksh
    #
    #  z.ksh by Zaphod_b
    #
    for i in {1..10}
    do
      echo $i
    done

    Tested with ksh version 8.1


    Cheers!

    Z
    Last edited by Zaphod_b; July 17th, 2012 at 03:23 PM.

  13. #88
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    83: C Shell script (tcsh, actually) Uses seq utility
    #!/bin/csh
    #
    # Zaphod_b
    #
    foreach x (`seq 1 1 10`)
         echo $x
    end
    #EOF

    Tested with tcsh 6.14.00


    Cheers!

    Z

  14. #89
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    84: C Shell with while loop
    #!/bin/csh
    #
    # Zaphod_b
    #
    @ i = 1
    while ($i <= 10)
      echo $i
      @ i++
    end
    #EOF

    Tested with tcsh 6.14.00


    Cheers!

    Z

  15. #90
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    85: bc script
    #!/usr/bin/bc
    #
    # For the unititiated: bc is an arbitrary precision binary calculator.
    #  You won't believe how much fun it is!
    #
    # Zaphod_b
    #
    for (i=1;i-11;i++)
    {
        print i, "\n"
    }
    quit

    Tested with bc version 1.06


    Cheers!

    Z

  16. #91
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    Quote Originally Posted by Freaky Chris View Post
    18. C++ (fixed (; )
    Well, by my count, the original number 18 had four errors. You corrected the "10 - 1" thing on line 8, right? So, by my count there are still three errors.

    1. Without any kind of statement about using std::cout or using namespace std, it won't compile with any of my compilers (GNU g++ with Linux, GNU/cygwin under Windows XP, two versions of Borland bcc32.exe and two versions of Microsoft cl.exe)

    2. Line 13 looks like this: cout << a* << " ";
    That does not compute. Surely it was supposed to be *a instead of a*.

    Fixing those things at least gets it to compile, but it does not print the numbers 1 through 10. (On my system it prints 0 through 9.) So we have arrived at bug number

    3. In fact there is undefined behavior, since, after the first loop, the variable a is pointing beyond the end of allocated memory.

    That means that the value of the first thing printed is garbage (may be zero for some compilers, something else for others, but its actual value is indeterminate according to the C++ language definition document). Then the other nine things printed are the last nine things stored, printed in reverse order, namely numbers 1 through 9.

    I respectfully suggest that the program can be "fixed" with a minor change or two, and its honored spot as number 18 on the list can be honestly preserved with something like the following:

    #include <iostream>
    // Fixes for number 18 suggested by
    //
    //   Zaphod_b
    //
     
    // The following is so that the compiler can know stuff about cout
    //
    using namespace std;
     
    int main()
    {
         int * a = new int[10];
         for (int i = 0; i < 10; i++)
         {
              *a = 10 - i;
              a++;
         }
     
         // Note that the variable a is now pointing beyond the end
         // of allocated memory!
     
         for (int i = 0; i < 10; i++)
         {
              cout << *(--a) << " "; // Decrement a before each access
         }
     
         // As a matter of personal style, I never return with the cursor
         // any place other than the beginning of the line.
         // 
         cout << endl;
     
         delete [] a;
     
         return 0;
    }

    Tested with GNU g++ version 4.1.2, among others, and memory access legitimacy validated with valgrind version 3.5.0

    Output

    1 2 3 4 5 6 7 8 9 10


    Cheers!

    Z
    Last edited by Zaphod_b; July 20th, 2012 at 03:46 PM.

  17. #92
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    86: forth
    Well, after I dug up my old PostScript documents, and had so much with the Stack architecture, could forth be far behind?

    \ z.fs
    \
    \ gforth demo program to print numbers 1 through 10
    \
    \ Zaphod_b
    \
    : Counter 11 1 ?DO i .  LOOP ; ( Define the Counter word )
    Counter ( Execute the Counter word )
    cr      ( Print a newline after the numbers )
    bye     ( Exit back to command shell )

    Tested with gforth 0.7.0 on my Centos 5.8 Linux workstation.

    Just enter gforth z.fs at a command line prompt.

    Output

    1 2 3 4 5 6 7 8 9 10

    Cheers!

    Z
    Last edited by Zaphod_b; July 21st, 2012 at 01:02 PM.

  18. #93
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    87: Java

    All right, a'ready. Enough of the non-Java stuff for a while. Maybe people here aren't really interested (much) in non-Java solutions, although I think it might not be too bad to color outside the lines once in a while (and the originator of this thread did say "no language boundaries" after all.)

    Anyhow...

    It's not really magic (not even close), but I think it may be a little weird to go to all that trouble just to print out the numbers 1 through 10

    //
    // It's really just plain old Java.  Nothing magical here.
    //
    // Zaphod_b
    //
    public class AlmostLikeMagic 
    {
        public static void main(String [] args)
        {
            int magicalValues[][] = 
            {
                {    30743,   109033},
                { 82232672,173679334},
                {299781132,601516389},
                { 16525540, 68164068},
                {  3261380, 98521395},
                {  7452438, 49358940},
                {369503274, 22219295},
                {  2452656, 89367080},
                { 34360335,  9279486},
                { 17819800, 42333410}
            };
            for (int i = 0; i < magicalValues.length; i++)
            {
                System.out.println(magicalValue(magicalValues[i]));
            }
        }
     
        static int magicalValue(int [] x)
        {
            return O_0(x[0], x[1]);
        }
     
        static int O_0(int _0, int _O)
        {
            while (_O != 0)
            {
                int O_ = _O;
                _O = _0 % _O;
                _0 = O_;
            }
            return _0;
        }
    }

    Tested with Java 1.6.SomethingOrOther

    Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10



    Cheers!

    Z
    Last edited by Zaphod_b; July 21st, 2012 at 01:02 PM.

  19. #94
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    88: Java (With a smidgen of numerical analysis.)
    /*
       I think it's more fun if you can figure out what it is doing
       (and how it is doing it) before reading the spoiler comment at
       the end.
     
       Zaphod_b
     
    */
     
    public class z
    {
        public static void main(String [] args)
        {
            double a [] =
            {
                      1,
                    -55,     1320,   -18150,    157773, -902055,
                3416930, -8409500, 12753576, -10628640, 3628800
            };
     
            int n = a.length;
     
            double b [] = new double[n];
            double c [] = new double[n];
     
            double x = 0;
            do
            {
                int it = 0;
                c[0] = a[0];
                b[0] = a[0];
                do
                {
                    for (int i = 1; i < n; i++)
                    {
                        b[i] = a[i] + x*b[i-1];
                    }
                    for (int i = 1; i < n; i++)
                    {
                        c[i] = b[i] + x*c[i-1];
                    }
                    x = x - b[n-1]/c[n-2];
                } while ((Math.abs(b[n-1]) > 1.0e-6) && (++it < 100));
     
                System.out.printf("%.0f\n", x);
     
                for (int i = 0; i < n-1; i++)
                {
                    a[i] = b[i];
                }
            } while (--n > 1);
        }
    }
    /*
       Note to numerical analysts:
       (I know you are out there; I can hear you breathing.)
     
       I know, I know: generally speaking, Newton's method with deflation
       is not considered to be the most reliable or effective for method for
       polynomial root solving. (Whadda ya want?  Eigenvalues obtained
       from SVD of the companion matrix, or what?  Well, maybe next time.)
     
       Anyhow...
     
       The point is that this little exercise not being suggested as a
       general purpose library routine for finding zeros of polynomials.
     
       The assignment was to print the numbers 1 through 10, by hook or crook,
       and all of the "easy" ways were already taken (or at least implied as
       being similar to previously posted methods).
     
       Well, after all is said and done, no one on Planet Earth has ever said
       it better than this:
     
        "The purpose of computing is insight not numbers."
        ---Richard W. Hamming
     
       So, as much fun as we all have with numbers, maybe don't look
       at just the numbers.
     
       Bottom line:
       Here's the Report---Mission Accomplished!
     
       Respectfully submitted by
     
              Zaphod_b
    */

    Tested with Java 1.6.SomethingOrOther

    Output

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10


    Cheers!

    Z
    Last edited by Zaphod_b; July 21st, 2012 at 01:03 PM.

  20. #95
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    89: Java (Intergalactic Morse)

    //
    // A possible implementation of a primitive Morse Code translator
    //
    // Could be fleshed out to detect and handle invalid sequences of dits and dahs
    // (and a lot of other stuff would be added for a 'real' translator).
    //
    // Zaphod_b
    //
    import java.util.Map;
    import java.util.HashMap;
     
    public class z
    {
        public static void main(String [] args)
        {
            // Individual Morse chars are separated by spaces.
            // Words are separated by two or more spaces.
            Morse message = new Morse(
            ".----  ..---  ...--  ....-  .....  " +       // 1-5
            "-....  --...  ---..  ----.  .---- ----- " +  // 6-10
            "-...-"                                       // Break for newline
            );
            System.out.print(message);
        }
    }
     
    class Morse
    {
        // Most sequences are mapped to a single character, but prosigns might
        // be mapped to a String, so the entire map is <String,String>
        static final Map<String, String> map = new HashMap<String, String>()
        {
          {
            // Numerals
            put("-----", "0");
            put(".----", "1");
            put("..---", "2");
            put("...--", "3");
            put("....-", "4");
            put(".....", "5");
            put("-....", "6");
            put("--...", "7");
            put("---..", "8");
            put("----.", "9");
     
            // Alphabet
            put(".-"   , "a");
            // Add other entries for alphabetical chars
            put("--.." , "z");
     
            // Punctuation, prosigns
            put(".-.-.-", ".");
            // Add other entries for common punctuation and prosigns
            put("...-.-", "SK"); // Print SK for End of Transmission
            put("-...-", "\n");  // BT for "break" gives newline.
          }
        };
     
        String [] words;
     
        Morse(String str)
        {
            words = str.split(" ");
        }
     
     
        // Might be useful for debugging
        public int getNumWords()
        {
            return words.length;
        }
     
        // Might be useful for debugging
        // Note: No protection against out-of-range access
        public String getWord(int n)
        {
            return words[n];
        }
     
        // The entire translated string
        public String toString()
        {
            String s = "";
            for (int i = 0; i < words.length; i++)
            {
                if (words[i].length() == 0)
                {
                    s += ' ';
                }
                else {
                    s += map.get(words[i]);
                }
            }
            return s;
        }
    }

    Output:

    1 2 3 4 5 6 7 8 9 10

    Cheers!

    Z
    Last edited by Zaphod_b; July 21st, 2012 at 01:03 PM.

  21. #96
    Member
    Join Date
    Jul 2012
    Posts
    83
    My Mood
    Cynical
    Thanks
    3
    Thanked 9 Times in 9 Posts

    Default Re: 500 Ways to Print 1 to 10

    public class OneToTen {
     
       public static final byte[] NUMBER_BYTES = { 
             0x4f, 0x6e, 0x65, 0x2c, 0x20, 0x54, 0x77, 0x6f, 0x2c, 0x20, 0x54,
             0x68, 0x72, 0x65, 0x65, 0x2c, 0x20, 0x46, 0x6f, 0x75, 0x72, 0x2c,
             0x20, 0x46, 0x69, 0x76, 0x65, 0x2c, 0x20, 0x53, 0x69, 0x78, 0x2c,
             0x20, 0x53, 0x65, 0x76, 0x65, 0x6e, 0x2c, 0x20, 0x45, 0x69, 0x67,
             0x68, 0x74, 0x2c, 0x20, 0x4e, 0x69, 0x6e, 0x65, 0x2c, 0x20, 0x54,
             0x65, 0x6e };
     
       public static void main(String[] args) {
     
          \u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
          \u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028
          \u006e\u0065\u0077 \u0053\u0074\u0072\u0069\u006e\u0067\u0028
          \u004e\u0055\u004d\u0042\u0045\u0052\u005f\u0042\u0059\u0054\u0045\u0053
          \u0029\u0029\u003b
     
       }
    }

    Do I win?
    Last edited by Fubarable; July 19th, 2012 at 04:42 PM.

  22. #97
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    Quote Originally Posted by Fubarable View Post
    public class OneToTen {
     
       public static final byte[] NUMBER_BYTES = { 
             0x4f, 0x6e, 0x65, 0x2c, 0x20, 0x54, 0x77, 0x6f, 0x2c, 0x20, 0x54,
             0x68, 0x72, 0x65, 0x65, 0x2c, 0x20, 0x46, 0x6f, 0x75, 0x72, 0x2c,
             0x20, 0x46, 0x69, 0x76, 0x65, 0x2c, 0x20, 0x53, 0x69, 0x78, 0x2c,
             0x20, 0x53, 0x65, 0x76, 0x65, 0x6e, 0x2c, 0x20, 0x45, 0x69, 0x67,
             0x68, 0x74, 0x2c, 0x20, 0x4e, 0x69, 0x6e, 0x65, 0x2c, 0x20, 0x54,
             0x65, 0x6e };
    ...
    Output

    One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten

    Well, everyone else has been printing numerals made up of decimal digits, but the original post said "Numbers," so I'm thinking numerals made up of words is also valid (although I'm not sure that commas between the numbers comply with the original).

    I mean, if this were a "real" program specification, I would ask for clarification. Also I note that some of the contributions put them all on the same line and some put each one on a separate line. I'm thinking that both ways have been accepted without complaint.

    Anyhow... I think your scheme should be numbered 90 (unless I lost count somewhere, and that's entirely possible).

    Furthermore...

    If people want to stick to decimal digit-based numerals, they could just change your definition to
       public static final byte[] NUMBER_BYTES = { 
           0x31, 0x20, 0x32, 0x20, 0x33, 0x20, 0x34, 0x20, 0x35, 0x20,
           0x36, 0x20, 0x37, 0x20, 0x38, 0x20, 0x39, 0x20, 0x31, 0x30
       };

    Output

    1 2 3 4 5 6 7 8 9 10


    Now, with your main(), the old familiar 1 2 3 ... appears, and this one should be numbered 91. (I think).

    I'm not sure that original contributors are still following this thread, since there hadn't been much activity lately until I got caught up in it when all those numbers began flitting back and forth between my left brain and my right brain...


    Cheers!

    Z
    Last edited by Zaphod_b; July 20th, 2012 at 05:17 PM.

  23. #98
    Member
    Join Date
    Jul 2012
    Posts
    83
    My Mood
    Cynical
    Thanks
    3
    Thanked 9 Times in 9 Posts

    Default Re: 500 Ways to Print 1 to 10

    Or even briefer:

    public static final byte[] NUMBER_BYTES = {0x31, 0x20, 0x74, 0x6f, 0x20, 0x31, 0x30};

  24. #99
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    93 (I think): Java
    //
    // Finding a real zero of a function f(x) involves solving the
    // equation f(x) = 0
    //
    // In particular: Finding cube root of a number, a, involves solving the
    // equation  x*x*x - a = 0
    //
    // One "easy" way (without using the Math.pow function) is Newton's method
    //
    // References:
    //    en.wikipedia.org/wiki/Cube_root
    //    en.wikipedia.org/wiki/Newton's_method
    //
    // Zaphod_b
    //
    public class z
    {
        public static void main(String [] args)
        {
            double nums [] =
            {
                1, 8, 27, 64, 125, 216, 343, 512, 729, 1000
            };
     
            for (int i = 0; i < nums.length; i++)
            {
                double a = nums[i];
                double x;
                int iter = 0;
                // Calculate approximate cube root by Newton's method
                // First approximation can be almost anything except zero.
                double xm1 = a/3.0;
                do
                {
                    x = (a/xm1/xm1 + 2.0*xm1)/3.0;
                    xm1 = x;
                    // For debugging and/or insight
                    //System.out.printf("a = %.0f, iter = %d, x = %.16e\n", a, iter, x);
     
                } while ((Math.abs(x*x*x-a) > 1.0e-6) && (++iter < 100));
     
                // Print value of x rounded to nearest integer
                System.out.printf("%.0f", x);
                if (i < nums.length-1)
                {
                    System.out.print(" ");
                }
                else
                {
                    System.out.println();
                }
            } // End of for() loop
        } // End of main()
    } // End of class definition

    Output

    1 2 3 4 5 6 7 8 9 10

    Cheers!

    Z
    Last edited by Zaphod_b; July 21st, 2012 at 01:03 PM.

  25. #100
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: 500 Ways to Print 1 to 10

    94: Java (Tridiagonal matrix)

    The mission: The numbers 1, 2, ..., 10 are a solution looking for a problem.

    Here's another possibility:
    //
    // Solution of tridiagonal matrix system by Gauss reduction
    //
    // Reference   en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm
    //
    //
    // Zaphod_b
    //
    public class z
    {
        public static void main(String [] str)
        {
            // Below main diagonal
            double a[] = {0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0};
     
            // Main diaglnal
            double b[] = {4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0};
     
            // Above main diagonal
            double c[] = {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0};
     
            // Right-hand side
            double d[] = {6.0, 12.0, 18.0, 24.0, 30.0, 36.0, 42.0, 48.0, 54.0, 49.0};
     
            int n = d.length;
     
            // Solution
            double x[] = new double[n];
     
     
            // Forward reduction
            c[0] = c[0]/b[0];
            d[0] = d[0]/b[0];
            for (int i = 1; i < n; i++)
            {
                double denominator = b[i] - c[i-1]*a[i];
                c[i] = c[i]/denominator;
                d[i] = (d[i] - d[i-1]*a[i])/denominator;
            } // End of forward reduction
     
            // Back substitution
            x[n - 1] = d[n - 1];
            for (int i = n - 2; i >= 0; i--)
            {
                x[i] = d[i] - c[i]*x[i+1];
            } // End of back substitution
     
            // Print out solution values as integers.
            for (int i = 0; i < n; i++)
            {
                // For debugging and/or insight
                //System.out.printf("%.16e\n", x[i]);
     
                System.out.printf("%.0f", x[i]);
                if (i < n-1)
                {
                    System.out.print(" ");
                }
                else
                {
                    System.out.println();
                }
            } // End of printout
        } // End of main()
    } // End of class definition

    Output

    1 2 3 4 5 6 7 8 9 10

    Cheers!

    Z
    Last edited by Zaphod_b; July 21st, 2012 at 01:04 PM.

Page 4 of 6 FirstFirst ... 23456 LastLast

Similar Threads

  1. print code to browser
    By bookface in forum Java Theory & Questions
    Replies: 4
    Last Post: April 21st, 2010, 01:09 AM
  2. print space
    By brainTuner in forum What's Wrong With My Code?
    Replies: 7
    Last Post: April 1st, 2010, 06:09 PM
  3. How to print results to screen
    By NinjaLink in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 19th, 2010, 01:46 PM
  4. Can someone please tell me why my code doesn't print out anything?
    By deeerek in forum What's Wrong With My Code?
    Replies: 3
    Last Post: February 6th, 2010, 08:35 AM
  5. print hex decimal value
    By ran830421 in forum Java Theory & Questions
    Replies: 1
    Last Post: November 25th, 2009, 07:23 PM