Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Programming Challenge (Out-of-Date)
New Posts  All Forums:Forum Nav:

Programming Challenge (Out-of-Date) - Page 23  

Poll Results: Are you interested in participating in and/or helping organise and post these programming challenges?

 
  • 100% (2)
    I want to participate.
  • 0% (0)
    I want to contribute by helping posting and organise these challenges.
  • 0% (0)
    I'll only take part if other people are willing to participate.
  • 0% (0)
    I can help and participate - I love programming!
  • 0% (0)
    I do not wish to participate or help.
2 Total Votes  
post #221 of 306
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.
post #222 of 306
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.
    
CPUMotherboardGraphicsRAM
Q6600 DG33TL XFX 6950 2GB 4gigs Corsair XMS2 DDR2 
Hard DriveOptical DriveOSMonitor
1.5TB seagate 2X640GB Samsung DVDRW Windows Vista & Debian Linux Samsung 19" + Acer 24" Wide 
KeyboardPowerCaseMouse
Microsoft SideWinder X6 Antec 750 TruePower Raidmax Smilodon COOLER MASTER Sentinel 
Mouse Pad
RocketFish 
  hide details  
    
CPUMotherboardGraphicsRAM
Q6600 DG33TL XFX 6950 2GB 4gigs Corsair XMS2 DDR2 
Hard DriveOptical DriveOSMonitor
1.5TB seagate 2X640GB Samsung DVDRW Windows Vista & Debian Linux Samsung 19" + Acer 24" Wide 
KeyboardPowerCaseMouse
Microsoft SideWinder X6 Antec 750 TruePower Raidmax Smilodon COOLER MASTER Sentinel 
Mouse Pad
RocketFish 
  hide details  
post #223 of 306
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:
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\
", line, COMMA(encode(line)));
                else if (line.matches("[1-9][0-9]*"))
                    System.out.printf("%-22s %s\
", decode(line), COMMA(line));

                else break;
                }
            }
        catch (Exception e){
            e.printStackTrace();
            }
        }
    }
Code:
PS C:\mp> 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:\mp>

Edited by wimcle - 1/26/11 at 8:49pm
water damage
(7 items)
 
  
CPUMotherboardGraphicsRAM
2600k 4.5Ghz Asus p8p67 deluxe evga gtx980ti classified SLI 16G ddr3 1600 
Hard DriveOSMonitor
Samsung 850pro x2 Windows 7 Seiki sm40unp 
  hide details  
water damage
(7 items)
 
  
CPUMotherboardGraphicsRAM
2600k 4.5Ghz Asus p8p67 deluxe evga gtx980ti classified SLI 16G ddr3 1600 
Hard DriveOSMonitor
Samsung 850pro x2 Windows 7 Seiki sm40unp 
  hide details  
post #224 of 306
Here it is in scala. Comma's sucked for me too.. so I just left them out

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)); }
   }
post #225 of 306
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)?
Synthkart
(13 items)
 
  
CPUMotherboardGraphicsRAM
1055T Asus Onboard x4200 2x2GB GeIL DDR 1333 (9-9-9) 
Hard DriveOptical DriveOSMonitor
Seagate 320GB Sata3.0 Liteon iHAS124 Win7 x64 Some old crt 
KeyboardPowerCaseMouse
digital Raidmax-450K Some cheap raidmax Labtec 
Mouse Pad
  hide details  
Synthkart
(13 items)
 
  
CPUMotherboardGraphicsRAM
1055T Asus Onboard x4200 2x2GB GeIL DDR 1333 (9-9-9) 
Hard DriveOptical DriveOSMonitor
Seagate 320GB Sata3.0 Liteon iHAS124 Win7 x64 Some old crt 
KeyboardPowerCaseMouse
digital Raidmax-450K Some cheap raidmax Labtec 
Mouse Pad
  hide details  
post #226 of 306
Here is mine I also skipped the commas. The long rows of z really messed with me on the change back to numbers

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.
Edited by Midpipps - 1/26/11 at 10:34pm
    
CPUMotherboardGraphicsRAM
Q6600 DG33TL XFX 6950 2GB 4gigs Corsair XMS2 DDR2 
Hard DriveOptical DriveOSMonitor
1.5TB seagate 2X640GB Samsung DVDRW Windows Vista & Debian Linux Samsung 19" + Acer 24" Wide 
KeyboardPowerCaseMouse
Microsoft SideWinder X6 Antec 750 TruePower Raidmax Smilodon COOLER MASTER Sentinel 
Mouse Pad
RocketFish 
  hide details  
    
CPUMotherboardGraphicsRAM
Q6600 DG33TL XFX 6950 2GB 4gigs Corsair XMS2 DDR2 
Hard DriveOptical DriveOSMonitor
1.5TB seagate 2X640GB Samsung DVDRW Windows Vista & Debian Linux Samsung 19" + Acer 24" Wide 
KeyboardPowerCaseMouse
Microsoft SideWinder X6 Antec 750 TruePower Raidmax Smilodon COOLER MASTER Sentinel 
Mouse Pad
RocketFish 
  hide details  
post #227 of 306
Quote:
Originally Posted by kenolak View Post
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.
    
CPUMotherboardGraphicsRAM
Q6600 DG33TL XFX 6950 2GB 4gigs Corsair XMS2 DDR2 
Hard DriveOptical DriveOSMonitor
1.5TB seagate 2X640GB Samsung DVDRW Windows Vista & Debian Linux Samsung 19" + Acer 24" Wide 
KeyboardPowerCaseMouse
Microsoft SideWinder X6 Antec 750 TruePower Raidmax Smilodon COOLER MASTER Sentinel 
Mouse Pad
RocketFish 
  hide details  
    
CPUMotherboardGraphicsRAM
Q6600 DG33TL XFX 6950 2GB 4gigs Corsair XMS2 DDR2 
Hard DriveOptical DriveOSMonitor
1.5TB seagate 2X640GB Samsung DVDRW Windows Vista & Debian Linux Samsung 19" + Acer 24" Wide 
KeyboardPowerCaseMouse
Microsoft SideWinder X6 Antec 750 TruePower Raidmax Smilodon COOLER MASTER Sentinel 
Mouse Pad
RocketFish 
  hide details  
post #228 of 306
Looks like I have something to do tonight now.
post #229 of 306
easy in C#

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;
        }
    }
}
    
CPUMotherboardOSMonitor
2500k P8P67 Windows 7 Ultimate x64 22" phillips 
KeyboardPowerMouseMouse Pad
Cheap Logitech Antec Earthwatts 650W Razer Deathadder Razer eXactMat 
  hide details  
    
CPUMotherboardOSMonitor
2500k P8P67 Windows 7 Ultimate x64 22" phillips 
KeyboardPowerMouseMouse Pad
Cheap Logitech Antec Earthwatts 650W Razer Deathadder Razer eXactMat 
  hide details  
post #230 of 306
Quote:
Originally Posted by serge2k View Post
easy in C#

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.
New Posts  All Forums:Forum Nav:
  Return Home
  Back to Forum: Coding and Programming
This thread is locked  
Overclock.net › Forums › Software, Programming and Coding › Coding and Programming › Programming Challenge (Out-of-Date)