# Programming Challenge (Out-of-Date)



## BFRD

Times up, Xaimus is the only one that got an entry in.

Code:



Code:


#include <iostream>
#include <string>
#include <sstream>

using namespace std;

string intToStr(int);
bool isNumber(char);
bool isNegate(char);

int main(int argv, char** argc) {
    if (argv < 2) {
        cout << "usage: \
"
             << argc[0] << " list,of,integers\
";
        return 1;
    }

    string list = argc[1], output;
    bool start = true, chain = false, negate = false;
    int current = 0, next = 0, i = 0;

    while (isNumber(list[i]) || isNegate(list[i])) {
        if (isNumber(list[i])) {
            current = (current * 10) + (list[i] - '0');
        } else {
            negate = !negate;
        }
        i++;
    }
    if (negate) {
        current *= -1;
    }

    while (i < list.length()) {
        negate = false;
        next = 0;

        if (isNumber(list[i]) || isNegate(list[i])) {
            while(isNumber(list[i]) || isNegate(list[i])) {
                if (isNumber(list[i])) {
                    next = (next * 10) + (list[i] - '0');
                } else {
                    negate = !negate;
                }
                i++;
            }
            if (negate) {
                next *= -1;
            }

            if (next - 1 == current) {
                if (!chain) {
                    if (start) {
                        start = false;
                    } else {
                        output += ',';
                    }
                    output += intToStr(current) + '-';
                    chain = true;
                }
            } else {
                if (chain) {
                    output += intToStr(current);
                    chain = false;
                } else {
                    if (start) {
                        start = false;
                    } else {
                        output += ',';
                    }
                    output += intToStr(current);
                }
            }
            current = next;
        } else {
            i++;
        }
    }

    if (chain || start) {
        output += intToStr(next);
    } else {
        output += ',' + intToStr(next);
    }
    cout << output << endl;
    return 0;
}

string intToStr(int x) {
    ostringstream o;
    o << x;
    return o.str();
}

bool isNumber(char x) {
    return x <= '9' && x >= '0';
}

bool isNegate(char x) {
    return x == '-';
}


----------



## BFRD

OK, Here is the next challenge.

Create a web-based application to display Pascals Triangle. Please allow your code to create any number of levels based on user input. Also include processing time.

Ex. (excuse spacing)

1
11
121
1331

Excuted to 4 levels.

Deadline for entries is Feb. 10th 11:59 PM GMT-6.


----------



## FaKk2

10 minutes of coding
5 minutes of refreshing PHP knowledge
5 minutes for debugging and formatting









Code:



Code:


<?
/* Challenge #2
Pascal Triangle
$_GET['level'] represents the triangle's level.
*/

$level = $_GET['level'];
$triangle = array();

$triangle[0][0] = 1;
for ($i = 1; $i < $level; $i++)
{
    $triangle[$i][0] = 1;
    $triangle[$i][count($triangle[$i-1])] = 1;
    for ($j = 1; $j < count($triangle[$i-1]); $j++)
    {
        $triangle[$i][$j] = $triangle[$i-1][$j-1] + $triangle[$i-1][$j];
    }
}

echo "[TABLE]";
for ($i = 0; $i < $level; $i++)
{
    echo "[TR]";
    for ($j = 0; $j < count($triangle[$i]); $j++)
        echo "[TD]".$triangle[$i][$j]."[/TD]";
    echo "[/TR]";
}
echo "[/TABLE]";
?>

Could be improved of course. For example get rid of the multidimensional array and render directly.


----------



## BFRD

Quote:


Originally Posted by *FaKk2*
10 minutes of coding
5 minutes of refreshing PHP knowledge
5 minutes for debugging and formatting









Code:



Code:


<?
/* Challenge #2
Pascal Triangle
$_GET['level'] represents the triangle's level.
*/

$level = $_GET['level'];
$triangle = array();

$triangle[0][0] = 1;
for ($i = 1; $i < $level; $i++)
{
    $triangle[$i][0] = 1;
    $triangle[$i][count($triangle[$i-1])] = 1;
    for ($j = 1; $j < count($triangle[$i-1]); $j++)
    {
        $triangle[$i][$j] = $triangle[$i-1][$j-1] + $triangle[$i-1][$j];
    }
}

echo "[TABLE]";
for ($i = 0; $i < $level; $i++)
{
    echo "[TR]";
    for ($j = 0; $j < count($triangle[$i]); $j++)
        echo "[TD]".$triangle[$i][$j]."[/TD]";
    echo "[/TR]";
}
echo "[/TABLE]";
?>

Could be improved of course. For example get rid of the multidimensional array and render directly.

Very nice. I didn't think of doing that way, I used a mathmatical formula to produce the results. Nice job of thinking simple. It is often times the simplest solution that is the best.


----------



## BFRD

OK, I borrowed this one from another site.

Find the largest number less than 100 quintillion* which is a palindrome and is also divisible by all primes between 10 and 30.

* American quintillion

EDIT: All entries must also include a manner of documenting how long it takes to find the answer.

PM me your answer and it if is correct I will then post your code after the deadline. Until then I will just post who completed here. The deadline for entries is Oct 14th. As stated before this is from a know challenge site, so don't just google the answer. This is about programming not the use of google.









===========================================
Results
===========================================

*rabidgnome229: Solution in Progress*
*Burn: Solution in Progress
FrankenPC: Completed Challenge (~15 seconds)
someone153: Solution in Progress
sniperscope: Completed Challenge (~5 seconds)*


----------



## BFRD

Ok times up.

sniperscope and FrankenPC completed the challenge.

Kudos go to both members as they were able to use some lateral thinking and come up with a solution without using the obvious route. In this particular case the obvious route would have been to start with the largest possible number "99999999999999999999" and work your way down until a match was found. As some of you found out that this takes a very very long time. What I found most interesting about this excersize is that the two solutions are completely different. I will post my code and a brief explanation of what I did. I will let the other two guys do the same.

