Coding Challenge #1

Anything and Everything about Uplink

Moderators: jelco, bert_the_turtle, Chris, Icepick, Rkiver

Stewsburntmonkey
level5
level5
Posts: 11553
Joined: Wed Jul 10, 2002 7:44 pm
Location: Nashville, TN
Contact:

Postby Stewsburntmonkey » Sat Oct 23, 2004 7:32 pm

My Perl code:

Code: Select all

#!/usr/perl -w


#  Determines if a number is happy.       
#  Outputs result of every step as well. 
#  -by David Stewart                     

$max = 100;

print "Enter a number you want to do a mood test on: ";
$s = <>;   # get console input
chomp($s);    # remove any newline

$sum = $s;
$count = 0;

while ($sum != 1 && !($previous{$sum}) && $count < $max) {
  print "$count \t $sum \n";
  $previous{$sum} = 1;      # add result to a hash so that we can check for repetition
  $s2 = $sum;
  $sum = 0;
  while ($s2) { $sum += chop($s2) ** 2; }   # sum of squares
  $count++;
}
print "$count \t $sum \n";

if ($sum == 1) { print "\nYay!  $s is a happy number!  :D\n"; }
elsif ($count >= $max) {
  print "\nBoo. . .  We could not determine the mood of $s quickly. :|\n";
}
else { print "\n$s is unhappy, very very unhappy.  :(\n"; }


:)
User avatar
NeoThermic
Introversion Staff
Introversion Staff
Posts: 6256
Joined: Sat Mar 02, 2002 10:55 am
Location: ::1
Contact:

Postby NeoThermic » Sat Oct 23, 2004 7:47 pm

Hmm, I find it intresting you gave a max. I would of expected that taking the squares of the digits and adding them would of ment that the number either repeats quickly, or results as a happy number quickly.

Have you had any numbers that have taken longer than 100 runs of the loop?


NeoThermic
Stewsburntmonkey
level5
level5
Posts: 11553
Joined: Wed Jul 10, 2002 7:44 pm
Location: Nashville, TN
Contact:

Postby Stewsburntmonkey » Sat Oct 23, 2004 7:50 pm

No, you are quite right that the sum of squares should terminate fairly quickly, but with loops like this I always like to have a definite bound, just in case. The most iterations I have managed is around 15. :)
elDiablo
level5
level5
Posts: 3111
Joined: Thu Mar 14, 2002 12:23 pm
Location: London, UK

Postby elDiablo » Sat Oct 23, 2004 8:00 pm

My Java code, written in the last 7 minutes:

Code: Select all

// Happy numbers
// Leander Hambley
//////////////////

import java.io.*;

class Happy
{
   /*
    * What makes the world (aka program) go round.
    */
   public static void main(String argvs[])
   {
      // Make something to read an input.
      BufferedReader keyboard = new BufferedReader(
         new InputStreamReader(
            System.in
         )
      );

      // Set some lovely variables.
      int[] numbers;      // Array of numbers to be held.
      int inputLength,   // A variable for the first input's length.
         squareTest = 0,   // A tester to see if its happy happy joy joy.
         squareBest = 0,   // For the while loop. Go see.
         counter = 0;   // Surprise, surprise, a counter.
      String input = "";   // The input. Could be null, or anything, but it cant be nothing!
                     // aka, has to be initialised as it might fail to be in the try brackets.

      // Say hello program. "Hello program.", etc.
      System.out.println("Input a number to find if it is happy.\n" +
            "NOTE: test will run for 100,000 loops before believing it is not a happy number.");

      // A try loop. Makes sure the input dont fail.
      try {
         input = keyboard.readLine();
      } catch (IOException ioe)
      {
         System.err.println("ERROR:" + ioe);
      }

      // Make the variables in accordance with the input.
      inputLength = input.length();      // Yep. The input's length.
      numbers = new int[inputLength*2];   // The array. Some maths to cover it:
                                    // If the input is a 6-digit character,
                                    // and is split into 6 separate numbers,
                                    // and each of these is squared, the result
                                    // can merely be placed over the original
                                    // separate numbers. Hence, the smallest poss
                                    // array size is the length of the input.
                                    // THANK YOU! AND GOD NIGHT!


      // A while loop. Counts to 100,000, or stops when the square is 1.
      while (squareBest != 1 && counter < 100000)
      {
         // Put the test back to zero.
         squareTest = 0;

         // For loop to read in the different digits
         for (int i = 0; i < input.length(); i++)
         {
            numbers[i] = Integer.parseInt(input.substring(0,1));
            input = input.substring(1,input.length());
         }

         // For loop to square all digits.
         for (int i = 0; i < inputLength; i++)
         {
            numbers[i] = numbers[i] * numbers[i];
         }

         // For loop to all the squares.
         for (int i = 0; i < inputLength; i++)
         {
            squareTest = squareTest + numbers[i];
         }
         
         // Reset the input to the new square if it failed to be 1.
         input = new Integer(squareTest).toString();

         // Test to see if its 1. If so, the while loop DIES.
         squareBest = squareTest;

         // So it aint an infinite loop and all.
         counter++;
      }

      // Final HAPPY/SAD test.
      if (squareTest == 1)
         System.out.println("HAPPY");
      else
         System.out.println("SAD");
   }
}