My Way (which as it turns out isn't the fastest):

Code:



Code:


 class Program
{
static void Main(string[] args)
{
//Initialize Timer
DateTime startTime = DateTime.Now;

//Set Roof
decimal iRoof = 9999999999M;
//Go
for (decimal i = iRoof; i > 0; i--)
{
bool bResult = CheckNumber(i);
if (bResult)
{
Console.WriteLine(AssembleNumber(i).ToString());
break;
}
}
//Stop Timer
DateTime stopTime = DateTime.Now;
//Calculate Time and Display
TimeSpan duration = stopTime - startTime;
Console.WriteLine("Execution Time: " + duration);
//Keep the Window Open
Console.WriteLine("\
\
q <enter> to quit.");
while (Console.Read() != 'q') ;
}
static bool PrimeCheck(decimal iNumber)
{
//11 13 17 19 23 29 
if (iNumber % 29 != 0)
return false;
if (iNumber % 23 != 0)
return false;
if (iNumber % 19 != 0)
return false;
if (iNumber % 17 != 0)
return false;
if (iNumber % 13 != 0)
return false;
if (iNumber % 11 != 0)
return false;
return true;
}
static bool CheckNumber(decimal dblNumber)
{ 
//Assemble Number
decimal dblPalindrome = AssembleNumber(dblNumber);
//Check Prime
if (PrimeCheck(dblPalindrome))
{
return true;
}
else
{
return false;
}
}
static decimal AssembleNumber(decimal dblNumber)
{
string tFirst = dblNumber.ToString();
char[] arLast = dblNumber.ToString().ToCharArray();
Array.Reverse(arLast);
string tLast = new string(arLast);

return Convert.ToDecimal(tFirst + tLast);
}
}

Since I knew we were dealing with palindromes I decided to assemble palindromes rather than look for them. I knew my largest possilbe palindrome was "99999999999999999999" so I split that number in half making 9999999999. Using that as a base to start from I decreased the base number by one, and then assembled a 20 digit palindrome using a custom function. To assemble the palindrom I converted my number to a string, and then converted the string to character array. Once I had the array, I reversed the array and then conatenated the original string with the new reversed string. So for my first loop (actually second) my base number was 9999999998 and the assembled palindrome being 99999999988999999999. From then I just checked each number for being divisible by the set of prime numbers. I used the modal method to determine if the number was evenly divisible and broke out of the function as soon as my test palindrome failed one of the divisible tests. So there isn't much to it, just took a little time out of the box to make it effcient.

EDIT: I will enclose my compiled program here. I promise it is trojan/virus free. Your results may vary. I get just a little under 7.5 seconds on my home rig. (but please lets not turn this into a benchmark thread







).


----------



## sniperscope

My entry:

Code:



Code:


Public Class Form1

    Public a As Decimal = 99999999999999999999D

    Public Sub go()
        Me.Text = "Running..."
        Dim time1 As Decimal = Now.Ticks
        For h As Integer = 0 To 9
            For g As Integer = 0 To 9
                For f As Integer = 0 To 9
                    For e As Integer = 0 To 9
                        For d As Integer = 0 To 9
                            For c As Integer = 0 To 9
                                For b As Integer = 0 To 9
                                    If frac(a / 30808063) = 0 Then GoTo 1
                                    a -= 11000000000D
                                Next
                                a += 9900000000D
                            Next
                            a += 990000000D
                        Next
                        a += 99000000D
                    Next
                    a += 9900000D
                Next
                a += 990000D
            Next
            a += 99000D
        Next
        MessageBox.Show(a & Environment.NewLine & "Multiple not Found...")
        GoTo 2
1:      Dim time2 As Decimal = Now.Ticks
        Me.Text = "Complete"
        Dim processtime As Decimal = ((time2 - time1) / 10000000)
        MessageBox.Show(a & Environment.NewLine & "Processing Time: " & processtime, "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information)
        TextBox1.Text = a
2:
    End Sub

    Public Function frac(ByVal num As Decimal)
        Return Math.Floor(num) - num
    End Function

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        a = 99999999999999999999D
        go()
    End Sub
End Class

Answer:

99976239844893267999

Divisible by primes:

99976239844893267999 / 11 = 9088749076808478909
99976239844893267999 / 13 = 7690479988068712923
99976239844893267999 / 17 = 5880955284993721647
99976239844893267999 / 19 = 5261907360257540421
99976239844893267999 / 23 = 4346793036734489913
99976239844893267999 / 29 = 3447456546375629931

Solved in 5.421875 seconds on 2.6Ghz Oc'd Athlon 64 3800+ proccy.


----------



## FrankenPC

This is how I dit it. Same concept as BFRD, slightly different code (VB.NET 2.0). NOTE: Only because the answer is so close to the starting position is the viable.

Dim I As Decimal

Dim Stringpart As String
Dim Reverse As String
Dim NewString As String
Dim NewNumber As Decimal

Dim Counter As Int32 = 0
Dim TotalCount As Int32 = 0

Dim Quint As Decimal = 9999999999

For I = Quint To 1 Step -1

Stringpart = I.ToString

'Need to adjust behavior due to even/odd Palindromes
If I Mod 2 = 0 Then
Reverse = StrReverse(Stringpart)
Else
Reverse = StrReverse(Microsoft.VisualBasic.Left(Stringpart, Len(Stringpart) - 1))
End If

NewString = Stringpart & Reverse
Decimal.TryParse(NewString, NewNumber)

If NewNumber Mod 11 = 0 Then
If NewNumber Mod 13 = 0 Then
If NewNumber Mod 17 = 0 Then
If NewNumber Mod 19 = 0 Then
If NewNumber Mod 23 = 0 Then
If NewNumber Mod 29 = 0 Then
msgbox (NewString) 'palindrome found
End If
End If
End If
End If
End If
End If

Next


----------



## BFRD

Here is a challenge from one of our members, ravicus. Lets make an old-school style encoder/decoder. Some of you may remember the decoder rings that used to come in cereal boxes. Where you could twist one set of the alphabet around to line up with the inner set. I will do my best to demonstrate with numbers only:

1234567890
8901234567

So 8004 = 1337.

I want you to create a system to encode and decode messages using a simple shift substitution as outlined above. You should allow for letters and numbers (case is up to you). Leave spaces and punctuation alone. You also need to figure out a way to set the shift. So if you send a message to your buddy, he knows what shift to use to decode your message. Understandably the shift method is much easier to break than a random substitution, but much easier when it comes to setting a key.

As always any common programming language is fine. Just make sure any exes you submit are clean. If you use a web based approach- No Ads!

Happy Programming, and lets give a round of thanks to ravicus for the idea. Let's set the deadline for submissions at May 18th 9:00 PM CST.


----------



## BFRD

Here is my application. It requires the .NET framework v2. It is very basic, and a little flawed. Enter in a message and press "Encode." You will then have a quasi-secret message that you can send to a friend. All they need to know is what setting you used to encode the message (using the slider at the bottom). Trial and error will of course get you to the appropriate value. This is entended to mostly show the weaknesses of shift encoding. I think when this challenge ends, we will try something more sophisticated.


----------



## dangerousHobo

Here's mine so far, I haven't been able to work on it for the past two days. Its a bit flawed too. I plan to work on it tonight and finish it.
To encode or decode you have to pass in a parameter when you run it.
Example:
Encode:

Code:


Code:


perl encode.pl -e

Decode:

Code:


Code:


perl encode.pl -d

Code:


Code:


#!/usr/bin/perl
use warnings;

#if the version of perl you are using is older than
#5.6, then get rid of the line "use warning;" and
#make the first line look like this: #!/usr/bin/perl -w

#array used for encoding and decoding
@code = ("A".."Z", "a".."z"," ",0..9);
$eString = "";
$index = 0;

#setting the shift
print "Enter shift => ";
chop($shift = <STDIN>);

if ($ARGV[0] =~ /[Ee]/) {

print "Enter a word => ";
#getting input and removing newline char.
chop ($word = <STDIN>);

$eString = &shifter ($word, '+');

#writing encoded word to file
open(OUTFILE, ">encode.txt");
print OUTFILE ($eString."\
");
close(OUTFILE);

} elsif ($ARGV[0] =~ /[Dd]/) {

unless (open(INFILE, "encode.txt")){
die("Cannot open the file encode.txt");
}
#reading line from file
$word = <INFILE>;
close(INFILE);

$eString = &shifter ($word, '-');

print $eString."\
";
}

sub shifter {
my ($word, $direction) = @_;

#making the string to an array, w/ one char per index
@wordA = split(//, $word);

#generating the encoded string
for (1..length($word)){
for ($i = 0; $i < @code; ++$i){
 if ($wordA[$index] eq $code[$i]){
if($direction eq '+'){
$eString .= $code[$i+$shift];
} else {
$eString .= $code[$i-$shift];
}
}
}
$index++;
}
return $eString;
}


----------



## rabidgnome229

Let's see if I can write this in a reply message









Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void encode(char *p, int key)
{
   if(*p>='a'&&*p<='z')
   {
      if(*p+key>'z') *p=*p+key-'z'+'0';
      else *p=*p+key;
   }else if(*p>='A' && *p<='Z')
      if(*p+key>'Z') *p=*p+key-'Z'+'a';
      else *p=*p+key;
   }else if(*p>='0' && *p<='9')
      if(*p+key>'9') *p=*p+key-'9'+'A';
      else *p=*p+key;
   }
}

void decode(char *p, int key)
{
   if(*p>='a'&&*p<='z')
   {
      if(*p-key<'a') *p=*p-key-'a'+'Z';
      else *p=*p-key;
   }else if(*p>='A' && *p<='Z')
      if(*p+key<'A') *p=*p-key-'A'+'9';
      else *p=*p+key;
   }else if(*p>='0' && *p<='9')
      if(*p+key<'0') *p=*p-key-'0'+'z';
      else *p=*p+key;
   }
}
int main(int argc, char *argv[])
{
   int key=3; /* Default encoding/decoding key */
   char *string, *p1, mode;

   if(argc<3 || argv[1][0] != '-') {printf("Usage: %s [flag] [string]\
Flags: -e Encode [string]\
-d Decode [string]", argv[0]); exit(EXIT_FAILURE);

   mode=argv[1][1];

   if(argc==4) key=atoi(argv[3]);
   strcpy(string, argv[2]);

   for(p1=string; *p1; p1++)
      if(mode=='e') encode(p1, key);
      else if(mode=='d') decode(p1, key);
      else{printf("Invalid mode\
"); exit(EXIT_FAILURE);}

   printf("%s\
", string);
}

I wonder if that even compiles


----------



## decompiled

I was bored so I did one that included all ASCII. There might be bugs in it because I'm not testing every case.









Code:


Code:


#include <stdio.h>
#include <string.h>

int main()
{

  char mode;
  char c;
  char input[500];
  char output[500];
  int i = 0;
  int key;

  puts("Enter your message:");

  while( ( c = getchar() ) != '\
' )
  {
    input[i++] = c;
  }

  input[i] = '\\0';

  printf("Do you want to [D]ecode or [E]ncode: ");
  scanf("%c", &mode);

  if ( mode == 'D' )
  {
    printf("Enter your key: ");
    scanf("%i", &key);
    /* Subtract key from each index. */
    int count = 0;
    int length = strlen(input);
    while( count <= length - 1 )
    {
      char temp = input[count];
      temp -= key;
      output[count] = temp;
      count++;
    }
    output[count] = '\\0';
  }

  if ( mode == 'E' )
  {
    printf("Enter your key: ");
    scanf("%i", &key);
    /* Add key from each index */
    int length = strlen(input);
    int count = 0;
    while( count <= length )
    {
      char temp = input[count];
      temp += key;
      output[count] = temp;
      count++;  
    }
    output[count] = '\\0';
  }

  puts("");   
  puts("Your input was:");
  puts(input);
  puts(""); 
  printf("Your key was: %i\
",key);
  puts("");
  puts("Your request has produced:");
  puts(output);

  return 0;
}


----------



## BFRD

Ok. The encoder challenge is over. Stay tuned for the next installment. Thanks to everyone that participated.


----------



## venar303

Wow, this challenge is OLD! but hey, I'm new here so i don't really mind unearthing a dino!
Here's an encrypting program that is a bit simpler than bit shift, and more powerful as well!
http://uploader.polorix.net//files/594/encrypt7.exe

Tips
-change the string "key" to change how it's encrypted
-Notice how the decoding, is the same as encoding! It works backwards!
-The only encoding occurs in here, everything else is just getting input (poorly i admit)
while(x<= (count-2))
{
string[x]=string[x]^key[x]; ///XOR check on the binaries
cout<<string[x];
x++;
}

the code

#include <iostream.h>
#include <stdio.h>
#include <string.h> //provides strcat() --adds to end of string
#include <conio.h> //provides getch() --gets int for key press

int main()
{
char string[400]="";

char temp[] = "1";
char key[400]="I am the key used for encryption";
int count = 0;
cout<<"input string to encrypt or type enter to decode"<<endl;
while ((int)temp[0] != 13) //while not key_enter
{
count++;
temp[0] =(char)getch();
strcat(string,temp);
cout<<temp;
}
if (count==1)
{
count--;
temp[0]=1;
cout<<"input string to decode: ";
while ((int)temp[0] != 13)
{
count++;
temp[0] =(char)getch();
strcat(string,temp);
cout<<temp;
}
cout<<endl<<endl<<"decoded it is: ";
}
else
{ cout<<endl<<endl<<"You wrote: "<<string<< endl<<"encrypted it is: "<<endl; }

int x=0;
while(x<= (count-2))
{
string[x]=string[x]^key[x]; ///XOR check on the binaries
cout<<string[x];
x++;
}

cout<<endl<<" Decoded it is:\
"<<endl;
x=0;
while(x<= (count-2))
{
string[x]=string[x]^key[x];
cout<<string[x];
x++;
}

getch();
return 0;
}


----------



## charbs152

bump


----------



## kdbolt70

Man, if I wasn't getting owned by programming projects this semester I'd be all over working on some fun challenges.


----------



## JoBlo69

Quote:


Originally Posted by *kdbolt70* 
Man, if I wasn't getting owned by programming projects this semester I'd be all over working on some fun challenges.

Second that. ^^


----------



## dangerousHobo

Yeah, been having one after another.








Not been getting owned, but they are eating up all my time.

Right now I have to basically build the TCP protocol out of UDP.


----------



## kdbolt70

I'm now in my third iteration of a spell checker. The first was only in C, using C strings, the second was in C++ but with out the <string> class, so we had to write our own, and our own ordered container. Now we get to use all of the standard library, but have tons of new features. Ugh... so much work. In DB class we're simulating a database using C++. And in my Java class I have some new project out but I didn't go to class so I have no idea what it is







.

3 programming classes = getting owned. Off to the library to study for my DB exam tomorrow


----------



## Admiral Doom

Here's my response- its written for the Java Console. Put this into Eclipse or something, compile, and run...it'll do the job. You I know there's a more efficient way to manage the encoding key for decoding text, but i don't really have a lot of time right now (exams for high school).

import java.util.*;
public class Encode
{

static Scanner scan;
public static void main(String[] args)
{
final int tSize = 200;
scan = new Scanner(System.in); 
System.out.println("Would you like to <1> Encode or <2> Decode a message?");
if(scan.nextInt()==1)
encode(tSize);
else
decode(tSize);
}
public static void encode(int tableSize)
{
Hashtable<Character, Character> table = new Hashtable<Character, Character>();
table.put((char)0, (char)tableSize);
for(int i=1; i<tableSize-1; i++)
table.put((char)i, (char)(i+1));
String input="", output="";
System.out.println("Hey, input a string!");
scan = new Scanner(System.in);
input = scan.nextLine();
for(int i=0; i<input.length(); i++)
{
output+=""+table.get(input.charAt(i));
}
System.out.println("This is the encoded text: "+output);
}
public static void decode(int tableSize)
{
Hashtable<Character, Character> table = new Hashtable<Character, Character>();
table.put((char)tableSize, (char)0);
for(int i=2; i<tableSize; i++)
table.put((char)i, (char)(i-1));
String input="", output="";
System.out.println("Hey, input an encoded string!");
scan=new Scanner(System.in);
input = scan.nextLine();
for(int i=0; i<input.length(); i++)
{
output+=""+table.get(input.charAt(i));
}
System.out.println("This is the decoded text: "+output);
}

}

Oh crap...the indents are screwed up. Lemme zip it up real quick


----------



## Admiral Doom

Ok it should be here...unzip and open with Eclipse


----------



## arjo_reich

Quote:



Originally Posted by *BFRD*


Ok. The encoder challenge is over. Stay tuned for the next installment. Thanks to everyone that participated.


Just stumbled into the thread, I'll look forward to the next installment. By the way, for anyone that was curious, the specific name of that type of cipher is called a "ceasar shift" ... because Julius Ceasar (supposedly) used a three character shift pattern as a means of communicating securely with his generals. :shrug:


----------



## Butterbum

When is the next challenge comming? These look awfully easy







. How about a 24 hour challenge?


----------



## hometoast

Quote:


Originally Posted by *Butterbum* 
When is the next challenge comming? These look awfully easy







. How about a 24 hour challenge?


Yes yes!


----------



## Butterbum

Quote:



Originally Posted by *hometoast*


Yes yes!


If you could pull enough people together for a 24h session i could moderate it and come up with a few challenges, ive done my fair share of them and know a few good ones


----------



## dangerousHobo

I'd love to start some more challenges. We'd need to have some that are fairly hard and some that can be easy as not everyone is at the same level here and we want to include as many people as possible. Post up some possible challenges and we can move forward from there. A 24 hour challenge sounds fun too.


----------



## heretic

Why not use the ACM programming contest stuff? One of my profs has a bunch of the problem sets on his school web space, but you'd have to trust people not to cheat and look at the answers.


----------



## hometoast

OOoooRR! I could post some problems I have *cough* at work









I'm not lazy! I'm efficient!


----------



## dangerousHobo

If we use some of the ACM challenges I don't think it'll matter that the answers can be found. You would be able to tell if they and you can find the answers to a lot of small programming problems with some searching.








If you have some challenges that could be used, then please post them or provide a link so we can start organizing everything!


----------



## BFRD

Please send all suggestions via PM to Hobo or myself. If we post them here members will be able to get a head-start and potentially ruin a time based challenge. Hopefully we can get this rolling again.


----------



## iridia912

If you guys are interested in more programming challenges for the time being, check out www.hackthissite.org and click on "Programming" missions on the left hand side.


----------



## ouroboros1827

Not to beat a dead horse, but I just noticed this thread (haven't been on this site in months). Tried the first one; took a while, mostly because it's haha, my first python program (learning, after years of java). Not perfect but working and...readable









Code:


Code:


import sys

input = "1,2,3,5,10,11,12,13,25,26"

if len(sys.argv) > 1:
    input = sys.argv[1]

list = input.split(",")

output = ""
run = 0

for i in range(0, len(list)):
    if i == 0 or output[-1] == ",":
        output += list[i]

    elif int(list[i]) == int(list[i-1]) + 1:
        run = 1
        pass

    else: 
        if run:
            output += "-" + list[i-1]
        output += "," + list[i]
        run = 0

if run:
    output += "-" + list[-1]

print output


----------



## ouroboros1827

Ok I did the third one (screw pascal, hehe).

First time I went through all the numbers divisible by that big factor, then checked each for palindromicityness







Took FOREVER...

Code:


Code:


def isPalindrome(num):
    return str(num) == str(num)[::-1]

factor = 11*13*17*19*23*29
max = 99999999999999999999

quotient = max / factor
num = factor * quotient

while not isPalindrome(num):
    quotient = quotient - 1
    num = factor * (quotient)
    print "testing " + str(num)

print "found it: " + str(num)

Second time I went through all the palindromes and checked for division...MUCH quicker...

Code:


Code:


import sys

factor = 11*13*17*19*23*29

for a in range(9,0,-1):
    for b in range(9,0,-1):
        for c in range(9,0,-1):
            for d in range(9,0,-1):
                for e in range(9,0,-1):
                    for f in range(9,0,-1):
                        for g in range(9,0,-1):
                            for h in range(9,0,-1):
                                for i in range(9,0,-1):
                                    for j in range(9,0,-1):
                                        num = 10000000000000000001 * a + 
                                               1000000000000000010 * b + 
                                                100000000000000100 * c + 
                                                 10000000000001000 * d + 
                                                  1000000000010000 * e + 
                                                   100000000100000 * f + 
                                                    10000001000000 * g + 
                                                     1000010000000 * h + 
                                                      100100000000 * i + 
                                                       11000000000 * j;
                                        if num % factor == 0:
                                            print "found it: " + str(num)
                                            sys.exit(0)

Code:


Code:


$ time p 2a.py
found it: 99976239844893267999

real    0m7.547s
user    0m7.506s
sys     0m0.033s


----------



## dangerousHobo

Quote:



Originally Posted by *ouroboros1827*


Not to beat a dead horse, but I just noticed this thread (haven't been on this site in months). Tried the first one; took a while, mostly because it's haha, my first python program (learning, after years of java). Not perfect but working and...readable









Code:


Code:


import sys

input = "1,2,3,5,10,11,12,13,25,26"

if len(sys.argv) > 1:
    input = sys.argv[1]

list = input.split(",")

output = ""
run = 0

for i in range(0, len(list)):
    if i == 0 or output[-1] == ",":
        output += list[i]

    elif int(list[i]) == int(list[i-1]) + 1:
        run = 1
        pass

    else: 
        if run:
            output += "-" + list[i-1]
        output += "," + list[i]
        run = 0

if run:
    output += "-" + list[-1]

print output


For fun I did the first one too. Used ruby

Code:


Code:


#!/usr/bin/env ruby

org = ARGV.to_s.split(/,s*/).map {|n| n.to_i}.sort.uniq
con = org.first.to_s
one = true
for n in 1...org.size.to_i
    if org[n].to_i > org[n-1]+1
        con.concat "#{org[n-1]},#{org[n]}" if not one
        con.concat ",#{org[n]}" if one
        one = true 
    elsif one
        con.concat "-" and one = false
    end    
end
p con

Code:


Code:


anomaly  [~]  
$ time ruby convert.rb 1,2,8,4,12,34,15,17,16
"1-2,4,8,12,15-17,34"

real    0m0.004s
user    0m0.000s
sys     0m0.004s


----------



## dangerousHobo

Just to give everyone a bit of a heads up, I plan to post a challenge Thursday (July 24) around 8pm EST. The dead line then I'm still not sure on. More details will come when the challenge is posted. I just wanted to give a heads up so no one (hopefully) sees the challenge at the last minute.


----------



## hometoast

Quote:



Originally Posted by *dangerousHobo*


Just to give everyone a bit of a heads up, I plan to post a challenge Thursday (July 24) around 8pm EST. The dead line then I'm still not sure on. More details will come when the challenge is posted. I just wanted to give a heads up so no one (hopefully) sees the challenge at the last minute.



will you post to this thread so we can get a subscription email?


----------



## dangerousHobo

Quote:



Originally Posted by *hometoast*


will you post to this thread so we can get a subscription email?


Yes, I will post the challenge here in this thread.


----------



## dangerousHobo

Hey everyone, here is the new challenge. This one did not sound to difficult, but I don't know what everyones skill level here is.

*The challenge:*
Create a program to convert a given dollar amount to written amounts. For example, the input $72.61 would output "seventy two dollars and sixty one cents". The dollar amount will be under $1000.00, so your program should be able to handle any dollar amount smaller then that.

Creativity, efficiency and elegance are weighed to decide the winner.

Any language is welcome.









It does not matter how you let someone enter an amount to your program, just as long as it has a dollar sign($) and a decimal point.

*Deadline:*
Wednesday July 30th at 11:59pm EST.

Wait to post your solutions till it's closer to the deadline. You don't want to give away how you solved it!
(We'll wait for a 24 hour challenge to see who can solve something first)

I plan to post another challenge then next Thursday at the same time (8:00pm _ish_ EST).

Post any questions you have.

If this is too easy or too hard then please let me know!


----------



## rabidgnome229

What are the parameter bounds? Should it be able to handle amounts in the hundreds? Thousands? Billions?


----------



## dangerousHobo

I set it to be under a thousand, so your program should be able to handle any dollar amount smaller then that, but you can go higher.


----------



## rabidgnome229

I just threw something together using a bash shell and ran into a problem. In bash $WHATEVER assumes WHATEVER is a variable (such as HOME or PATH) and expands it. Passing $12.11 expands $1 (to nothing) and passes only the string 2.11. In order to pass "$12.11" it must be in quotes or passed as \\$12.11


----------



## BiG O

So if we write this is something like java or c#, would it also be acceptable just to ask for the dollar amount? Maybe to allow someone to type as many as they want in a single line rather than having it stuctured like the run command you posted earlier. I'm going to assume yes while I start on this







.


----------



## dangerousHobo

Ok, it doesn't matter how someone can enter the amount to the program, just as long as it has a dollar sign($) and a decimal point.


----------



## BiG O

Quote:



Originally Posted by *dangerousHobo*


Ok, it doesn't matter how someone can enter the amount to the program, just as long as it has a dollar sign($) and a decimal point.


sounds good. Should be fun.


----------



## rabidgnome229

Here it is in C (not ideal for the task, but my default language) with the user input method. It does not check for erroneous input

Code:


Code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFF_SIZE 1024

char *toString(int num);
char *makeString(char *buffer);

int main(int argc, char **argv){

enum { file, arguments } mode;  //describes input type
FILE *infile;
int i = -1;//counts argument position
char read_buffer[BUFF_SIZE], *string, *curr_pos, *decimal_ptr;
int dollars, cents;

printf("Enter a string begining with $ to convert: ");
while(fgets(read_buffer, BUFF_SIZE, stdin)){
string = read_buffer;

curr_pos = string;
if(*curr_pos != '$'){
printf("Done converting, exitingn");
exit(1);
}

/* separate decimal from whole number amount */
while(*curr_pos && (*curr_pos != '.')) curr_pos++;
*curr_pos = '';
decimal_ptr = ++curr_pos;
curr_pos = string + 1;

/* get integer values of dollars/cents */
dollars = atoi(curr_pos);
cents = atoi(decimal_ptr);
char *d = (dollars == 1) ? "dollar" : "dollars";
char *c = (cents == 1) ? "cent" : "cents";

printf("%s %s and %s %sn", toString(dollars), d, toString(cents), c);
printf("Enter a string begining with $ to convert: ");
}
}

char *toString(int num){

char *ones[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
char *teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
char *tens[] = {"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };
char buffer[1024], *buff_ptr = buffer, *ret;
buffer[0] = '';

if(num == 0) return makeString(ones[0]);

int index = num/100;
if(index){
strcpy(buff_ptr, ones[index]);
buff_ptr += strlen(ones[index]);
*buff_ptr++ = ' ';
strcpy(buff_ptr, "hundred");
buff_ptr += strlen("hundred");
*buff_ptr = '';
}
num %= 100;

index = num/10;
if(index){
if(buffer[0])
*buff_ptr++ = ' ';

if(index == 1){
strcpy(buff_ptr, teens[num-10]);
return makeString(buffer);
}

strcpy(buff_ptr, tens[index-2]);
buff_ptr += strlen(tens[index-2]);
*buff_ptr = '';
}
num %= 10;

if(num){
if(buffer[0])
*buff_ptr++ = ' ';
strcpy(buff_ptr, ones[num]);
}

return makeString(buffer);
}

char *makeString(char *buffer){
char *ret;
size_t len = strlen(buffer);
if(len > 1024) return NULL;

ret = malloc(sizeof(char) * len);
strcpy(ret, buffer);
}


----------



## BiG O

Good job man. I haven't even started yet haha.


----------



## dangerousHobo

I did want solutions posted so early but I guess it doesn't really hurt.









Edit: looks a little messy if you don't know ruby, but works.

Code:


Code:


$ time ruby challenge_1.rb $56.08
"fifty six dollars and eight cents"

real0m0.008s
user0m0.004s
sys0m0.003s

Code:


Code:


#!/usr/bin/ruby

d1 = ARGV.shift

ones = { 0 => "", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 
         5 => "five", 6 => "six", 7 => "seven", 8 => "eight", 9 => "nine",
         10 => "ten", 11 => "eleven", 12 => "twelve", 13 => "thirteen", 14 => "fourteen",
         15 => "fifteen", 16 => "sixteen", 17 => "seventeen", 18 => "eighteen", 19 => "nineteen" }

tens = { 0 => "", 1 => "ten", 2 => "twenty", 3 => "thirty", 4 => "fourty", 
         5 => "fifty", 6 => "sixty", 7 => "seventy", 8 => "eighty", 9 => "ninety" }

d1 = d1.split('').map {|x| x.to_i}
d1.shift
d1[-3] = '.'
f = String.new
f = "#{ones[d1.shift]} hundred and " if d1.join.to_f > 100
if d1.join.to_f > 20.00
  f.concat "#{tens[d1.shift]} #{ones[d1.shift]} dollars "
else
  f.concat "#{ones[d1.shift]} #{ones[d1.shift]} dollars "
end
d1.shift
if d1.join.to_i < 20
  f.concat "and #{ones[d1.join.to_i]} cents"
else
  f.concat "and #{tens[d1.shift]} #{ones[d1.shift]} cents"
end

p f


----------



## alawadhi3000

Here's my code in C++

Code:


Code:


#include<iostream>
using namespace std;

//Printing Function
void print(int a)
{

int temp;
temp=a;
int i=0;
int tens=0;
int temp2;

temp2=temp;
i=temp2/100;
if(i==1) cout<<"One";
else if(i==2) cout<<"Two";
else if(i==3) cout<<"Three";
else if(i==4) cout<<"Four";
else if(i==5) cout<<"Five";
else if(i==6) cout<<"Six";
else if(i==7) cout<<"Seven";
else if(i==8) cout<<"Eight";
else if(i==9) cout<<"Nine";
if(i>0 && i<10)
cout<<" Hundred ";

temp2=temp;
i=temp2%100;
i=i/10;
if(i>0)
{
if(i==2) cout<<"Twenty";
else if(i==3) cout<<"Thirty";
else if(i==4) cout<<"Fourty";
else if(i==5) cout<<"Fifty";
else if(i==6) cout<<"Sixty";
else if(i==7) cout<<"Seventy";
else if(i==8) cout<<"Eightty";
else if(i==9) cout<<"Ninety";
tens=i;
cout<<" ";
}

temp2=temp;
i=temp2%10;

if(tens==1)
{
if(i==1) cout<<"Eleven";
else if(i==2) cout<<"Twelve";
else if(i==3) cout<<"Thirteen";
else if(i==4) cout<<"Fourteen";
else if(i==5) cout<<"Fifteen";
else if(i==6) cout<<"Sixteen";
else if(i==7) cout<<"Seventeen";
else if(i==8) cout<<"Eighteen";
else if(i==9) cout<<"Nineteen";
}

else if(i>0)
{
if(i==1) cout<<"One";
else if(i==2) cout<<"Two";
else if(i==3) cout<<"Three";
else if(i==4) cout<<"Four";
else if(i==5) cout<<"Five";
else if(i==6) cout<<"Six";
else if(i==7) cout<<"Seven";
else if(i==8) cout<<"Eight";
else if(i==9) cout<<"Nine";
}

cout<<endl;
}
//end of Function

//Main
int main()
{
int amount=0;
char dollar;

cout<<"Menu"<<endl;

cout<<"Please Enter the amount with the dollar sign first"<<endl;
cin>>dollar>>amount;

while(amount<0 || amount>1000)
{
cout<<"Please Enter the amount with the dollar sign first"<<endl;
cin>>dollar>>amount;
}

print(amount);

int b;
cout<<"Enter anything to Exit"<<endl;
cin>>b;
return 0;
}

After I finished I realized that the program should accepts two numbers after decimal point

Also it only accepts entering the data manually as I wanted to code it fast

I will try to fix them later


----------



## rabidgnome229

From the version that accepts cmd line args

Code:


Code:


time ./a.out $56.08
fifty six dollars and eight cents

real0m0.004s
user0m0.001s
sys0m0.003s

C may be messy for this sort of task (string manipulation), but it is fast as always


----------



## rabidgnome229

Quote:



Originally Posted by *alawadhi3000*


Here's my code in C++

After I finished I realized that the program should accepts two numbers after decimal point

Also it only accepts entering the data manually as I want to code it fast

I will try to fix them later


FYI, instead of writing code like this

Code:


Code:


i=temp2/100;
if(i==1) cout<<"One";
else if(i==2) cout<<"Two";
else if(i==3) cout<<"Three";
else if(i==4) cout<<"Four";
else if(i==5) cout<<"Five";
else if(i==6) cout<<"Six";
else if(i==7) cout<<"Seven";
else if(i==8) cout<<"Eight";
else if(i==9) cout<<"Nine";

You should write

Code:


Code:


i=temp2/100;
switch(i){
 case(1) :
  cout << "One";
  break;
 case(2) :
  cout << "Two";
  break;

//etc, etc

}

It will run faster than cascading else if's


----------



## dangerousHobo

Quote:



Originally Posted by *rabidgnome229*


From the version that accepts cmd line args

Code:


Code:


time ./a.out $56.08
fifty six dollars and eight cents

real    0m0.004s
user    0m0.001s
sys    0m0.003s

C may be messy for this sort of task (string manipulation), but it is fast as always










Yeah thats the downside of scripting languages. I was interested though in seeing how much faster it would be in C.


----------



## alawadhi3000

Quote:


Originally Posted by *rabidgnome229* 
FYI, instead of writing code like this

Code:



Code:


i=temp2/100;
if(i==1) cout<<"One";
else if(i==2) cout<<"Two";
else if(i==3) cout<<"Three";
else if(i==4) cout<<"Four";
else if(i==5) cout<<"Five";
else if(i==6) cout<<"Six";
else if(i==7) cout<<"Seven";
else if(i==8) cout<<"Eight";
else if(i==9) cout<<"Nine";

You should write

Code:



Code:


i=temp2/100;
switch(i){
 case(1) :
  cout << "One";
  break;
 case(2) :
  cout << "Two";
  break;

//etc, etc

}

It will run faster than cascading else if's

I know, I did what I was fast at
There's a lot of methods (class, another function, using an array to store values ....etc) which is smaller/consumes less memory but as I told you I did what I'm fast at









Thanks anyway


----------



## dangerousHobo

Quote:


Originally Posted by *rabidgnome229* 
From the version that accepts cmd line args

Code:



Code:


time ./a.out $56.08
fifty six dollars and eight cents

real    0m0.004s
user    0m0.001s
sys    0m0.003s

C may be messy for this sort of task (string manipulation), but it is fast as always










The last time I tested its execution speed was on my macbook pro. I just ran in on my linux box (Slackware 12.1) and it was this.

Code:



Code:


$ time ruby challange_1.rb $56.04                                             
"fifty six dollars and four cents"

real    0m0.004s
user    0m0.004s
sys     0m0.000s

I think it would make sense as its not a very big program.


----------



## rabidgnome229

Quote:


Originally Posted by *dangerousHobo* 
The last time I tested its execution speed was on my macbook pro. I just ran in on my linux box (Slackware 12.1) and it was this.

Code:



Code:


$ time ruby challange_1.rb $56.04                                             
"fifty six dollars and four cents"

real    0m0.004s
user    0m0.004s
sys     0m0.000s

I think it would make sense as its not a very big program.

Mine was tested on the low end macbook









Here is the code for the command line version if you want to test for consistency

Code:



Code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BUFF_SIZE 1024

char *toString(int num);
char *makeString(char *buffer);

int main(int argc, char **argv){

enum { file, arguments } mode;  //describes input type
FILE *infile;
int i = -1;//counts argument position
char read_buffer[BUFF_SIZE], *string, *curr_pos, *decimal_ptr;
int dollars, cents;

if(argc < 2){
printf("Usage: ./a.out [filename][amount...]n");
exit(1);
}else if(argv[1][0] == '$'){
mode = arguments;
i = 1;
}else{
printf("Reading from filen");
mode = file;
infile = fopen(argv[1], NULL);
if(!infile){
printf("Unable to open %sn", argv[1]);
}
fgets(read_buffer, BUFF_SIZE, infile);
printf("%sn", read_buffer);
}

while(((i > 0) && (i < argc)) || ((i < 0) && fgets(read_buffer, BUFF_SIZE, infile))){
if(mode == file)
string = read_buffer;
else
string = argv[i++];

curr_pos = string;
if(*curr_pos != '$'){
printf("Formatting error on input: %sn", string);
exit(1);
}

/* separate decimal from whole number amount */
while(*curr_pos && (*curr_pos != '.')) curr_pos++;
*curr_pos = '';
decimal_ptr = ++curr_pos;
curr_pos = string + 1;

/* get integer values of dollars/cents */
dollars = atoi(curr_pos);
cents = atoi(decimal_ptr);
char *d = (dollars == 1) ? "dollar" : "dollars";
char *c = (cents == 1) ? "cent" : "cents";

printf("%s %s and %s %sn", toString(dollars), d, toString(cents), c);
}
}

char *toString(int num){

char *ones[] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
char *teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
char *tens[] = {"twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };
char buffer[1024], *buff_ptr = buffer, *ret;
buffer[0] = '';

if(num == 0) return makeString(ones[0]);

int index = num/100;
if(index){
strcpy(buff_ptr, ones[index]);
buff_ptr += strlen(ones[index]);
*buff_ptr++ = ' ';
strcpy(buff_ptr, "hundred");
buff_ptr += strlen("hundred");
*buff_ptr = '';
}
num %= 100;

index = num/10;
if(index){
if(buffer[0])
*buff_ptr++ = ' ';

if(index == 1){
strcpy(buff_ptr, teens[num-10]);
return makeString(buffer);
}

strcpy(buff_ptr, tens[index-2]);
buff_ptr += strlen(tens[index-2]);
*buff_ptr = '';
}
num %= 10;

if(num){
if(buffer[0])
*buff_ptr++ = ' ';
strcpy(buff_ptr, ones[num]);
}

return makeString(buffer);
}

char *makeString(char *buffer){
char *ret;
size_t len = strlen(buffer);
if(len > 1024) return NULL;

ret = malloc(sizeof(char) * len);
strcpy(ret, buffer);
}


----------



## dangerousHobo

Quote:


Originally Posted by *rabidgnome229* 
Mine was tested on the low end macbook









Here is the code for the command line version if you want to test for consistency


Thanks,

Haha









Code:



Code:


$ time ./a.out $56.09                                                         
 fifty six dollars and  nine cents
real    0m0.001s
user    0m0.000s
sys     0m0.000s


----------



## NeoDeGenero

Hmm, when's the next contest?
need to sharpen up my programming skills again =D


----------



## rabidgnome229

Quote:



Originally Posted by *NeoDeGenero*


Hmm, when's the next contest?
need to sharpen up my programming skills again =D


You can still submit a solution to this one. Next one gets posted thursday according to DH


----------



## dangerousHobo

Hey guys. I'll be a little late on posting the next challenge. Worked late tonight! I'll try getting the next challenge though posted tonight.

As for the previous challenge, thanks rabidgnome229 and alawadhi3000 for participating.

rabidgnome provided the most efficient solution. Congrates!


----------



## dangerousHobo

*The Challenge:
*Create a program that takes a given list of scrambled words and searches a given word list and figures out what the scrambled words are.

Here are a few scrambled words that you can use to test with:

Code:


Code:


    hmyaaa
    lengod
    ouothns
    gitesnt
    nkpinu
    ikedoo
    pwtsaeee
    seengis
    shesinun
    brhoapeo

The attached file wordlist.txt contains a large list of words and the scrambled words above can be found in that file.

Like last challenge, you can either give the scrambled words to your program as parameters or from a file.

Creativity, efficiency and elegance are weighed to decide the winner.

Any language is welcome.









*Deadline:*
Wednesday August 7th at 5:00pm EST.

I'll continue to plan to post another challenge Thursday's at 8:00pm _ish_ EST.

Post any questions you have.


----------



## rabidgnome229

Quote:



Originally Posted by *dangerousHobo*


*The Challenge:
*Create a program that takes a given list of scrambled words and searches a given word list and figures out what the scrambled words are.

Here are a few scrambled words that you can use to test with:

Code:


Code:


    hmyaaa
    lengod
    ouothns
    gitesnt
    nkpinu
    ikedoo
    pwtsaeee
    seengis
    shesinun
    brhoapeo

The attached file wordlist.txt contains a large list of words and the scrambled words above can be found in that file.

Like last challenge, you can either give the scrambled words to your program as parameters or from a file.

Creativity, efficiency and elegance are weighed to decide the winner.

Any language is welcome.









*Deadline:*
Wednesday August 7th at 5:00pm EST.

I'll continue to plan to post another challenge Thursday's at 8:00pm _ish_ EST.

Post any questions you have.


There are things that are not words in your wordlist.


----------



## rabidgnome229

Attached is a zipped text file containing 172,000 actual words. We used it for a dictionary building program and it can serve as a stress test. I also attached a couple smaller dictionaries because a naive implementation will take an extremely long time on the 172,000 word dictionary


----------



## rabidgnome229

Here's my entry

Code:



Code:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BUFF_SIZE 1024

typedef struct List_Node_t{
char *word;
struct List_Node_t *next;
}ListNode;

typedef struct Trie_Node_t{
struct Trie_Node_t *children[26];
ListNode *head;
}TrieNode;

/* function prototypes */
void trim(char *string);
void insert(char *string, TrieNode *node);
void printScrambles(char *string, TrieNode *node);
int char_cmp(const void *c1, const void *c2);
void insertRec(char *word, char *sorted, TrieNode *node, int index);
void insertAtHead(ListNode **head, char *word);
void printRec(TrieNode *node, char *sorted, int index);

void printAll(TrieNode *node);

int main(int argc, char **argv){
//pathnames of input files
char *dictfile = "wordlist.txt", *listfile = "scrambles.txt";
FILE *infile; //handle to currently open file
char buffer[BUFF_SIZE]; //read buffer;
TrieNode *head = calloc(1, sizeof(TrieNode));

if(argc > 1){
dictfile = argv[1];
}
if(argc > 2){
listfile = argv[2];
}

infile = fopen(dictfile, "r");
if(!infile){
printf("Unable to open %s.  Exitingn");
exit(1);
}

//read words and insert into dictionary
while(fgets(buffer, BUFF_SIZE, infile)){
trim(buffer);
insert(buffer, head);
}

fclose(infile);
fopen(listfile, "r");
if(!infile){
printf("Unable to open %s.  Exitingn");
exit(1);
}

//find matches and print
while(fgets(buffer, BUFF_SIZE, infile)){
trim(buffer);
//printf("Unscrambling |%s|n", buffer);
printScrambles(buffer, head);
}

return 0;
}

/* 
 * Trims non-letter characters from end of a string
 */
void trim(char *string){
char *ptr;
for(ptr = string; ((*ptr >= 'a') && (*ptr <= 'z')) || ((*ptr >= 'A') && (*ptr <= 'Z')); ptr++);
*ptr = '';
}

/*
 * inserts given word into trie
 */
void insert(char *string, TrieNode *node){
char *sorted = calloc(strlen(string) + 1, sizeof(char));
strcpy(sorted, string);
qsort(sorted, strlen(sorted), sizeof(char), char_cmp);

char *copy = calloc(strlen(string) + 1, sizeof(char));
strcpy(copy, string);

//printf("-Inserting |%s| |%s|n", copy, sorted);
insertRec(copy, sorted, node, 0);
}

/*
 * compares two characters
 * for qsort
 */
int char_cmp(const void *c1, const void *c2){
return (*((char *)c1) - *((char *)c2));
}

/*
 * recursive method that inserts a word into the trie
 */
void insertRec(char *word, char *sorted, TrieNode *node, int index){
if(!sorted[index]){
//printf("-Targer node found.  Insertingn");
insertAtHead(&(node->head), word);
free(sorted);
return;
}

int trieIndex = (sorted[index] < 'a') ? (sorted[index] - 'A') : (sorted[index] - 'a');
//printf("-Looking at letter |%c|, index |%d|n", sorted[index], trieIndex);
if(!(node->children[trieIndex])){
//printf("-No Node found, creating newn");
node->children[trieIndex] = calloc(1, sizeof(TrieNode));
}

insertRec(word, sorted, node->children[trieIndex], index+1);
}

/*
 * inserts word into head of linked list of ListNodes
 */
void insertAtHead(ListNode **head, char *word){
ListNode *node = calloc(1, sizeof(ListNode));
node->word = word;
node->next = *head;
*head = node;
}

/*
 * prints words matching given scramble
 */
void printScrambles(char *string, TrieNode *node){
//printf("Sorting/copying %sn", string);
char *sorted = calloc(strlen(string) + 1, sizeof(char));
strcpy(sorted, string);
//printf("String copiedn");
qsort(sorted, strlen(sorted), sizeof(char), char_cmp);
//printf("String sortedn");

printf("Matches for %s: ", string);
printRec(node, sorted, 0);
free(sorted);
}

/* 
 * recursive method to trawl trie for matches
 */
void printRec(TrieNode *node, char *sorted, int index){
//printf("Looking at |%s| index |%d| character |%c|n", sorted, index, sorted[index]);

if(!(sorted[index])){
if(!node->head){
printf("No matches foundn");
}else{
ListNode *ptr;
for(ptr = node->head; ptr; ptr = ptr->next)
printf("%s, ", ptr->word);

printf("n");
}
}else{
int trieIndex = (sorted[index] < 'a') ? (sorted[index] - 'A') : (sorted[index] - 'a');
if(node->children[trieIndex])
printRec(node->children[trieIndex], sorted, index+1);
else{
printf("No matches foundn");
return;
}
}
}

void printAll(TrieNode *node){
ListNode *ptr;
for(ptr = node->head; ptr; ptr = ptr->next){
printf("%sn", ptr->word);
}

int i;
for(i=0; i<26; i++){
if(node->children[i])
printAll(node->children[i]);
}
}

If no command line arguments are given it looks for words in wordlist.txt and targets in scrambles.txt. If one argument is given it assumes that the given filename specifies the dictionary to be used. If two arguments are given it assumes the given filename specifies a file containing words to unscramble.

It only works for words made from letters, but its fast as hell


----------



## hometoast

stop posting solutions so fast!


----------



## dangerousHobo

This is what I came out with last night using my word list. I'll try going through and seeing if it'll work with the others. I wrote it in perl too but its not 100% complete.

Code:


Code:


#!/usr/bin/env ruby

unless ARGV[0] 
    puts "Usage: ruby wordsort.rb [word_1 word_2 ...]"
    exit 0
end

scram_words = ARGV.compact.map {|x| x.split(//).sort.join}

File.open("wordlist.txt").each do |word|
    word.chop!
    scram_words.each {|scram| p word if word.split(//).sort.join == scram}
end


----------



## rabidgnome229

Attached is a file containing ~10K scrambled words. The words are in both 42K-words.txt and 172K-words.txt


----------



## dangerousHobo

Updated code handle the input being two files

Code:



Code:


#!/usr/bin/env ruby

unless ARGV.size == 2
    puts "Usage: ruby wordsort.rb scram_file wordlist_file"
    exit 0
end

scram = Array.new
File.open(ARGV[0]).each do |word|
    scram << word.chop.split(//).sort.join
end

File.open(ARGV[1]).each do |word|
    word.chop!
    (0...scram.size).each { |i| 
        if word.split(//).sort.join == scram[i]
            p word 
            scram.delete_at i
            break
        end
    }
end

Using my wordlist and a scrambled list of 10 words:

Code:



Code:


time ruby wordsort.rb scram.txt wordlist.txt         
real    0m0.082s
user    0m0.076s
sys     0m0.000s

Using the big list: (haha kind of sad)

Code:



Code:


time ruby wordsort.rb shuffle.txt 172K-words.txt   
real    35m27.748s
user    30m21.790s
sys     0m5.708s


----------



## dangerousHobo

A few changes for improvements
Still nothing to impressive..

Code:


Code:


#!/usr/bin/env ruby

unless ARGV.size == 2
    puts "Usage: ruby wordsort.rb scram_file wordlist_file"
    exit 0
end

scram = Array.new
real = Array.new

File.open(ARGV[0]).each do |word|
    scram << word.chop.split(//).sort.join
end

File.open(ARGV[1]).each do |word|
    real << word.chop    
end

scram.sort!
real.sort!

real.each do |word|
    sword = word.split(//).sort.join
    (0...scram.size).each do |i| 
        break if sword[0] < scram[i][0]
        if sword == scram[i]
            p word 
            scram.delete_at i
            break
        end
    end
end

Code:


Code:


time ruby wordsort.rb scram.txt wordlist.txt         
real    0m0.024s
user    0m0.024s
sys     0m0.000s

Code:


Code:


time ruby wordsort.rb shuffle.txt 172K-words.txt   
real    10m55.095s
user    10m54.685s
sys     0m0.376s


----------



## rabidgnome229

Quote:



Originally Posted by *dangerousHobo*


Updated code handle the input being two files

Using my wordlist and a scrambled list of 10 words:

Code:


Code:


time ruby wordsort.rb scram.txt wordlist.txt         
real    0m0.082s
user    0m0.076s
sys     0m0.000s

Using the big list: (haha kind of sad)

Code:


Code:


time ruby wordsort.rb shuffle.txt 172K-words.txt   
real    35m27.748s
user    30m21.790s
sys     0m5.708s


Rofl - yeah that's the problem with the easy way. It has to check every shuffled word against every word in the dictionary.

I used a trie for this, which is actually kinda nifty. A trie is a tree where the head node represents an empty string. Hanging off of that are 26 nodes (one for each letter). The first node corresponds to a string containing 'a' as the first letter. Hanging off of that are 26 nodes, where the first node represents a string containing 'aa', the second represents 'ab', and so on. The end result is that when you're matching a shuffled word, it doesn't depend on the number of words you're checking against, only the length of the shuffled word. It takes just as long to find the word using a dictionary of 10 words as it does with a dictionary of 10 million words.


----------



## dangerousHobo

Quote:



Originally Posted by *rabidgnome229*


Rofl - yeah that's the problem with the easy way. It has to check every shuffled word against every word in the dictionary.

I used a trie for this, which is actually kinda nifty. A trie is a tree where the head node represents an empty string. Hanging off of that are 26 nodes (one for each letter). The first node corresponds to a string containing 'a' as the first letter. Hanging off of that are 26 nodes, where the first node represents a string containing 'aa', the second represents 'ab', and so on. The end result is that when you're matching a shuffled word, it doesn't depend on the number of words you're checking against, only the length of the shuffled word. It takes just as long to find the word using a dictionary of 10 words as it does with a dictionary of 10 million words.


Nice.

I ran yours for fun against the 172K word list. Quite impressive

Code:


Code:


real    0m1.947s
user    0m0.344s
sys     0m0.028s


----------



## rabidgnome229

Quote:



Originally Posted by *dangerousHobo*


Nice.

I ran yours for fun against the 172K word list. Quite impressive

Code:


Code:


real    0m1.947s
user    0m0.344s
sys     0m0.028s


My prof would have a bone to pick with me if the results had been anything else. The first few labs in my freshman C and UNIX course revolved around loading a dictionary (first with a resizing array, then a linked list, then whatever you want - meaning go learn how to make a trie if you want an A)


----------



## dangerousHobo

Code:


Code:


#!/usr/bin/env ruby

unless ARGV.size == 2
    puts "Usage: ruby wordsort.rb scram_file wordlist_file"
    exit 0
end

scram = Hash.new

File.open(ARGV[0]).each do |word|
    word.chop!
    scram[word.split(//).sort.join] = word
end

File.open(ARGV[1]).each do |word|
    word.chop!
    #print "#{word} " if scram.has_key? word.split(//).sort.join
end

Code:


Code:


$ time ruby wordsort-hash.rb shuffle.txt 172K-words.txt

real    0m0.356s
user    0m0.304s
sys     0m0.004s

No way I can do better then that.

Note the commented out "print" line if it printed out everything to the terminal it'll obviously take longer:
real 0m3.832s

rabidgnome:
The execution time on yours if nothing it outputted.

Code:


Code:


$ time ./a.out

real    0m0.353s
user    0m0.324s
sys     0m0.024s


----------



## rabidgnome229

Good call with the hashtable, I'm throwing together a quick one in C to compare performance (only cheating a little bit







). They should be similar (both are constrained by the length of the input, the trie from moving through the tree letter by letter, the table because it has to hash the string). I think the hashtable will have better constant factors though, because it doesn't have to move through a tree - it just has to jump into a table


----------



## dangerousHobo

For fun I wrote it in perl too.
Not as elegant as ruby

Code:


Code:


#!/usr/bin/env perl

use warnings;
use strict;

if ($#ARGV+1 < 2) {
    print "Usage: perl wordsort.pl scram_file wordlist_filen";
    exit(0);
}

my %scram = ();

open(FILE, $ARGV[0]) || die "could not open file $ARGV[0]";
foreach (<FILE>) {
    chomp($_);
    my $sorted = join( "", sort { lc($a) cmp lc($b) } split(//,$_) ); # alphabetical sort
    $scram{$sorted} = $_;
}
close(FILE);

open(FILE2, $ARGV[1]) || die "could not open file $ARGV[1]";
foreach (<FILE2>) {
    chomp($_);
    print "matched: $_  " if $scram{join( "", sort { lc($a) cmp lc($b) } split(//,$_) )};
}
close(FILE2);
print "n";


----------



## dangerousHobo

*The Challenge:
*Ok this week I'm hoping to see some more submissions so we'll try one thats hopefully a little easier.

Write a program that can print out a shape given the desired number of lines and the character to be used.
The shapes that your program can handle is up to you, but of course the more the better.

_Creativity and elegance _are weighed to decide the winner. There is no prize, just bragging rights.

Any language is welcome.









*Deadline:*
Wednesday August 13th at 11:00pm EST.

Post any questions you have.


----------



## dangerousHobo

Only three shapes.

Code:


Code:


#!/usr/bin/env ruby

if ARGV.size < 2
    puts "Useage: ruby shape.rb [shape] [char] {size}"
    exit 0
end

SHAPE = ARGV.shift
CHAR = ARGV.shift
if SHAPE !~ /triangle|diamond|square/
    puts "unknown shape....exiting"
    exit 0
end

if ARGV[0]
    Size = ARGV.shift.to_i
else
    Size = 5
end

def pad(pos, shape)
    case shape
    when 'triangle' : " "*CHAR.size*(Size+1 - pos)
    when 'diamond' : " "*CHAR.size*(Size/2+1 - pos)
    end
end

case SHAPE
when 'square'
    (1..Size).each { puts CHAR*Size }
when 'triangle'
    (1..Size).each { |n| puts pad(n, 'triangle') + ("#{CHAR}"+" "*CHAR.size)*n }
when 'diamond'
    (1..Size/2+1).each { |n| puts pad(n, 'diamond') + ("#{CHAR}"+" "*CHAR.size)*n }
    (Size/2).downto(1) { |n| puts pad(n, 'diamond') + ("#{CHAR}"+" "*CHAR.size)*n }
end


----------



## OasisGames

Something I'm working on: PHP + SVG. Should be able to do virtually any shape when done. Draws an SVG, calls rsvg to rasterize it, then processes it through the gd libraries and generates some ascii art. Works in a terminal as well. (granted, for the currently hard-coded drawing, you need a really big terminal window) (it'll work perfectly in a standard 80-wide terminal now)

Shouldn't take much time to add some options. (done)

Question: Do you want some compensation for the none-square aspect of a typical console font? (I'll add an option later)

Shapes so far:
- Rectangles
- Circles
- Lines
- Star
- Triangle
- Diamond
- OCN Logo - haha, had to draw it myself

Specify a shape with do=[square | circle | line | star | triangle | diamond | ocn], size with &size=[##], character with &char=[character]
Default is a square, size of 80, char=#

Code:



Code:


[CODE]
<?php
$chars = array('#', ' ');
function rasterize($svg) {
    $svgfile = fopen("/tmp/rasterize.svg", 'w');
    fwrite($svgfile, $svg);
    fclose($svgfile);
    $rsvg = exec("rsvg /tmp/rasterize.svg /tmp/rasterize.png");
}
function draw($url)     {
    global $chars;
    $quality = 1;
    $img = imagecreatefrompng($url);
    $width = imagesx($img);
    $height = imagesy($img);
    $output = '';
    for($y = 0; $y < $height; $y = $y + $quality) {
        for($x = 0; $x < $width; $x = $x + $quality) {
            $pixel_color = imagecolorat($img, $x, $y);
            $rgb = imagecolorsforindex($img, $pixel_color);
            $brightness = $rgb['red'] + $rgb['green'] + $rgb['blue'];
            $brightness = round($brightness / (765 / (count($chars) - 1)));
            $char = $chars[$brightness];
            $output .= $char;
        }
        $output .= "n";
    }

    return $output;
}
function drawSquare($size = 80) {
rasterize(<<<END
   <svg width="$size" height="$size" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="stroke:black;fill:black;stroke-width:0" >
       <rect x="10" y="10" width="$size" height="$size" />
     </g>
   </svg>
END
);
}
function drawStar($size = 80) {
    $sizeb = $size / 240;
rasterize(<<<END
   <svg width="$size" height="$size" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="fill:white">
        <rect x="0" y="0" width="$size" height="$size" />
     </g>
     <g style="stroke:black;fill:black;stroke-width:0" >
         <path
       d="M 0,-80 L 30,10 L 120,10 L 40,60 L 70,150 L 0,90 L -70,150 L -40,60 L -120,10 L -30,10 L 0,-80 z"
       transform="scale($sizeb) translate(120, 80)" />
     </g>
   </svg>
END
);
}
function drawTriangle($size = 80) {
    $sizeb = $size / 2;
rasterize(<<<END
   <svg width="$size" height="$size" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="fill:white">
        <rect x="0" y="0" width="$size" height="$size" />
     </g>
     <g style="stroke:black;fill:black;stroke-width:0" >
         <path
       d="M $sizeb,0 L $size,$size L 0,$size L $sizeb,0 z" />
     </g>
   </svg>
END
);
}
function drawDiamond($size = 80) {
    $sizeb = $size / 2;
rasterize(<<<END
   <svg width="$size" height="$size" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="fill:white">
        <rect x="0" y="0" width="$size" height="$size" />
     </g>
     <g style="stroke:black;fill:black;stroke-width:0" >
         <path
       d="M $sizeb,0 L $size,$sizeb L $sizeb,$size L 0,$sizeb L $sizeb,0 z" />
     </g>
   </svg>
END
);
}
function drawCircle($size = 80) {
    $sizeb = $size / 2;
rasterize(<<<END
   <svg width="$size" height="$size" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="fill:white">
        <rect x="0" y="0" width="$size" height="$size" />
     </g>
     <g style="stroke:black;fill:black;stroke-width:0" >
         <circle cx="$sizeb" cy="$sizeb" r="$sizeb" />
     </g>
   </svg>
END
);
}
function drawLine($size = 80) {
rasterize(<<<END
   <svg width="$size" height="$size" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="fill:white">
        <rect x="0" y="0" width="$size" height="$size" />
     </g>
     <g style="stroke:black;fill:black;stroke-width:0" >
         <line x1="0" y1="$size" x2="$size" y2="0"
            style="stroke-width: 4" />
     </g>
   </svg>
END
);
}
function drawOCN($size = 80) {
$sizeb = $size / 80;
$sizec = 96 * $size / 80;
rasterize(<<<END
   <svg width="$size" height="$sizec" 
     xmlns="http://www.w3.org/2000/svg" 
     xmlns:xlink="http://www.w3.org/1999/xlink">
     <g style="fill:white">
        <rect x="0" y="0" width="$size" height="$sizec" />
     </g>
  <g
     transform=" scale($sizeb) translate(-96.64074,-24.50504)"
     id="layer1">
    <path
       d="M 101.00841,64.905786 C 96.712639,72.218833 85.823676,105.94921 130.15832,118.70526 C 174.57281,127.06068 176.85863,79.617965 176.49133,75.747505 C 176.02174,76.68422 174.65028,77.179431 172.60467,78.611356 C 170.55907,80.043281 168.30889,80.452402 168.30889,80.452402 C 168.30889,80.452402 172.91151,75.133823 173.21835,66.13315 C 173.41144,60.405051 169.53626,53.450385 169.53626,53.450385 C 169.53626,53.450385 168.67563,61.529547 164.52453,65.826309 C 158.69454,71.86085 150.81895,74.31558 150.81895,74.31558 C 150.81895,74.31558 156.03526,66.746833 153.58053,58.053001 C 151.83512,51.871349 142.63653,41.892702 138.13619,36.778685 C 134.19626,32.30149 133.49839,30.038614 131.48796,24.50504 C 131.21631,30.835988 132.63378,42.669473 130.46516,46.49532 C 128.20956,50.474615 126.02706,54.794102 121.66905,52.734422 C 116.43392,50.2602 119.21432,41.17674 119.21432,41.17674 C 119.21432,41.17674 108.45284,45.496234 107.55435,58.973524 C 106.32699,77.486271 111.85013,90.475879 111.85013,90.475879 C 110.57595,88.50665 106.32699,84.645896 103.66771,77.793112 C 101.18551,71.396674 101.48141,68.373764 101.00841,64.905786 z"
       id="path2409"
       style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
    <path
       d="M 163.39944,50.688814 C 167.00779,49.41993 166.87697,47.594831 166.5957,44.833263 C 166.30342,41.937024 159.8452,32.610759 159.8452,32.610759 C 159.8452,32.610759 159.43608,35.70474 159.23152,39.079993 C 159.02695,42.455244 159.47012,43.733302 159.76849,46.54646 C 160.12647,49.896142 162.03103,51.170018 163.39944,50.688814 z"
       id="path3181"
       style="fill:#000000;fill-opacity:0.96078431;fill-rule:evenodd;stroke:#000000;stroke-width:0.14319251px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
    <path
       d="M 143.55084,111.94341 C 147.8453,111.79566 152.27765,110.17876 155.11473,105.40881 C 159.74426,97.62525 156.35964,87.437423 156.35964,87.437423 C 156.35964,87.437423 156.2411,88.26779 154.53313,91.128734 C 153.20517,93.353156 147.54599,97.430942 147.54599,97.430942 C 147.54599,97.430942 150.10299,92.108287 149.34466,86.58302 C 148.75081,82.284457 147.5034,77.712836 140.70454,70.850456 C 142.29517,73.570894 144.77514,88.859826 135.68146,91.805521 C 129.21434,93.900399 123.89382,82.308057 118.70292,76.668029 C 118.72832,82.892522 119.3166,89.759915 121.77133,94.05569 C 125.42534,100.45021 130.772,104.28373 130.772,104.28373 C 130.772,104.28373 128.21499,105.30653 125.24886,104.69285 C 122.34425,104.0919 118.49836,102.8518 118.49836,102.8518 C 118.49836,102.8518 123.86838,107.53628 128.62412,109.6023 C 141.10232,115.02316 143.14793,105.20425 143.14793,105.20425 C 143.14793,105.20425 144.37529,105.92021 144.47758,108.17038 C 144.57985,110.42055 143.81275,111.72955 143.55084,111.94341 z"
       id="path3183"
       style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
    <path
       d="M 131.7181,83.469672 C 131.7181,83.469672 129.22131,78.954188 129.85148,75.133823 C 131.4169,65.669214 135.23723,63.00979 136.90882,60.124178 C 137.85147,58.49693 137.75296,56.553847 137.62479,54.473187 C 137.03634,56.739443 135.58859,59.690662 133.76371,62.297636 C 132.68976,63.831843 125.12101,72.397822 125.45342,76.668028 C 125.71008,79.945317 128.64968,81.961038 131.7181,83.469672 z"
       id="path3185"
       style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1" />
  </g>
</svg>
END
);
}
$arg = $_GET['do'];
$no_pre = false;
if ($argc > 1) {
    $arg = $argv[1];
    $no_pre = true;
}
if ($argc > 2) {
    $size = $argv[2];
} else {
    $size = 80;
    if ((int)$_GET['size'] > 0) {
        $size = (int)$_GET['size'];
    }
}
if ($argc > 3) {
    if ($argv[3] == "-aa") {
        $chars = array("#","%","&","*","0","Z","z","\\"","'","."," ");
    }
}
if ($_GET['aa'] == "yes") {
    $chars = array("#","%","&","*","0","Z","z","\\"","'","."," ");
}
if (isset($_GET['char'])) {
    $chars = array($_GET['char'], " ");
}
if ($argc > 4) {
    $chars = array($argv[4], " ");
}
if ($arg == "square") {
    drawSquare($size);
} elseif ($arg == "star") {
    drawStar($size);
} else if ($arg == "circle") {
    drawCircle($size);
} else if ($arg == "line") {
    drawLine($size);
} else if ($arg == "triangle") {
    drawTriangle($size);
} else if ($arg == "diamond") {
    drawDiamond($size);
} else if ($arg == "ocn") {
    drawOCN($size);
} else {
    drawSquare($size);
}
$asc = draw('/tmp/rasterize.png');
if (!$no_pre) {
print "" . $asc . "";
} else {
print $asc;
}
unlink("/tmp/rasterize.png");
unlink("/tmp/rasterize.svg");
?>

[/CODE]


----------



## rabidgnome229

More string manipulation huh? If my haskell book gets here I might take a whack at this


----------



## loco1172

im taking my :turd: ms compiler and going home


----------



## OasisGames

I think I may be taking this a bit too far...


----------



## dangerousHobo

Quote:



Originally Posted by *OasisGames*




I think I may be taking this a bit too far...


That is wicked.


----------



## C-bro

Quote:



Originally Posted by *OasisGames*




I think I may be taking this a bit too far...


Yipes! Please tell me you just used an image to ASCII converter and hardcoded the strings.

I think it's time to dust out my cranial cobwebs and try that dictionary one.


----------



## slyoteboy

how do I run this stuff on my comp? Like if I wanted to check your guys leet skillz.


----------



## OasisGames

Quote:



Originally Posted by *C-bro*


Yipes! Please tell me you just used an image to ASCII converter and hardcoded the strings.

I think it's time to dust out my cranial cobwebs and try that dictionary one.


I wrote an SVG -> ASCII converter in PHP, drew up an SVG, and piped it through. Code is on the previous page. You can set any size you want, default is 80 characters wide, but please don't kill my weak server.


----------



## OasisGames

So is the challenge over, with just two entries? I was hoping to see more...


----------



## dangerousHobo

I'll keep the challenge open till Friday night and then I'll post a new challenge. Try to think of something not string manipulation related.


----------



## error10

Quote:


Originally Posted by *dangerousHobo* 
I'll keep the challenge open till Friday night and then I'll post a new challenge. Try to think of something not string manipulation related.









So where's the next challenge? I'm bored...


----------



## bartista

^ ^ ^ what he said!


----------



## GodofGrunts

Yeah, I'm back and I want to play! C'mon dB.


----------



## xtascox

Hm looks like fun. Looking forward to the next challenge.


----------



## MrDanny

k info for beginner


----------



## Djibrille

I know I'm a little late but I was intrigued by the dictionary programming challenge after I did the brute force approach and found it not finishing after 1/2 hour on my aging AthlonXP laptop. So I changed it to use a HashMap and now it only takes about 8 secs to print the results. That surprised me to say the least.

Code:



Code:


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

public class Words{
public static String sort(String word){
char[] cwd=word.toCharArray();
Arrays.sort(cwd);
return new String(cwd);
}
public static void main (String args[]){
if(args.length!=2){
              System.out.println("Usage: java Words [filename_scrambled_words] [filename_wordlist]");
System.exit(0);
}
File scrambled=new File(args[0]);
File wordlist=new File(args[1]);
if(!scrambled.isFile()){
System.out.println(scrambled+" Not a file!");
System.exit(0);                              
}
if(!wordlist.isFile()){
System.out.println(wordlist+" Not a file!");
System.exit(0);
}                                                           
try{
BufferedReader brScram=new BufferedReader(new FileReader(scrambled));
BufferedReader brWords=new BufferedReader(new FileReader(wordlist));
String scrWord,goodWord;
HashMap dictMap=new HashMap();
while((goodWord=brWords.readLine())!=null){
goodWord=goodWord.trim();
String sortedGood=sort(goodWord);
LinkedList el=new LinkedList();                                      
if(dictMap.get(sortedGood)!=null)
el=(LinkedList)(dictMap.get(sortedGood));
el.add(goodWord);
dictMap.put(sortedGood,el);
}
int count=0;                                                                             
while((scrWord=brScram.readLine())!=null){
scrWord=scrWord.trim();
System.out.println("nSearching for: "+scrWord+"--n");
System.out.println("      Found: "+dictMap.get(sort(scrWord))+"n");
count++;
}                                                                             
System.out.println("     Searched : "+count+" scrambled words");
brWords.close();
brScram.close();
}catch(Exception e){
System.out.println("      Could not read file(s)!!! Exiting......"+e); 
System.exit(0);
}
}
}


----------



## Djibrille

Final version of my java program takes ~6 secs to print the results(the ruby solution presented earlier here takes almost 13 secs on my sistem):

Code:



Code:


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

public class Words{
public static String sort(String word){
char[] cwd=word.toCharArray();
Arrays.sort(cwd);
return new String(cwd);
}
public static void main (String args[]){
if(args.length!=2){
System.out.println("Usage: java Words [filename_scrambled_words] [filename_wordlist]");
System.exit(0);
}
File scrambled=new File(args[0]);
File wordlist=new File(args[1]);
if(!scrambled.isFile()){
System.out.println(scrambled+" Not a file!");
System.exit(0);                              
}
if(!wordlist.isFile()){
System.out.println(wordlist+" Not a file!");
System.exit(0);
}                                                           
try{
BufferedReader brScram=new BufferedReader(new FileReader(scrambled));
BufferedReader brWords=new BufferedReader(new FileReader(wordlist));
String scrWord,goodWord;
HashMap<String,LinkedList<String>> dictMap=new HashMap<String,LinkedList<String>>();
while((goodWord=brWords.readLine())!=null){
goodWord=goodWord.trim();
String sortedGood=sort(goodWord);
LinkedList<String> el=new LinkedList<String>();                                      
if(dictMap.get(sortedGood)!=null)
el=dictMap.get(sortedGood);
el.add(goodWord);
dictMap.put(sortedGood,el);
}
int count=0;                                                                             
while((scrWord=brScram.readLine())!=null){
scrWord=scrWord.trim();
System.out.println("nSearching for: "+scrWord+"--n");
System.out.println("      Found: "+dictMap.get(sort(scrWord))+"n");
count++;
}                                                                             
System.out.println("     Searched : "+count+" scrambled words");
brWords.close();
brScram.close();
}catch(Exception e){
System.out.println("      Could not read file(s)!!! Exiting......"+e); 
System.exit(0);
}
}
}

I would have liked to compare the speed with the c solution of rabidgnome's but I can't get it to compile with gcc on my linux OS(something about a blank character i'm too lasy to try and fix it as is quite hard to follow c code).


----------



## rabidgnome229

I tried copy/pasting my solution and I got the same thing, I think the forum is formatting something badly. Attached to this post is the code (rename to .c)

Never got around to doing that hash table


----------



## Djibrille

I just did some tests on my laptop.
Best results on my Java program: ~4.4 secs(this happens from second run onwards, os must be doing some caching, probably the dict file that's what takes the most time)
Best result on Rabid's c program:~1,5 secs(same thing here -- not the first run)
Wow, 3 times faster, i never beleived the difference would be so big. I could probably make it a little faster by removing some of the printing statements but I dont think it will ever be near as fast. That's something for the java developpers to think about, they claimed only 30% slower code comparing to C(maybe C++ I dont quite remember).
Anyway thanks rabid for the code! Nicely done!


----------



## GodofGrunts

I always knew Java was slow, but 3x times? Wow, I'm glad I decided to dumb Java early.


----------



## Asus Mobile

Dude I ain't going to do your homework!


----------



## GodofGrunts

Where did that come from?


----------



## Spotswood

Here's portions of my implementation of the "scrambled text" challenge. This C# implementation stores a dictionary of the list of scrambled words that have a given "weight." The large file test executes in NUnit in around ~1.3 seconds.









Code:



Code:


using System;
using System.Collections.Generic;
using System.Text;

namespace Scrambled
{
    public class ScrambledWord : IScrambledWord
    {
        private String scrambledLetters;    // As read from stream
        private int weight;                 // Summation of the character values in scrambledLetters

        public ScrambledWord(String scrambledLetters)
        {
            this.scrambledLetters = scrambledLetters;
            this.weight = CalculateWeight(scrambledLetters);
        }

        public bool LettersMatch(String text)
        {
            if (text.Length != scrambledLetters.Length) return false;
            for (int i = 0; i < scrambledLetters.Length; i++)
            {
                int index = text.IndexOf(scrambledLetters[i]);
                if (index == -1)
                    return false;
                text = text.Remove(index, 1);
            }
            return true;
        }

        public String Letters
        {
            get { return scrambledLetters; }
        }

        public int Weight
        {
            get { return weight; }
        }

        public static unsafe int CalculateWeight(String text)
        {
            int weight = 0;
            fixed (char* str = text)
            {
                for (int i = 0; i < text.Length; i++)
                    weight += str[i];
            }
            return weight;
        }

    }
}

Code:



Code:


using System;
using System.Collections.Generic;
using System.Text;

namespace Scrambled
{
    public class ScrambledWordList : IScrambledWordList
    {
        IDictionary<int /*weight*/, List<IScrambledWord> /*words with same weight*/> wordList;

        public ScrambledWordList()
        {
            wordList = new Dictionary<int, List<IScrambledWord>>();
        }

        public ScrambledWordList(IWordStream stream)
        {
            wordList = new Dictionary<int, List<IScrambledWord>>();
            String word;
            while ((word = stream.ReadWord()) != null)
                AddScrambledWord(new ScrambledWord(word));
        }

        public bool ContainsWord(String text)
        {
            int textWeight = ScrambledWord.CalculateWeight(text);
            List<IScrambledWord> list;
            if (wordList.TryGetValue(textWeight, out list) == false)
                return false;
            return AnyWordLettersMatch(list, text);
        }

        public void Add(IScrambledWord sw)
        {
            AddScrambledWord((ScrambledWord)sw);
        }

        void AddScrambledWord(ScrambledWord sw)
        {
            List<IScrambledWord> list;
            if (wordList.TryGetValue(sw.Weight, out list) == false)
            {
                list = new List<IScrambledWord>();
                wordList.Add(sw.Weight, list);
            }
            list.Add(sw);
        }

        bool AnyWordLettersMatch(List<IScrambledWord> list, String text)
        {
            int matches = 0;
            foreach (IScrambledWord sw in list)
            {
                // There could be many scrambled words 
                // that match the supplied text.
                if (sw.LettersMatch(text) == true)
                {
                    ++matches;
                    // This is wicked slow:
                    //Console.WriteLine(sw.Letters + " is " + text);
                }
            }
            return matches == 0 ? false : true;
        }
    }
}

Code:



Code:


// snip...

        [Test]
        public void ContainsWord_matches_in_huge_word_list()
        {
            IScrambledWordList scrambledList = 
                ScrambledWordListFactory.CreateWordList(
                    WordStreamFactory.CreateWordStream(GetManifestResourceStream("UnitTest.Resources.shuffle.txt")));
            IWordStream ws = 
                WordStreamFactory.CreateWordStream(GetManifestResourceStream("UnitTest.Resources.172K-words.txt"));
            String word;
            int count = 0;
            while ((word = ws.ReadWord()) != null)
                count += scrambledList.ContainsWord(word) ? 1 : 0;
            Assert.AreEqual(12877, count);
        }


----------



## Spotswood

Here's my C# implementation of the "convert dollar amount" challenge:

Code:



Code:


using System;

namespace WrittenAmount
{
    public class ConvertDollar
    {
        public string ToWrittenAmount(string dollarAndCentsAmount)
        {
            // Strip off the leading '$'.
            string cleanDollarAndCentsAmount = ExtractDollarAmount(dollarAndCentsAmount);

            // Separate the dollars and cents.
            string[] dollarAndCents = ExtractCentsAmount(cleanDollarAndCentsAmount);
            if (dollarAndCents.Length == 0)
            {
                return string.Empty;
            }

            // Just dollars?
            if (dollarAndCents.Length == 1)
            {
                return DollarsAndCentsToText(dollarAndCents[0], "0");
            }

            // Dollars and (possibly nul) cents.
            return DollarsAndCentsToText(dollarAndCents[0], 
                    String.IsNullOrEmpty(dollarAndCents[1]) ? "0" : dollarAndCents[1]);
        }

        private string DollarsAndCentsToText(string dollars, string cents)
        {
            // ConvertDollarResources.DollarsAndCentsFormat fetches the format
            // string from the .resx file.
            return String.Format(ConvertDollarResources.DollarsAndCentsFormat, NumberToText(dollars), NumberToText(cents));
        }

        //
        // This is the "meat" of the conversion process.
        //
        private string NumberToText(string number)
        {
            string text = "";
            char[] digits = number.ToCharArray();
            for (int i = 0; i < digits.Length; ++i)
            {
                string thisNumber;

                // Ugh. Special case the teens (10 through 19).  :(
                if (IsTensPlace(i, digits.Length) && IsTeenNumber(digits[i].ToString() + digits[i + 1].ToString()))
                {
                    thisNumber = TeenNumberToText(digits[i].ToString() + digits[i + 1].ToString());
                    i += 2;
                }
                else
                {
                    thisNumber = NumberToText(digits[i].ToString(), digits.Length - i);
                }

                if (thisNumber.Length > 0)
                    text = String.Concat(text, thisNumber, " ");
            }

            return text;
        }

        private bool IsTensPlace(int currentDigit, int totalDigits)
        {
            // 1112.00
            //   ^
            //   +-- Are we here?
            if ((totalDigits - currentDigit) == 2)
                return true;
            return false;
        }

        private bool IsTeenNumber(string possibleTeen)
        {
           if (Convert.ToInt16(possibleTeen) >= 10 && Convert.ToInt16(possibleTeen) <= 19)
                return true;
            return false;
        }

        private string TeenNumberToText(string teen)
        {
            string resourceKey = "N" + teen;
            return GetResourceString(resourceKey);
        }

        private string NumberToText(string digit, int place)
        {
            // i.e. "N9_4" is equivalent to "nine thousand"
            string resourceKey = "N" + digit + "_" + place.ToString();
            return GetResourceString(resourceKey);
        }

        private string ExtractDollarAmount(string dollarAmount)
        {
            int indexOfDollarSign = dollarAmount.IndexOf('$');
            if (indexOfDollarSign < 0)
            {
                return dollarAmount;
            }

            return dollarAmount.Remove(indexOfDollarSign, 1);
        }

        private string[] ExtractCentsAmount(string amount)
        {
            return amount.Split(new Char[] { '.' });
        }

        private string GetResourceString(string key)
        {
            return ConvertDollarResources.ResourceManager.GetString(key);
        }

    }
}

NUnit test fixture:

Code:



Code:


using System;
using NUnit.Framework;
using WrittenAmount;

namespace WrittenAmount.UnitTest
{
    [TestFixture]
    public class ConvertDollarTests
    {
        [Test]
        public void ToText_0()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$0.0");
            StringAssert.AreEqualIgnoringCase("zero dollars and zero cents", text);
        }

        [Test]
        public void ToText_0_16()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$0.16");
            StringAssert.AreEqualIgnoringCase("zero dollars and sixteen cents", text);
        }

        [Test]
        public void ToText_16_0()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$16.0");
            StringAssert.AreEqualIgnoringCase("sixteen dollars and zero cents", text);
            text = converter.ToWrittenAmount("$16.00");
            StringAssert.AreEqualIgnoringCase("sixteen dollars and zero cents", text);
        }

        [Test]
        public void ToText_1_03()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$1.03");
            StringAssert.AreEqualIgnoringCase("one dollars and three cents", text);
        }

        [Test]
        public void ToText_1_23()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$1.23");
            StringAssert.AreEqualIgnoringCase("one dollars and twenty three cents", text);
        }

        [Test]
        public void ToText_10_23()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$10.23");
            StringAssert.AreEqualIgnoringCase("ten dollars and twenty three cents", text);
        }

        [Test]
        public void ToText_12_34()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$12.34");
            StringAssert.AreEqualIgnoringCase("twelve dollars and thirty four cents", text);
        }

        [Test]
        public void ToText_112_34()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$112.34");
            StringAssert.AreEqualIgnoringCase("one hundred twelve dollars and thirty four cents", text);
        }

        [Test]
        public void ToText_123_45()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$123.45");
            StringAssert.AreEqualIgnoringCase("one hundred twenty three dollars and fourty five cents", text);
        }

        [Test]
        public void ToText_1234_56()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$1234.56");
            StringAssert.AreEqualIgnoringCase("one thousand two hundred thirty four dollars and fifty six cents", text);
        }

        [Test]
        public void ToText_9999()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$9999");
            StringAssert.AreEqualIgnoringCase("nine thousand nine hundred ninety nine dollars and zero cents", text);
        }

        [Test]
        public void ToText_9999_()
        {
            WrittenAmount.ConvertDollar converter = new WrittenAmount.ConvertDollar();
            string text = converter.ToWrittenAmount("$9999.");
            StringAssert.AreEqualIgnoringCase("nine thousand nine hundred ninety nine dollars and zero cents", text);
        }
    }
}


----------



## Burn

Is anyone up for some NTLM hash work?


----------



## GodofGrunts

Just wondering, can we start this again?


----------



## newbie1911

i'd like to join too.


----------



## GodofGrunts

Apparently no one is interested?


----------



## grumpymonkey

this sounds like fun..good thing I checked the date before trying any of the challenges









Someone should start this up again


----------



## GodofGrunts

I'll see if I can come up with anything.


----------



## serge2k

could do some old ACM competition questions.


----------



## GodofGrunts

Quote:



Originally Posted by *serge2k*


could do some old ACM competition questions.


Do you have access to those?


----------



## serge2k

http://cm.baylor.edu/ICPCWiki/Wiki.jsp?page=Problems

archive seems to be down though. The questions for the finals work but the input files don't seem to be there.

Their is also the UVA online judge which has similar problems.
http://uva.onlinejudge.org/

I was looking at old google code jam problems last night. A lot are simple but still might be interesting.


----------



## T0yK4T

Well, hope this is how you "sign up" for the competition, here's my entry,
it does a bit more than what was required, but well, was a fun exercise!
Will attach the GUI I made aswell (Zipped) - Exe + Source!







- have fun ^.^
written in C# - spent a lot of time thinking about performance of the shift operations etc. (Few hours I think, this includes doing benchmarks XD) But think I finally managed to get something that performs,
at least reasonably descent:

Code:


Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Substitution_Encoder1
{
public class EncodingController
{
private int shift = 0;
private List<char> letters = new List<char>();

public EncodingController()
{
for (int i = 0; i < 255; i++)
{
if (char.IsLetterOrDigit((char)i))
letters.Add((char)i);
}
this.shift = 0;
}

public void ShiftLeft(int amount)
{
this.shift = (this.shift + amount) % this.Length;
}

public void Reset()
{
this.shift = 0;
}

public void ShiftRight(int amount)
{
this.shift = (this.shift - amount) % this.Length;
this.shift = this.shift < 0 ? this.Length + this.shift : this.shift;
}

public int Length
{
get { return this.letters.Count; }
}

public string Encode(string txt)
{
char[] res = new char[txt.Length];
for (int i = 0; i < txt.Length; i++)
{
if (char.IsLetterOrDigit(txt[i]))
res[i] = this.letters[(this.letters.IndexOf(txt[i]) + this.shift) % this.letters.Count];
else
res[i] = txt[i];
//res[i] = (byte)((txt[i] + shift) % 256);
}
return new string(res);
}

public string Decode(string txt)
{
string res = string.Empty;
foreach (char c in txt)
{
if (char.IsLetterOrDigit(c))
{
int idx = (this.letters.IndexOf(c) - this.shift) % this.letters.Count;
idx = idx < 0 ? this.letters.Count + idx : idx;
res += this.letters[idx];
}
else
res += c;
}
return res;
}

public string Encode(string txt, byte[] key)
{
this.Reset();
char[] res = new char[txt.Length];
for (int i = 0; i < txt.Length; i++)
{
foreach (byte b in key)
this.ShiftRight(b);
//res[i] = (byte)((txt[i] + shift) % 256);
if (char.IsLetterOrDigit(txt[i]))
res[i] = this.letters[(this.letters.IndexOf(txt[i]) + this.shift) % this.letters.Count];
else
res[i] = txt[i];
}
return new string(res);
}

public string Decode(string txt, byte[] key)
{
this.Reset();
string res = string.Empty;
foreach (char c in txt)
{
foreach (byte kb in key)
this.ShiftRight(kb);
//res += (char)((byte)((b - shift) % 256));
if (char.IsLetterOrDigit(c))
{
int idx = (this.letters.IndexOf(c) - this.shift) % this.letters.Count;
idx = idx < 0 ? this.letters.Count + idx : idx;
res += this.letters[idx];
}
else
res += c;
}
return res;
}
}
}

Edit1: Revised some of the code - especially the way the shift and encoding / decoding is happening - should now perform a lot better - and look better too








Re-up'ed the source + exe.

Edit2: Apparently I didn't read the rules XD Was supposed to leave punctuation alone :/
Well, here goes another one, should still be performing "within expected parameters", just a bit different... Spaces and punctuation are left alone! Only thing being encoded are letters and digits (according to .Net atleast)









Edit3: Should've read the next few posts i guess  This challenge ended 3 years ago? XD Talk about late handin








The first post said the current challenge was on Post #10, so didn't think a lot about that woot!
Anyways, Is there anything going on here? Or?


----------



## Console-hater

oldschool style coder:

md5.php

Code:



Code:


[CODE]
<?php

$q = $_GET['q'];

$response = md5($q);

echo $response

?>

[/CODE]

md5test.htm

Code:



Code:


[B][SIZE=15] MD5 Convertor
[/SIZE][/B]

[TABLE]
[TR][TD]please enter a text here[/TD][/TR]

[TR][TH][/TH][/TR]
[/SIZE][/B]

[/TABLE]

I'm not sure if this is allowed.


----------



## Midpipps

I do have a bunch of packets lying around of programming challenges from MICS Programming Competition and some ACM ones. If anyone is interested let me know and I will post one. The MICS ones are a tad easier but still good fun.


----------



## xtascox

Quote:



Originally Posted by *Midpipps*


I do have a bunch of packets lying around of programming challenges from MICS Programming Competition and some ACM ones. If anyone is interested let me know and I will post one. The MICS ones are a tad easier but still good fun.


Post up son


----------



## Midpipps

Here is one that was deceptively simple sounding but gave us some trouble at the competition because darn if we could remember exactly how the last frame was scored and they would allow us no access to the internet to look it up.
We were required to make it with console input and output but make it as graphical or none graphical as you would like. Should be a good one for most any level of programmer.

*MICs Programming Contest 2010 
Bowling*

*History*
Bowling has been traced to articles found in the tomb of an Egyptian child buried in 5200 BC. The primitive implements included nine pieces of stone at which a stone "ball" was rolled, the ball having first to roll through an archway made of three pieces of marble. 
Another ancient discovery was the Polynesian game of ula maika, which also used pins and balls of stone. The stones were to be rolled at targets 60 feet away, a distance which is still one of the basic regulations of tenpins. 
Bowling at tenpins probably originated in Germany, not as a sport but as a religious ceremony. Martin Luther is credited with settling on nine as the ideal number of pins. 
Tracing history reveals the game moved through Europe, the Scandinavian countries and finally to the United States, where the earliest known reference to bowling at pins in America was made by author Washington Irving about 1818 in Rip Van Winkle. 
Although the game was being played throughout the world, rules were different almost everywhere, and even basic equipment was not the same. In fact, why and when the 10th pin was added from the European game of ninepins to the American game of tenpins is still a mystery. 
Rules
A single bowling game consists of ten frames. The object in each frame is to roll a ball at ten bowling pins arranged in an equilateral triangle and to knock down as many pins as possible. 
For each frame, a bowler is allowed a maximum of two rolls to knock down all ten pins. If the bowler knocks them all down on the first attempt, the frame is scored as a strike. If the bowler does not knock them down on the first attempt in the frame the bowler is allowed a second attempt to knock down the remaining pins. If the bowler succeeds in knocking the rest of the pins down in the second attempt, the frame is scored as a spare. 
The score for a bowling game consists of sum of the scores for each frame. The score for each frame is the total number of pins knocked down in the frame, plus bonuses for strikes and spares. In particular, if a bowler scores a strike in a particular frame, the score for that frame is ten plus the sum of the next two rolls. If a bowler scores a spare in a particular frame, the score for that frame is ten plus the score of the next roll. If a bowler scores a strike in the tenth (final) frame, the bowler is allowed two more rolls. Similarly, a bowler scoring a spare in the tenth frame is allowed one more roll. 
The maximum possible score in a game of bowling (strikes in all ten frames plus two extra strikes for the tenth frame strike) is 300. 
*Input*
The input will consist of a sequence of bowling game scores. Each line will contain the scores for a single game, with the scores for each roll of the ball separated by a single space. The score for a single roll will be represented by a single character -- either a number indicating the number of pins knocked down, a '/' for a spare or a 'X' for a strike. 
The end of input is indicated by a single line containing the text Done (terminated with a newline). 
*Output*
Your program should output the total game score for each game in the input file. The game scores should be left justified and each score should be printed on a separate line. The order of the scores on the output should correspond to the order of the games on the input. 
*Sample Input*
4 3 6 2 1 3 4 2 7 1 1 0 2 3 4 5 8 0 5 2
1 0 1 / 2 2 X 3 3 X 1 / 3 / X 1 2
1 0 1 / 2 2 X 3 3 X 1 / 3 / 1 / 8 / 9
Done
Output for the Sample Input
63
108
120

Was thinking about a week for this one to be up and done will post another next week unless someone else wants to post one. 7/21/2010 End Date


----------



## impatient

Here is a scala implementation.

Code:



Code:


class Frame(aOne:String, aTwo:String) {

def frameTyp:String = {
if(one==10) return "strike"; 
if(one + two == 10) return "spare"; 
return "normal";
}
var one:Int = aOne.toInt;
var two:Int = if(aTwo.equals("/")) 10 - one; else aTwo.toInt

var nextFrame:Frame = null;
//too lazy to do a bunch of null checks
def getNextFrame():Frame = { if(nextFrame == null) return new Frame("0","0"); return nextFrame;}

 def nextTwo(): Int = {
getNextFrame.frameTyp match {
  case "strike" => getNextFrame.one + getNextFrame.getNextFrame.one
                          case _        => getNextFrame.one + getNextFrame.two
}
           }
 def score():Int = { 
                   var a = frameTyp match {
                      case "strike" => 10 + nextTwo()
                      case "spare" => 10 + getNextFrame.one
                      case "normal" => one + two;
}
return a;
}

override def toString():String = { "(" + one + "," + two + ") =>" + score}
}

def totalFrames(inpList:String)
{
//replace X's with 10 0
var frameList = List.fromString(inpList.replace("X", "10 0"), ' ')

//if odd number of times bowled, add empty one 
if(frameList.size %2 == 1) frameList = frameList ::: List("0")
frameList = frameList.reverse
var operationList:List[Frame] = List[Frame]()

//store the "next" frame 
var currFrame:Frame = null

//every frame is two turns now
//doing this in reverse so that we always have the next frame handy
while(frameList.size > 0)
{
        //get first two items in list
var a = frameList.take(2);

        //1,0 due to reverse
val tempFrame = new Frame(a(1), a(0))
tempFrame.nextFrame=currFrame

        //get remaining frames
        frameList=frameList.drop(2);
        //always adding to the front of the list, so this list ends up in the proper order
operationList = tempFrame::operationList 
currFrame=tempFrame

}

//fancy way to sum
var total = operationList.map(x => x.score).foldLeft(0)(_ + _)

//apparently i didn't understand how bowling worked forever
//don't count the last two if beyond the 10'th frame except for scoring in 9th + 10th frames
if(operationList.size > 10) { total = total - operationList.drop(10).map(x => x.score).foldLeft(0)(_ + _) }
println(total)
}

//abuses memory
scala.io.Source.fromFile("sample.txt").getLines.mkString.lines.foreach{i => println(i); totalFrames(i)}

4 3 6 2 1 3 4 2 7 1 1 0 2 3 4 5 8 0 5 2
63
1 0 1 / 2 2 X 3 3 X 1 / 3 / X 1 2
108
1 0 1 / 2 2 X 3 3 X 1 / 3 / 1 / 8 / 9
120


----------



## xtascox

Will give it a go tomorrow evening after I finish some unit tests on some new stuff for work.


----------



## impatient

good call not to do it at work... i had to spend an evening catching up


----------



## Midpipps

OK I did a really quick one just for fun it is horribly programmed and definitely not what anyone would call good but it works.

Code:



Code:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Bowling
{
    public partial class frmBowling : Form
    {
        private TextReader fileReader;
        public frmBowling()
        {
            InitializeComponent();
        }

        private void frmBowling_Load(object sender, EventArgs e)
        {
            fileReader = new StreamReader("sample.txt");

        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            if (!(fileReader.Peek() == -1))
            {
                String[] gameString = fileReader.ReadLine().Split(' ');
                //I know this is a crappy way of doing this but don't really care it works 
                //and I don't want to take the time to position all those darned textboxes
                TextBox[] pins = new TextBox[] {txtpins1_1, txtpins1_2, txtpins2_1, txtpins2_2, 
                    txtpins3_1, txtpins3_2, txtpins4_1,   txtpins4_2, txtpins5_1, txtpins5_2, txtpins6_1,
                    txtpins6_2, txtpins7_1, txtpins7_2, txtpins8_1, txtpins8_2, txtpins9_1, txtpins9_2,
                    txtpins10_1, txtpins10_2, txtpins10_3};
                for (int i = 0; i < pins.Length; i++)
                    pins[i].Text = "";

                /*Put the pin counts into the upper textboxes sort of like the standard bowling sheet*/
                int count = 0;
                int frame = 0;
                for (int i = 0; i < gameString.Length; i += 1)
                {
                    if (gameString[i].ToLower().Contains('x'))
                    {
                        pins[count].Text = gameString[i];
                        if (frame != 10)
                            frame += 1;
                        if (frame == 10)
                            count += 1;
                        else
                        {
                            count += 2;
                        }
                    }
                    else
                    {
                        pins[count].Text = gameString[i];
                        count++;
                        if (count % 2 == 0 && frame != 10)
                        {
                            frame += 1;
                        }
                    }
                }

                /*Yep Being lazy again gonna make it one long program :)*/
                TextBox[] scores = new TextBox[] {txtScore1, txtScore2,txtScore3,txtScore4,
                    txtScore5,txtScore6,txtScore7,txtScore8,txtScore9,txtScore10};
                count = 0;
                frame = 0;
                int currentScore = 0;
                for (int i = 0; i < scores.Length; i++)
                    scores[i].Text = "";

                for (int i = 0; i < scores.Length; i += 1)
                {
                    frame++;
                    if (frame == 10)
                    {
                        if (pins[18].Text.ToLower().Contains('x'))
                            currentScore += 10;
                        else if (pins[18].Text.ToLower().Contains('/'))
                            currentScore += 10;
                        else if (pins[18].Text.Length > 0  && !(pins[19].Text.ToLower().Contains('/')))
                            currentScore += int.Parse(pins[18].Text);

                        if (pins[19].Text.ToLower().Contains('x'))
                            currentScore += 10;
                        else if (pins[19].Text.ToLower().Contains('/'))
                            currentScore += 10;
                        else if (pins[19].Text.Length > 0)
                            currentScore += int.Parse(pins[19].Text);

                        if (pins[20].Text.ToLower().Contains('x'))
                            currentScore += 10;
                        else if (pins[20].Text.ToLower().Contains('/'))
                            currentScore += 10;
                        else if (pins[20].Text.Length > 0)
                            currentScore += int.Parse(pins[20].Text);
                    }
                    else
                    {
                        if (pins[i * 2].Text.Length > 0)
                        {
                            if (pins[i * 2].Text.ToLower().Contains('x'))
                            {
                                currentScore += 10;
                                if (pins[(i * 2) + 2].Text.ToLower().Contains('x'))
                                {
                                    currentScore += 10;
                                    if (pins[(i * 2) + 4].Text.ToLower().Contains('x'))
                                        currentScore += 10;
                                    else
                                    {
                                        currentScore += int.Parse(pins[(i * 2) + 4].Text);
                                    }
                                }
                                else if (pins[(i * 2) + 3].Text.ToLower().Contains('/'))
                                    currentScore += 10;
                                else
                                {
                                    currentScore += int.Parse(pins[(i * 2) + 2].Text);
                                    currentScore += int.Parse(pins[(i * 2) + 3].Text);
                                }
                            }
                            else if (pins[(i * 2) + 1].Text.ToLower().Contains('/'))
                            {
                                currentScore += 10;
                                if (pins[(i * 2) + 2].Text.ToLower().Contains('x'))
                                    currentScore += 10;
                                else
                                    currentScore += int.Parse(pins[(i * 2) + 2].Text);
                            }
                            else
                                currentScore += int.Parse(pins[i * 2].Text) + int.Parse(pins[(i * 2) + 1].Text);

                        }
                    }
                    scores[i].Text = "\
\
\
\
" + currentScore.ToString();

                }

            }
            else
            {
                MessageBox.Show("There are no more score sorry", "ERROR", MessageBoxButtons.OK);
                this.Close();
            }
        }

    }
}

the sample.txt

Code:



Code:


4 3 6 2 1 3 4 2 7 1 1 0 2 3 4 5 8 0 5 2
1 0 1 / 2 2 X 3 3 X 1 / 3 / X 1 2
1 0 1 / 2 2 X 3 3 X 1 / 3 / 1 / 8 / 9
4 3 6 2 1 3 4 2 7 1 1 0 2 3 4 5 8 0 5 2
1 0 1 / 2 2 X 3 3 X 1 / 3 / X 1 2
1 0 1 / 2 2 X 3 3 X 1 / 3 / 1 / 8 / 9
1 0 1 / 2 2 X 3 3 X 1 / 3 / 1 / X 8 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
X X X X X X X X X X X X

and a screenshot for you all


----------



## nathris

Code:



Code:


#include <iostream>
#include <string>
using namespace std;
struct frame{ int t1,t2,s; };
int main(int argc, char** argv)
{
int total = 0, i = 0;
frame score[10];
string c = argv[1];
for(int f = 0; f<10; f++){
if(c[i] == 'X' && f != 9)   score[f] = {10,-1,-i++};
else if (c[i] == 'X' && f == 9){   
  score[f].t1 = 10;
  if(c[i+1] == 'X') score[f].t2 = 10;
  else    score[f].t2 = c[i+1] - '0';
  if(c[i+2] == 'X' || c[i+2] == '/') score[f].t2 +=10;
  else    score[f].t2 +=c[i+2] - '0';
  score[f].s = score[f].t1 + score[f].t2;
}else if (c[i+1] == '/' && f!=9)   score[f] = {c[i++]-'0',10,-i++};
else if (c[i+1] == '/' && f==9)   score[f] = {c[i]-'0', 10, 10+c[i+2]-'0'};
else       score[f] = {c[i]-'0',c[i+1]-'0',c[i++]-'0' + c[i++]-'0'};
}
for(int f = 9; f>=0; f--){
if(score[f].s <= 0){
if(score[f].t1 == 10){
if(score[f+1].t1 == 10 && f != 8) score[f].s = 20 + score[f+2].t1;
else if(score[f+1].t1 == 10 && f == 8) score[f].s = 10 + score[f+1].t2;
else if(score[f+1].t2 == 10) score[f].s = 20;
elsescore[f].s = 10 + score[f+1].t1 + score[f+1].t2;
}else if(score[f].t2 == 10) score[f].s = 10 + score[f+1].t1;
}
total += score[f].s;
}
cout << "Total is " << total << endl;
}

Managed to get it down to 35 lines (without making it completely unreadable).

It should be less, but there are too many special conditions to handle.


















I deviated a little from the format, but its really only a couple of extra lines of string parsing to get it to comply with the spec.


----------



## Midpipps

Yeah don't worry about Following them to the T this is supposed to be fun. Bowling is deviously simple looking until you start programming it though isn't it?


----------



## nathris

It wasn't too bad, and now I finally understand bowling scores.

I tried doing it in a single pass. Almost got it too, but I couldn't figure out how to tell the difference between a strike in the 9th frame followed by an open frame and a strike in the 10th followed by 2 additional throws.


----------



## Midpipps

OK Here is the next one

*Palindrome Crawler*

A palindrome is a string that reads the same forwards as backwards. Examples include abba and yobananaboy.
You are to develop a program that, given a string, indentifies all its substrings of length three or more that are palindromes.

*Input:
*The first line contains a positive integer, n, indicating the number of strings that are to be analyzed. Each of the following lines contains one string.

*Output:*
For each string given as input, echo that string on one line and then on subsequent lines, list all its substrings of length three of more that are palindromes, one per line. A blank line should be printed between each set of solutions. Each palindromic substring should appear only once in the string's output, even if it occurs multiple times in the string. The order the solutions appear does not matter.

*Sample Input:*
3
baabbab
bbacb
aabababaab

*Corresponding output:*
baabbab
baab
abba
bab

bbacb

aabababaab
aabababaa
aba
bab
ababa
babab
abababa
baab

Next Program post: 7/28/2010


----------



## impatient

Now fixed... i think

Code:



Code:


def getString(l:Int, str:String):List[String] = { if(str.length <= 0) return List[String](str) else return List[String](str) ::: getString(l,str.drop(1))  }

def buildString(l:Int, str:String):List[String] = { if(str.length <= l) return List[String](str) else return List[String](str) ::: buildString(l,str.drop(1)) }

def isPal(str:String):Boolean = { 
val meet = str.length % 2 ; 
val spl = str.length / 2; 
val strList = str.toList
val zipperd = strList.slice(0,spl).zip(strList.slice(spl+meet,str.length).reverse)
zipperd.map( x => if(x._1 != x._2) return false); 
if(str.length >= 3){
println(str); return true;
}
return false; 
}

val lineList = scala.io.Source.fromFile("sample2.txt").getLines.mkString.lines.toList
val size = lineList(0).toInt
val samples = lineList.drop(1)

def getPals(l:Int,str:String)
{
  println("Evaluating " + str)
  buildString(l, str).map(x => getString(size,x.reverse)).flatMap(x=>x).map(x => isPal(x))
}
samples.foreach(
  y => getPals(2, y));

I don't check for uniqueness, so I have some dupes on the last one.

Evaluating baabbab
baab
abba
bab
Evaluating bbacb
Evaluating aabababaab
aabababaa
abababa
ababa
aba
babab
bab
ababa
aba
bab
aba
baab


----------



## xtascox

Here's my quick Java implementation:

*PalindromeCrawler.java*

Code:



Code:


package ocn.challenges.palindrome;

import java.util.List;

public class PalindromeCrawler {
public static void main(String[] args) throws Exception{

if(args.length != 1) {
System.out.println("Please provide a filename as an argument");
System.exit(0);
}

PalindromeFinder pf = new PalindromeFinder();

List<String> strings = pf.getStringsFromFile(args[0]);

System.out.println("********* \
");

for(String string : strings) {
if(string.length() >= 3) {
List<String> strs = pf.splitString(string);

System.out.println(string + "\
");

strs = pf.findPalindromes(strs);

for(String str : strs)
System.out.println(str);

System.out.println("\
********* \
");
}
}
}
}

*PalindromeFinder.java*

Code:



Code:


package ocn.challenges.palindrome;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class PalindromeFinder {
public static final int MIN_STRING_SPLIT = 3;

public List<String> splitString(String str) {
List<String> stringList = new ArrayList<String>();

if (str.length() < MIN_STRING_SPLIT) {
stringList.add("String length must be atleast " + MIN_STRING_SPLIT);
return stringList;
}

for(int i = 0; i < str.length() - (MIN_STRING_SPLIT - 1);  i++) {
for(int j = (i + MIN_STRING_SPLIT); j <= str.length(); j++) {
stringList.add(str.substring(i, j));
}
}

return stringList;
}

public List<String> findPalindromes(List<String> stringList) {
String temp = "";
List<String> result = new ArrayList<String>();

for(String str : stringList) {
temp = reverseString(str);

if(temp.equals(str))
result.add(str);
}

return result;
}

public List<String> getStringsFromFile(String fileName) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
List<String> strings = new ArrayList<String>();
String holder = "";

while(true) {
holder = reader.readLine();
if(holder != null){
strings.add(holder);
continue;
}
break;
}
return strings;
}

private String reverseString(String str) {
String temp = "";
char[] chars = new char[str.length()];
str.getChars(0, str.length(), chars, 0);

for(int i = 0; i < chars.length; i++)
temp += chars[chars.length - 1 -i];

return temp;
}
}


----------



## Midpipps

This is for Xtasco

Code:



Code:


import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int problems = 0;
problems = console.nextInt();
for ( int i = 0; i < problems;i++){
String input = "";
input = console.next();
System.out.println(input);
String used = "";
for(int a = 0; a < input.length();a++){
for (int j = a; j < input.length(); j++){
if (ispal(input.substring(a,j+1))){
if(input.substring(a,j+1).length() > 2 && used.indexOf(","+input.substring(a,j+1)+",") == -1 )
System.out.println(input.substring(a,j+1));
used += "," + input.substring(a,j+1) +",";
}
}
}
System.out.println("");
}//end for i
}
public static boolean ispal(String str){
int len = str.length();
int z,g;
g = len-1;
for (z = 0; z <= (len - 1)/2; z++){
if (str.charAt(z) != str.charAt(g))
return false;
g--;
}
return true;
}
}

next comes the one for python my try at python something is still wrong with it though.
Edited the code it is fixed I was missing a part of the check string

Code:



Code:


import fileinput
import linecache

#going to give python a shot don't laugh to hard
fileIn = open("palindrome.txt", "r")
numberOfLines = int(fileIn.readline())
for i in range(0, numberOfLines):
    originalString = fileIn.readline()
    print()
    print(originalString)
    alreadyused = ""
    for a in range(0,len(originalString)):
        for j in range(a, len(originalString)):
            test = originalString[a:j]
            if test == test[::-1] and len(test) >=3 and ("," + test + ",") not in alreadyused:
                print(test)
                alreadyused += "," + test + ","


----------



## GodofGrunts

Quote:

next comes the one for python my try at python something is still wrong with it though.
Edited the code it is fixed I was missing a part of the check string

Code:



Code:


import fileinput
import linecache

#going to give python a shot don't laugh to hard
fileIn = open("palindrome.txt", "r")
numberOfLines = int(fileIn.readline())
for i in range(0, numberOfLines):
    originalString = fileIn.readline()
    print()
    print(originalString)
    alreadyused = ""
    for a in range(0,len(originalString)):
        for j in range(a, len(originalString)):
            test = originalString[a:j]
            if test == test[::-1] and len(test) >=3 and ("," + test + ",") not in alreadyused:
                print(test)
                alreadyused += "," + test + ","


O.O You're python code is so simple that it's brilliant!


----------



## Midpipps

Quote:


Originally Posted by *GodofGrunts* 
O.O You're python code is so simple that it's brilliant!

Thank you. It is simple yes. Not very efficient but it works.


----------



## GodofGrunts

Quote:


Originally Posted by *Midpipps* 
Thank you. It is simple yes. Not very efficient but it works.

Exactly, but the pure simplicity blows my mind.


----------



## dangerousHobo

*Palindrome Crawler* in C++
does not handle duplicates, but might fix that later
See C++ can be simple and clean too (and fast)

Code:



Code:


#include <iostream>
#include <fstream>
#include <string>

bool compare(const int i, const int k, const std::string s) {
    if (i == k)
        return true;
    if (i + 1 == k)
        return (s[i] == s[k]);
    return (compare(i+1, k-1, s) && s[i] == s[k]);
}

int main(const int argc, const char **argv) {
    std::ifstream inFile;
    inFile.open(argv[1], std::ios::in);
    if (!inFile) exit(1);

    std::string s;
    while (!inFile.eof()) {
        inFile >> s;
        std::cout << "EVAL: " << s << std::endl;
        for (int i = 0; i < s.size() - 2; i++) {
            for (int k = i + 2; k < s.size(); k++) {
                if (compare(i, k, s))
                    std::cout << s.substr(i,k+1-i) <<  std::endl;
            }
        }
    }
    inFile.close();

}


----------



## Midpipps

Quote:


Originally Posted by *dangerousHobo* 
*Palindrome Crawler* in C++
does not handle duplicates, but might fix that later
See C++ can be simple and clean too (and fast)

Code:



Code:


#include <iostream>
#include <fstream>
#include <string>

bool compare(const int i, const int k, const std::string s) {
    if (i == k)
        return true;
    if (i + 1 == k)
        return (s[i] == s[k]);
    return (compare(i+1, k-1, s) && s[i] == s[k]);
}

int main(const int argc, const char **argv) {
    std::ifstream inFile;
    inFile.open(argv[1], std::ios::in);
    if (!inFile) exit(1);

    std::string s;
    while (!inFile.eof()) {
        inFile >> s;
        std::cout << "EVAL: " << s << std::endl;
        for (int i = 0; i < s.size() - 2; i++) {
            for (int k = i + 2; k < s.size(); k++) {
                if (compare(i, k, s))
                    std::cout << s.substr(i,k+1-i) <<  std::endl;
            }
        }
    }
    inFile.close();

}


That is some nice code I like it.


----------



## rabidgnome229

python

Code:



Code:


#!/usr/bin/env python
import sys

def main(argv):
    f = open(argv[1], "r")
    for line in f.readlines()[1:]:
        print line[:-1]
        palindromes = set()
        for start in range(0, len(line) - 2): 
            for end in range(start+3, len(line)):
                substring = line[start:end]
                if (substring == substring[::-1]) and (substring not in palindromes):
                    print substring
                    palindromes.add(substring)
        print ''

if __name__ == "__main__":
    main(sys.argv)


----------



## Midpipps

Quote:


Originally Posted by *rabidgnome229* 
python

Code:



Code:


#!/usr/bin/env python
import sys

def main(argv):
    f = open(argv[1], "r")
    for line in f.readlines()[1:]:
        print line[:-1]
        palindromes = set()
        for start in range(0, len(line) - 2): 
            for end in range(start+3, len(line)):
                substring = line[start:end]
                if (substring == (substring)[::-1]) and (substring not in palindromes):
                    print substring
                    palindromes.add(substring)
        print ''

if __name__ == "__main__":
    main(sys.argv)


I like this one too looks so much cleaner then mine and doesn't waste doing the less then 3 like mine does.


----------



## dangerousHobo

now it can handle duplicates, thanks to the STL

Code:



Code:


#include <iostream>
#include <fstream>
#include <string>
#include <set>

using namespace std;

bool compare(const int i, const int k, const string& s) {
    if (i == k)
        return true;
    if (i + 1 == k)
        return (s[i] == s[k]);
    return (compare(i+1, k-1, s) && s[i] == s[k]);
}

int main(const int argc, const char **argv) {
    ifstream inFile;
    inFile.open(argv[1], ios::in);
    if (!inFile) exit(1);

    set<string> st;
    pair<set<string>::iterator, bool> ret;
    string s;
    while (!inFile.eof()) {
        inFile >> s;
        cout << "EVAL: " << s << endl;
        for (int i = 0; i < s.size() - 2; i++) {
            for (int k = i + 2; k < s.size(); k++)
                if (compare(i, k, s)) {
                    ret = st.insert(s.substr(i, k+1-i));
                    if (ret.second == true)
                        cout << s.substr(i,k+1-i) << endl;
                }
        }
        st.clear();
    }
    inFile.close();
    return 0;
}

I like the python rabid.


----------



## Midpipps

Was looking through all the ones I had and none jumped out as fun for this week so I decided to change it up a little and make one up.

Gonna give xtascox suggestion from this thread to see if we can maybe pull in a few more people.

gonna split into levels so that it can be as hard or easy as you would like.

So here it is.

*TIC-TAC-TOE*

Make a game of TIC-TAC-TOE

*level 1:* simple 2 player game

can be based in console window if you would like to just make it text based
does not have to have a win condition if you do not want to program one.
*level 2:* 2 player game

graphical user interface
has a win condition
*level 3:* player vs computer

has to have an system in place for the human player to play against
has to have a win condition built into the game part.
*Side programming challenge:* If I get enough responses I will work on a program to pit computer against computer will make it in C++ or whatever language most people want to use. your program would have to be in a class that I could include and call.

How it would work:
instantiation = will be passed in a char of whether you are X or O
data passed to class when getting next move= 3X3 array of chars
returned value = where you would like your piece to go have not figured out exactly what I would do here was thinking maybe a string position 1 = left to right and position 2 = top to bottom
Example: a return of 02 would be left most bottom cell. etc. 00 left most top cell 20 right most top cell.

just a thought will not worry about it unless I get some replies though.

Head here and weigh in on whether the last few programs have been too easy or not

Next challenge post 8/4/2010

The versus Challenge has a 2 week go so next versus will be: 8/11/2010


----------



## xtascox

This one looks fun. Maybe I'll have a co-worker of mine that happens to have a Ph.D. in A.I. give me some tips on the computer controlled aspect


----------



## xtascox

How about for the side challenge someone or I will throw together a simple tic-tac-toe server?

Here's my idea:

Code:


Code:


>RESTful web services as a listener

-Wait for two clients to want to start a game
-Assign each a unique id
-Wait for move commands from each client
  --Reject any additional moves sent during a turn
  --When both clients moves have been sent, record each move respectfully
     and then return the following response to the clients:
                ---OpponentMoveGridLocation
                ---MoveSuccessful or MoveFailed
                ---EndGameConditionReached

MoveFailed could most likely be caused by the opponent moving into the spot you wanted.

Ideally you can use any language you are comfortable with as long as you can do HTTP GETs and POSTs with it.

Who knows, we may end up expanding this and allowing for larger grids and multiple concurrent games.


----------



## chatch15117

Quote:



Originally Posted by *xtascox*


This one looks fun. Maybe I'll have a co-worker of mine that happens to have a Ph.D. in A.I. give me some tips on the computer controlled aspect










You don't need AI. Just a simple backtracking algorithm etc.


----------



## xtascox

Quote:



Originally Posted by *chatch15117*


You don't need AI. Just a simple backtracking algorithm etc.


Yes I know, I was over exaggerating


----------



## wcdolphin

Quote:



Originally Posted by *chatch15117*


You don't need AI. Just a simple backtracking algorithm etc.


Backtracking will present you with every option, are you planning to rank each outcome?
Things could get interesting if you hashed using a node like structure, adding probability to a given outcome based upon the summation of different outcomes possible after making a given move








Minimax theroem anyone?http://en.wikipedia.org/wiki/Minimax...inimax_theorem
Totally doable...
Setup the webserver and I am in...It will likely be Java however, my C++ is not up to scratch >.<


----------



## xtascox

Quote:



Originally Posted by *cdolphin*


Backtracking will present you with every option, are you planning to rank each outcome?
Things could get interesting if you hashed using a node like structure, adding probability to a given outcome based upon the summation of different outcomes possible after making a given move








Minimax theroem anyone?http://en.wikipedia.org/wiki/Minimax...inimax_theorem
Totally doable...
Setup the webserver and I am in...It will likely be Java however, my C++ is not up to scratch >.<


I'll work on something in my free time and post up the API along with the URI's.

Any chance we can make this a 2 week project?


----------



## chatch15117

I'm ready but I have it in java









Code:


Code:


/****************************************************************/
/*                      TicTacToe                            */
/*@author               chatch15117                           */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * Summary description for TicTacToe
 *
 */
public class TicTacToe extends JFrame
{
// Variables declaration
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JButton jButton1;
private JButton jButton2;
private JPanel contentPane;
//-----
private JButton jButton3;
private JButton jButton4;
private JButton jButton5;
private JButton jButton6;
private JButton jButton7;
private JButton jButton8;
private JButton jButton9;
private JButton jButton10;
private JButton jButton11;
private JButton jButton12;
private JButton jButton13;
private JPanel jPanel1;
//-----
// End of variables declaration

public TicTacToe()
{
super();
initializeComponent();

this.setVisible(true);
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always regenerated
 * by the Windows Form Designer. Otherwise, retrieving design might not work properly.
 * Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
 * to retrieve your design properly in future, before revising this method.
 */
private void initializeComponent()
{
jLabel1 = new JLabel();
jLabel2 = new JLabel();
jLabel3 = new JLabel();
jButton1 = new JButton();
jButton2 = new JButton();
contentPane = (JPanel)this.getContentPane();
//-----
jButton3 = new JButton();
jButton4 = new JButton();
jButton5 = new JButton();
jButton6 = new JButton();
jButton7 = new JButton();
jButton8 = new JButton();
jButton9 = new JButton();
jButton10 = new JButton();
jButton11 = new JButton();
jButton12 = new JButton();
jButton13 = new JButton();
jPanel1 = new JPanel();
//-----

//
// jLabel1
//
jLabel1.setText("Turn: X");
//
// jLabel2
//
jLabel2.setText("X- Wins: 0");
//
// jLabel3
//
jLabel3.setText("O- Wins: 0");
//
// jButton12
//
jButton12.setText("CPU");
jButton12.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton12_actionPerformed(e);
}
});
//
// jButton13
//
jButton13.setText("Person");
jButton13.setEnabled(false);
jButton13.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton13_actionPerformed(e);
}
});
//
// jButton1
//
jButton1.setText("New Game");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton1_actionPerformed(e);
}

});
//
// jButton2
//
jButton2.setText("Reset");
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton2_actionPerformed(e);
}

});
//
// contentPane
//
contentPane.setLayout(null);
addComponent(contentPane, jLabel1, 175,0,60,18);
addComponent(contentPane, jLabel2, 175,15,60,18);
addComponent(contentPane, jLabel3, 175,30,60,18);
addComponent(contentPane, jButton1, 175,45,90,28);
addComponent(contentPane, jButton2, 175,73,90,28);
addComponent(contentPane, jButton12, 175,101,90,28);
addComponent(contentPane, jButton13, 175,130,90,28);
addComponent(contentPane, jPanel1, 2,0,175,175);
//
// jButton3
//
jButton3.setText("");
jButton3.setMaximumSize(new Dimension(50, 50));
jButton3.setMinimumSize(new Dimension(50, 50));
jButton3.setPreferredSize(new Dimension(50, 50));
jButton3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton3_actionPerformed(e);
}

});
//
// jButton4
//
jButton4.setText("");
jButton4.setMaximumSize(new Dimension(50, 50));
jButton4.setMinimumSize(new Dimension(50, 50));
jButton4.setPreferredSize(new Dimension(50, 50));
jButton4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton4_actionPerformed(e);
}

});
//
// jButton5
//
jButton5.setText("");
jButton5.setMaximumSize(new Dimension(50, 50));
jButton5.setMinimumSize(new Dimension(50, 50));
jButton5.setPreferredSize(new Dimension(50, 50));
jButton5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton5_actionPerformed(e);
}

});
//
// jButton6
//
jButton6.setText("");
jButton6.setMaximumSize(new Dimension(50, 50));
jButton6.setMinimumSize(new Dimension(50, 50));
jButton6.setPreferredSize(new Dimension(50, 50));
jButton6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton6_actionPerformed(e);
}

});
//
// jButton7
//
jButton7.setText("");
jButton7.setMaximumSize(new Dimension(50, 50));
jButton7.setMinimumSize(new Dimension(50, 50));
jButton7.setPreferredSize(new Dimension(50, 50));
jButton7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton7_actionPerformed(e);
}
});
//
// jButton8
//
jButton8.setText("");
jButton8.setMaximumSize(new Dimension(50, 50));
jButton8.setMinimumSize(new Dimension(50, 50));
jButton8.setPreferredSize(new Dimension(50, 50));
jButton8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton8_actionPerformed(e);
}
});
//
// jButton9
//
jButton9.setText("");
jButton9.setMaximumSize(new Dimension(50, 50));
jButton9.setMinimumSize(new Dimension(50, 50));
jButton9.setPreferredSize(new Dimension(50, 50));
jButton9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton9_actionPerformed(e);
}
});
//
// jButton10
//
jButton10.setText("");
jButton10.setMaximumSize(new Dimension(50, 50));
jButton10.setMinimumSize(new Dimension(50, 50));
jButton10.setPreferredSize(new Dimension(50, 50));
jButton10.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton10_actionPerformed(e);
}
});
//
// jButton11
//
jButton11.setText("");
jButton11.setMaximumSize(new Dimension(50, 50));
jButton11.setMinimumSize(new Dimension(50, 50));
jButton11.setPreferredSize(new Dimension(50, 50));
jButton11.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton11_actionPerformed(e);
}
});
//
// jPanel1
//
jPanel1.setLayout(new FlowLayout(FlowLayout.CENTER, 3, 3));
jPanel1.add(jButton3, 0);
jPanel1.add(jButton4, 1);
jPanel1.add(jButton5, 2);
jPanel1.add(jButton6, 3);
jPanel1.add(jButton7, 4);
jPanel1.add(jButton8, 5);
jPanel1.add(jButton9, 6);
jPanel1.add(jButton10, 7);
jPanel1.add(jButton11, 8);
//
// TicTacToe
//
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
this.setTitle("TicTacToe");
this.setLocation(new Point((int)screensize.getWidth() /2 - 138, (int)screensize.getHeight()/2 - 93));
this.setSize(new Dimension(275, 185));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.setResizable(false);
}

/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
{
c.setBounds(x,y,width,height);
container.add(c);
}

int turn = 1, xwins = 0, owins = 0;
boolean win = false, cpu = false;
private void jButton1_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton1_actionPerformed(ActionEvent e) called.");
newGame();
}

private void jButton2_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton2_actionPerformed(ActionEvent e) called.");
reset();
}

private void jButton3_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton3_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton3.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton3.setText("O");
jLabel1.setText("Turn: X");
}
jButton3.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(3);

}

private void jButton4_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton4_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton4.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton4.setText("O");
jLabel1.setText("Turn: X");
}
jButton4.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(4);
}

private void jButton5_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton5_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton5.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton5.setText("O");
jLabel1.setText("Turn: X");
}
jButton5.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(5);
}

private void jButton6_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton6_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton6.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton6.setText("O");
jLabel1.setText("Turn: X");
}
jButton6.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(6);
}

private void jButton7_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton7_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton7.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton7.setText("O");
jLabel1.setText("Turn: X");
}
jButton7.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(7);
}

private void jButton8_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton8_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton8.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton8.setText("O");
jLabel1.setText("Turn: X");
}
jButton8.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(8);
}

private void jButton9_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton9_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton9.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton9.setText("O");
jLabel1.setText("Turn: X");
}
jButton9.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(9);
}