SOOOOO Much better then LLama's ;)

And yay me for being too lazy to do it before. Yay for Java. Yay for pointlessness
We dont stop playing cos we get old... We get old cos we stop playing.
User avatar
LLamaBoy
level5
level5
Posts: 1627
Joined: Sun Aug 18, 2002 12:18 pm
Location: Cyprus
Contact:

Postby LLamaBoy » Sat Oct 23, 2004 8:16 pm

Here's the good code now:

Code: Select all

/*************************************
 * Happy.java                        *
 * Check for happy numbers           *
 * Written by Mark Vine aka LLamaBoy *
 * 16/10/2004                        *
 ************************************/

import java.io.*;
import java.util.*;

public class Happy
{
   static String number = "";
   static boolean running = true;
   
   //start here
   public static void main(String args[])
   {
      while(running) //keep running until the user wants to stop
      {
         boolean goodNumber = false, goodConfirm = false;
         
         while(!goodNumber) //keep looping til there's an actual number input
         {
            number = read("Enter a number to check it's happiness: "); //read the number
            
            //check the number is valid
            try
            {
               for(int i = 0 ; i < number.length() ; i++)
                  Integer.parseInt("" + number.charAt(i));   //check each char if it's a number.
               goodNumber = true;      //if the parse is successful, it's a good number.
            }
            catch(Exception x)
            {
               System.out.println("Your input was not a number, please try again.\n"); //is happy
            }
         }   //exit while goodInput
         
         if(checkHappy(number)) //call the check method
            System.out.println("The number " + number + " is a happy number! :D"); //is happy
         else
            System.out.println("The number " + number + " is not happy :("); //is unhappy
            
         while(!goodConfirm) //kepp looping until a y or n is typed
         {
            String confirm = read("Try another number? (Y/N) "); //try again?
            
            if(new String("" + confirm.charAt(0)).equalsIgnoreCase("n")) //check for n (upper or lower case)
            {
               goodConfirm = true; //was a good input (n)
               running = false;   //stop the program from running
               System.out.println("\nThank you for using LLamaBoy's number happiness checker.");
            }
            else if(!(new String("" + confirm.charAt(0)).equalsIgnoreCase("y"))) //check for bad input
               System.out.println("\nSorry, your input was invalid, please try again.");
            else //otherwise, a y.
            {
               goodConfirm = true;   //was a good input (y)
               System.out.println();
            }
         }   //exit while goodConfirm
      }   //exit while running
   }   //exit main method
   