private void jButton10_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton10_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton10.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton10.setText("O");
jLabel1.setText("Turn: X");
}
jButton10.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(10);
}

private void jButton11_actionPerformed(ActionEvent e)
{
System.out.println("\
jButton11_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton11.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton11.setText("O");
jLabel1.setText("Turn: X");
}
jButton11.setEnabled(false);
checkWin();
turn *= -1;
if(cpu && !win) playCPU(11);
}

private void jButton12_actionPerformed(ActionEvent e)
{
jButton12.setEnabled(false);
jButton13.setEnabled(true);
cpu = true;
}

private void jButton13_actionPerformed(ActionEvent e)
{
jButton12.setEnabled(true);
jButton13.setEnabled(false);
cpu = false;
}

private void checkWin()
{
if( jButton3.getText() == jButton4.getText() && jButton4.getText() == jButton5.getText() && jButton3.getText() != ""){
win = true;
}
else if(jButton6.getText() == jButton7.getText() && jButton7.getText() == jButton8.getText() && jButton6.getText() != ""){
win = true;
}
else if(jButton9.getText() == jButton10.getText() && jButton10.getText() == jButton11.getText() && jButton9.getText() != ""){
win = true;
}

//virticle wins
else if(jButton3.getText() == jButton6.getText() && jButton6.getText() == jButton9.getText() && jButton3.getText() != ""){
win = true;
}
else if(jButton4.getText() == jButton7.getText() && jButton7.getText() == jButton10.getText() && jButton4.getText() != ""){
win = true;
}
else if(jButton5.getText() == jButton8.getText() && jButton8.getText() == jButton11.getText() && jButton5.getText() != ""){
win = true;
}

//diagonal wins
else if(jButton3.getText() == jButton7.getText() && jButton7.getText() == jButton11.getText() && jButton3.getText() != ""){
win = true;
}
else if(jButton5.getText() == jButton7.getText() && jButton7.getText() == jButton9.getText() && jButton5.getText() != ""){
win = true;
}
else {
win = false;
}
if (win && turn == 1) 
{
JOptionPane.showMessageDialog(null, "X Wins!!");
xwins++;
}
if (win && turn == -1)
{
JOptionPane.showMessageDialog(null, "O Wins!!");
owins++;
}
if (win)
{
jButton3.setEnabled(false);
jButton4.setEnabled(false);
jButton5.setEnabled(false);
jButton6.setEnabled(false);
jButton7.setEnabled(false);
jButton8.setEnabled(false);
jButton9.setEnabled(false);
jButton10.setEnabled(false);
jButton11.setEnabled(false);
}
}

private void newGame()
{
jButton3.setEnabled(true);
jButton4.setEnabled(true);
jButton5.setEnabled(true);
jButton6.setEnabled(true);
jButton7.setEnabled(true);
jButton8.setEnabled(true);
jButton9.setEnabled(true);
jButton10.setEnabled(true);
jButton11.setEnabled(true);

jButton3.setText("");
jButton4.setText("");
jButton5.setText("");
jButton6.setText("");
jButton7.setText("");
jButton8.setText("");
jButton9.setText("");
jButton10.setText("");
jButton11.setText("");

jLabel2.setText("X- Wins: " + xwins);
jLabel3.setText("O- Wins: " + owins);

}

private void reset()
{
xwins = 0;
owins = 0;
newGame();
}

private void playCPU(int i)
{
if (i == 3)
{
if (jButton5.getText() == "") cpu5();
else if (jButton3.getText() == "") cpu3();
else if (jButton7.getText() == "") cpu7();
else if (jButton9.getText() == "") cpu9();
else if (jButton11.getText() == "") cpu11();
else if (jButton4.getText() == "") cpu4();
else if (jButton8.getText() == "") cpu8();
else if (jButton6.getText() == "") cpu6();
else if (jButton10.getText() == "") cpu10();
}
if (i == 4)
{
if (jButton7.getText() == "") cpu7();
else if (jButton10.getText() == "") cpu10();
else if (jButton5.getText() == "") cpu5();
else if (jButton9.getText() == "") cpu9();
else if (jButton11.getText() == "") cpu11();
else if (jButton3.getText() == "") cpu3();
else if (jButton8.getText() == "") cpu8();
else if (jButton6.getText() == "") cpu6();
else if (jButton4.getText() == "") cpu4();
}
if (i == 5)
{
if (jButton7.getText() == "") cpu7();
else if (jButton3.getText() == "") cpu3();
else if (jButton5.getText() == "") cpu5();
else if (jButton9.getText() == "") cpu9();
else if (jButton11.getText() == "") cpu11();
else if (jButton4.getText() == "") cpu4();
else if (jButton8.getText() == "") cpu8();
else if (jButton6.getText() == "") cpu6();
else if (jButton10.getText() == "") cpu10();
}
if (i == 6)
{
if (jButton9.getText() == "") cpu9();
else if (jButton8.getText() == "") cpu8();
else if (jButton5.getText() == "") cpu5();
else if (jButton7.getText() == "") cpu7();
else if (jButton11.getText() == "") cpu11();
else if (jButton4.getText() == "") cpu4();
else if (jButton3.getText() == "") cpu3();
else if (jButton6.getText() == "") cpu6();
else if (jButton10.getText() == "") cpu10();
}
if (i == 7)
{
if (jButton7.getText() == "") cpu7();
else if (jButton3.getText() == "") cpu3();
else if (jButton5.getText() == "") cpu5();
else if (jButton9.getText() == "") cpu9();
else if (jButton11.getText() == "") cpu11();
else if (jButton8.getText() == "") cpu8();
else if (jButton4.getText() == "") cpu4();
else if (jButton6.getText() == "") cpu6();
else if (jButton10.getText() == "") cpu10();
}
if (i == 8)
{
if (jButton7.getText() == "") cpu7();
else if (jButton6.getText() == "") cpu6();
else if (jButton5.getText() == "") cpu5();
else if (jButton11.getText() == "") cpu11();
else if (jButton9.getText() == "") cpu9();
else if (jButton4.getText() == "") cpu4();
else if (jButton8.getText() == "") cpu8();
else if (jButton3.getText() == "") cpu3();
else if (jButton10.getText() == "") cpu10();
}
if (i == 9)
{
if (jButton7.getText() == "") cpu7();
else if (jButton3.getText() == "") cpu3();
else if (jButton5.getText() == "") cpu5();
else if (jButton9.getText() == "") cpu9();
else if (jButton11.getText() == "") cpu11();
else if (jButton8.getText() == "") cpu8();
else if (jButton6.getText() == "") cpu6();
else if (jButton4.getText() == "") cpu4();
else if (jButton10.getText() == "") cpu10();
}
if (i == 10)
{
if (jButton7.getText() == "") cpu7();
else if (jButton4.getText() == "") cpu4();
else if (jButton5.getText() == "") cpu5();
else if (jButton9.getText() == "") cpu9();
else if (jButton11.getText() == "") cpu11();
else if (jButton3.getText() == "") cpu3();
else if (jButton8.getText() == "") cpu8();
else if (jButton6.getText() == "") cpu6();
else if (jButton10.getText() == "") cpu10();
}
if (i == 11)
{
if (jButton3.getText() == "") cpu3();
else if (jButton5.getText() == "") cpu5();
else if (jButton9.getText() == "") cpu9();
else if (jButton7.getText() == "") cpu7();
else if (jButton11.getText() == "") cpu11();
else if (jButton4.getText() == "") cpu4();
else if (jButton8.getText() == "") cpu8();
else if (jButton6.getText() == "") cpu6();
else if (jButton10.getText() == "") cpu10();
}

}

private void cpu3()
{
System.out.println("\
jButton3_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton3.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton3.setText("O");
jLabel1.setText("Turn: X");
}
jButton3.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu4()
{
System.out.println("\
jButton4_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton4.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton4.setText("O");
jLabel1.setText("Turn: X");
}
jButton4.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu5()
{
System.out.println("\
jButton5_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton5.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton5.setText("O");
jLabel1.setText("Turn: X");
}
jButton5.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu6()
{
System.out.println("\
jButton6_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton6.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton6.setText("O");
jLabel1.setText("Turn: X");
}
jButton6.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu7()
{
System.out.println("\
jButton7_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton7.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton7.setText("O");
jLabel1.setText("Turn: X");
}
jButton7.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu8()
{
System.out.println("\
jButton8_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton8.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton8.setText("O");
jLabel1.setText("Turn: X");
}
jButton8.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu9()
{
System.out.println("\
jButton9_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton9.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton9.setText("O");
jLabel1.setText("Turn: X");
}
jButton9.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu10()
{
System.out.println("\
jButton10_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton10.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton10.setText("O");
jLabel1.setText("Turn: X");
}
jButton10.setEnabled(false);
checkWin();
turn *= -1;
}

private void cpu11()
{
System.out.println("\
jButton11_actionPerformed(ActionEvent e) called.");
if (turn == 1)
{
jButton11.setText("X");
jLabel1.setText("Turn: O");
}
else if (turn == -1)
{
jButton11.setText("O");
jLabel1.setText("Turn: X");
}
jButton11.setEnabled(false);
checkWin();
turn *= -1;
}

public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception ex)
{
System.out.println("Failed loading L&F: ");
System.out.println(ex);
}
new TicTacToe();
}
//= End of Testing =

}

doesn't even use backtracking... so simple









two weeks for _this???_


----------



## xtascox

Quote:



Originally Posted by *chatch15117*


I'm ready but I have it in java










I was referring to developing the server and making the clients interact with it so we can pit algorithm against algorithm.


----------



## dangerousHobo

My first go at it in C++. 
I'll do the AI tomorrow night, and maybe a Gtk gui if I have the time.


----------



## Midpipps

Quote:


Originally Posted by *xtascox* 
I'll work on something in my free time and post up the API along with the URI's.

Any chance we can make this a 2 week project?

I think we could push the Versus out to 2 weeks. To give us time to work out all the details and then run it. I think I will post another challenge next week but leave the Versus at 2 weeks that way if someone wants to take time on it then they can. I will hit you up on steam tonight to see what I can help with on the API and such. Might be worth it to make a sample class in a couple of other languages to hit your API.


----------



## xtascox

Quote:


Originally Posted by *Midpipps* 
I think we could push the Versus out to 2 weeks. To give us time to work out all the details and then run it. I think I will post another challenge next week but leave the Versus at 2 weeks that way if someone wants to take time on it then they can. I will hit you up on steam tonight to see what I can help with on the API and such. Might be worth it to make a sample class in a couple of other languages to hit your API.

I probably won't be on until Sunday as I'm going to be out of town. I'll pm you my e-mail address and we can communicate on there until I get back.


----------



## Midpipps

Quote:


Originally Posted by *chatch15117* 
I'm ready but I have it in java









Code:



Code:


snip for length

doesn't even use backtracking... so simple









two weeks for _this???_

I like it but I beat the computer every time









Quote:


Originally Posted by *dangerousHobo* 
My first go at it in C++.
I'll do the AI tomorrow night, and maybe a Gtk gui if I have the time.

this one was good too let see the AI


----------



## dangerousHobo

Quote:



Originally Posted by *Midpipps*


this one was good too let see the AI










Thanks, but I decided not to write one, who ever goes first can always win, the game is just to simple to make writing an AI worth while. If we do another game though I'll do it. I miss doing this type of competitions, did may of them in my AI course a few years back.


----------



## GodofGrunts

Quote:



Originally Posted by *dangerousHobo*


My first go at it in C++. 
I'll do the AI tomorrow night, and maybe a Gtk gui if I have the time.


OMG YOU'RE BACK.

I missed you.







:


----------



## xtascox

Quote:


Originally Posted by *dangerousHobo* 
Thanks, but I decided not to write one, who ever goes first can always win, the game is just to simple to make writing an AI worth while. If we do another game though I'll do it. I miss doing this type of competitions, did may of them in my AI course a few years back.

How about AI that works for a grid of size _n_?


----------



## dangerousHobo

Quote:


Originally Posted by *xtascox* 
How about AI that works for a grid of size _n_?

Like for a large tictactoe game or a general game that uses a grid? Can't really write a smart AI for a generic game that uses a grid because you'll need to know more about the game, how it's played, etc, so you can write some heuristics functions.


----------



## xtascox

Quote:


Originally Posted by *dangerousHobo* 
Like for a large tictactoe game or a general game that uses a grid? Can't really write a smart AI for a generic game that uses a grid because you'll need to know more about the game, how it's played, etc, so you can write some heuristics functions.

Square grid of size _n x n_ where the object is to get _n_ boxes in a row while preventing the other player from doing the same.


----------



## Safetydan

Connect 4 is a bit harder to write an AI for, but still doable in a week even if you're just learning I think. The game has been solved, a perfect player will always win if they go first, but writing a perfect AI isn't a simple task.









A large tic tac toe game would be interesting and there are several other fairly simple games that the challenge could focus on.


----------



## wcdolphin

Lol! I love the idea of tictac toe with a grid size of N, but I fear that the time required to play would increase on the order of N squared, with no real change in algorithim/ ability for either party to win ^_^


----------



## imagine2112x

will you accept matlab? it is not like C++ or anything but it is made for physical sciences/engineering/data analysis and can do all of this fine


----------



## xtascox

Whew. I'm still down to write that tic tac toe server if anyone is interested in pitting their code against someone else's...


----------



## Midpipps

Sorry I have not posted any challenges school kind of took over my life. I am up for doing more in the tic tac toe thing too. Now that school is over will try and start posting once a week again. I still have stacks of challenges.


----------



## xtascox

Quote:



Originally Posted by *Midpipps*


Sorry I have not posted any challenges school kind of took over my life. I am up for doing more in the tic tac toe thing too. Now that school is over will try and start posting once a week again. I still have stacks of challenges.


Same situation except its work and not school


----------



## Midpipps

OK here we go I am still not against doing the tic tac toe server but wanted to get this going again now that I have time to post these again. 1 week to finish unless we want to extend it due to holiday season.

*On to the challenge*
Quote:


> *Weighing on a Tertiarian Scale*
> 
> Back in the Hellenic era, there was a small island in the Mediterranean Sea known as Tertiaria. It was close to Sparta, but because of its mountainous terrain the Spartans found it difficult to conquer and it remained an independent state until the great earthquake of 729BC when it sank beneath the sea. It had a remarkable civilization and some modern historians think it is the basis for the mythological city of Atlantis.
> Tertiaria is still known for its fundamental contributions to science and mathematics, many of which were adopted by the Greeks and later by the Romans. For example, Tertiarians were the first group to use the standard weight of pounds, which we still use today. Tertiarian mathematics used base 3 for all its calculations. (Historians postulate this was out of respect for King Ternary who lost two fingers on each hand while battling the Spartans.)
> Tertiarian trade scales were a standard for many centuries. They were known for their accuracy and ease of use. They were the first to model a scale with weighing pans on each side and a fulcrum in the middle (see picture above). The object to be weighed was placed on the left side of the balance and weights were placed on both sides, until balance was obtained. This sounds strange by modern standards, because typically, on modern scales we would only place weights on the right side. However, the modern method requires additional weights. The Tertiarian method only requires one weight for each power of three pounds, e.g. 1 weight of 1lb, 1 weight of 3lbs, 1 weight of 9lbs, etc.
> 
> Say you are weighing a 2 pound Tertiarian hen (known for their succulent white meat). You place the hen on the left side. Place the 3 pound weight on the right side. This is too heavy, so place the 1 pound weight with the hen on the left side to achieve balance. Note that the weights on the right side minus the weights on the left side equals the weight of the object. (3-1 = 2).
> 
> As another example, consider weighing a 21lbs Tertiarian squash. Using the Tertiarian system, you would place weights of 27lbs and 3lbs in the right pan and a weight of 9lbs in the left pan (along with the object) again achieving balance. (30 - 9 = 21).
> 
> Write a program that accepts as input a series of weights for various objects in base 10 and outputs the weights to be placed in both pans for each case. Remember that you have only one weight of each power of 3lbs.
> 
> *Input:*
> The first line contains a positive integer, n, less than or equal to 100, indicating how many instances of the problem are to be solved. On each of the next n lines there is a non-negative integer no greater than one million, giving the weight of an object.
> 
> *Output:*
> For each of the n weights, the program should produce a single line of output containing the measuring weights to be placed in each pan, in descending order on each side, as formatted below.
> Slight variations in the formatting, such as differences in the number of spaces around the numbers, are acceptable.
> 
> *Sample Input:*
> 4
> 2
> 3
> 21
> 250
> 
> *Corresponding output:*
> left pan: right pan: 3 1
> left pan: 1 right pan: 3
> left pan: right pan: 3
> left pan: 9 right pan: 27 3
> left pan: 3 right pan: 243 9 1


----------



## Midpipps

I think I will leave this up for another week I have not had time to make my entry yet and not sure if no one else is interested or not but maybe someone else will jump in and have some fun with it too.


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11817061*
> I think I will leave this up for another week I have not had time to make my entry yet and not sure if no one else is interested or not but maybe someone else will jump in and have some fun with it too.


Yea I'm still trying to find what some people refer to as "free time." I still wonder if it is real or a myth.


----------



## Midpipps

I vote for myth


----------



## Midpipps

Yeah got some free time thank you insomnia

Code:


Code:


import java.util.Scanner;
import java.lang.Math;

public class Tertiarian {
private static int leftWeight = 0;
private static int rightWeight = 0;
private static String leftTray = "";
private static String rightTray = "";
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int initialWeight = 0;

System.out.println("Please enter the weight of the object in the left tray");
initialWeight = in.nextInt();

if ( initialWeight > 0 ){
leftWeight = initialWeight;
findWeights();
}

System.out.println("left pan:" + leftTray + " right pan:" + rightTray);

}

private static void findWeights(){
double logResult;
while(leftWeight != rightWeight){
logResult = 0;
if (leftWeight > rightWeight){
logResult = Math.log((double)(leftWeight-rightWeight))/Math.log((double)(3));
logResult = Math.floor(logResult + 0.5);
rightWeight += Math.pow(3.0, logResult);
rightTray += " " + (int)Math.pow(3.0, logResult);
}else if (rightWeight > leftWeight){
logResult = Math.log((double)(rightWeight-leftWeight))/Math.log((double)(3));
logResult = Math.floor(logResult + 0.5);
leftWeight += (int)Math.pow(3.0, logResult);
leftTray += " " + (int)Math.pow(3.0, logResult);
}
}
}

}


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11871321*
> Yeah got some free time thank you insomnia
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> import java.util.Scanner;
> import java.lang.Math;
> 
> public class Tertiarian {
> private static int leftWeight = 0;
> private static int rightWeight = 0;
> private static String leftTray = "";
> private static String rightTray = "";
> public static void main(String[] args) {
> Scanner in = new Scanner(System.in);
> int initialWeight = 0;
> 
> System.out.println("Please enter the weight of the object in the left tray");
> initialWeight = in.nextInt();
> 
> if ( initialWeight > 0 ){
> leftWeight = initialWeight;
> findWeights();
> }
> 
> System.out.println("left pan:" + leftTray + " right pan:" + rightTray);
> 
> }
> 
> private static void findWeights(){
> double logResult;
> while(leftWeight != rightWeight){
> logResult = 0;
> if (leftWeight > rightWeight){
> logResult = Math.log((double)(leftWeight-rightWeight))/Math.log((double)(3));
> logResult = Math.floor(logResult + 0.5);
> rightWeight += Math.pow(3.0, logResult);
> rightTray += " " + (int)Math.pow(3.0, logResult);
> }else if (rightWeight > leftWeight){
> logResult = Math.log((double)(rightWeight-leftWeight))/Math.log((double)(3));
> logResult = Math.floor(logResult + 0.5);
> leftWeight += (int)Math.pow(3.0, logResult);
> leftTray += " " + (int)Math.pow(3.0, logResult);
> }
> }
> }
> 
> }


Nice, I recently developed a neck problem affecting the nerves in the back of my neck. Long story short, any chance of free time just got filled with zoning out on muscle relaxers...


----------



## Midpipps

LOL yeah was hoping if I posted some code some others will too. It actually turned out to be a lot easier then it sounded at first. Algebra win.

Sucks to hear about your neck problem


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11876923*
> LOL yeah was hoping if I posted some code some others will too. It actually turned out to be a lot easier then it sounded at first. Algebra win.
> 
> Sucks to hear about your neck problem


Dude I just woke up with it one day. It's called Occipital Neuralgia. I did get to work from home today though


----------



## Midpipps

Another Wednesday Another program. Really hope more people start this up again. This is another one from the MICS competition last year.
Quote:


> *Perrin Numbers*
> 
> *Description:*
> The Perrin sequence {A(0), A(1), A(2), &#8230;} is defined as follows:
> 
> A(0) = 3
> A(1) = 0
> A(2) = 2
> For i >= 3, A(i) = A(i-2) + A(i-3)
> 
> This sequence has the following interesting property - if P is a prime number, then P evenly divides A(P).
> 
> *Problem:*
> Write a program that verifies the above property of the Perrin numbers for the first 30 primes and their related Perrin numbers. The output should be a list of the first k primes, P(1), &#8230;, P(k), their associated Perrin numbers (A(P(1)), &#8230;, A(P(k))), and confirmation that P(k) divides A(P(k)) by generating the output of A(P(k)) modulus P(k).
> 
> *Technical Data:*
> This is a timed problem. Any program that takes longer than two real-time minutes to complete will be rejected on time.
> 
> *Sample Input:*
> None - k value is hardcoded.
> 
> Sample Output: (assuming k=5; again, your program should use k = 30)
> P(1) = 2; A(P(1)) = 2; 2 modulus 2 => 0
> P(2) = 3; A(P(2)) = 3; 3 modulus 3 => 0
> P(3) = 5; A(P(3)) = 5; 5 modulus 5 => 0
> P(4) = 7; A(P(4)) = 7; 7 modulus 7 => 0
> P(5) = 11; A(P(5)) = 22; 22 modulus 11 => 0


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11898985*
> Another Wednesday Another program. Really hope more people start this up again. This is another one from the MICS competition last year.


This one is interesting enough that I think I'll set aside some time tonight to give it a go. The question is, what language to use?


----------



## Midpipps

LISP







or how about AJAX I know your company loves or used to love that


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11899635*
> LISP
> 
> 
> 
> 
> 
> 
> 
> or how about AJAX I know your company loves or used to love that


Old job used AJAX in the most annoying places. New job we use it but I don't deal with the web stuff anymore. I write the core code and API that our web interface relies on.

LISP eh? I could give it a go...


----------



## Midpipps

Quote:



Originally Posted by *xtascox*


Old job used AJAX in the most annoying places. New job we use it but I don't deal with the web stuff anymore. I write the core code and API that our web interface relies on.

LISP eh? I could give it a go...



I think my goal is going to make the program run for as long as possible while doing the 30 primes I just cannot fathom how to make it run for over 2 minutes.


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11900196*
> I think my goal is going to make the program run for as long as possible while doing the 30 primes I just cannot fathom how to make it run for over 2 minutes.


Write it in javascript and run it on a 386?


----------



## Midpipps

Quote:



Originally Posted by *xtascox*


Write it in javascript and run it on a 386?










How inefficient can i make it while still having it do what it is supposed to. without extra steps like wait commands or anything that should be part of the challenge.







You pick the language and I will duel you for inefficient code







or closest to a 2 minute run time.


----------



## xtascox

Quote:



Originally Posted by *Midpipps*


How inefficient can i make it while still having it do what it is supposed to. without extra steps like wait commands or anything that should be part of the challenge.







You pick the language and I will duel you for inefficient code







or closest to a 2 minute run time.


How about a SQL procedure?


----------



## Midpipps

Quote:



Originally Posted by *xtascox*


How about a SQL procedure?










I am up for it I suppose would not be my first choice but if that is what you want. I was more thinking along the lines of C++, C, Java, python, perl, VB, C#, Jscript, or some other standard language







. But if you want SQL Procedure I am up.


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11900874*
> I am up for it I suppose would not be my first choice but if that is what you want. I was more thinking along the lines of C++, C, Java, python, perl, VB, C#, Jscript, or some other standard language
> 
> 
> 
> 
> 
> 
> 
> . But if you want SQL Procedure I am up.


I was trying to think along the lines of something that would be a bad choice and inefficient for the job









Rules:
1.) Every line of code must have a purpose toward completing the task (e.g. no nonsense lines to take up time)
2.) Final run should be on the latest version of MySQL.
3.) Output will be a final SELECT statement.


----------



## impatient

Edit[This is busted.. better solution on next page]

Didn't have time to do any cleanup. I'd probably have handled it a little bit different. Also, I don't stop on the first denominator.

This is scala 2.8

Code:


Code:


package test

import scala.collection.mutable.{MutableList => List}

class FindPrime {

def getNextPerin(inp:List[Int]):List[Int] = 
{
val out = inp(inp.length-3) + inp(inp.length-2)
return inp += out  
}

def primeList(k:Int):List[Int] = 
{
  var curr:Int = 3;
  var primeList:List[Int] = new List() += 2; 
  while(primeList.length != k)
   {
   if(isPrime(curr)) { 
    primeList += curr; 
    }

   curr+=1;
   }
   return primeList
}

def isPrime(curr:Int):Boolean = {

var start:Int = curr/2;
if(start == 1) {start = 2; }
while(start > 1)
{
if(curr % start == 0)
{
return false;
}
start -=1;
}

return true;

}

}

object FindPrime {

  def main(args : Array[String]) : Unit = {
 var fp =  new FindPrime();
 var primeList = fp.primeList(30);
 var perinList = new List() +=  3 += 0 += 2
 val max = primeList.reverse.head
 while(perinList.size != max+1)
 {
 fp.getNextPerin(perinList)
 }

 for(i <- primeList)
 {
 val matched: List[Int] =  perinList.filter(q => q != 0).filter(j => j >=  2 * i && j % i ==0 )
 if(matched.length > 0) { println(matched.head + " is divisible by " + i); }

 }

  }
}


----------



## impatient

bah.. now i've solved the wrong problem.. not too horribly inefficient


----------



## Midpipps

Quote:



Originally Posted by *xtascox*


I was trying to think along the lines of something that would be a bad choice and inefficient for the job









Rules:
1.) Every line of code must have a purpose toward completing the task (e.g. no nonsense lines to take up time)
2.) Final run should be on the latest version of MySQL.
3.) Output will be a final SELECT statement.


I agree to your terms and add 1 more has to be in by next Tuesday in case I don't get time tonight







.

Quote:



Originally Posted by *impatient*


bah.. now i've solved the wrong problem.. not too horribly inefficient










Your code looks good though now how inefficient can you make it in MySQL. Take you out of that scala comfort zone









and with that note I say 
"To BATTLE"


----------



## xtascox

Quote:



Originally Posted by *Midpipps*


I agree to your terms and add 1 more has to be in by next Tuesday in case I don't get time tonight







.

Your code looks good though now how inefficient can you make it in MySQL. Take you out of that scala comfort zone









and with that note I say 
"To BATTLE"


It's on!


----------



## impatient

Pipps pointed out that I wasn't doing exactly what the problem wanted.. i added in the zip function (noted by the woohoo) and had to change the Perin vals to a bigint.

Interesting thing is... that the primes would divide the perin numbers multiple times... i'm trying to say something like p(12) % a(4) == 0 was valid a lot of the time. Anyhow.. proper run for 30 took 15 milliseconds, 300 115 milliseconds, 3000 15 seconds... and somehow prime generation doesn't seem to be the bulk of it. Gonna look into that.

Code:


Code:


package test

import scala.collection.mutable.{MutableList => List}
import scala.math.BigInt;

class FindPrime {

def getNextPerin(inp:List[BigInt]):List[BigInt] = 
{
val out = inp(inp.length-3) + inp(inp.length-2)
return inp += out  
}

def primeList(k:Int):List[Int] = 
{
  var curr:Int = 3;
  var primeList:List[Int] = new List() += 2; 
  while(primeList.length != k)
   {
   if(isPrime(curr)) { 
    primeList += curr; 
    }

   curr+=1;
   }
   return primeList
}

def isPrime(curr:Int):Boolean = {

if(curr % 2 == 0) { return false; }
var start:Int = curr/2;
if(start == 1) {start = 2; }
while(start > 1)
{
if(curr % start == 0)
{
return false;
}
start -=1;
}

return true;

}

}

object FindPrime {

  def main(args : Array[String]) : Unit = {

  println(System.currentTimeMillis)
  val start = System.currentTimeMillis 
 var fp =  new FindPrime();
 var primeList = fp.primeList(30);
 var perinList:List[BigInt] = new List() +=  BigInt(3) += BigInt(0) += BigInt(2)
 val max = primeList.reverse.head
 while(perinList.size != max+1)
 {
 fp.getNextPerin(perinList)
 }
 //woohoo
 val divs:Seq[(Int,BigInt)] = primeList.zip(primeList.map(i => perinList(i) ));
 for(i <- divs)
 {

 if(i._2 % i._1 == 0) { println(i._2 + "%" + i._1 + "=0")  }
 else
 {
 println("error " + i._2 + "%" + i._1 )

 }

 }

println(System.currentTimeMillis)
println(System.currentTimeMillis - start);   
  }
}


----------



## Midpipps

Here is my java shot at it to make up for the masochistic code to come.

Code:


Code:


import java.util.Vector;

public class PerrinNumber {

private static Vector<Long> perrin = new Vector<Long>();
private static Vector<Long> prime = new Vector<Long>();

public static void main(String[] args) {
makePrimes(30);
makePerrin(prime.get(prime.size() - 1));
for (int i = 0; i < prime.size(); i ++)
{
System.out.println("P(" + (i+1) + ") = " + prime.get(i)
+ "; A(P(" + (i+1) + ")) = " + perrin.get(prime.get(i).intValue())
+ "; " + perrin.get(prime.get(i).intValue()) + " modulus " + prime.get(i)
+ " => " + (perrin.get(prime.get(i).intValue()) % prime.get(i)));
}
}

private static void makePrimes(int numOfPrimes)
{
boolean primeFound = false;
long primeNumber = 1;
prime.clear();
prime.add((long)2);
for (int i = 0; i < numOfPrimes; i++)
{
primeFound = false;
while (!primeFound)
{
primeNumber += 2;
for (int a = 2; a <= primeNumber; a++)
{
if (a == primeNumber)
primeFound = true;

if ((primeNumber % a) == 0)
break;
}
}
prime.add(primeNumber);
}
}

private static void makePerrin(Long long1)
{
perrin.clear();
perrin.add((long)3);
perrin.add((long)0);
perrin.add((long)2);
for (int i = 3; i < (long1 + 1); i++)
{
perrin.add(perrin.get(i - 2) + perrin.get(i - 3));
}
}

}

and the outpu

Code:


Code:


P(1) = 2; A(P(1)) = 2; 2 modulus 2 => 0
P(2) = 3; A(P(2)) = 3; 3 modulus 3 => 0
P(3) = 5; A(P(3)) = 5; 5 modulus 5 => 0
P(4) = 7; A(P(4)) = 7; 7 modulus 7 => 0
P(5) = 11; A(P(5)) = 22; 22 modulus 11 => 0
P(6) = 13; A(P(6)) = 39; 39 modulus 13 => 0
P(7) = 17; A(P(7)) = 119; 119 modulus 17 => 0
P(8) = 19; A(P(8)) = 209; 209 modulus 19 => 0
P(9) = 23; A(P(9)) = 644; 644 modulus 23 => 0
P(10) = 29; A(P(10)) = 3480; 3480 modulus 29 => 0
P(11) = 31; A(P(11)) = 6107; 6107 modulus 31 => 0
P(12) = 37; A(P(12)) = 33004; 33004 modulus 37 => 0
P(13) = 41; A(P(13)) = 101639; 101639 modulus 41 => 0
P(14) = 43; A(P(14)) = 178364; 178364 modulus 43 => 0
P(15) = 47; A(P(15)) = 549289; 549289 modulus 47 => 0
P(16) = 53; A(P(16)) = 2968530; 2968530 modulus 53 => 0
P(17) = 59; A(P(17)) = 16042867; 16042867 modulus 59 => 0
P(18) = 61; A(P(18)) = 28153269; 28153269 modulus 61 => 0
P(19) = 67; A(P(19)) = 152149094; 152149094 modulus 67 => 0
P(20) = 71; A(P(20)) = 468557684; 468557684 modulus 71 => 0
P(21) = 73; A(P(21)) = 822261415; 822261415 modulus 73 => 0
P(22) = 79; A(P(22)) = 4443758532; 4443758532 modulus 79 => 0
P(23) = 83; A(P(23)) = 13684979327; 13684979327 modulus 83 => 0
P(24) = 89; A(P(24)) = 73957919629; 73957919629 modulus 89 => 0
P(25) = 97; A(P(25)) = 701410194695; 701410194695 modulus 97 => 0
P(26) = 101; A(P(26)) = 2160059765855; 2160059765855 modulus 101 => 0
P(27) = 103; A(P(27)) = 3790640640857; 3790640640857 modulus 103 => 0
P(28) = 107; A(P(28)) = 11673640327812; 11673640327812 modulus 107 => 0
P(29) = 109; A(P(29)) = 20485810695074; 20485810695074 modulus 109 => 0
P(30) = 113; A(P(30)) = 63088012960224; 63088012960224 modulus 113 => 0
P(31) = 127; A(P(31)) = 3233514234548132; 3233514234548132 modulus 127 => 0


----------



## Midpipps

after playing a little bit maybe the better challenge would have been how high can you go


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11903332*
> after playing a little bit maybe the better challenge would have been how high can you go


That could be another challenge







How high can you go in two minutes?


----------



## Midpipps

I can get to 30000 in 3 minutes but I need to add a different data type cause longs overflow so it does not technically work


----------



## xtascox

This is a sloppily re-factored version of Midpipps' code. Adds support for massive numbers and file output. It does 10,000 primes in roughly 252 seconds on my system.

Code:



Code:


package challenge.perrin;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.Vector;

public class PerrinPrime {
private static final int NUM_PRIMES = 1000;

private static Vector<BigInteger> perrinList = new Vector<BigInteger>();
private static Vector<BigInteger> primeList = new Vector<BigInteger>();

private long start;
private long end;

private void startTimer() {
this.start = System.currentTimeMillis();
}

private void stopTimer() {
this.end = System.currentTimeMillis();
}

private double getTimedResult() {
return (end - start);
}

public static void main(String[] args) throws Exception {
PerrinPrime perrinPrime = new PerrinPrime();
perrinPrime.startTimer();
makePrimes(NUM_PRIMES);
makePerrin(primeList.get(primeList.size() - 1));
OutputStream os = new BufferedOutputStream(new FileOutputStream("C:\\results.txt"));
for (int i = 0; i < primeList.size() - 1; i ++)
{
String line = ("P(" + (i+1) + ") = " + primeList.get(i)
+ "; A(P(" + (i+1) + ")) = " + perrinList.get(primeList.get(i).intValue())
+ "; " + perrinList.get(primeList.get(i).intValue()) + " modulus " + primeList.get(i)
+ " => " + (perrinList.get(primeList.get(i).intValue()).mod(primeList.get(i))) + "\n");

byte[] bytes = line.getBytes();

os.write(bytes);
}
perrinPrime.stopTimer();
os.close();
System.out.println("Executed in " + (perrinPrime.getTimedResult() / 1000) + " seconds");
}

private static void makePrimes(int numOfPrimes)
{
boolean primeFound = false;
BigInteger primeNumber = new BigInteger("1");
primeList.clear();
primeList.add(new BigInteger("2"));
for (int i = 0; i < numOfPrimes; i++)
{
primeFound = false;
while (!primeFound)
{
primeNumber = primeNumber.add(new BigInteger("2"));

BigInteger index = new BigInteger("2");

while(index.compareTo(primeNumber) <= 0) {
if (index.compareTo(primeNumber) == 0)
primeFound = true;

if ((primeNumber.mod(index)).compareTo(new BigInteger("0")) == 0)
break;

index = index.add(new BigInteger("1"));
}
}
primeList.add(primeNumber);
}
}

private static void makePerrin(BigInteger long1)
{
perrinList.clear();
perrinList.add(new BigInteger("3"));
perrinList.add(new BigInteger("0"));
perrinList.add(new BigInteger("2"));

BigInteger index = new BigInteger("3");

while(index.compareTo(long1) < 0) {
perrinList.add(perrinList.get(Integer.parseInt(index.toString()) - 2).add(perrinList.get(Integer.parseInt(index.toString()) - 3)));
index = index.add(new BigInteger("1"));
}
}
}


----------



## impatient

Check out how much big int's slow you down. If you make the prime vector int's(I guess Integer) instead of big ints. I did 20k without displaying the Perrin numbers in about 16 seconds. Will update it tomorrow to print Perrin's out to a file and use similar stop watchery.


----------



## Midpipps

Ah a fun night of coding

We made a graph of xTasco run of 10K with his code of how long between iterations.
His code is posted above.

here is the newest code that we are working with less memory intensive but faster we are not sure yet the initial view looks good but will not know for sure until we graph another set of data on it.

Code:



Code:


import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Vector;

public class PerrinNumber {

private static Vector<BigInteger> perrin = new Vector<BigInteger>();
private static BigInteger prime = BigInteger.valueOf(2);
private static BigInteger currentPerrinPosition = BigInteger.valueOf(3);
private static final int tests = 20000;
private static PrintWriter out = null;

public static void main(String[] args) {
try {
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
e.printStackTrace();
}
long before = System.currentTimeMillis();
perrin.add(BigInteger.valueOf(-1));
perrin.add(BigInteger.valueOf(3));
perrin.add(BigInteger.valueOf(0));
perrin.add(BigInteger.valueOf(2));
printMessage(0);
prime = prime.subtract(BigInteger.valueOf(1));
for (int i = 1; i < tests; i ++)
{
makePrime();
nextPerrin(prime);
printMessage(i);
}
long after = System.currentTimeMillis();
out.close();
System.out.println((after-before)/1000);
}

private static void makePrime()
{
boolean primeFound = false;
while (!primeFound)
{
prime = prime.add(BigInteger.valueOf(2));
for (BigInteger a = BigInteger.valueOf(2); a.compareTo(prime) <= 0; a = a.add(BigInteger.valueOf(1)))
{
if (a.compareTo(prime) == 0)
primeFound = true;
if (prime.mod(a) == BigInteger.valueOf(0))
break;
}

}
}

private static void nextPerrin(BigInteger B)
{
while(currentPerrinPosition.compareTo(prime) <= 0)
{
perrin.add(perrin.get(2).add(perrin.get(1)));
perrin.remove(0);
currentPerrinPosition = currentPerrinPosition.add(BigInteger.valueOf(1));
}
}

private static void printMessage(int i)
{
/*System.out.println("P(" + (i+1) + ") = " + prime.toString()
+ "; A(P(" + (i+1) + ")) = " + perrin.get(3).toString()
+ "; " + perrin.get(3).toString() + " modulus " + prime.toString()
+ " => " + (perrin.get(3).mod(prime)));*/
out.println("P(" + (i+1) + ") = " + prime.toString()
+ "; A(P(" + (i+1) + ")) = " + perrin.get(3).toString()
+ "; " + perrin.get(3).toString() + " modulus " + prime.toString()
+ " => " + (perrin.get(3).mod(prime)));
}
}

Will try and run all codes including imps tomorrow on my machine to see the comparability and post results if anyone else wants in on the optimization fun have at it make your own or improve ours have fun it was basically a full night so far of try this run code try that run code. I would upload the data set that is output but it is 499 MB for 20K iterations


----------



## impatient

I hosed mine.. trying to make it use actors. Should have just done the normal thread model. Must.. do.. work.


----------



## Wingzero

Ah I slacked up on my C++ studying and now I found this thread proper gonna get back into it.

I should be joining the festivities pretty soon!


----------



## xtascox

Ran a 50k iteration with Midpipps's code modified for file output. According to the logs it took just under 8 hours and the output file was 3.5 gigs... Then I realized I never closed the outputstream and I lost the last few iterations. Fixed the issue and reran it before I left for work. We'll see the results when I get home.


----------



## Midpipps

Quote:



Originally Posted by *xtascox*


Ran a 50k iteration with Midpipps's code modified for file output. According to the logs it took just under 8 hours and the output file was 3.5 gigs... Then I realized I never closed the outputstream and I lost the last few iterations. Fixed the issue and reran it before I left for work. We'll see the results when I get home.


Sad to say I modified it again and during my initial test I was getting a 70% average increase in speed for 1000 primes. Good to read some more information on prime numbers have another possibility to speed it up but it is much more math intensive and I am not sure yet whether it will actually speed up as much

Code:


Code:


import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Vector;

public class PerrinNumber {

private static Vector<BigInteger> perrin = new Vector<BigInteger>();
private static Vector<BigInteger> oldPrimes = new Vector<BigInteger>();
private static BigInteger prime = BigInteger.valueOf(2);
private static BigInteger currentPerrinPosition = BigInteger.valueOf(3);
private static final int tests = 1000;
private static PrintWriter out = null;

public static void main(String[] args) {
try {
out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
e.printStackTrace();
}
long before = System.currentTimeMillis();
perrin.add(BigInteger.valueOf(-1));
perrin.add(BigInteger.valueOf(3));
perrin.add(BigInteger.valueOf(0));
perrin.add(BigInteger.valueOf(2));
printMessage(0);
oldPrimes.add(BigInteger.valueOf(2));
prime = prime.subtract(BigInteger.valueOf(1));
for (int i = 1; i < tests; i ++)
{
//makePrime();
makePrime2();
nextPerrin(prime);
printMessage(i);
//System.out.println("iteration = " + i 
//+ " makePrime = " + prime.toString() 
//+ "  makePrime2 = " + oldPrimes.get(oldPrimes.size() - 1));

}
long after = System.currentTimeMillis();
out.close();
System.out.println(((double)after-(double)before)/(double)1000);
}

private static void makePrime()
{
boolean primeFound = false;
while (!primeFound)
{
prime = prime.add(BigInteger.valueOf(2));
for (BigInteger a = BigInteger.valueOf(2); a.compareTo(prime) <= 0; a = a.add(BigInteger.valueOf(1)))
{
if (a.compareTo(prime) == 0)
primeFound = true;
if (prime.mod(a) == BigInteger.valueOf(0))
break;
}

}
}

private static void makePrime2()
{
boolean primeFound = false;
while (!primeFound)
{
prime = prime.add(BigInteger.valueOf(2));
for (int a = 0; a < oldPrimes.size(); a ++)
{
if (prime.mod(oldPrimes.get(a)) == BigInteger.valueOf(0))
break;
if ((oldPrimes.size() - 1) == a)
{
primeFound = true;
oldPrimes.add(prime);
}
}
}
}

private static void nextPerrin(BigInteger B)
{
while(currentPerrinPosition.compareTo(prime) <= 0)
{
perrin.add(perrin.get(2).add(perrin.get(1)));
perrin.remove(0);
currentPerrinPosition = currentPerrinPosition.add(BigInteger.valueOf(1));
}
}

private static void printMessage(int i)
{
System.out.println("P(" + (i+1) + ") = " + prime.toString()
+ "; A(P(" + (i+1) + ")) = " + perrin.get(3).toString()
+ "; " + perrin.get(3).toString() + " modulus " + prime.toString()
+ " => " + (perrin.get(3).mod(prime)));
/*out.println("P(" + (i+1) + ") = " + prime.toString()
+ "; A(P(" + (i+1) + ")) = " + perrin.get(3).toString()
+ "; " + perrin.get(3).toString() + " modulus " + prime.toString()
+ " => " + (perrin.get(3).mod(prime)));*/
}
}

big difference is I actually added the prime array back in but now cut out the checks for mod with nonprime numbers.


----------



## xtascox

I think one of the features I'm going to add today is splitting the output into multiple files. It may add a little to the processing time but should give us a clearer and more manageable output. Imagine if we found a case where the property fails







I'll include some log info in the files, such as processing time for that batch.


----------



## xtascox

New challenge today?


----------



## Midpipps

Quote:



Originally Posted by *xtascox*


New challenge today?


Wednesday is new challenge day


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11972850*
> Wednesday is new challenge day


And to think I actually thought it was Wednesday


----------



## Midpipps

Went with a little simpler one today will come back with a harder one again next week. This is the last one I have from MICS but I have more from ACM competitions. They are a little harder.

The MICS ones are designed to be given in sets of 5 or 6 and you have 3 hours or so to solve as many as you can in the fastest time you can so they are a little easier.
Quote:


> *The Maximum Sum of a Contiguous Subsequence*
> 
> This problem is simple to state. It may or may not be simple to solve.
> Given a sequence of integers, find the maximum sum of a contiguous subsequence of zero or more of those numbers.
> For example, suppose the data is: 0, -1, 2, -1, 3, -1 0. The sum of the maximum subsequence is 4. The contiguous subsequence consists of 2, -1, 3.
> 
> *Input:*
> Each line thereafter consists of a line containing the sequence.
> 
> *Output:*
> For each of the lines, the program should produce a single number giving the sum of the maximum subsequence.
> 
> *Sample Input:*
> 1 2 3
> 0 -1 2 -1 3 -1 0
> -1 0
> 
> *Corresponding output:*
> 6
> 4
> 0
> 
> One Note on this: Since 0 is a viable answer if you have something like -1 -1 -4 -2 your answer would be 0 because the largest list would be not to pick one and just stay with the 0.


----------



## rabidgnome229

The maximum sub sequence for the third sample sequence should be 1, not 0


----------



## Midpipps

Quote:


> Originally Posted by *rabidgnome229;11983867*
> The maximum sub sequence for the third sample sequence should be 1, not 0


You are right sorry I copied another line and never payed attention. Thank you and it is fixed.


----------



## xtascox

Sweet I'm going to do this on a 10,000,000 index sequence of randomly generated numbers


----------



## Waffleboy

I'm new to this (and not an experienced programmer), but here's what I got. I'm sure it's not the most efficient or best way, but it seems to work.

Code:



Code:


import java.util.ArrayList;
import java.util.Scanner;

public class Sums
{

    public static int getSum(ArrayList<Integer> arr, int size, int base)
    {
        int sum = 0;
        for (int i = 0; i < size; i++)
        {
            sum += arr.get(base + i);
        }
        return sum;
    }

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        ArrayList<Integer> arr = new ArrayList<Integer>();
        int maxSum = 0;
        int testSum = 0;

        System.out.println("Enter the numbers, terminating character is a /.");
        String str = in.next();
        while (!str.equals("/"))
        {
            arr.add(Integer.parseInt(str));
            str = in.next();
        }

        for (int size = 1; size <= arr.size(); size++)
        {
            for (int base = 0; base + size <= arr.size(); base++)
            {
                testSum = getSum(arr, size, base);
                if (testSum > maxSum)
                {
                    maxSum = testSum;
                }
                testSum = 0;
            }            
        }
        System.out.println("Max Sum: " + maxSum);

    }
}


----------



## Midpipps

Quote:


> Originally Posted by *Waffleboy;11984556*
> I'm new to this (and not an experienced programmer), but here's what I got. I'm sure it's not the most efficient or best way, but it seems to work.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> his code go up and look at it :)


I like it. Works on all the test cases. That is basically what we did for the competition in Wisconsin.
only 1 issue if all numbers are negative it chooses the highest negative number when technicality it should choose 0. I know it is weird but that is actually the way the writeup was written. You can choose not to add anything to your starting number of 0 which such as in the case of -1 -1 would be 0. But awesome job.

Also welcome to the programming challenge glad to have you. Hope to see more code from you when the next question gets posted.


----------



## xtascox

Rather easy challenge









Code:


Code:


package challenges.maxcontiguoussum;

public class MaxContiguousSum {

public static void main(String[] args) {
long largest = 0;
long temptotal;
for(int i = 0;  i < args.length; i++) {
temptotal = Long.parseLong(args[i]);
if(temptotal > largest)
largest = temptotal;
for(int j = (i+1); j < args.length; j++) {
if((temptotal += Long.parseLong(args[j])) > largest)
largest = temptotal;
}
}
System.out.println(largest);
}
}


----------



## Midpipps

here it is in C# I really tried to think of a different algorithm for this but it seems I am drawing a blank on anything other then the two pointer method

Code:



Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCNTest
{
    class Program
    {
        static void Main(string[] args)
        {
            int highestNumber = 0;
            int tempNumber = 0;
            List<Int32> numbers = new List<Int32>();
            foreach (String s in args)
                numbers.Add(Int32.Parse(s));

            tempNumber = numbers.Max();
            if (tempNumber > highestNumber)
                highestNumber = tempNumber;

            for (int i = 0; i < numbers.Count; i++)
            {
                tempNumber = 0;
                numbers.GetRange(i, numbers.Count - i).ForEach(delegate(Int32 newNumber)
                {
                    tempNumber += newNumber;
                    if (tempNumber > highestNumber)
                        highestNumber = tempNumber;
                });
            }

            Console.WriteLine(highestNumber);

        }
    }
}


----------



## xtascox

Quote:


> Originally Posted by *Midpipps;11996950*
> here it is in C# I really tried to think of a different algorithm for this but it seems I am drawing a blank on anything other then the two pointer method


Yea I think this is probably the best algorithm. Although I'm sure there are far worse and far slower algorithms.


----------



## Waffleboy

Quote:


> Originally Posted by *Midpipps;11984722*
> I like it. Works on all the test cases. That is basically what we did for the competition in Wisconsin.
> only 1 issue if all numbers are negative it chooses the highest negative number when technicality it should choose 0. I know it is weird but that is actually the way the writeup was written. You can choose not to add anything to your starting number of 0 which such as in the case of -1 -1 would be 0. But awesome job.
> 
> Also welcome to the programming challenge glad to have you. Hope to see more code from you when the next question gets posted.


Thanks, I forgot about the zero thing lol, so I just set 0 as the initial value for the maxSum instead of the MIN_VALUE constant. Thanks for the tip and the welcome, I'll probably try these every week now


----------



## impatient

I did it a little differently. I get a list of all of the positive numbers and then only do sums of positive number A to positive number B.

Code:



Code:


class MaxSeq {

}

object MaxSeq {

def sumAB(lst:List[Tuple2[Int,Int]], st: Int, end:Int): Int = {

var sum:Int = 0;
lst.slice(st, end).foreach{x => sum+=x._1 };
if(sum < 0) { 0}
else { return sum; }
}

def main(args : Array[String]) : Unit = {

val intList: List[Int] = args.toList.map(x => x.toInt)
val indList = intList.zipWithIndex;

//get all positive peaks
var posIndex = indList.filter(x => x._1 >= 0)
var working = posIndex
var maxSum = 0
while(working.size > 0)
{
var ent = working(0)
working = working.tail
if(working.size > 0)
        {
val sumList = for(a<- working) yield sumAB(indList, ent._2, a._2+1);
if(sumList.max > 0 && sumList.max > maxSum)
{
maxSum = sumList.max

}
}
}

println(maxSum);

}

}