   //method for console input reading
   public static String read(String request)
   {
      String cmd;
      
      try
      {
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         System.out.print(request);
         cmd = in.readLine();
         
         return cmd;
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
      
      return null;
   }
   
   //check for happiness in this method
   public static boolean checkHappy(String num)
   {   
      if(num.equals("0"))
         return false;
      else if(num.equals("1")) //if the number is eventually 1, we have a happy number
         return true;
      else
      {
         int nums[] = new int[num.length()],      //array for each digit
            sum = 0;                     //the sum to send next time.
         
         for(int i = 0 ; i < num.length() ; i++)
         {
            nums[i] = Integer.parseInt("" + (num.charAt(i))); //turn each digit into a number
            nums[i] *= nums[i]; //and square it
            sum += nums[i]; //then add it to the running total
         }
         
         System.out.println("sum is now: " + sum);
         
         if(sum == 4)   //when the sum becomes 4, the sum sequence begins looping,
            return false;   //so it's not a happy number
         
         return checkHappy("" + sum); //and call the method again for recursive checking.
      }
   }
}


I'm sure you'll see which is the superior! :D - Note the recursion. *nods*

(Take that, elD!)
Fartan
level1
level1
Posts: 11
Joined: Wed Sep 04, 2002 2:21 pm
Location: Germany

Postby Fartan » Sat Oct 23, 2004 9:33 pm

Code: Select all

If OpenWindow(0,200,200,300,40,#PB_Window_SystemMenu,"Happy Number Tester II ("+Str(?asm2-?asm1)+" Bytes)") And CreateGadgetList(WindowID())
  StringGadget(0,0,0,300,20,"",#PB_String_Numeric)
  TextGadget(1,0,20,300,20,"Enter Number")
  Repeat
    EventID.l=WaitWindowEvent()
    If EventType()=#PB_EventType_Change
      s.s=GetGadgetText(0)
asm1:
      !MOV Esi, [v_s] ; Load Pointer to string
      !XOR Eax, Eax   ; Eax: one digit
      !XOR Ebx, Ebx   ; Ebx: Sum
     
      d:!MUL Eax      ; square
        !ADD Ebx, Eax ; add to sum
        !LODSB        ; Get the next digit
        !SUB al, 48   ; ASCII to number
      !JNS l_d        ; end of String?

      !XCHG Eax, Ebx  ; Eax: The current value
     
     
      !PUSH 10
      !POP Ecx        ; Ecx: Divisor(10)
       
      a:!XOR Ebx, Ebx   ; Ebx: The sum of the squares
     
        !DEC Eax        ; is the sum happy?
        !JLE l_happy
        b:!INC Eax
     
          !XOR Edx, Edx   ; Edx: one extracted digit
     
          !DIV Ecx        ; Get the next digit
     
          ;Add the square to Ebx
          !IMUL Edx, Edx
          !ADD  Ebx, Edx
     
          !DEC Eax      ; Every digit processed?
        !JNS l_b        ; if not, get the next one
     
        !XCHG Eax, Ebx  ; replace the current Value with the sum
     
        !CMP al, 42     ; unhappy?
      !JNE l_a          ; repeat if not
asm2:
      SetGadgetText(1,"Unhappy")
      Goto c
      happy:
      SetGadgetText(1,"Happy")
      c:
    EndIf
  Until EventID=#PB_Event_CloseWindow
EndIf

only 46 bytes between asm1: and asm2: doing all the calculations (20 bytes string to integer + 26 bytes integer to integer with happyness checks)
ODDin
level5
level5
Posts: 2521
Joined: Fri Jul 04, 2003 10:44 pm
Location: Haifa, Israel
Contact:

Postby ODDin » Sat Oct 23, 2004 10:05 pm

LLama, can you please post your VB solution as well?
elDiablo
level5
level5
Posts: 3111
Joined: Thu Mar 14, 2002 12:23 pm
Location: London, UK

Postby elDiablo » Sat Oct 23, 2004 11:29 pm

Llama - Recursion == bad. While == good. Heh. And you're right, they can now see that mine is BY FAR the best ;)
We dont stop playing cos we get old... We get old cos we stop playing.
einstein
level5
level5
Posts: 1463
Joined: Mon Mar 04, 2002 5:23 pm
Location: Scotland

Postby einstein » Sun Oct 24, 2004 1:40 am

my solution is like TINY compared to all of that... especially blasted heath's php implementation (being in the same language and all)...

The code of the actual happy number calculator bitty...

Code: Select all

<?
$_GET[number] = $number; //retrieves the number from form
while (($number != "1") && ($number != "4")){
   $array = preg_split('//', $number, -1, PREG_SPLIT_NO_EMPTY); //creating an array in which each element is a digit of the entered number
   foreach ($array as $value) { //goes through each digit
      $value = $value * $value; //squares them
      $newarray[] = $value; //stores new value in an array of their own
      }
   $number = array_sum($newarray); //calculating the sum of the squared elements in the new array
   unset($newarray); //clearing the array for use in next loop
   }
if ($number == "1") {
   echo "$_GET[number] <b>is</b> a happy number!"; //inform user that the number they entered is happy
   } else {
      echo "$_GET[number] <b>is not</b> a happy number!"; //inform user that the number they entered is unhappy
      }
?>


and the code of the form, javascript blocking thingy and php calculator....

Code: Select all

<?
if (!$number) {
?>
   <html>
<head>
   <title>Happy Numbers!</title>
   <script language="JavaScript">
      var numb = "0123456789";
      function res(t,v){
         var w = "";
         for (i=0; i < t.value.length; i++) {
            x = t.value.charAt(i);
            if (v.indexOf(x,0) != -1)
            w += x;
         }
         t.value = w;
      }
</script>
</head>
<body>
<form  name="number_form" action="<? echo $_SERVER[PHP_SELF]; ?>" method="post" onSubmit="return checkban()">
<input name="number" type="text" onkeyup="res(this,numb);" >
<input type="submit" value="is this number happy?">
</FORM>
<script language="JavaScript1.2">
function checknumber(){
var x=document.number_form.number.value
var anum=/(^\d+$)|(^\d+\.\d+$)/
if (anum.test(x))
testresult=true
else{
alert("Only a number can be checked - please only enter numeric characters!")
testresult=false
}
return (testresult)
}
</script>
<script>
function checkban(){
if (document.layers||document.all||document.getElementById)
return checknumber()
else
return true
}
</script>
</body>
</html>
<?
} else {
$_POST[number] = $number;
if ($number == "0") {
   echo "Zero is special and cannot be tested as being happy or unhappy - consider it like just an 'ok' number!";
   } else {
      while (($number != "1") && ($number != "4")){
         $array = preg_split('//', $number, -1, PREG_SPLIT_NO_EMPTY); //creating an array in which each element is a digit of the entered number
         foreach ($array as $value) { //goes through each digit
            $value = $value * $value; //squares them
            $newarray[] = $value; //stores new value in an array of their own
         }
         $number = array_sum($newarray); //calculating the sum of the squared elements in the new array
         unset($newarray); //clearing the array for use in next loop
      }
      if ($number == "1") {
         echo "$_POST[number] <b>is</b> a happy number!"; //inform user that the number they entered is happy
      } else {
         echo "$_POST[number] <b>is not</b> a happy number!"; //inform user that the number they entered is unhappy
      }
   }
}
?>
User avatar
NeoThermic
Introversion Staff
Introversion Staff
Posts: 6256
Joined: Sat Mar 02, 2002 10:55 am
Location: ::1
Contact:

Postby NeoThermic » Sun Oct 24, 2004 1:49 am

Hmm. My PHP version is miniture. I just go all comment happy :D

Code: Select all

<?PHP

/************************************************************************
*         HappyNumber.php               *
*            -------------------            *
*   Begin:      Saturday, Oct 16, 2004            *
*   Copyright:   (C) NeoThermic.com            *
*   Email:         scripts@neothermic.com         *
*                           *
************************************************************************/

/************************************************************************
*         Description               *
*                           *
*   This script calculates if a number is happy or not. Happy    *
*   numbers are decsribed here:               *
*   http://mathworld.wolfram.com/HappyNumber.html         *
*                           *
************************************************************************/


error_reporting(E_ALL ^ E_NOTICE); //cap the errors.

$computed = array();

//function IsHappy
//takes: Double input
//output: true if input is happy, false if otherwise.



function IsHappy ($input) {
//ok, to start, we need an empty array to store the already computed numbers
//(Unhappy numbers have eventually periodic sequences of Si which do not reach 1)
$runtot = 0;
global $computed;

//first, 1 is happy. Echo out true if so
if ($input == 1) {
   return true;
}
//force the input to be a string so we can use the natrual string array
$input = (string)$input;
   //calculate the sum of the square of the digits of the input
   for ($i = 0; $i <  strlen($input); $i++) {
      $runtot += ($input[$i] * $input[$i]);
   }
   
//ok, now check if result is 1
if ($runtot == 1) {
   //happy!
   echo " <br>  Si(A) : $runtot  <br>" ;
   return true;
   //exit;
}

//check result is not repeated

if (in_array( $runtot, $computed)) {
   //if it is, its not happy
   echo " <br>  Si(b) : $runtot  <br>" ;
   return false;
   exit;
} else {   
   //put result into an array
   $computed[] = $runtot;
   echo " <br>  Si(c) : $runtot  <br>" ;
}

//call itself with the new number
IsHappy($runtot);

}

?>


I ran into a weird return problem, which is why the echo's are labled Si(a), Si(b), and Si(c). If it ends out with an echo on line Si(a), then the number is happy, on a c, the number isn't 1 and doesn't repeate (and thus is going into the array), and if it echos out on b, then the number isn't happy.

NeoThermic
User avatar
LLamaBoy
level5
level5
Posts: 1627
Joined: Sun Aug 18, 2002 12:18 pm
Location: Cyprus
Contact:

Postby LLamaBoy » Sun Oct 24, 2004 5:11 am

ODDin wrote:LLama, can you please post your VB solution as well?


Ok, here you go.

Code: Select all

'LLamaBoy's VB Happy number checker.
'16/10/2004
'refer to the java implementation, basic funtionality is the same

Public Class Form1
    Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        'This call is required by the Windows Form Designer.
        InitializeComponent()

        'Add any initialization after the InitializeComponent() call

    End Sub

    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer. 
    'Do not modify it using the code editor.
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents NumberField As System.Windows.Forms.TextBox
    Friend WithEvents Go As System.Windows.Forms.Button
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.NumberField = New System.Windows.Forms.TextBox()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.Go = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'NumberField
        '
        Me.NumberField.Location = New System.Drawing.Point(8, 24)
        Me.NumberField.Name = "NumberField"
        Me.NumberField.Size = New System.Drawing.Size(232, 20)
        Me.NumberField.TabIndex = 0
        Me.NumberField.Text = ""
        '
        'Label1
        '
        Me.Label1.Location = New System.Drawing.Point(8, 8)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(80, 16)
        Me.Label1.TabIndex = 1
        Me.Label1.Text = "Enter number:"
        Me.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft
        '
        'Go
        '
        Me.Go.Location = New System.Drawing.Point(192, 56)
        Me.Go.Name = "Go"
        Me.Go.Size = New System.Drawing.Size(80, 24)
        Me.Go.TabIndex = 2
        Me.Go.Text = "Go!"
        '
        'Form1
        '
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(280, 85)
        Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.Go, Me.Label1, Me.NumberField})
        Me.Name = "Form1"
        Me.Text = "Happy numbers checker"
        Me.ResumeLayout(False)