----------



## Midpipps

Quote:



Originally Posted by *impatient*


I did it a little differently. I get a list of all of the positive numbers and then only do sums of positive number A to positive number B.

Code:


Code:


CODE HERE


I like it especially that it is different then the rest


----------



## SKl

I cant find the challenge?
also can we use coldfusion?


----------



## Midpipps

Quote:



Originally Posted by *SKl*


I cant find the challenge?
also can we use coldfusion?


Sorry the new challenge will go up later today when I get some time to post it up. The latest challenge is always linked in my sig. Yes you can use coldfusion or any other programming language you would like.


----------



## Korben

I'm a novice at best. I tried really hard to do this challenge, but I had never used Vectors before so I had to do some good ol research. Please comment on my code, any advice would be greatly appreciated.

Code:



Code:


#include <iostream>
#include <vector>
using namespace std;

int maxSubSum( const vector<int> & myvector )
{
     int maxSum = 0, thisSum = 0;

     for( int j = 0; j < myvector.size( ); j++ )
     {
          thisSum += myvector[ j ];

          if( thisSum > maxSum )
              maxSum = thisSum;
          else if( thisSum < 0 )
               thisSum = 0;
     }

return maxSum;
}

int main()
{
    vector<int> myvector;
    int myint;

    cout << "Enter the numbers (Enter -256 to end): ";

    do{
         cin >> myint;
         myvector.push_back (myint);
         }while(myint != -256);

    int maxSum;

    maxSum = maxSubSum( myvector );
    cout << "Max sum is " <<  maxSum << endl;
    cin.get();
    cin.get();
    return 0;
}


----------



## Midpipps

Here is this weeks it is not as hard as the one I was going to post but I thought it is a nice middle ground for some of the new people that are coming in. Although it turns out not as hard as initially looked. Note for some of the newer people you do not have to follow the rules to the T this is for fun.

These are ACM Competition problems I did not make them up. they are copied word for word.
Quote:


> *1997-98 North Central Regionals*
> 
> *Is It A Tree? -- Problem 2*
> A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties.
> 
> There is exactly one node, called the root, to which no directed edges point.
> Every node except the root has exactly one edge pointing to it.
> There is a unique sequence of directed edges from the root to each node.
> For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> 
> In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.
> 
> *Input*
> 
> The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.
> 
> *Output*
> 
> For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1).
> 
> *Sample Input*
> 
> 6 8
> 5 3
> 5 2
> 6 4
> 5 6
> 0 0
> 
> 8 1
> 7 3
> 6 2
> 8 9
> 7 5
> 7 4
> 7 8
> 7 6
> 0 0
> 
> 3 8
> 6 8
> 6 4
> 5 3
> 5 6
> 5 2
> 0 0
> 
> -1 -1
> 
> *Expected Output*
> 
> Case 1 is a tree.
> Case 2 is a tree.
> Case 3 is not a tree.


----------



## impatient

Please use different languages. It makes us all smarter to see what other people did/what features languages have.

Either way, we win.

And.. thanks in advance


----------



## impatient

Quote:


> Originally Posted by *Korben;12066850*
> I'm a novice at best. I tried really hard to do this challenge, but I had never used Vectors before so I had to do some good ol research. Please comment on my code, any advice would be greatly appreciated.


I don't do enough c++ to comment on syntax/style, but it's the best way to tackle the problem so far. I think Pipps is trying to break it.

I think your running time is O and everyone else's is O(n!)


----------



## Midpipps

Quote:


> Originally Posted by *Korben;12066850*
> I'm a novice at best. I tried really hard to do this challenge, but I had never used Vectors before so I had to do some good ol research. Please comment on my code, any advice would be greatly appreciated.
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> go look at it seriously.


It is simple and elegant I was trying to think of a way that would break it and came up with nothing. You sir have shown us all up your answer is simple and works + rep to you my friend.


----------



## impatient

Here it is in scala. I just ran it in the interpreter. You need 2.8.1 in order for this to work, some of the file syntax changed.. (not sure why in a point release).

Code:



Code:


//used to keep count of how many times key is in the list
def addToMap(key:String, map:Map[String,Int]):Map[String,Int] =
{
  if(map.contains(key))
  {
return  map + (key -> (map(key)+1 ));
  }
  return map + (key -> 1);
}

  //read file and split on 0 0
  var lines = io.Source.fromFile("input.txt").getLines.map(x => ' ' + x.trim).mkString.split("0 0").map(x => x.trim);
  //consider all but the last line as something we care about
  lines = lines.slice(0,lines.length-1);

  for(line <- lines) 
  {
    //split on space, put all the odd indexed entries in one list
    val listTpl = line.split(' ').toList.zipWithIndex.partition(x => x._2 % 2 == 0);
   //recombine the separated lists, each connection is now a tuple (int, int)
    val pairs = listTpl._1.map(x=>x._1).zip(listTpl._2.map(x=>x._1));

    //place store information about starting nodes
    var sourceMap: Map[String, Int] = Map();

    //place to store information about endpoints
    var endMap: Map[String, Int] =  Map();

    //for each entry in the pair list, add the first item to the sourceMap, add the second item to the endMap
    for(x <- pairs){sourceMap = addToMap(x._1,sourceMap); endMap = addToMap(x._2,endMap);}
    println(sourceMap)
    println(endMap)
    println(pairs.map(x=>x._1).removeDuplicates)

    //if an item is hit twice, not a tree
    val isDoublyHit = endMap.filter(x => x._2 > 1).size > 0

    //if exactly one element has no parent we have a valid tree (if more than one have 0, we technically have 2 trees)
    val hasOneHead = pairs.map(x => x._1).removeDuplicates.filter(x => !endMap.contains(x)).size == 1;

    if(isDoublyHit || !hasOneHead)
    {
   println(pairs , " -> Is not a Tree")
    }
    else
    {
   println(pairs , " -> Is a Tree")
    }

  }


----------



## Waffleboy

Here's mine. I first find the root number (if there is one and only one). This also detects any 'dangling' parts, so it ensures everything is connected. Then I make sure nothing is pointed to more than once. It works on the test cases and I think it works for the problem, but please give me any constructive criticism if you have any, I'm still trying to learn









Code:


Code:


import java.util.Scanner;
import java.util.ArrayList;
public class tree
{

    public static int getRoot(int[][] arr)
    {
       int root = 0;       
       boolean testIsRoot = true;
       int possibleRoots = 0;

        for (int i = 0; i < arr.length; i++)
        {
            for (int i2 = 0; i2 < arr.length; i2++)
            {
                if (arr[i][0] == arr[i2][1])
                    testIsRoot = false;
            }
            if (testIsRoot)
            {
                if (root != arr[i][0])
                    possibleRoots++;
                root = arr[i][0];                
            }
            testIsRoot = true;
        } 
        if (possibleRoots == 1)
        {
            return root;
        }
        else
            return -1;       
    }

    public static boolean allConnected(int root, int[][] arr)
    {
        ArrayList<Integer> arrList = new ArrayList<Integer>();
        // populating a list of all the numbers except the root
        for (int i = 0; i < arr.length; i++)
        {
            if (!arrList.contains(arr[i][0]) && (arr[i][0] != root))
            {
                arrList.add(arr[i][0]);
            }
        }

        for (int i = 0; i < arr.length; i++)
        {
            if (!arrList.contains(arr[i][1]) && (arr[i][1] != root))
            {
               arrList.add(arr[i][1]);
            }
        }

        int numPointedTo = 0;
        for (int i = 0; i < arrList.size(); i++)
        {
            for (int i2 = 0; i2 < arr.length; i2++)
            {
                if (arrList.get(i) == arr[i2][1])
                    numPointedTo++;
            }
            if (numPointedTo != 1)
                return false;
            numPointedTo = 0;
        }
        return true;
    }

    public static void main(String[] args)
    {
        Scanner in = new  Scanner(System.in);
        int numPairs;
        System.out.print("How many pairs will you input: ");
        numPairs = Integer.parseInt(in.nextLine());

        int[][] arr = new int[numPairs][2];
        String input = "";
        int spaceInd;
        for (int i = 0; i < numPairs; i++)
        {
            input = in.nextLine();            
            spaceInd = input.indexOf(' ');
            arr[i][0] = Integer.parseInt(input.substring(0, spaceInd));
            arr[i][1] = Integer.parseInt(input.substring(spaceInd + 1));
        }
        int root = getRoot(arr);
        System.out.println(root);
        if (root != -1)
        {
            if (allConnected(root, arr))
            {
                System.out.println("This case is a tree.");              
            }
            else
            {
                System.out.println("This case is not a tree.");           
            }
        }
        else
        {
            System.out.println("This case is not a tree.");            
        }
    }
}


----------



## Midpipps

Some samples to test against if you wanted more these are the samples

Code:



Code:


6 8  5 3  5 2  6 4
5 6  0 0

8 1  7 3  6 2  8 9  7 5
7 4  7 8  7 6  0 0

3 8  6 8  6 4
5 3  5 6  5 2  0 0

0 0

1 2
1 3
0 0

1 2
1 3
1 4
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
0 0

1 2
0 0

1 1
0 0

1 2
1
4 5
0 0

1 2
2 1
0 0

1 2
1 2
0 0

1 2
1 3
2 4
2 5
2 6
2 7
3 8
8 9
9 10
10 11
11 12
12 13
0 0

-1 -1

and answers.

Code:



Code:


Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
Case 4 is a tree.
Case 5 is a tree.
Case 6 is a tree.
Case 7 is a tree.
Case 8 is not a tree.
Case 9 is not a tree.
Case 10 is not a tree.
Case 11 is not a tree.
Case 12 is a tree.

these are the actual test cases they used for judging.


----------



## impatient

Quote:


> Originally Posted by *Waffleboy;12084158*
> Here's mine. I first find the root number (if there is one and only one). This also detects any 'dangling' parts, so it ensures everything is connected. Then I make sure nothing is pointed to more than once. It works on the test cases and I think it works for the problem, but please give me any constructive criticism if you have any, I'm still trying to learn
> 
> 
> 
> 
> 
> 
> 
> 
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Above


It looks like it works, which is probably the most important part. I think it's a little hard to read(which you probably think about mine). I tried reasoning about the complexity of parts of it and had a whole post about it.. before I realized I didn't really clearly see your rules and might be wrong. As for making it more readable, you have some decent variable names(with the exception of an array named arr and an arrayList called arrayList.. I think the double nested array makes it more of a pain to think about, but that's probably more my issue than something most people would worry about. I guess I don't feel it is immediately clear is what your real conditions are..

for example.. in mine I have.

Code:



Code:


    //if an item is hit twice, not a tree
    val isDoublyHit = endMap.filter(x => x._2 > 1).size > 0

    //if exactly one element has no parent we have a valid tree (if more than one have 0, we technically have 2 trees)
    val hasOneHead = pairs.map(x => x._1).removeDuplicates.filter(x => !endMap.contains(x)).size == 1;

I think where I put my rules it is pretty clear what my conditions are. When you do your root test, I have to think more.

Anyhow.. keep them coming and good job









_
[Also.. looking back at my code.. I never use the sourceMap object..oops]

Edit: if you got rid of the nested arrays and used a class with members head and tail, your root code would be more like if item_.head == item[j].tail, which seems a lot clearer to me.


----------



## wimcle

Tried to make it shorter but couldn't.

Code:


Code:


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

class isTree{
    public static void main(String[] args){
        try {
            int count =0;
            boolean done = false;
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            DONE: while (!done){
                Collection set1 = new TreeSet(); // pointer
                Collection set2 = new TreeSet(); // pointee
                String line, val1, val2;
                boolean dup = true;

                CASE: while ((line = in.readLine()) != null){
                    String[] sa = line.split(" ");
                    if (sa != null && sa.length == 2){
                        val1 = sa[0].trim();
                        val2 = sa[1].trim();
                        }
                    else
                        throw new Exception(line + "\
Unexpected input, exiting");

                    if (val1.equals("-1") && val2.equals("-1")){
                        done = true;
                        break DONE;
                        }
                    if (val1.equals("0") && val2.equals("0")){
                        in.readLine(); // take care of that blank line
                        break CASE;
                        }

                    set1.add(val1);
                    dup &= set2.add(val2); // false if weve been pointed to twice
                    }

                if (dup == false){
                    System.out.println("Case " + count++ + " is not a Tree");
                    continue;
                    }

                set1.removeAll(set2);
                if (set1.size() != 1) // should only be one pointer thats never been a pointee
                    System.out.println("Case " + count++ + " is not a Tree");
                else 
                    System.out.println("Case " + count++ + " is a Tree");
                }
            }
        catch (Exception e){
            System.out.println(e);
            }
        }
    }


----------



## xtascox

Nice job guys. I'm going to be sitting this one out as I just realized I have to refactor about 5 weeks worth of code in 1 week.


----------



## Midpipps

Well here is this weeks one. Have fun.

Quote:



*Numerically Speaking -- Problem 6*
A developer of crossword puzzles (and other similar word games) has decided to develop a mapping between every possible word with from one to twenty characters and unique integers. The mapping is very simple, with the ordering being done first by the length of the word, and then alphabetically. Part of the list is shown below.

a 1
b 2
...
z 26
aa 27
ab 28
...
snowfall 157,118,051,752
...
Your job in this problem is to develop a program which can translate, bidirectionally, between the unique word numbers and the corresponding words.

*Input*

Input to the program is a list of words and numbers, one per line starting in column one, followed by a line containing a single asterisk in column one. A number will consist only of decimal digits (0 through 9) followed immediately by the end of line (that is, there will be no commas in input numbers). A word will consist of between one and twenty lowercase alphabetic characters (a through z).

*Output*

The output is to contain a single line for each word or number in the input data. This line is to contain the word starting in column one, followed by an appropriate number of blanks, and the corresponding word number starting in column 23. Word numbers that have more than three digits must be separated by commas at thousands, millions, and so forth.

*Sample Input*

29697684282993
transcendental
28011622636823854456520
computationally
zzzzzzzzzzzzzzzzzzzz
*
*Expected Output*

elementary 29,697,684,282,993
transcendental 51,346,529,199,396,181,750
prestidigitation 28,011,622,636,823,854,456,520
computationally 232,049,592,627,851,629,097
zzzzzzzzzzzzzzzzzzzz 20,725,274,851,017,785,518,433,805,270


side note: I can't believe I did not do last weeks all who did they look awesome. 
Although wimcle can't say I have seen many people use goto statements in java before don't know how I feel about that one







but i can't say too much as I did not get around to doing one of my own.


----------



## wimcle

I tried to get the comma into the printf, but it was giving up after about 20digits... I'll edit it and get rid of that ugly COMMA() function.

Code:



Code:


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

class encode{
    static final BigInteger bi26 = new BigInteger("26");

    static String decode(String s){
        BigInteger b = new BigInteger(s);
        StringBuffer sb = new StringBuffer("");

        while (b.compareTo(BigInteger.ZERO) >0){
            BigInteger[] ba = b.divideAndRemainder(bi26);
            b = ba[0];
            sb.insert(0, (char)(ba[1].intValue() - 1 + 'a'));
            }
        return sb.toString();
        }

    static String encode(String s){
        BigInteger ret = BigInteger.ZERO;

        for (int i=0; i<s.length(); i++){
            Integer j = 1 + (s.charAt(i) - 'a');
            BigInteger J = new BigInteger(j.toString());
            BigInteger pow = bi26.pow(s.length() - i - 1);
            ret = ret.add(pow.multiply(J));
            }
        return ret.toString();
        }

    static String COMMA(String s){
        if (s == null)
            return null;
        StringBuffer sb = new StringBuffer(s);
        for (int i= 1; i<= s.length()/3; i++){
            int k = s.length() -i*3;
            if (k>0)
                sb.insert(k, ",");
            }
        return sb.toString();
        }

    public static void main(String[] args){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String line;
            while ((line = in.readLine()) != null){
                if (line.matches("[a-z]*"))
                    System.out.printf("%-22s %s\n", line, COMMA(encode(line)));
                else if (line.matches("[1-9][0-9]*"))
                    System.out.printf("%-22s %s\n", decode(line), COMMA(line));

                else break;
                }
            }
        catch (Exception e){
            e.printStackTrace();
            }
        }
    }

Code:



Code:


PS C:\tmp> java encode
29697684282993
transcendental
28011622636823854456520
computationally
zzzzzzzzzzzzzzzzzzzz
*
elementary             29,697,684,282,993
transcendental         51,346,529,199,396,181,750
prestidigitation       28,011,622,636,823,854,456,520
computationally        232,049,592,627,851,629,097
zzzzzzzzzzzzzzzzzzzz   20,725,274,851,017,785,518,433,805,270
PS C:\tmp>


----------



## impatient

Here it is in scala. Comma's sucked for me too.. so I just left them out









Code:



Code:


import scala.math

//here i am overusing maps agains (map 1 to a .. 26 to z)
 val map = (((1 to 26).zip('a' to 'z')).toList).toMap +  (0 -> "")

//map a to 1... z to 26
 val rMap =(for(rev <- map.iterator) yield  rev._2 -> rev._1).toMap

 def toNum(str:String):BigInt = {
   val nums:List[BigInt] = 
      for(item <- str.reverse.zipWithIndex.toList) yield  
      BigInt(rMap(item._1)) * BigInt(26).pow(item._2)
   (nums.sum)
  }

 def toStr(num:BigInt):String = {
  var malNum = num;
  val max:Int = (math.log(malNum.doubleValue) / math.log(26)).intValue;
  var numList = (0 to max).toList.reverse;
  var letters:String = "";
  while(malNum > 0)  
  {val depth =numList.head;
        numList= numList.tail;
val pval =  BigInt(26).pow(depth);
        val div = (malNum / pval).intValue;
        malNum = malNum - pval * div;
letters = letters + map(div); 
  } 
  letters.mkString 
}

var lines = io.Source.fromFile("input.txt").getLines.map(x => x.trim).toList
  //consider all but the last line as something we care about
  lines = lines.slice(0,lines.length-1); 
  lines.foreach{x =>  
    if(('0' to '9') contains x(0))
      { println(x,toStr(BigInt(x)));} 
    else 
      { println(x,toNum(x)); }
   }


----------



## kenolak

The pace of this coding section is slow.
Anyone want to ramp things up a bit(and by a bit, I mean 4x your stock)?


----------



## Midpipps

Here is mine I also skipped the commas. The long rows of z really messed with me on the change back to numbers









Code:



Code:


public class NumericallySpeaking {

   final private BigInteger TWENTYSIX = new BigInteger("26");
   public NumericallySpeaking(){
   }

   public void main(){
      String theTextOrNumber = "703";
      String output = "";
      BigInteger b;

      //find out if the number is a character or integer if character use text to number else use numbertotext
      if ((int)theTextOrNumber.toLowerCase().charAt(0) >= 97 && (int)theTextOrNumber.toLowerCase().charAt(0) <= 122){
         b = new BigInteger("0");
 for (int i = 0; i < theTextOrNumber.length(); i++){
    b = b.add(textToNumber(i, theTextOrNumber.toLowerCase().charAt(theTextOrNumber.length() - i - 1)));
 }
 output = b.toString();
  }else{
 b = new BigInteger(theTextOrNumber);
 output = numberToText(b);
  }

  System.out.println(output);
   }

   //pretty simple really just standard conversion of base10 to base26
   public BigInteger textToNumber(int position, char letter){
      return TWENTYSIX.pow(position).multiply(BigInteger.valueOf(letter - 96));
   }

   //this one got a little messy
   public String numberToText(BigInteger n){
      String returnString = "";
      BigInteger [] valAndRemainder;
      BigInteger remainder;
      while(n.compareTo(TWENTYSIX) > 0)
      {
         valAndRemainder = n.divideAndRemainder(TWENTYSIX);
 n = valAndRemainder[0];
 remainder = valAndRemainder[1];
 //this is since we are using a numbering system with no 0 z is both 0 and 26
 if (remainder.compareTo(BigInteger.ZERO) == 0)
 {
    n = n.subtract(BigInteger.ONE);
remainder = TWENTYSIX;
 }
 returnString = (char)(remainder.intValue() + 96) + returnString;
  }
      returnString = (char)(n.intValue() + 96) + returnString;
  return returnString;
   }
}

not it is its own class I keep pretty much all the java that I do for OCN in one folder and just run it from a main method.