    End Sub

#End Region

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Go.Click
        Dim number As Integer

        Try
            number = NumberField.Text
        Catch x As Exception
            MessageBox.Show("The number you entered is invalid.", "Invalid value", _
                MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

        If checkHappy(NumberField.Text.ToCharArray()) Then
            MessageBox.Show("The number " & number & " is happy! :D", "Happy", _
                MessageBoxButtons.OK, MessageBoxIcon.Information)
        Else
            MessageBox.Show("The number " & number & " is unhappy :(", "Not Happy", _
                MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub

    Function checkHappy(ByVal num As Char()) As Boolean
        If num = "1" Then
            Return True
        Else
            Dim i As Integer, _
                sum As Integer = 0, _
                nums As Integer() = New Integer(num.Length - 1) {}

            For i = 0 To nums.GetUpperBound(0)
                nums(i) = New String("" & num(i))
                nums(i) *= nums(i)
                sum += nums(i)
            Next

            If sum = 4 Then
                Return False
            End If

            Return checkHappy(New String("" & sum).ToCharArray())
        End If
    End Function
End Class


The actual Happy Numbers bit comes after the #End Region directive a little down from the middle.
camman977
level2
level2
Posts: 85
Joined: Wed Sep 29, 2004 10:45 pm
Location: Michigan, U.S.A.
Contact:

Postby camman977 » Sun Oct 24, 2004 2:07 pm

what is all that stuff at the top?
Image
User avatar
LLamaBoy
level5
level5
Posts: 1627
Joined: Sun Aug 18, 2002 12:18 pm
Location: Cyprus
Contact:

Postby LLamaBoy » Sun Oct 24, 2004 4:31 pm

It's the code generated by the VB IDE to create the actual GUI form for the user to enter the number and press a button.
ODDin
level5
level5
Posts: 2521
Joined: Fri Jul 04, 2003 10:44 pm
Location: Haifa, Israel
Contact:

Postby ODDin » Sun Oct 24, 2004 4:41 pm

Oh boy, you did it in VB.net...
What makes it a little bit hard for me to get, from the depths of my VB6. But I think I got the general idea.

Only few things I totally can't get:
1) You can condition a definition of a variable? Neat.

2) What do the "New String" and "New Ineger" things do, exactly? I know that in VB.net even strings and integers are considered objects, but how does that work?

3) WHY, oh WHY did you use recursion?
elDiablo
level5
level5
Posts: 3111
Joined: Thu Mar 14, 2002 12:23 pm
Location: London, UK