I like the commas and code whimcle but 20725274851017785518433805270 returns aaaaaaaaaaaaaaaaaaaa` I like it though other then the z conversion. Have not had time to test imps.


----------



## Midpipps

Quote:


> Originally Posted by *kenolak;12157993*
> The pace of this coding section is slow.
> Anyone want to ramp things up a bit(and by a bit, I mean 4x your stock)?


It is weekly mostly just for the fact that we want people to have time to get them in with all the other duties of the week. IE spend an little while making the code then back to work/play/school/family/etc.


----------



## xtascox

Looks like I have something to do tonight now.


----------



## serge2k

easy in C#

Code:



Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;

namespace base26
{
    class Program
    {
        static void Main(string[] args)
        {
            new Program();
        }

        public Program()
        {
            List<string> RawLines = new List<string>();
            List<string> strings = new List<string>();
            List<BigInteger> numbers = new List<BigInteger>();

            string inputLine = "";
            while ((inputLine = Console.ReadLine()) != "*")
                RawLines.Add(inputLine);

            foreach (string s in RawLines)
            {
                //check if it's a number
                BigInteger t;
                if (BigInteger.TryParse(s, out t))
                {
                    numbers.Add(t);
                    strings.Add(Base26ToString(t));
                }
                else
                {
                    strings.Add(s);
                    numbers.Add(StringToBase26(s));
                }
            }

            //display
            for (int i = 0; i < numbers.Count; i++)
            {
                Console.WriteLine("{0}, {1:###,###}", strings[i], numbers[i]);
            }
            Console.ReadKey();
        }

        public string Base26ToString(BigInteger t)
        {
            BigInteger largestPower = 26;
            string ret = "";
            while (largestPower * 26 < t)
            {
                largestPower *= 26;
            }
            while (t > 0)
            {
                char nextCharacter = (char)((t / largestPower)+96);
                t %= largestPower;
                largestPower /= 26;
                ret += nextCharacter;
            }
            return ret;
        }

        public BigInteger StringToBase26(string s)
        {
            BigInteger retval = 0;
            for (int i = s.Length-1, j = 0; i >= 0; i--, j++)
            {
                retval += (BigInteger)((s[i] - 96) * (Math.Pow(26, j)));
            }
            return retval;
        }
    }
}


----------



## impatient

Quote:


> Originally Posted by *serge2k;12167453*
> easy in C#
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Console.WriteLine("{0}, {1:###,###}", strings[i], numbers[i]);


I have an irrational dislike for C#... but that's pretty cool. I spent an hour trying to get the java variant working, to no avail. It should have been so easy.


----------



## serge2k

For everyday applications on windows (i.e. those that don't require highly optimized C/C++) C# is awesome.


----------



## impatient

I've recently had to do some ASP.net and it was pretty rough. I did some stuff in mono a long time ago. Their default time/date stuff blows java's out of the water iirc.

Maybe it's all the capital letters.. damn self important properties.. treating themselves like proper names.


----------



## Midpipps

Here is the new one the problem writeup is long but it should not be too difficult.
Quote:


> *Problem B -- SameGame Simulation -- Filename SAMEGAME*
> 
> The one-player game of SameGame is played on an M row by N column rectangular grid. In each cell of the grid is placed a positive integer in the range 0 through 9. The goal of the game is to remove all the integers from the grid. The player attempts this by repeatedly selecting a cell for removal. Each time a cell is selected for removal, all the cells in the connected region (defined below) containing the same integer found in selected cell are removed, and all cells above those that were removed 'drop down' (toward the bottom of the grid). When all the cells in a column have been removed, then columns to the right of the removed column slide to the left. The game is over when all cells are removed (a win), or when no more cells can be removed. A region can only be removed if it contains at least two cells.
> A connected region consists of all cells that can be reached by moving horizontally (left or right) and/or vertically (up or down) from any cell in the region, subject to the restriction that all cells in the connected region must contain the same value.
> Cells will be numbered starting with the lower left corner of the grid; this is cell (1,1). The cell above it is cell (2,1), and the cell to its right is cell (1,2).
> Consider this small (3 by 5) example:
> 1 3 5 2 2
> 2 2 3 5 1
> 1 2 3 5 5
> 
> The cells at (1,1), (2,5), (3,1) (3,2) and (3,3) may not be successfully selected for removal, since they aren't parts of connected regions (i.e., regions that contain at least two connected cells with the same value). The cell at (2,1) is part of the connected region also containing the cells at (2,2) and (1,2). Likewise, the connected region containing the cell at (1,5) also contains the cells at (1,4) and (2,4), but not the cell at (3,3). Starting with the original grid shown above, the following selections will result in a win:
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Step 1. Select cell (3,5):
> 
> 1 3 5
> 2 2 3 5 1
> 1 2 3 5 5
> 
> Step 2. Select cell (2,2):
> 
> 5
> 1   3 5 1
> 1 3 3 5 5
> 
> Step 3. Select cell (1,2):
> 
> 1   5 1
> 1 5 5 5
> 
> Step 4. Select cell (1,2):
> 
> 1
> 1 1
> 
> Finally, in step 5, selecting cell (1,1), (1,2) or (2,1) will remove the remaining integers from the grid.
> In the input for this problem your program will be presented with a sequence of grids, each having no more than 10 rows and 40 columns. For each grid there will also be given a sequence of cell removal selections. Apply these selections, in order, to each grid, ignoring those that are not permitted (e.g. they select non-existant cells, or they select regions with fewer than two cells). Then display the resulting grid or, if appropriate, the message "Game Won".
> Input
> 
> The input will consist entirely of non-negative integers without regard to line structure. Each grid and sequence of removal selections will begin with values for M and N. If either of these values is zero, then the input is terminated.
> Following M and N will appear the MxN integers for the grid, in row major order. That is, the values are given in order for cells (1,1), (1,2), ..., (1,N), (2,1), ..., (M,N). Following the grid data will appear pairs of integers, each pair indicating the row and column of a grid cell selected for removal. The end of this sequence will be marked by a pair of zeroes. If a game is won, your program must skip any remaining pairs of integers (if any) through and including the pair of zeroes to reach the data for the next grid in the input.
> Output
> 
> As noted above, the output for each grid in the input data should be either the grid that remains after considering all selections, or the message 'Game Won'. Precede the output for each grid by its sequence in the input; the first grid is numbered 1.
> Sample solution
> 
> *Example Input*
> 
> 3 5
> 1 2 3 5 5
> 2 2 3 5 1
> 1 3 5 2 2
> 3 5
> 2 2
> 1 2
> 1 2
> 1 1
> 0 0
> 
> 3 5
> 1 2 3 5 5
> 2 2 3 5 1
> 1 3 5 2 2
> 2 2 1 2 1 4 1 2
> 99 99 0 0
> 
> 4 3
> 1 4 4
> 4 4 2
> 1 2 3
> 3 1 3
> 1 2 1 1 1 3 1 1 0 0
> 0 0
> 
> *Expected Output*
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> Grid 1.
> Game Won
> 
> Grid 2.
> 
> 1   2
> 1 2 1
> 
> Grid 3.
> Game Won


----------



## wimcle

Code:


Code:


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

public class samegame2{
    public static class Mask extends board{

        public Mask(int i, int j){
            super(i,j);
            }
        public void set(int i, int j){
            Vector v = (Vector)rows.get(i);
            v.set(j, new Integer("1"));
            }
        public int size(){
            int size = 0;
            for (int x=rows.size() -1; x >= 0; x--){
                Vector v = (Vector)rows.get(x);
                for (int y=v.size() -1; y>= 0; y--)
                    if ((Integer)v.get(y) == 1)
                        size++;
                }
            return size;
            }
        }
    public static class board{
        Vector rows;
        int x,y;

        public board(){
            this(0,0);
            }
        public board(int i, int j){
            rows = new Vector(i,1);
            for (int x=0; x<i; x++){
                Vector v = new Vector(j,1);
                rows.add(v);
                for (int y=0; y<j; y++)
                    v.add(new Integer(0));
                }
            x=i;
            y=j;
            }

        public void set(int i, int j, int val){
            Vector v = (Vector)rows.get(i);
            v.set(j, new Integer(val));
            }

        public int get(int i, int j){
            Vector v = (Vector)rows.get(i);
            if (v.size() <= j)
                return 0;
            Integer I = (Integer)v.get(j);
            return I.intValue();
            }

        public void remove1(int i, int j){
            Vector v = (Vector)rows.get(i);
            v.removeElementAt(j);
            }

        public void rremove(int i, int j, Mask mask){
            int I = get(i,j);
            mask.set(i,j);

            int top = j;
            int bottom = j;
            Vector v = (Vector)rows.get(i);
            while (top < v.size() -1)
                if (I == get(i,top + 1))
                    top +=1;
                else
                    break;
            while (bottom > 0)
                if (I == get(i,bottom -1))
                    bottom -= 1;
                else
                    break;
            for (int m=top; m >=bottom; m--){
                if (mask.get(i,m) == 0)
                    rremove(i,m,mask);
                }

            int left = i;
            int right = i;
            while (left > 0)
                if (I == get(left -1,j))
                    left -= 1;
                else
                    break;
            while (right < rows.size() -1)
                if (I == get(right +1,j))
                    right += 1;
                else
                    break;
            for (int m=left;  m<=right; m++){
                if (mask.get(m,j) == 0)
                    rremove(m,j, mask);
                }
            }

        public int remove(int i, int j){
            Mask mask = new Mask(x,y);
            rremove(i,j, mask);

            int _size = 0;
            for (int x=rows.size() -1; x >= 0; x--){
                Vector v = (Vector)rows.get(x);
                _size += v.size();
                for (int y=v.size() -1; y>= 0; y--)
                    if (mask.get(x,y) == 1){
                        if (mask.size() > 1){
                            remove1(x,y);
                            _size -= 1;
                            }
                        }
                if (v.size() == 0)
                    rows.remove(x);
                }
            return _size;
            }

        public String toString(){
            StringBuffer sb =new StringBuffer();
            int max=0;
            for (int i=0; i< rows.size(); i++){
                Vector v = (Vector)rows.get(i);
                if (v.size() > max)
                    max = v.size();
                }
            while (--max >= 0){
                for (int i=0; i< rows.size(); i++){
                    Vector v = (Vector)rows.get(i);
                    if (v.size() > max)
                        sb.append(get(i,max) + " ");
                    else
                        sb.append("  ");
                    }
                sb.append("\
");
                }
            return sb.toString();
            }
        }
    public static void main(String[] args){
        try {
            char c;
            int C;
            LinkedList ll = new LinkedList();
            int lli = 0;
            int grid = 1;
            StringBuffer sb = new StringBuffer();
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            while ((C = in.read()) != -1){
                c = (char)C;
                if (c >= '0' && c <= '9')
                        sb.append(c);
                else {
                    if (sb.length() >0)
                        ll.add(new Integer(sb.toString()));
                        sb.setLength(0);
                    }
                }

            while (lli < ll.size() -3){
                int x = (Integer)ll.get(lli++);
                int y = (Integer)ll.get(lli++);
                if (x == 0 || y == 0)
                    continue;

                System.out.println("Grid " + grid++ + ".");    
                board b = new board(y,x);
                for (int i=x; i>=1; i--)
                    for (int j=1; j<= y; j++)
                        b.set(j-1, i-1, (Integer)ll.get(lli++));

                System.out.println(b);
                System.out.println();
                int x2, y2;
                int ret = 0;
                while (true){
                    x2 = (Integer)ll.get(lli++);
                    y2 = (Integer)ll.get(lli++);
                    if (x2 == 0 || y2 == 0)
                        break;
                    if (x2 >x || y2 > y)
                        continue;

                    ret = b.remove(y2-1,x2-1);
                    System.out.println(b);
                    System.out.println();
                    if (ret == 0){
                        System.out.println("Game Won");
                        break;
                        }
                    }
                if (ret > 0)
                    System.out.println(b);

                while (x2 !=0 || y2 != 0){
                    x2 = (Integer)ll.get(lli++);
                    y2 = (Integer)ll.get(lli++);
                    }
                }
            }
        catch (Exception e){
            e.printStackTrace();
            }
        }
    }

Code:


Code:


Grid 1.
1 2 3 5 5
2 2 3 5 1
1 3 5 2 2

1 2 3
2 2 3 5 5
1 3 5 5 1

    3
1   3 5 5
1 3 5 5 1

1   3
1 3 3 1

1
1 1

Game Won


----------



## Midpipps

Quote:



Originally Posted by *wimcle*


I think your example input needs some work... for example grid 3 has one '2' in it, it can never win.



Grid 3 has 2 twos in it.
1 4 4
4 4 2
1 2 3
3 1 3

But I do see the problem in the example the tabs were not kept should have used code instead of quote the 5 in the example problem should be moved over one spot fixing now


----------



## wimcle

Quote:



Originally Posted by *Midpipps*


Grid 3 has 2 twos in it.
1 4 4
4 4 2
1 2 3
3 1 3

But I do see the problem in the example the tabs were not kept should have used code instead of quote the 5 in the example problem should be moved over one spot fixing now


been typeing on this two long, going blind


----------



## impatient

Quote:



Originally Posted by *wimcle*


A kinda verbose java one


I think they are all going to be verbose.


----------



## wimcle

A test case for regions:
all the 2s should drop out

Code:



Code:


4 5
2 2 2 1 1
2 1 2 2 1
1 2 1 2 2
2 2 2 2 1
2 4
1 1
0 0


----------



## Midpipps

Quote:


> Originally Posted by *wimcle;12246238*
> A test case for regions:
> all the 2s should drop out
> 
> Code:
> 
> 
> 
> Code:
> 
> 
> 4 5
> 2 2 2 1 1
> 2 1 2 2 1
> 1 2 1 2 2
> 2 2 2 2 1
> 2 4
> 1 1
> 0 0


nice that is actually a good idea.


----------



## Midpipps

It is a little convoluted but hear it is. It is very breakable but it works well I think the revursive call was the funnest part everything else was just fluff

Code:


Code:


import java.util.Scanner;
import java.util.Vector;

public class SameGame {
private static Vector <Vector<Integer>> mColumnV; //made global just so that I did not have to pass it all the time
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int rows = in.nextInt();
int columns = in.nextInt();
//get the vectors ready 0's are just place holders till they are filled this is so we can put them in reverse order.
mColumnV = new Vector<Vector<Integer>>(columns);
for (int i = 0; i < columns; i++)
mColumnV.add(i, new Vector<Integer>(rows));

//things will automagically fall into place :) just need to flip it for output
for (int r = 0; r < rows; r++)
for (int c = 0; c < mColumnV.size(); c++){
int tempNumberRead = in.nextInt();
mColumnV.get(c).add(r, tempNumberRead);
}

int r = -1;
int c = -1;
while ( (r = in.nextInt()) != 0 && (c = in.nextInt()) != 0){
r = r - 1;
c = c - 1;

if(c < mColumnV.size()  && c >= 0){
removeThisPlusNeighbors(r, c, -1, new Vector<String>(), 0);//uses -1 as a key to know the first entrance to the function the zero is going to be used as a counter
//look for 0's if there are some remove them :) the map will collapse
for (int i = 0; i < mColumnV.size(); i ++)
while (mColumnV.get(i).contains(0))
mColumnV.get(i).remove(mColumnV.get(i).indexOf(0));
//look for any empty vectors to collapse the map again
for (int i = mColumnV.size() - 1; i >= 0; i--)
if (mColumnV.get(i).size() == 0)
mColumnV.remove(i);
}
}
//end game
if (mColumnV.size() > 0){
System.out.println("You loose");
printGame(rows);
}
else
System.out.println("Game Won");
}

public static void printGame(int rows){
String output = "";
for (int a = rows - 1; a >= 0; a--){
for (int i = 0; i < mColumnV.size() ; i++){
if( a < mColumnV.get(i).size())
output += mColumnV.get(i).get(a) + " ";
else
output += "  ";
}
output += "\
";
}
System.out.println(output);
}

public static int removeThisPlusNeighbors(int r, int c, int numberBeingChecked, Vector<String> previouslyChecked, int toBeZeroed){
previouslyChecked.add("" + r + "," + c + ""); //the vector is to keep track so that we do not remove something we have already been to. 
if (numberBeingChecked == -1)
numberBeingChecked = mColumnV.get(c).get(r);

if (numberBeingChecked == mColumnV.get(c).get(r))
{
toBeZeroed++;
//check right
if (c - 1 >= 0   && c < mColumnV.size() && !previouslyChecked.contains("" + (r) + "," + (c - 1) + ""))
if (r < mColumnV.get(c - 1).size())
toBeZeroed = removeThisPlusNeighbors(r, c-1, numberBeingChecked, previouslyChecked, toBeZeroed);
//check left
if (c + 1 < mColumnV.size() && c >= 0 && !previouslyChecked.contains("" + (r) + "," + (c + 1) + ""))
if (r < mColumnV.get(c + 1).size())
toBeZeroed = removeThisPlusNeighbors(r, c+1, numberBeingChecked, previouslyChecked, toBeZeroed);
//check down
if (r - 1 >= 0 && !previouslyChecked.contains("" + (r - 1) + "," + (c) + ""))
toBeZeroed = removeThisPlusNeighbors(r - 1, c, numberBeingChecked, previouslyChecked, toBeZeroed);
//check up
if (r + 1 < mColumnV.get(c).size() && !previouslyChecked.contains("" + (r + 1) + "," + (c) + ""))
toBeZeroed = removeThisPlusNeighbors(r + 1, c, numberBeingChecked, previouslyChecked, toBeZeroed);
// 0 is a locator to show us where there are items to be removed only zero things out if we have more then 2 to be zeroed
if (toBeZeroed > 1)
mColumnV.get(c).set(r, 0);
}
return toBeZeroed;
}
}

Code:


Code:


run 1:  game won
run 2: You loose

1   2 
1 2 1

run 3:
game won

Test Data from wimcle:
game won

Decided to do spoiler tags that way people won't have to see code if they want a clean look at the problem. Without being tainted by others code.


----------



## _GTech

I just don't pick my brain for fun, too much work, lol!









Well, I use to, then I went broke, so I decided it was time to get paid for my brain!









Now, I stopped coding mostly and started running my own computer business...

Looking back, I'm very happy I stopped programming, whoosh!

I can't join the competition, not that advanced, but it was nice watching all of you code like, very impressive.


----------



## impatient

Here's mine. I'm not done, but I probably won't have time to finish before tomorrow. It should only need the code to load the square holder and to do the clicks.

I tried not looking at any of your guys' code, just to see if I could come up with something unique. I really wanted to just have to keep track of one square and have it do everything from there, but I figured this would be easier to debug.

I don't read input. It's just loaded in the main method right now.

Code:


Code:


import scala.collection.mutable.{MutableList => MList }

case class Square(intVal: Int) {

var top:Square= Square.empty;
var bottom:Square = Square.empty
var left:Square = Square.empty
var right:Square = Square.empty
var dirty = false

def clear() 
    {
top = Square.empty
bottom = Square.empty
right = Square.empty
left = Square.empty
}

def listRep =  List(top , right , bottom , left);

def intEquals(sqr:Square) =  sqr.intVal == intVal;

def canConstrict() =  listRep.filter(x => intEquals(x)).size > 0

def doConstrict() { listRep.filter(x => intEquals(x) && !x.dirty).foreach{y => y.dirty = true; y.doConstrict()}  }

override def toString() = intVal + "<=>"  + (for( i <- listRep) yield i.intVal).toList.toString;

}

object Square
{
val emptySquare = new Square(-1)
def empty():Square = return emptySquare;

  def main(args : Array[String]) : Unit = {
   println("woohoo");
   var sh = new SquareHolder();

   sh.addRow(List(1,1,2,2));
   sh.addRow(List(2,1,2,2));
   sh.addRow(List(2,2,2,1));
   sh.printSquares();
   //sh.doMove(2,2);
   sh.doMove(1,1);
   sh.doMove(1,1);

  }

}
class SquareHolder()
{
def addRow(numList:List[Int]) 
{  
for(i <- 0 to (numList.size - buildList.size))
{buildList += new MList[Square]()}
numList.zip(0 to numList.size).foreach{x =>    new Square(x._1) +=: buildList(x._2); };
    yList = (for(col <- buildList) yield List() ++ col).toList 
}

def clear() { yList = List[List[Square]](); buildList = new MList[MList[Square]](); }
var buildList = new MList[MList[Square]]();
var yList = List[List[Square]]()
def click(x:Int, y:Int) { val sq = (yList(x-1))(y-1);
  if(!sq.canConstrict()){ println("Click would do nothing.")}
  else
   { sq.doConstrict(); }   
  }

def printSquares() {
val mx = (yList.map(x => x.size)).max(Ordering[Int])
var st = for(  ht <- (0 to mx).reverse; ls <- yList) yield getOrBlank(ls,ht)
for(line <- st.grouped(yList.size))
{ for(n  <- line) { print(n);}
println("");}
}

def getOrBlank(sqList:List[Square], idx:Int): String =
{
if(idx >= sqList.size) { return " "; }
else
{ sqList(idx).intVal  + "" }
}

def link() { 
//clear
yList.foreach{ x => x.foreach{ y => y.clear } }
//link left and right squares
yList.sliding(2,1).foreach{ x => 
    if(x.size == 2) {
var leftList = x(0)
var rightList = x(1)
val min = (x.map(y => y.size)).min(Ordering[Int])
for(i <- 0 to min-1)
{
leftList(i).right  = rightList(i)
rightList(i).left = leftList(i)
}
    }
}
//link top and bottom squares
yList.foreach{ x => x.sliding(2,1).foreach{ y => if(y.size == 2) {y(0).top = y(1); y(1).bottom = y(0) } } }

}
def clearDirty():List[List[Square]] = {
val newY = for(y <- yList ) yield y.filter{x:Square => !x.dirty}
newY.toList
}
def removeEmptyColumns():List[List[Square]] = {
val newY = for(y <- yList if(y.filter{x => x != Square.empty }.size > 0)) yield y
newY.toList
}

def remaining():Int = yList.map(x => x.size).sum

def doMove(x:Int, y:Int) {

link();
click(x,y); 
yList=clearDirty();
yList = removeEmptyColumns();
if(remaining == 0)
{ println("Game Won"); }
else
{printSquares();}

}
}


----------



## impatient

I generated a 2000 x 2000 grid, just to see how long the individual things took to process. It tries 100 clicks.

If you need the size to be at the top, you will need to manually add it. It is about 8 megs unzipped. The game won't complete or anything, I just did timing on how long each click took and to see where to speed up my code.

http://f5complex.com/data.txt.bz2


----------



## Midpipps

Here is the new one. Sorry it is late I forgot about it and was running imps massive grid to watch it break









Code:


Code:


[B]Problem C - Machined Surfaces[/B]

An imaging device furnishes digital images of two machined surfaces that eventually will be assembled in contact with each other.The roughness of this final contact is to be estimated.
A digital image is composed of the two characters, "X" and " " (space). There are always 25 columns to an image, but the number of rows, N, is variable. Column one (1) will always have an "X" in it and will be part of the left surface. The left surface can extend to the right from column one (1) as contiguous X's. Similarly, column 25 will always have an "X" in it and will be part of the right surface. The right surface can extend to the left from column 25 as contiguous X's.

Digital-Image View of Surfaces
       Left         Right

       XXXX         XXXXX  <-- 1
       XXX        XXXXXXX
       XXXXX         XXXX
       XX          XXXXXX
       .                .
       .                .
       .                .
       XXXX          XXXX
       XXX         XXXXXX  <-- N
       |                |
       1               25
In each row of the image, there can be zero or more space characters separating the left surface from the right surface. There will never be more than a single blank region in anyrow.
Foreach image given, you are to determine the total "void" that will exist after the left surface has been brought into contact with the right surface. The "void" is the total count of the spaces that remains between the left and right surfaces after they have been brought into contact.

The two surfaces are brought into contact by displacing them strictly horizontally towards each other until a rightmost "X" of the left surface of some row is immediately to the left of the leftmost "X" of the right surface of that row. There is no rotation or twisting of these two surfaces as they are brought into contact; they remain rigid, and only move horizontally.

Note: The original image may show the two surfaces already in contact, in which case no displacement enters into the contact roughness estimation.

[B]Input[/B]

The input consists of a series of digital images. Each image data set has the following format:
First line -- A single unsigned integer, N, with value greater than zero (0) and less than 13. The first digit of N will be the first character on a line.
Next N lines -- Each line has exactly 25 characters; one or more X's, then zero or more spaces, then one or more X's.

The end of data is signaled by a null data set having a zero on the first line of an image data set and no further data.

[B]Output[/B]

For each image you receive as a data set, you are to reply with the total void (count of spaces remaining after the surfaces are brought into contact). Use the default output for a single integer on a line.
Sample Input

4
XXXX                XXXXX
XXX               XXXXXXX
XXXXX                XXXX
XX                 XXXXXX
2
XXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXX
1
XXXXXXXXX              XX
0

[B]Output for the Sample Input[/B]

4
0
0


----------



## impatient

Quote:



Originally Posted by *Midpipps*


Here is the new one. Sorry it is late I forgot about it and was running imps massive grid to watch it break










sure sure. you beat mine


----------



## impatient

Quote:



Originally Posted by *Midpipps*


Here is the new one. Sorry it is late I forgot about it and was running imps massive grid to watch it break









Code:


Code:


[B]Problem C - Machined Surfaces[/B]


I guess this is technically a one liner... a really long one. The last bit, where I assign vals seems like cheating.

Code:


Code:


io.Source.fromFile(new java.io.File("data.txt")).getLines().map{x:String => if(('0' to '9').mkString.contains(x)) { "~"} else{ x.filter( y => y.equals('X')).size} }.mkString(" ").split("~").filter(x => x.size > 0).foreach{x:String => val sz = x.split(" ").filter{y:String => y.length > 0}.map( _.toInt); val mx = sz.max(Ordering[Int]); println(sz.map( mx - _).sum)}


----------



## Midpipps

here is my take on it not as schnazzy as imps 1 liner but it works mine is 1 line as long as it is hidden by a spoiler tag at least until you click it









spaces)highAndLow[0] = spaces;highAndLow[1] += spaces;}System.out.println(highAndLow[1] - (highAndLow[0] * rows));}in.close();}}">

Code:


Code:


import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class MachinedSurface {
public static void main(String[] args) throws IOException{
Scanner in = new Scanner(new FileReader("machinedin.txt"));
while(in.hasNext() && !in.hasNext("0")){
int rows = Integer.parseInt(in.nextLine());
int[] highAndLow = {Integer.MAX_VALUE, 0};//if there are more spaces then max value program will break regardless
for (int i = 0; i < rows; i++){
String temp = in.nextLine();
int spaces = 0;
if (temp.contains(" "))
spaces = temp.lastIndexOf(' ') - temp.indexOf(' ') + 1;
if (highAndLow[0] > spaces)
highAndLow[0] = spaces;
highAndLow[1] += spaces;
}
System.out.println(highAndLow[1] - (highAndLow[0] * rows));
}
in.close();
}
}


----------



## wimcle

Could have chopped out a few lines, but wanted to play with regex

Code:


Code:


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

public class machinedSurfaces{
    public static void main(String[] args){
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            int count = 0;
            String line = in.readLine();
            while ((count = Integer.parseInt(line)) != 0){
                int min = 25, sum = 0;
                for (int i=0; i< count; i++){
                    line = in.readLine();
                    if (line == null || line.length() != 25)
                        throw new Exception("Bad input: " + line + " length <> 25");
                    Pattern pattern = Pattern.compile("[X]+([\\\\s]*)[X]*");
                    Matcher matcher = pattern.matcher(line);
                    if (!matcher.matches())
                        throw new Exception("Input: " + line + " doesnt match regex");
                    int sp_cnt = matcher.group(1).length();
                    if (sp_cnt < min)
                        min = sp_cnt;
                    sum = sum + sp_cnt;
                    }
                System.out.println(sum - (min * count));
                line = in.readLine();
                }
            }
        catch (Exception e){
            e.printStackTrace();
            }
        }
    }


----------



## Midpipps

Quote:



Originally Posted by *wimcle*


Could have chopped out a few lines, but wanted to play with regex

How do you do the show/hide ?

Code:


Code:


good stuff


It is using the {spoiler="Your spoiler Message"]Whatever you want hidden{/spoiler] replacing the { with [ of course


----------



## xtascox

I promise, I will find time to do another challenge.


----------



## Midpipps

Quote:


> Originally Posted by *xtascox;12335763*
> I promise, I will find time to do another challenge.


You should they are fun







. How goes OCNix?


----------



## xtascox

Quote:



Originally Posted by *Midpipps*


You should they are fun







. How goes OCNix?


OCNix needs more man power


----------



## Midpipps

Hmm a new challenge going to stick with the easier ones for a little while to see if we can't get a few more people involved. this one should satisfy most people has sorting and has decently easy math.

Quote:



*Number Chains*

Given a number, we can form a number chain by
1. arranging its digits in descending order

2. arranging its digits in ascending order

3. subtracting the number obtained in (2) from the number obtained (1) to form a new number

4. and repeat these steps unless the new number has already appeared in the chain

Note that 0 is a permitted digit. The number of distinct numbers in the chain is the length of the chain. You are to write a program that reads numbers and outputs the number chain and the length of that chain for each number read.
The input consists of a sequence of positive numbers, all less than 10^9, each on its own line, terminated by 0. The input file contains at most 10 numbers.

The output consists of the number chains generated by the input numbers, followed by their lengths exactly in the format indicated below. After each number chain and chain length, including the last one, there should be a blank line. No chain will contain more than 1000 distinct numbers.

*Sample Input*

123456789
1234
444
0

*Sample Output*
Original number was 123456789
987654321 - 123456789 = 864197532
987654321 - 123456789 = 864197532
Chain length 2

Original number was 1234
4321 - 1234 = 3087
8730 - 378 = 8352
8532 - 2358 = 6174
7641 - 1467 = 6174
Chain length 4

Original number was 444
444 - 444 = 0
0 - 0 = 0
Chain length 2


Here is an example in case the write up is confusing.

Code:


Code:


Original number was 2134

1: arrange in ascending order  | 1234
2: arrange in descending order | 4321
3: subtract step 2 from step 1 | 4321 - 1234  = 3087

Repeat with new number of 3087
1: arrange in ascending order  | 0378
2: arrange in descending order | 8730
3: subtract step 2 from step 1 | 8730 - 0378 = 8352

Repeat this until the new number has already been seen as a calculate number


----------



## impatient

Here it is in scala.

Code:


Code:


def nc(inp:String, oldVal:List[Int], depth:Int) {    
  val big = inp.sorted.reverse.toInt
  val small = inp.sorted.toInt
  val newVal = big - small
  println(big + " - " + small + " = " + newVal + " at depth " + depth)
  if(oldVal.contains(newVal))
  { println("End of chain with depth " + depth);}
  else { nc(newVal.toString, newVal :: oldVal, depth+1) }
}

def compStr(inp:String) {  nc(inp, List(-1), 0); }

scala> compStr("123456789")
987654321 - 123456789 = 864197532 at depth 0
987654321 - 123456789 = 864197532 at depth 1
End of chain with depth 1

scala> compStr("444")      
444 - 444 = 0 at depth 0
0 - 0 = 0 at depth 1
End of chain with depth 1

scala> compStr("1234")
4321 - 1234 = 3087 at depth 0
8730 - 378 = 8352 at depth 1
8532 - 2358 = 6174 at depth 2
7641 - 1467 = 6174 at depth 3
End of chain with depth 3

Does anyone else's 8675309 get caught in a loop? Edit: fixed (Thanks Pipps)


----------



## Midpipps

man mine is ugly compared to Imps if there is a better way in java I do not know it.

Code:



Code:


import java.util.Arrays;
import java.util.Vector;
public class OCNTest {
public static void main(String [] args)
{
String startNumber = "8675309";
int chainLength = -1;
Vector<String> oldNumbers = new Vector<String>();
System.out.println("The original Number was " + startNumber);
while (oldNumbers.indexOf(startNumber) < 0){
chainLength += 1;
oldNumbers.add(startNumber);
char[] ascending = startNumber.toCharArray();
Arrays.sort(ascending);
String temp = new String(ascending);
startNumber = new String((Integer.parseInt(reverse(ascending)) - Integer.parseInt(temp)) + "");
System.out.println(reverse(ascending) + " - " + temp + " = " + startNumber + " depth=" + chainLength);
}
System.out.println("Chain length " + chainLength);
}

public static String reverse(char [] c){
for (int i = 0; i < (c.length/2); i ++){
char right = c[c.length - 1 - i];
c[c.length - 1 - i] = c[i];
c[i] = right;
}
return new String(c);
}
}


----------



## impatient

Pipps is on vacation this week, so I volunteered to post a problem. I found a fun problem in a Haskell book. I'm switching up the format a bit. I'm going to present the problem and have two possible different approaches in spoilers.
Quote:


> *Deciphering Caesar*
> 
> The Caesar Shift Cipher is a way of encoding a string to hide the contents, by shifting the characters by a certain number of letters.
> 
> For example with a shift of one:
> 
> "YAY ROBOTS" -> "ZBZ SPCPUT"
> 
> For a shift of two:
> 
> "YAY ROBOTS" -> "ACA TQDQVU"
> 
> The challenge is, if given a block of text, encoded, how can you determine the shift size and get the original string.
> 
> Below are two links, one which contains the frequency of each letter in normal English and the other a list of the 2000 most common words in the English language(from who knows how long ago). I don't think either will help you out with "YAY ROBOTS" since neither yay or robots are in the 2000 most common words. They also have an unusual amount of different letters. For example, Y should appear with a frequency of 2%, whereas in the sample, it makes up 22% of the letters.
> 
> 2000 most common words
> Letter frequency
> 
> So.. the question is.. what does this text say?
> 
> SIO QCH U JLCTY. NBY ZYYFCHA IZ U DIV QYFF XIHY.
> 
> 
> Spoiler: Spoiler - Dictionary
> 
> 
> 
> Build a program that can encode and decode strings, when passed a string and a shift number.
> 
> For example shiftMe("YAY ROBOTS", 1) should return "ZBZ SPCPUT"
> And shiftMe("ZBZ SPCPUT", -1) should return "YAY ROBOTS"
> 
> Load the dictionary and see if you can find word matches when shifting. (If you're using YAY ROBOTS to test, add them ;p)
> 
> 
> 
> 
> 
> Spoiler: Spoiler - Frequency
> 
> 
> 
> Build a function that will return the percentages of each letter as they are part of your string. For input, "ABCD", A->25% and B->25% and C->25%...
> 
> Learn some statistics. Wikipedia
> 
> In short, you will rotate the frequency list and see which shifted frequency table best fits with the frequency of letters in the sample.
> 
> 
> 
> As the size of the test data goes up, the more likely a match will occur.
> EDIT: Just for the record, for frequency, the YAY ROBOTS won't work, but a shifted HURRAY ROBOTS will work just fine.


----------



## impatient

I wrote this during lunch last week. It does the frequency method and took a whole 19 lines of actual code.

Code:


Code:


//frequency of letters
val knownFreq = List(8.2f, 1.5f,2.8f,4.3f,12.7f,2.2f,2.0f,6.1f,7.0f,.2f,.8f,4.0f,2.4f,6.7f,7.5f,1.9f,.1f,6.0f,6.3f,9.1f,2.8f,1.0f,2.4f,.2f,2.0f,.1f);
val knFreq = knownFreq.zipWithIndex

//method to shift percentage estimates (for chi square test)
def shift(update : Map[Char,Float], sz:Int) : Map[Int,Float] = { for(i <- update) yield ((i._1.toInt - 97 + sz) % 26 -> i._2) }

//crack method
def crack(str:String): String =
{
  val original = str.toLowerCase
  //only include letters
  val sample = original.filter{i: Char => i != ' ' && i != '.' && i != ',' && i != '\\''}

  //get percentage each letter makes up of whole string
  var freq = (for(i <- sample.distinct) yield (i -> sample.count(_ == i).toFloat / sample.size)).toMap
  var bfData = Map[Double, Int]()

  /*
     loop that moves frequency generated above to try different letter values
  */
  for(i <- 0 to 25)
  {
    //actual shifting of frequency
    val mv = shift(freq, i)
    // (observed - expected)^2/ expected  
    val sumFit = (knFreq.map{ j => scala.math.pow( mv.getOrElse(j._2,0f) - j._1,2)/ j._1}).sum
    bfData = bfData + (sumFit -> i)
  }

  //best fit is the minimum of the sumFit value
  val bestFit = bfData.min._2
  println("Best guess at shift size is " + bestFit)

  //shift data the best fit number of letters
  //the shift function should be moved to its own method (the above shift should probably have a different name
  return original.map{ i =>  if(i != ' ' && i != '.' && i!= ',' && i != '\\'') { ((i -97 + bestFit) % 26 + 97).toChar;} else { i } }
}

More samples:

Code:


Code:


crack("YJGP, KP VJG EQWTUG QH JWOCP GXGPVU, KV DGEQOGU PGEGUUCTA HQT QPG RGQRNG VQ FKUUQNXG VJG RQNKVKECN DCPFU YJKEJ JCXG EQPPGEVGF VJGO YKVJ CPQVJGT, CPF VQ CUUWOG COQPI VJG RQYGTU QH VJG GCTVJ, VJG UGRCTCVG CPF GSWCN UVCVKQP VQ YJKEJ VJG NCYU QH PCVWTG CPF QH PCVWTG'U IQF GPVKVNG VJGO, C FGEGPV TGURGEV VQ VJG QRKPKQPU QH OCPMKPF TGSWKTGU VJCV VJGA UJQWNF FGENCTG VJG ECWUGU YJKEJ KORGN VJGO VQ VJG UGRCTCVKQP.");

crack("UFCL, GL RFC AMSPQC MD FSKYL CTCLRQ, GR ZCAMKCQ LCACQQYPW DMP MLC NCMNJC RM BGQQMJTC RFC NMJGRGAYJ ZYLBQ UFGAF FYTC AMLLCARCB RFCK UGRF YLMRFCP, YLB RM YQQSKC YKMLE RFC NMUCPQ MD RFC CYPRF, RFC QCNYPYRC YLB COSYJ QRYRGML RM UFGAF RFC JYUQ MD LYRSPC YLB MD LYRSPC'Q EMB CLRGRJC RFCK, Y BCACLR PCQNCAR RM RFC MNGLGMLQ MD KYLIGLB PCOSGPCQ RFYR RFCW QFMSJB BCAJYPC RFC AYSQCQ UFGAF GKNCJ RFCK RM RFC QCNYPYRGML.");

//warning... not english
crack("NQTGO KRUWO FQNQT UKV COGV, EQPUGEVGVWT CFKRKUKEKPI GNKV, UGF FQ GKWUOQF VGORQT KPEKFKFWPV WV NCDQTG GV FQNQTG OCIPC CNKSWC. WV GPKO CF OKPKO XGPKCO, SWKU PQUVTWF GZGTEKVCVKQP WNNCOEQ NCDQTKU PKUK WV CNKSWKR GZ GC EQOOQFQ EQPUGSWCV. FWKU CWVG KTWTG FQNQT KP TGRTGJGPFGTKV KP XQNWRVCVG XGNKV GUUG EKNNWO FQNQTG GW HWIKCV PWNNC RCTKCVWT. GZEGRVGWT UKPV QEECGECV EWRKFCVCV PQP RTQKFGPV, UWPV KP EWNRC SWK QHHKEKC FGUGTWPV OQNNKV CPKO KF GUV NCDQTWO");

Frequency clarification:

For the frequency solution, you use the chi square analysis to determine the best fitting data. It works surprisingly well, even for some non-english data.

The list given for letter frequency is the expected value. If you compare the expected value and the given value, the one that is closest overall, will have the lowest sum.

The formula is (observed-expected)^2/expected summed over all the frequencies.

For example if we have the sample text "fcf" and want to run through a couple iterations, here is what we have.
f's make up 66% of the values
and 
c makes up 33% of the letters.

//abc frequency (expected values)
[8.2f, 1.5f,2.8f,4.3f,12.7f,2.2f,2.0f,6.1f,7.0f,.2f,.8f,4 .0f,2.4f,6.7f,7.5f,1.9f,.1f,6.0f,6.3f,9.1f,2.8f,1. 0f,2.4f,.2f,2.0f,.1f]

//observed values
Run one(shift 0):
[0,0,.33f,0,0,.66f, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] => 98.54167
Run two(shift 1):
[0,0,0,.33f,0,0,.66f, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] => 98.54806
Run three(shift 2):
[0,0,0,0,.33f,0,0,.66f, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] => 98.38160
...

As you can see, the frequencies are moving across the board. The proper shift is the run with lowest value when the function is applied. For a perfect match, the formula would return 0, since the expected and observed are the same (expected - observed)^2/expected == 0. For the above sample, a shift of 2 has the value of 98.38160979033131, which is the lowest of any values. So f+2 = h and c + 2 = e yields "heh" when shifted.


----------



## purplestrain

Hi,

This my attempt at using a dictionary method using C# - it's not just ugly, it's PUGLY and bloated. But...it works









Code:



Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

static void Main(string[] args)
        {
SearchText("SIO QCH U JLCTY. NBY ZYYFCHA IZ U DIV QYFF XIHY.");
}

 private static void SearchText(string text)
        {
            int searchIndex = 0;            
            List<string> wordList = new List<string>();
            List<string> dictionaryList = new List<string>();
            List<int> foundIterations = new List<int>();
            while (searchIndex != 26)
            {
                string Result = ShiftText(text, searchIndex);                
                wordList = buildwordList(Result);
                dictionaryList = buildwordList("2000.txt", true);
                List<string> fI = new List<string>();
                bool foundMatch = false;
                foreach (string word in wordList)
                {
                    foreach (string dWord in dictionaryList)
                    { 
                        if (word == dWord)
                        {
                            foundMatch = true;
                            fI.Add(word);
                        }
                    }
                }
                if (foundMatch == true)
                {
                    Console.WriteLine("Match found:");
                    Console.WriteLine(Result);
                    Console.WriteLine("Iteration:" + searchIndex.ToString());
                    Console.WriteLine("Do you wish to see the matched words?");
                    System.ConsoleKey A = Console.ReadKey().Key;
                    if (A == ConsoleKey.Y)
                    {
                        Console.Write("\n");
                        foreach (string f in fI)
                        {
                            Console.Write(f + " ");
                        }
                        Console.Write("\n");
                        Console.WriteLine("Press any key.");
                        Console.ReadKey();
                    }

                }
                searchIndex = searchIndex + 1;

            }

            Console.WriteLine("End");
            Console.ReadKey();
        }

private static string ShiftText(string text, int shiftVal)
        {
            string textResult = "";
            string alphaBet = "abcdefghijklmnopqrstuvwxyz";
            char[] alphaChar = alphaBet.ToCharArray();            
            char[] charText = text.ToLower().ToCharArray();
            char nVal;
            List<char> charResult = new List<char>();
            foreach (char charVal in charText)
            {
                int alphaPosCount = 0;
                int foundPos = 0;
                bool foundVal = false;
                List<char> Results = new List<char>();
                foreach (char charTestVal in alphaChar)
                {
                    //Console.WriteLine(charVal.ToString() + " > " + charTestVal.ToString());
                    if (charVal == charTestVal)
                    {
                        foundPos = alphaPosCount;
                        foundVal = true;
                    }

                    alphaPosCount = alphaPosCount + 1;
                }
                if (foundVal == true)
                {
                    int tVal = foundPos + shiftVal;
                    if (tVal > 25) tVal = (tVal - 26);
                     nVal = alphaChar[tVal];
                    //Console.WriteLine(charVal.ToString() + " is now " + nVal.ToString());
                    //Console.ReadKey();
                }
                else
                {
                     nVal = charVal;
                }
                charResult.Add(nVal);

            }
            foreach (char charVal in charResult)
            {
                textResult = textResult + charVal;
            }
            //Console.Write("\nProcess complete.");
            //Console.ReadKey();
            return textResult;
        }

        private static List<string> buildwordList(string wordList)
        {
            List<string> results = new List<string>();
            string[] Words = wordList.Split(' ');

            foreach (string word in Words)
            {
                results.Add(word);
                //Console.WriteLine(word);
            }
            //Console.ReadKey();
            return results;            
        }

        private static List<string> buildwordList(string fileName, bool fileLoadFlag)
        {
            System.IO.StreamReader file = new System.IO.StreamReader(fileName);
            List<string> results = new List<string>();
            string Res = file.ReadToEnd();
            string[] words = Res.Split('\n');
            foreach (string word in words)
            {   
                results.Add(word);
            }
            //Console.ReadKey();
            return results;
        }


----------



## ZTR1760

After looking through this thread for the first time I've come to the conclusion that my education is seriously lacking...


----------



## Midpipps

Quote:


> Originally Posted by *ZTR1760;13235078*
> After looking through this thread for the first time I've come to the conclusion that my education is seriously lacking...


Nah they are alot of fun if I get time I would like to get back to posting these again. I have just been busy lately. I think if you actually sat down and did them you would get them pretty quickly alot of them sound harder then they actually are


----------



## superhead91

I would love for this thread to get revived. Summers almost here and I'd like to have something to keep my programming skills sharp.


----------



## wimcle

I didn't do the last few, was busy lining up this years work. But I'm back now.

-- Will


----------



## Midpipps

Here we go new challenge sorry forgot to post yesterday here it is

Quote:



Professor Smith is a long-time MICS attendee, but she especially likes it when the College of St. Scholasitca (CSS) hosts. Therefore, she want you to write a program to generate the initials 'CSS' using asterisks ('*') to form block letters.

*INPUT SPECIFICATION:* You will be given a set of input cases, each of which will begin with an odd decimal integer between 5 and 31 (specifying the height and width of each block letter) followed by <EOLN>. The last input case will be followed by â€œ0<EOLN>â€.

*OUTPUT SPECIFICATION:* The output cases should appear in the same order as the input cases. Each output case will be of the form â€œCase c: CSS of dimensions h and w.â€ (where c is the number of the input case, h is the height, and w is the width) followed by <EOLN>. The 'CSS' initials in block letters with one space between each letter. The initials are followed by a blank line before the next case.

*SAMPLE INPUT:*
5<EOLN>
11<EOLN>
0<EOLN>
<EOF>

*SAMPLE OUTPUT:*

Code:


Code:


Case•1:•CSS•of•dimensions•5•and•5.<EOLN>
***** ***** *****<EOLN>
*     *     *    <EOLN>
*     ***** *****<EOLN>
*         *     *<EOLN>
***** ***** *****<EOLN>
<EOLN>

Code:


Code:


Case•2:•CSS•of•dimensions•11•and•11.<EOLN>
*********** *********** ***********<EOLN>
*           *           *          <EOLN>
*           *           *          <EOLN>
*           *           *          <EOLN>
*           *           *          <EOLN>
*           *********** ***********<EOLN>
*                     *           *<EOLN>
*                     *           *<EOLN>
*                     *           *<EOLN>
*                     *           *<EOLN>
*********** *********** ***********<EOLN>
<EOLN>

<EOF>


----------



## MakubeX

I did it in Javascript so my take is a little different, but here it is:

Copy paste it in an HTML file and throw it in your browser. It should work.








Quote:


> *Input an odd number between 5 and 31*
> 
> Value:
> 
> Display CSS


----------



## Midpipps

That is pretty awesome. Just need to find time to do it but I will get one in.


----------



## csm725

Next challenge?


----------



## lunan1t4

I'm pitching in








since i just learnt Algorithms techniques, why dont i ask you guys to write me implementation of shortest path using
1.DFS BFS (uniformed search)
2.Hill Climbing, Djikstra, and A*(informed search)
list all the cost path, path traveled, heuristic cost, time taken to finish calculation.

restriction
1. use OO or Recursive only
2. there are no sets of questions, you make it up yourself, but it have to be CYCLIC GRAPH. you can't use Binary tree, Acyclic graph, or any other iteration. example for simple question is a shortest path on map

feel free to use advanced technique as multithreading (especially when traversing), parallel programming.
also list your Level of complexity. whether it's for beginner, intermediate or advanced.
dont show complex codes(intermediate and advanced) here...put in GIT,SVN, or Mercurial somewhere.

example of my codes (Intermediate,done in 2 weeks, 1 week to wrap my head around on how to represent the nodes, 1 week to code, using OOP and VS2010.)
https://bitbucket.org/lunan/a.i-1


----------



## Chris++

Huzzah, summer is pretty much here, and on vacation, bring them challanges!


----------



## MakubeX

Quote:


> Originally Posted by *Chris++;13896354*
> Huzzah, summer is pretty much here, and on vacation, bring them challanges!


Fun ones though... *cough not like lunan1t4's cough*.


----------



## Midpipps

I really need to write myself a reminder for this I have been so nuts with work etc lately I totally space on it till someone posts something and I get the reminder email. Fun ones you say hmmm I don't think I have posted this one yet.
Quote:


> *Problem 2 - Sum of Digits Squared*
> 
> Professor Smith loves number games. One game she likes is finding the sum of the squares of all the digits of a number. If you do this repeatedly, you will ultimately get to either one or four. For example, 16 becomes 37 (12 + 62) which becomes 58 (32+72) which becomes 89 (52+82), becoming 145, 42, 20, and 4, in succession.
> 
> Given a positive number, you are to print the sequence of digit square sums starting with that number and ending with 1 or 4. (If the number is either 1 or 4, you should apply the pattern at least once.)
> 
> *INPUT SPECIFICATION:* You will be given a set of input cases, each of which will be an unsigned decimal integer less than 10000000. The last input case will be followed by -1. There may be any number of spaces and 's before, after, and between the input cases and the terminating -1.
> 
> *OUTPUT SPECIFICATION:* The output cases should appear in the same order as the input cases. Each output case will be of the form "Case c" (where c is the number of the input case) followed by followed by the sequence of digit square sums beginning with the input case and ending with 1 or 4. Each number is followed by and an extra follows the output case.
> 
> *SAMPLE INPUT:*
> 1
> 4194304
> -1
> 
> *SAMPLE OUTPUT:*
> Case•1
> 1
> 1
> 
> Case•2
> 4194304
> 139
> 91
> 82
> 68
> 100
> 1


----------



## Midpipps

go here for the problem http://www.overclock.net/coding-programming/67741-programming-challenge-27.html#post13906339

Here are the full test cases they used in the competition
Input
Quote:


> 1 999999 3 22
> 100
> 4 5 6 7 8 9 10
> 9999999
> -1


Output
Quote:


> Case 1
> 1
> 1
> 
> Case 2
> 999999
> 486
> 116
> 38
> 73
> 58
> 89
> 145
> 42
> 20
> 4
> 
> Case 3
> 3
> 9
> 81
> 65
> 61
> 37
> 58
> 89
> 145
> 42
> 20
> 4
> 
> Case 4
> 22
> 8
> 64
> 52
> 29
> 85
> 89
> 145
> 42
> 20
> 4
> 
> Case 5
> 100
> 1
> 
> Case 6
> 4
> 16
> 37
> 58
> 89
> 145
> 42
> 20
> 4
> 
> Case 7
> 5
> 25
> 29
> 85
> 89
> 145
> 42
> 20
> 4
> 
> Case 8
> 6
> 36
> 45
> 41
> 17
> 50
> 25
> 29
> 85
> 89
> 145
> 42
> 20
> 4
> 
> Case 9
> 7
> 49
> 97
> 130
> 10
> 1
> 
> Case 10
> 8
> 64
> 52
> 29
> 85
> 89
> 145
> 42
> 20
> 4
> 
> Case 11
> 9
> 81
> 65
> 61
> 37
> 58
> 89
> 145
> 42
> 20
> 4
> 
> Case 12
> 10
> 1
> 
> Case 13
> 9999999
> 567
> 110
> 2
> 4


----------



## travesty

this is the first programming challenge i've done on here







thanks for posting these problems, it'll help keep me sharp over summer break. here's my recursive solution in java for the Sum of Digits Squared problem.

Code:



Code:


import java.util.ArrayList;

public class sum{
public static void main(String[] args){
for(int i=0; i<args.length; i++){
int input = 0;
try{
input = Integer.parseInt(args[i]);
}
catch(NumberFormatException e){
System.err.println("Please restart the program and enter an Ingeter");
System.exit(0);
}
if(input != -1){
int caseNum = i+1;
System.out.println("Case "+caseNum);
System.out.println(input);
int unused = parseNumber(input);
System.out.println("");
}
else{
System.exit(0);
}
}
}

public static int parseNumber(int input){
ArrayList<Integer> digits = getDigitsSquared(input);
int sum = 0;
for(int i=0; i<digits.size(); i++){
sum+=digits.get(i);
}
System.out.println(sum);
if((sum==1)||(sum==4))
return sum;

return parseNumber(sum);
}

public static ArrayList<Integer> getDigitsSquared(int input){
ArrayList<Integer> digits = new ArrayList<Integer>();
    while(input > 0) {
        digits.add((input % 10)*(input % 10));
        input /= 10;
    }
    return digits;
}
}


----------



## Midpipps

Good Answer new one is acoming
Quote:


> *Problem 3 - Sorting by Exclusion*
> 
> Professor Smith has been given a list of words to sort. However, she decided it would be easier to throw some words away so that the rest of the list (in the same relative order) will be sorted. Sadly, she can't even do this trick without help. That's why you need to do this.
> 
> *INPUT SPECIFICATION:* You will be given a set of input cases, each of which will begin with an unsigned decimal integer (representing the size of the list of words, no larger than 1000) followed by. Then will follow the list of words, consisting only of capital letters, of length not exceeding twenty, each followed by . The last input case will be followed by "0".
> 
> *OUTPUT SPECIFICATION:* The output cases should appear in the same order as the input cases. Each output case will be of the form "Case c: You only need to remove w word(s)!" (where c is the number of the input case and w is the SMALLEST number of words that can render the rest of the list sorted by their removal) followed by .
> 
> *SAMPLE INPUT:*
> 5
> OH
> THAT
> CAT
> IS
> HIGH
> 5
> A
> B
> C
> D
> E
> 0
> 
> *SAMPLE OUTPUT:*
> Case•1:•You•only•need•to•remove•3•word(s)!
> Case•2:•You•only•need•to•remove•0•word(s)!


----------



## serge2k

C#

Code:



Code:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Word_Remover
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            if (args.Length != 1)
                p.Go();
            else p.Go(args[0]);
            Console.ReadLine();
        }

        private void Go()
        {
            List<string[]> wordLists = new List<string[]>();
            while (true)
            {
                Console.Write("Number of words: ");
                int numWords;
                string input = Console.ReadLine();
                if (input == "")
                    break;
                if (!int.TryParse(input, out numWords))
                {
                    Console.WriteLine("Error: please enter an integer");
                    continue;
                }
                if (numWords == 0)
                    break;
                string[] words = new string[numWords];
                Console.WriteLine("Please enter words");
                for (int i = 0; i < numWords; i++)
                {
                    words[i] = Console.ReadLine();
                    if (string.IsNullOrEmpty(words[i]))
                    {
                        Console.WriteLine("You must enter a word: ");
                        i--;
                    }
                }
                wordLists.Add(words);
            }
            for(int i = 0; i < wordLists.Count; i++)
            {
                Remove(wordLists[i], i+1);
            }
        }

        private void Go(string filename)
        {
        }

        private void Remove(string[] words, int Case)
        {
            string[] sorted = (string[])words.Clone();
            Array.Sort(sorted);
            int removed = 0;
            int SP = 0, WP = 0;
            while(WP < words.Length && SP < sorted.Length)
            {
                if(words[WP] == sorted[SP])
                    SP++;
                else removed++;
                WP++;
            }
            Console.WriteLine("Case {0}: You only need to remove {1} words!", Case, removed);

        }
    }
}

It works interactively, don't really feel like finishing up the reading from file component.


----------



## austinb324

I have a pretty good challenge that I would like to post. I had to do it to get my current job. Should I post it in a week when Midpipps challenge is over or get two going?


----------



## impatient

I think he's trying to get it going every Wednesday, so people know when to come back. If you pm him, he will probably just not put one out if you want to do yours on Wednesday.

That said.. here's my broken implementation of the last one. It removes the ones not sorted.. it doesn't end up with the longest, since ZABC would only return Z, instead of the longer sorted ABC. Just haven't had time to fix it.

Code:


Code:


val s = io.Source.fromFile("input.txt").getLines.map(x => x.trim).toList

//val s ="5<EOLN>OH<EOLN>THAT<EOLN>CAT<EOLN>IS<EOLN>HIGH<EOLN>5<EOLN>A<EOLN>B<EOLN>C<EOLN>D<EOLN>E<EOLN>0<EOLN><EOF>"
var workArray = s.toList.reverse.tail.reverse //hhah

def excludeUnordered(uo:List[String], ord:List[String]):List[String] =
{

  val filtr = uo.takeWhile{i:String => /*println("A: " + i + " B:" + ord.head);*/ i >= ord.head}
  if(filtr.length == 0) { return ord.reverse; }
  return excludeUnordered(filtr.tail, filtr.head :: ord);
}

while(workArray.nonEmpty)
{
   var toSort = workArray.tail.takeWhile{i:String => !(('0' to '9') contains (i(0).toChar))}
   workArray = workArray.drop(1 + toSort.length)
   if(toSort.nonEmpty)
   { val ordered = excludeUnordered(toSort.tail, List(toSort.head));
     println("Change is " + (toSort.length - ordered.length) );
   }
 }


----------



## newbie1911

*C++*

Code:


Code:


#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

int getint (const string &str) {
stringstream ss(str);
int n;
ss >> n;
return n;
}

int main ()
{
  int length=1,c,w,max,current;
  int* values;
  string line;
  istringstream buffer;
  ifstream in;
  ofstream out;
  in.open("prob3in.txt");
  out.open("prob3out.txt");
  while(!in.eof()&& length != 0)
  {
      c++;
      getline (in,line);
      length = getint(line);
      values = new (nothrow) int[length];
      for(int i=0;i<length;i++)
      {
          getline (in,line);
          values[i] = (int)line[0];
      }
      for(int i=0;i<length;i++)
      {
          current = values[i];
          for(int x=i;x<length;x++)
          {
              if(current<values[x])
              {
                  w++;
                  current = values[x];
              }
              if(w>max) max = w;
          }
          w=1;
      }
      max = length - max;
      out << "Case " << c << ": You only need to remove " << max << " word(s)!\
";
      delete[] values;
      max = 0;
   }
   in.close();
   out.close();
   return 0;
}

my semi working code. 
right now the code looks for the longest string of sequential numbers (letters). the problem is that if there's a larger number and like three smaller ones the program ignores them since they're lower than the one we just got. so for example QWERTYUIOP is 81,87,69,82,84,89,85,73,79,80. so when looking for a string of numbers it takes 81 then 87 then ignores 69,82,84 sin they're all smaller then gets 89 and again ignores 85,73,79,80 since they're all lower than 89. now if we remove 87 then the string would be 81,82,84,89. now if there was a 86,87,88 etc.. after 85 then again we wouldn't reach those since 89 would be blocking them. 
tl;dr: no idea how to solve this.


----------



## MakubeX

Hey guys, please include what language you're using when you post the code. Like newbie1911 above should put C++ above the code block. That would be great, thanks.


----------



## austinb324

Well Wednesday is here and as promised I will post this weeks challenge. As stated before this is a challenge that I was given as a test to get my current job, as such it is a scanned image rather than text like previous posts. But anyways, I will post mine in a few days after a few people post theirs.


----------



## MakubeX

Quote:



Originally Posted by *austinb324*


Well Wednesday is here and as promised I will post this weeks challenge. As stated before this is a challenge that I was given as a test to get my current job, as such it is a scanned image rather than text like previous posts. But anyways, I will post mine in a few days after a few people post theirs.

http://i925.photobucket.com/albums/a...gChallenge.png


Is that current job with IBM?


----------



## austinb324

Quote:



Originally Posted by *MakubeX*


Is that current job with IBM?


I wish lol. No its a small software company called Wetstone Technologies. They make forensics software as well as doing gov contract work. I can see why you would think that though.


----------



## MakubeX

The test looks like a fun challenge, I'll see if I can find some time to do it.


----------



## austinb324

Quote:



Originally Posted by *MakubeX*


The test looks like a fun challenge, I'll see if I can find some time to do it.


Awesome. I hope several people attempt it b/c I always enjoy comparing methods of doing things. I will be really interested to see if anyone gets the first step exactly correct and whether it is different than my method.


----------



## newbie1911

C++

Code:



Code:


#include <iostream>
#include <conio.h>
#include <vector>

using namespace std;

int AtoE(const unsigned int c)
{
static unsigned int a2e[256] = {
          0,  1,  2,  3, 55, 45, 46, 47, 22,  5, 37, 11, 12, 13, 14, 15,
         16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31,
         64, 79,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97,
        240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111,
        124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,
        215,216,217,226,227,228,229,230,231,232,233, 74,224, 90, 95,109,
        121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150,
        151,152,153,162,163,164,165,166,167,168,169,192,106,208,161,  7,
         32, 33, 34, 35, 36, 21,  6, 23, 40, 41, 42, 43, 44,  9, 10, 27,
         48, 49, 26, 51, 52, 53, 54,  8, 56, 57, 58, 59,  4, 20, 62,225,
         65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87,
         88, 89, 98, 99,100,101,102,103,104,105,112,113,114,115,116,117,
        118,119,120,128,138,139,140,141,142,143,144,154,155,156,157,158,
        159,160,170,171,172,173,174,175,176,177,178,179,180,181,182,183,
        184,185,186,187,188,189,190,191,202,203,204,205,206,207,218,219,
        220,221,222,223,234,235,236,237,238,239,250,251,252,253,254,255
};
        return a2e[c];
}

int main()
{
int a;
vector<int> keyboard;
while(1)
{
if (_kbhit())
{ 
keyboard.push_back(_getch());
a = keyboard.size();
a--;
if(keyboard[a] >= 48 && keyboard[a] <= 57 || keyboard[a] >= 65 && keyboard[a] <= 90 || keyboard[a] >= 97 && keyboard[a] <= 122 || keyboard[a] == 32 || keyboard[a] == 33 || keyboard[a] == 46 || keyboard[a] == 44 || keyboard[a] == 59 || keyboard[a] == 63)
{
cout << (char)keyboard[a]; 
}
else if(keyboard[a] == 13)
{
system("cls");
for(int i=0;i<keyboard.size()-1;i++)
{
printf("%X ", keyboard[i]);     //hex
}
for(int i=0;i<keyboard.size();i++)
{
printf("%c", keyboard[i]);      //ascii
}
printf("\n");
for(int i=0;i<keyboard.size()-1;i++)
{
printf("%X ", AtoE(keyboard[i]));   //EBCDIC hex
}
for(int i=0;i<keyboard.size();i++)
{
printf("%c", keyboard[i]);        //ascii
}
}
else if(keyboard[a] == 8)
{
cout << (char)8 << (char)32 << (char)8; 
keyboard.pop_back();
keyboard.pop_back();
}
else keyboard.pop_back();
}
}
return 0;
}


----------



## austinb324

Good job man ^. I like the idea of a lookup table.


----------



## newbie1911

there's just two problems. in the example there's word wrap. no idea if that's important but i didn't bother doing that and also i have no idea what ADDR is ( address? if so an address of what? )


----------



## MakubeX

Quote:


> Originally Posted by *austinb324;14047279*
> Good job man ^. I like the idea of a lookup table.


Except he violated rule #4.


----------



## pjBSOD

I don't want to go off topic here, but does anyone know an actual site that can teach me the basics to learning programming on the side? I'm going to be studying CompSci, so having secondary early knowledge in programming would be awesome.

If you're going to ask what language, I'm most interested in C++ currently.


----------



## austinb324

Quote:


> Originally Posted by *newbie1911;14047347*
> there's just two problems. in the example there's word wrap. no idea if that's important but i didn't bother doing that and also i have no idea what ADDR is ( address? if so an address of what? )


That was just used for showing an example output. I dont know why it said ADDR but the output should look exactly as it did on the sheet.
Quote:


> Originally Posted by *MakubeX;14048317*
> Except he violated rule #4.


Well if your referring to conio.h, I don't think there is any other way to do it. I would love to see a solution where conio is not used. It is in the grey area b/c it is not technically a standard lib function but it is still included with all modern compilers.
Quote:


> Originally Posted by *E-Peen;14048343*
> I don't want to go off topic here, but does anyone know an actual site that can teach me the basics to learning programming on the side? I'm going to be studying CompSci, so having secondary early knowledge in programming would be awesome.
> 
> If you're going to ask what language, I'm most interested in C++ currently.


You know, I am not sure how good of a tutorial this site will have but I use cplusplus.com on a daily basis as a reference. click me


----------



## MakubeX

Quote:



Originally Posted by *austinb324*


Well if your referring to conio.h, I don't think there is any other way to do it. I would love to see a solution where conio is not used. It is in the grey area b/c it is not technically a standard lib function but it is still included with all modern compilers.
[/URL]


As long as it's ok with your employer.


----------



## austinb324

Quote:



Originally Posted by *MakubeX*


As long as it's ok with your employer.










Haha, apparently they didn't mind since I have a job







.


----------



## travesty

finally got around to doing the exclusion sort challenge. here's my solution in java. i only coded it to work for 1 case at a time though.

Code:


Code:


import java.util.*;

public class exclusionSort {

public static int sort(ArrayList<Integer> array){
int total_deletes = 0;
int num_deletes = -1;
while(num_deletes != 0){
num_deletes = 0;
for(int i=0; i<array.size()-1; i++){
if(array.get(i)>array.get(i+1)){
num_deletes++;
total_deletes++;
array.remove(i);
}
}
}
return total_deletes;
}

public static void main( String args[] ) {
int length = 0;
ArrayList<Integer> array = new ArrayList<Integer>();
try{
length = Integer.parseInt(args[0]);
}
catch(Exception e){
System.err.println("First argument must be an integer!");
}
for(int i=1; i<=length; i++){
array.add(Character.getNumericValue(args[i].charAt(0)));
}
int num_deletes = sort(array);
System.out.println("You only need to remove " + num_deletes + " word(s)!");
}
}

@austinb324, i will be attempting your challenge tomorrow. pretty sure i did a ascii/hex converter in assembly language last fall. now i just have to find that code lol.


----------



## austinb324

C++(without comments) I have one without comments b/c it is much easier to read the code this way(for me anyways).

Code:



Code:


#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>     
#include <vector>
#include <sstream>
#define ENTER 13

using namespace std;

void readFile(vector<string> &charV);    
void displayTable(const vector<char> input, const vector<string> charSet, 
                  const int numChars, const bool isASCII);

int main()
{
    vector<string> charSet;  
    vector<char> input;      
    char tempInput;          
    int numChars = 0;       
    int x, i;

    readFile(charSet);

    cout << "Begin your input: " << endl;
    do      
    {
         tempInput = getch();        
         if((tempInput >= 48 && tempInput <= 57)||(tempInput >= 65 && 
             tempInput <= 90)||(tempInput >= 97 && tempInput <= 122)||
             tempInput == 32||tempInput == 33||tempInput == 44||
             tempInput == 46||tempInput == 63||tempInput == 59)    
         {                                                                                                             
              input.push_back(tempInput);  
              cout << input.at(numChars);  
              numChars++;                 
         }
         else if(tempInput == 8 && numChars > 0)    
         {
              numChars--;     
              input.pop_back();   
              system("cls");

              cout << "Begin your input: " << endl;      
              for(x=0; x<numChars; x++)    
              {
                   cout << input.at(x);
              }    
         }
    }
    while(tempInput != ENTER);

    displayTable(input, charSet, numChars, true);    
    displayTable(input, charSet, numChars, false);

    cout << endl << endl;
    system("PAUSE");
    return 0;
}

void displayTable(const vector<char> input, const vector<string> charSet, 
                  const int numChars, const bool isASCII) 
{
     int i, x;   
     string tempString;  
     if(isASCII)     
          cout << "\n\nADDR  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F   ASCII" << endl;
     else
          cout << "\n\n\nADDR  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F   EBCDIC" << endl;

    i = 0;
    while(i < numChars)        
    {
         cout << endl;
         cout.width(4);   
         cout.fill('0');  
         cout << hex << i << ": ";

         for(x=0; x < 16; x++)  
         {
              if((x+i) < numChars)  
              {   
                   if(isASCII)      
                        cout << hex << (int)input[i+x] << " ";  
                   else
                   {
                        for(int j=0; j<charSet.size(); j++) 
                        {

                             stringstream ss;

                             ss << input[i+x];  
                             ss >> tempString;  
                             if((int)input[i+x] == 32)
                             {     
                                  cout << "40 ";   
                                  break;           
                             }
                             else if((charSet.at(j).compare(tempString)== 0)&&((int)input[i+x] != 32))
                                  cout << hex << j << " ";        
                        }    
                   }  
              }      
              else
                   cout << "   "; 
         }

         cout << "\t";

         for(x=0; x < 16 && x < numChars; x++)
         {
              if((x+i) < numChars)
                   cout << input[i+x];
              else
                   cout << " ";       
         } 
         i+=x; 
    }        
}

void readFile(vector<string> &charV)
{
     ifstream infile;  
     string tempChar;  
     infile.open("EBCDIC.txt" , ifstream::in);
     while (infile.good())
     {
          getline(infile, tempChar);   
          charV.push_back(tempChar);   
     }

     infile.close();   
}

C++(with comments)

Code:



Code:


#include <iostream>
#include <fstream>
#include <string>
#include <conio.h>       //Library that allows for unbuffered input from the keyboard
#include <vector>
#include <sstream>
#define ENTER 13

using namespace std;

void readFile(vector<string> &charV);     //function for reading file with the EBCDIC characters in it 
void displayTable(const vector<char> input, const vector<string> charSet, const int numChars, const bool isASCII);     //prints the char table in either ASCII or EBCDIC

int main()
{
    vector<string> charSet;  //vector where the EBCDIC char set is stored

    vector<char> input;      //vector where the keyboard is stored
    char tempInput;          //variable used for input validation
    int numChars = 0;        //counter to keep track of the number of characters entered
    int x, i;                //loop counters

    readFile(charSet);       //function call to read in the EBCDIC file

    cout << "Begin your input: " << endl;
    do      //main loop for keyboard input
    {
         tempInput = getch();        //function call from conio.h that detects keyboard event and takes the character off of the input buffer
         if((tempInput >= 48 && tempInput <= 57)||(tempInput >= 65 && tempInput <= 90)||(tempInput >= 97 && tempInput <= 122)||
             tempInput == 32||tempInput == 33||tempInput == 44||tempInput == 46||tempInput == 63||tempInput == 59)    //input validation that restricts the 
                                                                                                                      // possible input characters to the challenge requirements
         {
              input.push_back(tempInput);  //if the char passes validation, it gets pushed onto the storage vector
              cout << input.at(numChars);  //if the char passes validation, it gets displayed on the screen
              numChars++;                  //number of entered chars gets incremented
         }
         else if(tempInput == 8 && numChars > 0)    //if the entered char fails first validation, it is then tested to see if it is the backspace char
         {
              numChars--;     //number of chars is devcremented
              input.pop_back();   //the last entered char is popped out of the storage vector
              system("cls");      //the screen is cleared

              //The next 5 lines recreate the screen as if it had never been cleared except the last char is removed
              cout << "Begin your input: " << endl;      
              for(x=0; x<numChars; x++)    //loop to reprint all characters
              {
                   cout << input.at(x);
              }    
         }
    }
    while(tempInput != ENTER);

    displayTable(input, charSet, numChars, true);    //funciton call to create the Hex/ASCII table
    displayTable(input, charSet, numChars, false);   //funciton call to create the Hex/EBCDIC table

    cout << endl << endl;
    system("PAUSE");
    return 0;
}

void displayTable(const vector<char> input, const vector<string> charSet, const int numChars, const bool isASCII) //note - const used to be sure none of the variables values 
                                                                                                                  // are changed as this could cause problems
{
     int i, x;    //loop counters
     string tempString;  //temp variable used when converting input vector values from char to string for comparison
     if(isASCII)     //determines which char table heading will be printed
          cout << "\n\nADDR  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F   ASCII" << endl;
     else
          cout << "\n\n\nADDR  00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F   EBCDIC" << endl;

    i = 0;
    while(i < numChars)        //main print loop. Programmaticaly prints each line of the table
    {
         cout << endl;
         cout.width(4);   //sets width of left hand side line number to 4 as to emulate the challenge specification
         cout.fill('0');  //sets the empty space to be filled with the char 0. ie: 20 would be printed as 0020
         cout << hex << i << ": ";   //prints the position in the table of the first element in the current line. Each line has 16 elements.

         for(x=0; x < 16; x++)  //loop that will print one line of the left side of the table
         {
              if((x+i) < numChars)  //conditional statement that checks to see if you have reached the last item to be printed in the table. If so, 
                                    // line 106 prints blank spaces for each time this happens (up to 15 times)
              {   
                   if(isASCII)      //conditional statement to check to see which version of the table is supposed to be printed
                        cout << hex << (int)input[i+x] << " ";  //prints the integer value that is associated with each char(ASCII) in hexidecimal notation
                   else
                   {
                        for(int j=0; j<charSet.size(); j++) //loop that for each char, it will search for it in the vector where the EBCDIC values are stored.
                        {                                   // Upon finding it in the vector, the hexidecimal notaion of the position where it was found in the vector 
                                                            // is printed out.

                             stringstream ss;   //creation of string stream variable to handle conversion from char to string. This must be done since the 
                                                // input vector is in char form where the EBCDIC vector is in string form

                             ss << input[i+x];  //insertion of the current position of the input vector into the string stream variable
                             ss >> tempString;  //extraction of the value in string format
                             if((int)input[i+x] == 32) //test to see if the current char is a space. This was a cheap fix to handle an error the next statement 
                                                       // was having of not being able to match the space char
                             {     
                                  cout << "40 ";   //Prints the EBCDIC hex value for space
                                  break;           //stops loop from continueing. Breaks to the nearest outer loop.
                             }
                             else if((charSet.at(j).compare(tempString)== 0)&&((int)input[i+x] != 32)) //if the tempString value matches the current EBCDIC value then 
                                                                                                       // the loop counter will be equivalent to the char's EBCDIC value.
                                  cout << hex << j << " ";        
                        }    
                   }  
              }      
              else
                   cout << "   "; //comments on line 84
         }

         cout << "\t"; //Puts some space between the Hex side of the table and the char side of the table

         for(x=0; x < 16 && x < numChars; x++) //Prints all of the input characters in lines of 16 until the last char is reached, then it prints blank space
         {
              if((x+i) < numChars)
                   cout << input[i+x];
              else
                   cout << " ";       
         } 
         i+=x;  //outer while loop is incremented this way so that it only runs as many times as there is line to print     
    }        
}

void readFile(vector<string> &charV)  //note - vector variable passed by reference
{
     ifstream infile;  //create input file stream variable
     string tempChar;  //temp variable to store fileinput before it is pushed onto the vector
     infile.open("EBCDIC.txt" , ifstream::in);  //open the file in readonly mode
     while (infile.good())   //loop that runs until the end of file is reached or there is an error
     {
          getline(infile, tempChar);     //reads one line from file and stores it in the temp variable
          charV.push_back(tempChar);     //pushes value in the temp variable onto the vector
     }

     infile.close();     //closes input file
}


----------



## impatient

Here it is in scala. I can't filter the input from java, unless I made a gui or used something like JLine(which is essentially a wrapper around a terminal), which I looked at, but it's got different code for windows and linux. It'd be easier to write it in another language.

Another option was doing something like this. It just seemed like a hack.

Code:


Code:


package ebcdic
import java.nio.charset.Charset

object PuzzleReadline {

  val valid = (('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') ++ List(' ', '?', '.','!' , ':')).toSet
  val charSet = Charset.forName("cp500")

  def process()
  {
  val s = Console.readLine().filter(valid.contains(_))
  val hexValues = s.toList.map{c:Char =>Integer.toHexString(c.intValue) }

  val ebc = charSet.encode(s).array

  val ebcHex = ebc.map{ b:Byte => Integer.toHexString(b.toInt & 0xff)}

  println("Original:\ " + s.mkString("  |"))
  println("Hex:\\ " + hexValues.mkString(" |"))
  println("EBC Hex:\ " + ebcHex.mkString(" |"))
  }

  def main(args: Array[String])
  {
   process()

  }
}


----------



## S0ULphIRE

Easy to do in Cocoa by creating a new subclass of NSTextField.
edit: wow easy, this guy's done most of the work already. http://blog.gruby.com/2008/03/29/nst...-capabilities/

just add a popup window for the info that needs to be displayed, hidden until an IBAction is triggered to show it.
Ground work done, just need to add fields for ascii/hex to display in the window when triggered, and also a subroutine to convert from ascii to whatever.

edit: woo that's awesome, can't attach zip file
http://www.mediafire.com/file/s3o7d7n9vvaf0iv/PC1.zip


----------



## newbie1911

i would like to see another challenge.


----------



## Midpipps

Well here you go then









Quote:



*Problem 7 â€" Postage Stamps*

Professor Smith loves to travel around the United States during her summer break. She often writes long letters to her children detailing her adventures. Since a post office is not always handy, she buys large quantities of various stamp denominations and prints a current postal chart before she starts her travels. She carries a digital postage scale to weigh the letters so she can use exact postage to the penny. Being a bit eccentric, she always uses the fewest number of stamps possible using the stamp denominations she has previously purchased. She always buys 1-cent stamps to ensure exact postage, and enough stamps of each denomination so she never runs out of any denomination of stamps.

*INPUT SPECIFICATION:* You will be given a set of stamp denominations followed by several postage amounts. The first line begins with a single unsigned decimal (representing the number of stamp denominations) followed by <EOLN>. The second line contains that many unsigned decimal integers (representing the stamp denominations) separated by one space and followed by <EOLN>. The stamp denominations are sorted in ascending order and always start with 1 to ensure exact postage. The remaining lines each contain a single unsigned decimal integer (representing a postage amount) and followed by<EOLN>. The last input case will be followed by â€œ0<EOLN>â€.

*OUTPUT SPECIFICATION:* The output cases should appear in the same order as the input cases. Each output case will be of the form â€œCase c: The postage amount p can be made using s stamp(s).â€ (where c is the number of the input case, p is the postage amount, and s is the FEWEST number of stamps necessary to arrive at the postage amount) followed by <EOLN>.

*SAMPLE INPUT:*
6<EOLN>
1•5•10•12•25•50<EOLN>
18<EOLN>
120<EOLN>
79<EOLN>
0<EOLN>
<EOF>

*SAMPLE OUTPUT:*
Case•1:•The•postage•amount•18•can•be •made•using•3•stamp(s).<EOLN>
Case•2:•The•postage•amount•120•can•b e•made•using•4•stamp(s).<EOLN>
Case•3:•The•postage•amount•79•can•be •made•using•4•stamp(s).<EOLN>
<EOF>


and some inputs

Quote:



6
1 5 10 12 25 50
18
120
79
214
13
0


and their outputs

Quote:



Case 1: The postage amount 18 can be made using 3 stamp(s).
Case 2: The postage amount 120 can be made using 4 stamp(s).
Case 3: The postage amount 79 can be made using 4 stamp(s).
Case 4: The postage amount 214 can be made using 7 stamp(s).
Case 5: The postage amount 13 can be made using 2 stamp(s).


----------



## Tomiger

Dynamic programming ftw


----------



## MakubeX

Damn it, more challenges keep coming but my free time keeps getting shorter.


----------



## S0ULphIRE

Still learning Java







how's this?
edit: hmmm logic errors in stamp calculation still...derp dynamic programming was even mentioned already. facepalm.jpg

Code:


Code:


public class StampCalc {

    public static void main(String[] args) {
        Scanner kb = new Scanner(in);Scanner intkb = new Scanner(in);
        int i=0, count=0, u=0;
        out.print("Input available number of stamp denominations: ");
        int start = kb.nextInt();
        kb.nextLine();
        u = start - 1;
        out.print("Input stamp values serparated by spaces: ");
        String temp = kb.nextLine();
        int[] stampArray = new int[start]; 
        int[] amountArray;
        StringTokenizer sA = new StringTokenizer(temp);
        while (sA.hasMoreTokens())
        {
            stampArray[i] = Integer.parseInt(sA.nextToken());
            i++;
        }
        Arrays.sort(stampArray);
        ArrayList stampAmount = new ArrayList();
        out.print("Input postage amount, or enter 0 to finish: ");
        for( ; ; )
        {
            int chk = intkb.nextInt();
            if (chk == 0){
                amountArray = new int[stampAmount.size()];
                for (int p=0; p<stampAmount.size(); p++) amountArray[p] = (int)stampAmount.get(p);
                break;
            }
            stampAmount.add(chk);
            out.print("Next?: ");
        } 
        for(int z = 0; z < amountArray.length; z++){
            int totalAmount = amountArray[z];
            while (amountArray[z] != 0){
                if (amountArray[z] >= stampArray[u]){
                    amountArray[z] = amountArray[z] - stampArray[u];
                    count++;
                }
                else u--;
            }
            out.print("Case ");out.print(z);out.print(": The postage amount ");out.print(totalAmount);out.print(" can be made using ");out.print(count);out.println(" stamps");
            u = start-1; count=0;
        }
    }
}


----------



## S0ULphIRE

I was trying to implement HashMap but wasn't getting anywhere (didn't use when I declared the Map). Found this page though, even though it uses Hashtables instead it's pretty much the same thing. Props to that guy for making this work lol

Code:



Code:


import static java.lang.System.out;
import static java.lang.System.in;
import java.util.*;

public class StampCalc {
    public static HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
    public static void main(String[] args) {

        Scanner kb = new Scanner(in);Scanner intkb = new Scanner(in);
        int i=0;
        out.print("Input available number of stamp denominations: ");
        int start = kb.nextInt(); kb.nextLine();
        out.print("Input stamp values serparated by spaces: ");
        String temp = kb.nextLine();
        int[] stampArray = new int[start]; 
        int[] amountArray;
        StringTokenizer sA = new StringTokenizer(temp);
        while (sA.hasMoreTokens())
        {
            stampArray[i] = Integer.parseInt(sA.nextToken());
            i++;
        }
        Arrays.sort(stampArray);

        ArrayList stampAmount = new ArrayList();
        out.print("Input postage amount, or enter 0 to finish: ");
        for( ; ; )
        {
            int chk = intkb.nextInt();
            if (chk == 0){
                amountArray = new int[stampAmount.size()];
                for (int p=0; p<stampAmount.size(); p++) amountArray[p] = (int)stampAmount.get(p);
                break;
            }
            stampAmount.add(chk);
            out.print("Next?: ");
        }

        for(int y = 0;y<amountArray.length;y++){
        int minimum = dynTable(stampArray, amountArray[y]);
        out.print("Case ");out.print(y+1);out.print(": The postage amount ");out.print(amountArray[y]);out.print(" can be made using ");out.print(minimum);out.println(" stamps");
        }
    }

    public static int dynTable(int[] stampValue, int postAmount){
        if (postAmount <=0) return postAmount;
        int min = -1; 
        for (int z =0; z <= stampValue.length - 1; z++) 
        {
            int updateAmount = postAmount - stampValue[z];
            int stampCount=0;
            if (hash.get(updateAmount) != null) {
                stampCount = hash.get(updateAmount) + 1;
            } 
            else {
                stampCount = dynTable(stampValue, updateAmount);
                if (stampCount >= 0) stampCount++;
            }
            if ((stampCount > 0) && (min == -1 || stampCount < min)) {
                min = stampCount;
            }
        }
        hash.put(postAmount, min);
        return min;
    }
}


----------



## Midpipps

Here is the next one









Quote:



*Problem 1 â€" 15-Tile Puzzle*

Professor Smithâ€™s favorite puzzle as a child is the 15-tile puzzle in which 15 tiles and one blank space occupy a 4x4 grid. Tiles adjacent to the blank space horizontally or vertically can be slid into the blank space. The goal is to move the tiles around so that the numbers 1-15 are arranged numerically left to right and top to bottom with the blank space in the lower right corner. Not all initial arrangements result in a valid solution. In fact, exactly half of them do! Any arrangement may be moved to either the solution position or a â€œnear solutionâ€ position in which the 14 and 15 tiles are reversed. Given an initial arrangement of tiles, you are to determine whether the puzzle can be solved from that position.

*INPUT SPECIFICATION:* You will be given a set of input cases, each of which will be a 
16-character string followed by <EOLN>. The last input case will be followed by an extra <EOLN>.
Each input string will consist of 1-9, A-F (representing 10-15) and an asterisk, â€˜*â€™ (representing the blank space). Each of these characters will appear in the string exactly once, but they could appear in any order. This string represents a initial position in the 4x4 grid, with the first 4 characters representing the first row, the second 4 characters representing the second row, and so forth.

*OUTPUT SPECIFICATION:* The output cases should appear in the same order as the input cases. Each output case will be either â€œCase c: YESâ€ or â€œCase c: NOâ€ (where c is the case number) depending on whether the grid can be solved. <EOLN> follows each output case.

*SAMPLE INPUT:*
123456789ABCDEF*<EOLN>
123456789ABCDFE*<EOLN>
*123456789ABCDEF<EOLN>
<EOLN>
<EOF>

*SAMPLE OUTPUT:*
Case•1:•YES<EOLN>
Case•2:•NO<EOLN>
Case•3:•NO<EOLN>
<EOF>


----------



## newbie1911

Code:


Code:


#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
ofstream yourfile;
ifstream myfile;
string str;
int sum=0,cas=0,blank=0;
yourfile.open("prob1out.txt");
myfile.open("prob1.txt");
while(!myfile.eof())
{
cas++;
getline (myfile,str);
if(!str.empty())
{
for(int i = 0;i<str.length();i++)
{
if(str[i] != '*')
{
for(int x=i;x<str.length();x++)
{
if(str[x] != '*')
if((int)str[i] > (int)str[x]) sum++;
}
}
else blank = i;
}
blank = ceil((double)blank/4);
cout << blank << endl;
if(sum%2 == 0 && blank%2 != 0 || sum%2 != 0 && blank%2 == 0)
yourfile << "Case " << cas << ": YES" << " dot is in " << blank << "number is " << sum << endl;
else
yourfile << "Case " << cas << ": NO" << " dot is in " << blank << "number is " << sum << endl;
sum = 0;
}
}
myfile.close();
yourfile.close();
getchar();
    return 0;
}

here's an explanation how to solve this : http://www.cs.bham.ac.uk/~mdr/teachi...lvability.html

count inversions -> if the number is even the empty square has to be on an odd line or the opposite if the number's odd.
but that doesn't seem to comply with the given answers so i'm lost


----------



## {Unregistered}

It's been a while since any programming challenges were posted here. Midpips was the last person providing the challenges but it appears that he hasn't logged in in months.

I intend to update this thread with new challenges and anyone who wishes to contribute is welcome to PM me or post here.
*In fact, I'd really appreciate your help guys.*
Maybe we can discuss a way to organise this by dividing the responsibility of managing the challenges between members who are willing to help.

However, when I come to think of it, there is no point of this thread if no one is willing to participate as simply posting programming tasks will be pretty useless. I will put up a poll now to see how many people are interested in this kicking off again. Otherwise, I'll have to let this go.










~ {Unregistered}


----------



## Coma

You should make a new thread. It isn't obvious that people should go to the last post.


----------



## {Unregistered}

Quote:


> Originally Posted by *Coma*
> 
> You should make a new thread. It isn't obvious that people should go to the last post.


Thank you for the suggestion. Done and locked (until ever needed)!


----------