Postby elDiablo » Sun Oct 24, 2004 5:12 pm

Rar for GUIs and all

Code: Select all

// Happy numbers
// in GUI
// Leander Hambley
// 28/10/04
//////////////////

import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class HappyFrame extends JFrame implements ActionListener
{
   private JLabel happyLabel;
   private JTextField inputTextField;
   private JButton goButton;

   public HappyFrame()
   {
      super("HappyFrame");

      Container c = getContentPane();
      setSize(300,100);

      inputTextField = new JTextField("Enter a number here. Dont put text!");
      c.add(inputTextField, BorderLayout.NORTH);

      goButton = new JButton("Happify!");
      c.add(goButton, BorderLayout.CENTER);
      goButton.addActionListener(this);

      happyLabel = new JLabel("Happy/Sad results go here!");
      c.add(happyLabel, BorderLayout.SOUTH);

      setVisible(true);
   }

   public void actionPerformed(ActionEvent event)
   {
      happyLabel.setText(testTheHappyness(inputTextField.getText()));
   }

   public String testTheHappyness(String test)
   {
      // Set some lovely variables.
      int[] numbers;      // Array of numbers to be held.
      int inputLength,   // A variable for the first input's length.
         squareTest = 0,   // A tester to see if its happy happy joy joy.
         squareBest = 0,   // For the while loop. Go see.
         counter = 0;   // Surprise, surprise, a counter.

      // Make the variables in accordance with the input.
      inputLength = test.length();      // Yep. The input's length.
      numbers = new int[inputLength];      // The array. Some maths to cover it:
                                    // If the input is a 6-digit character,
                                    // and is split into 6 separate numbers,
                                    // and each of these is squared, the result
                                    // can merely be placed over the original
                                    // separate numbers. Hence, the smallest poss
                                    // array size is the length of the input.
                                    // THANK YOU! AND GOD NIGHT!


      // A while loop. Counts to 100,000, or stops when the square is 1.
      while (squareBest != 1 && counter < 100000)
      {
         // Put the test back to zero.
         squareTest = 0;

         // For loop to read in the different digits
         for (int i = 0; i < test.length(); i++)
         {
            numbers[i] = Integer.parseInt(test.substring(0,1));
            test = test.substring(1,test.length());
         }

         // For loop to square all digits.
         for (int i = 0; i < inputLength; i++)
         {
            numbers[i] = numbers[i] * numbers[i];
         }

         // For loop to all the squares.
         for (int i = 0; i < inputLength; i++)
         {
            squareTest = squareTest + numbers[i];
         }
         
         // Reset the input to the new square if it failed to be 1.
         test = new Integer(squareTest).toString();

         // Test to see if its 1. If so, the while loop DIES.
         squareBest = squareTest;

         // So it aint an infinite loop and all.
         counter++;
      }

      // Final HAPPY/SAD test.
      if (squareTest == 1)
         return "HAPPY =o";
      else
         return "SAD =(";
   }

   public static void main(String argvs[])
   {
      HappyFrame hf = new HappyFrame();
      hf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}


Yay for Java. Conversion from all code to shiny new stuff: 3minutes. No, I didnt submit this, but rar for human knowledge.
We dont stop playing cos we get old... We get old cos we stop playing.

Return to “General”

Who is online

Users browsing this forum: No registered users and 19 guests