Showing posts with label UVA Online Judge Problem. Show all posts
Showing posts with label UVA Online Judge Problem. Show all posts

UVA - 401 - Palindromes

8:49 PM | , , , , ,



There is a problem on UVA online judge which called Palindrome. A palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers.Composing literature in palindromes is an example of constrained writing

A regular palindrome is a string of numbers or letters that is the same forward as backward. For example, the string "ABCDEDCBA" is a palindrome because it is the same when the string is read from left to right as when the string is read from right to left.


A mirrored string is a string for which when each of the elements of the string is changed to its reverse (if it has a reverse) and the string is read backwards the result is the same as the original string. For example, the string "3AIAE" is a mirrored string because "A" and "I" are their own reverses, and "3" and "E" are each others' reverses.


A mirrored palindrome is a string that meets the criteria of a regular palindrome and the criteria of a mirrored string. The string "ATOYOTA" is a mirrored palindrome because if the string is read backwards, the string is the same as the original and because if each of the characters is replaced by its reverse and the result is read backwards, the result is the same as the original string. Of course, "A""T""O", and "Y" are all their own reverses.


A list of all valid characters and their reverses is as follows.


CharacterReverseCharacterReverseCharacterReverse
AAMMYY
BNZ5
COO11
DP2S
E3Q3E
FR4
GS25Z
HHTT6
IIUU7
JLVV88
KWW9
LJXX



Note that O (zero) and 0 (the letter) are considered the same character and therefore ONLY the letter "0" is a valid character.

Input 

Input consists of strings (one per line) each of which will consist of one to twenty valid characters. There will be no invalid characters in any of the strings. Your program should read to the end of file.

Output 

For each input string, you should print the string starting in column 1 immediately followed by exactly one of the following strings.

STRINGCRITERIA
" -- is not a palindrome."if the string is not a palindrome and is not a mirrored string
" -- is a regular palindrome."if the string is a palindrome and is not a mirrored string
" -- is a mirrored string."if the string is not a palindrome and is a mirrored string
" -- is a mirrored palindrome."if the string is a palindrome and is a mirrored string

Note that the output line is to include the -'s and spacing exactly as shown in the table above and demonstrated in the Sample Output below.
In addition, after each output line, you must print an empty line.

Sample Input 

NOTAPALINDROME 
ISAPALINILAPASI 
2A3MEAS 
ATOYOTA

Sample Output 

NOTAPALINDROME -- is not a palindrome.
 
ISAPALINILAPASI -- is a regular palindrome.
 
2A3MEAS -- is a mirrored string.
 
ATOYOTA -- is a mirrored palindrome.



Source Code with java



import java.util.Scanner;
class Palindrome {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        String mir1="AEHIJLMOSTUVWXYZ12358";
        String mir2="A3HILJMO2TUVWXY51SEZ8";
        boolean NP,RP,MP,MS; //NP=Not Poly RP=Regular Poly
        //MP=Mirror Poly  MS=Mirror String
        String hasil;
        while(s.hasNext()){
            //if(s.hasNextLine()) System.out.println("Pindah baris");
            String asli=s.nextLine();          
            String kata=asli;
            kata.replaceAll("0", "O");
            int i=0,k,N=kata.length();
            k=N/2;
            int l=-1,m=-1;
            if(N%2==0) k++;
            MP=true;
            RP=true;
            NP=true;
            MS=true;
            while((i<=k)){
                l=mir1.indexOf(kata.charAt(i));
                m=mir2.indexOf(kata.charAt(N-i-1));
                if(((kata.charAt(i)==kata.charAt(N-i-1)))&&((MP==true)||(RP==true))){                  
                    MP=false;
                    RP=true;
                    if((l>=0)&&(m>=0)){
                        if(mir1.charAt(l)==mir2.charAt(m)){
                            MP=true;                      
                        }
                    }                      
                }else{
                    MP=false;
                    RP=false;
                    if((l>=0)&&(m>=0)){
                        if((mir1.charAt(l)==mir2.charAt(m))&&(MS==true)){
                            MS=true;                      
                        }
                    }else{
                        MS=false;
                    }
                }
                i++;
            }
            System.out.print(asli+" -- ");
            if(MP==true){
                System.out.println("is a mirrored palindrome");
            }else if(RP==true){
                System.out.println("is a regular palindrome");
            }else if(MS==true){
                System.out.println("is a mirrored string");
            }else{
                System.out.println("is not a palindrome");
            }
        }
    }
}






Read More

UVA – 575 – Skew Binary Code

8:29 PM | , , , , , , ,



There is a problem on UVA online judge which called Skew Binary Code Problem. When a number is expressed in decimal, the k-th digit represents a multiple of 10k. (Digits are numbered from right to left, where the least significant digit is number 0.) For example,

\begin{displaymath}81307_{10} = 8 \times 10^4 + 1 \times 10^3 + 3 \times 10^2 + ...
...mes 10^1 +
7 \times 10 0 = 80000 + 1000 + 300 + 0 + 7
= 81307.
\end{displaymath}


When a number is expressed in binary, the k-th digit represents a multiple of 2k. For example,

\begin{displaymath}10011_2 = 1 \times 2^4 + 0 \times 2^3 + 0 \times 2^2 + 1 \times 2^1 +
1 \times 2^0 = 16 + 0 + 0 + 2 + 1 = 19.
\end{displaymath}


In skew binary, the k-th digit represents a multiple of 2k+1 - 1. The only possible digits are 0 and 1, except that the least-significant nonzero digit can be a 2. For example,

\begin{displaymath}10120_{skew} = 1 \times (2^5 - 1) + 0 \times (2^4-1) + 1 \tim...
...2 \times (2^2-1) + 0 \times (2^1-1)
= 31 + 0 + 7 + 6 + 0 = 44.
\end{displaymath}


The first 10 numbers in skew binary are 0, 1, 2, 10, 11, 12, 20, 100, 101, and 102. (Skew binary is useful in some applications because it is possible to add 1 with at most one carry. However, this has nothing to do with the current problem.)

Input 

The input file contains one or more lines, each of which contains an integer n. If n = 0 it signals the end of the input, and otherwise n is a nonnegative integer in skew binary.

Output 

For each number, output the decimal equivalent. The decimal value of n will be at most 231 - 1 = 2147483647.

Sample Input 

10120
200000000000000000000000000000
10
1000000000000000000000000000000
11
100
11111000001110000101101102000
0

Sample Output 

44
2147483646
3
2147483647
4
7
1041110737



Code with java programming


import java.util.Scanner;
public class BinarySkew {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        String bil="";
        while(!(bil.equalsIgnoreCase("0"))){
            bil=s.next();
            int hasil=0;
            for (int i = 0; i < bil.length(); i++) {
                hasil+=(Integer.parseInt(bil.substring(i, i+1))*(Math.pow(2, bil.length()-i)-1));
            }
            System.out.println(hasil);
        }
    }
}



Output

















Read More

10776 - Determine The Combination UVA Online Judge Solve with Java

6:34 AM | , , , , , ,



import java.util.Scanner;
class Combinations {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        int M=-1,N=-1;
        while((M!=0)&&(N!=0)){
            N=s.nextInt();
            M=s.nextInt();
            long C,a=1,b=1;
            for (int i = 1; i <=M; i++) {
               a*=(N-i+1);
               b*=i;
            }
            C=a/b;
            System.out.println(N+" things taken "+M+" at a time is "+C+" exactly");
        }
    }
}

Read More

11512 - GATTACA - UVa Online Judge

6:29 AM | , , , , , , ,



import java.util.*;

class Gataca {
    public static void main(String[] args) {
        Scanner scn = new Scanner(System.in);
        int caseNum;
        caseNum = scn.nextInt();
        String dna ="";
        scn.nextLine();

        for(int i = 0; i < caseNum; i++) {
            dna = scn.nextLine();
            int len = dna.length();
            if(len > 1000) continue;
            String greater = null;
            int occur = 0;

            for (int j= len-1; j > 0; j--) {
                /// panjang substring
                ArrayList<String> arlSub = new ArrayList<String>();
                int tmpOcc = 0;
                String gTmp = "";
                for (int k = 0; (k+j) <= len; k++) {
                    String sub = dna.substring(k,k+j);
                    if(!arlSub.isEmpty()) {
                        if(arlSub.indexOf(sub) > 0) {
                            continue;
                        }
                    }
                    arlSub.add(sub);

                    int start = k;
                    int ocrTmp = 0;
                    while(start != -1) {
                        ocrTmp++;
                        start = dna.indexOf(sub, start +1);
                    }
                    if(ocrTmp >= tmpOcc) {
                        tmpOcc = ocrTmp;
                        gTmp = sub;
                    }
                }
                if(tmpOcc > 1) {
                    greater = gTmp;
                    occur = tmpOcc;
                    break;
                }
            }
            if(occur > 1) {
                System.out.println(greater + " " + occur);
            } else {
                System.out.println("No repetitions found!");
            }
        }
    }
}

Read More

101 - The Block Problem UVA Online Judge Solution with Java

5:47 AM | , , , ,



import java.util.Scanner;
public class blockproblem {
    int[] cariStack(int n,String str[],String cari){
        int x=-1,i=0;
        int indx=-1;
        int hasil[]=new int[2];
        do{
            if(str[i]!=null){
                x=str[i].indexOf(cari);
            }
            if(x>=0) indx=i;
            i++;
        }while((x<0)&&(i<n));
        hasil[0]=indx;
        hasil[1]=x;
        return hasil;
    }
    public static void main(String[] args) {
       Scanner s=new Scanner(System.in);
       blockproblem bp=new blockproblem();
       int n=s.nextInt();
       String st[]=new String[n];
       for (int i = 0; i < n; i++) {
            st[i]=String.valueOf(i);
       }
       String cmd="",src,pos,des;
       while(!(cmd.equalsIgnoreCase("quit"))){
            cmd=s.next();
            if(!(cmd.equalsIgnoreCase("quit"))){
                src=s.next();
                pos=s.next();
                des=s.next();
                if(cmd.equalsIgnoreCase("move")){
                    if(pos.equalsIgnoreCase("onto")){
                        int [] urut=bp.cariStack(n,st,src);
                        int [] urutdes=bp.cariStack(n,st,des);
                        if(urut[0]>=0){
                           if(st[urutdes[0]]==null) st[urutdes[0]] = src;
                           else st[urutdes[0]] += src;
                           if(st[urut[0]].length()==src.length()) {
                                st[urut[0]]=null;
                           }else if(urut[1]==0){
                                st[urut[0]]=st[urut[0]].substring(1, st[urut[0]].length());
                           }else if(urut[1]==st[urut[0]].length()-1){
                               st[urut[0]]=st[urut[0]].substring(0, st[urut[0]].length()-1);
                           }else{
                               st[urut[0]]=st[urut[0]].substring(0, urut[1]-1)
                                       + st[urut[0]].substring(urut[1]+1, st[urut[0]].length());
                           }
                        }
                    }else if(pos.equalsIgnoreCase("over")) {
                        int [] urut=bp.cariStack(n,st,src);
                        int [] urutdes=bp.cariStack(n,st,des);
                        if(urut[0]>=0){
                           if(st[urutdes[0]+1]==null) st[urutdes[0]+1] = src;
                           else st[urutdes[0] + 1] += src;
                           if(st[urut[0]].length()==src.length()) {
                                st[urut[0]]=null;
                           }else if(urut[1]==0){
                                st[urut[0]]=st[urut[0]].substring(1, st[urut[0]].length());
                           }else if(urut[1]==st[urut[0]].length()-1){
                               st[urut[0]]=st[urut[0]].substring(0, st[urut[0]].length()-1);
                           }else{
                               st[urut[0]]=st[urut[0]].substring(0, urut[1]-1)
                                       + st[urut[0]].substring(urut[1]+1, st[urut[0]].length());
                           }
                        }
                   }
                }else if(cmd.equalsIgnoreCase("pile")){
                    if(pos.equalsIgnoreCase("onto")){
                        if(Integer.parseInt(des)<n){
                            int [] urut=bp.cariStack(n,st,src);
                            if(urut[0]>=0){
                               if(st[Integer.parseInt(des)]==null) st[Integer.parseInt(des)] = st[urut[0]];
                               else st[Integer.parseInt(des)] += st[urut[0]];
                               st[urut[0]]=null;
                            }
                        }
                    }else if(pos.equalsIgnoreCase("over")) {
                        if(Integer.parseInt(des)<n-1){                           
                            int [] urut=bp.cariStack(n,st,src);
                            if(urut[0]>=0){
                               if(st[Integer.parseInt(des)+1]==null) st[Integer.parseInt(des) + 1] = st[urut[0]];
                               else st[Integer.parseInt(des) + 1] += st[urut[0]];
                               st[urut[0]]=null;
                            }
                        }
                    }
                }
           }
       }
        for (int i = 0; i < st.length; i++) {
            System.out.println(i+":"+st[i]);
        }
    }
}
Read More

100 - The 3n + 1 problem UVA Online Judge Solution

7:24 PM | , , , ,



import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        while(s.hasNextInt()){
            int bil1=s.nextInt();
            int bil2=s.nextInt();
            int max=1;
            int a,b;
            if(bil1>bil2){
                a=bil2;
                b=bil1;
            }else{
                a=bil1;
                b=bil2;
            }
            for (int i = a; i <= b; i++) {
                int n=i,jml=1;
                while(n!=1){
                    if(n%2!=0) n=3*n+1;
                    else n=n/2;
                    jml++;
                }
                if(jml>max) max=jml;
            }
            System.out.println(bil1 + " " + bil2 + " " +max);
            }
    }
}
Read More

263 - Number Chains - UVA Online Judge

2:37 PM | , , , ,


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.

Input and Output

The input consists of a sequence of positive numbers, all less than tex2html_wrap_inline27 , each on its own line, terminated by 0. The input file contains at most 5000 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

Solve of Problem

Number Chains Algorithm
1.   Get a number (M) as an integer number
2.   Check M value  If  M is a positive number greater than 0  then do next step ,  if M=0 then terminate the program , otherwise just  re input  M
3.   Set N by get a descending value of  M
4.   Set O by  an ascending value of M
5.   Set  P=N – O
6.   Set counter=1
7.   Print M as original number
8.   Do step 9 until 13 while N – O  is not same P ( I use Do … While ) , otherwise jump to step 14
9.   Print number chain ( N – O = P )
10. Set P =N – O
11. Set N by get a descending value of  P
12. Set O by get an ascending value of  P
13. Increase the counter  by 1
14. Print the counter as chain length
15. Back to step 1 for the next input until EOF

 Here is the code with java language

import java.util.Scanner;
class NumberChains {
    String getAsc(int num){
        char temp;
        char no[]=String.valueOf(num).toCharArray();
        for (int  i =0 ; i < (no.length)-1; i++) {
            for (int  j =0 ; j < (no.length)-1-i; j++) {
                if(no[j]>no[j+1]){
                    temp=no[j];
                    no[j]=no[j+1];
                    no[j+1]=temp;
                }
            }
        }
        return String.valueOf(no, 0, no.length);
    }
    String getDesc(int num){
        char temp;
        char no[]=String.valueOf(num).toCharArray();
        for (int  i =0 ; i < (no.length)-1; i++) {
            for (int  j =0 ; j < (no.length)-1-i; j++) {
                if(no[j]<no[j+1]){
                    temp=no[j];
                    no[j]=no[j+1];
                    no[j+1]=temp;
                }
            }
        }
        return String.valueOf(no, 0, no.length);
    }
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        NumberChains nc=new NumberChains();
        int M=-1;
        int counter;
        while(M!=0){
            M=s.nextInt();
            if(M!=0){
                int N=Integer.parseInt(nc.getDesc(M));
                int O=Integer.parseInt(nc.getAsc(M));
                counter=1;
                System.out.println("Original number was "+M);
                int P=N-O;
                do{
                    System.out.println(N+" - "+O+" = "+(N-O));
                    P=N-O;
                    N=Integer.parseInt(nc.getDesc(P));
                    O=Integer.parseInt(nc.getAsc(P));
                    counter++;
                }while(N-O!=P);
                System.out.println("Chain length "+counter);
            }
       }
    }
}

Read More

272 - TEX Quotes

11:58 AM | , , , ,

You are to write a program which converts text containing double-quote (") characters into text that is identical except that double-quotes have been replaced by the two-character sequences required by TeX for delimiting quotations with oriented double-quotes. The double-quote (") characters should be replaced appropriately by either `` if the " opens a quotation and by '' if the " closes a quotation. Notice that the question of nested quotations does not arise: The first " must be replaced by ``, the next by '', the next by ``, the next by '', the next by ``, the next by '', and so on. 
Input will consist of several lines of text containing an even number of double-quote (") characters. Input is ended with an end-of-file character. The text must be output exactly as it was input except that:

  • the first " in each pair is replaced by two ` characters: `` and
  • the second " in each pair is replaced by two ' characters: ''.
For this problem , you can try to resolve with this algorithm
  1. First of all you must identify an EOF input scanner
  2. Split string into some substring, for example i try with loop one by one (if you know better you can use it)
  3. Identify a variable as a sign of the first pair  or the second one , i use a boolean variable
  4. Test substring if contains " (double quoted) and replace them with `` for the first and '' for the second
Here is a complete source with java

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
        Scanner inp=new Scanner(System.in);
        boolean ganjil=true;
        while(inp.hasNext()){
            String str=inp.nextLine();
            if(str.isEmpty()) break;
                 for (int i = 0; i < str.length(); i++) {
                      String a=str.substring(i, i+1);
                      if(a.contains("\"")){
                           if(ganjil) {
                                a = a.replaceFirst("\"", "``");
                                ganjil=false;
                           }else{
                                a = a.replaceFirst("\"", "''");
                                ganjil=true;
                           }}
                     System.out.print(a);
             }
             System.out.println("");
     }
}

}
Read More

458 - The Decoder

1:16 AM | , , , , , , ,



This problem is writing a complete program that will correctly decode a set of characters into a valid message. It should read a given file of a simple coded set of characters and print the exact message that the characters contain. The code key for this simple coding is a one for one character substitution based upon a single arithmetic manipulation of the printable portion of the ASCII character set. For the complete information The Decode Problem

Here is soulution with java code 
import java.util.Scanner;
class Decode{
   public static void main(String args[]){
     Scanner s=new Scanner(System.in);
     char c;
     String kal;
     while((s.hasNext())){
       kal=s.nextLine();
       if(kal.isEmpty()==false){
        for(int i=0;i<kal.length();i++){
           c=(char) (kal.charAt(i)-7);
           System.out.print(c);
        }
        System.out.println();
      }else break;
    }
   }
}

 Here is ansi c code

#include <stdio.h>
main() {
   char *str;
   char c;
   int i;
   while(scanf("%s",str)!=EOF){
       for(i=0;i<str[i]!='\0';i++){
          c=str[i]-7;
            printf("%c",c);
       }
       printf("\n");
    }
}


Here is c++ code
#include <iostream>
using namespace std;
int main() {
   char str[255];
   char c;
   while(cin>>str){
       for(int i=0;str[i]!='\0';i++){
          c=str[i]-7;
            cout<<c;
       }
       cout<<endl;
    }
   return 0;
}
Read More

10055 - Hashmat the Brave Warrior

12:13 AM | , , , , , , ,



Hashmat is a brave warrior who with his group of young soldiers moves from one place to another to fight against his opponents. Before fighting he just calculates one thing, the difference between his soldier number and the opponent's soldier number. From this difference he decides whether to fight or not. Hashmat's soldier number is never greater than his opponent. The problem is make a program which finding difference of his soldier and his opponent's soldier. For the complete information read from http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=94&page=show_problem&problem=996.

Here is solution with java code

import java.util.Scanner;
class Hasmit {
    public static void main(String[] args) {
        Scanner inp=new Scanner(System.in);
        while(inp.hasNextLong()){
            long hasmit=inp.nextLong();
            long opp=inp.nextLong();
            long diff=Math.abs(opp-hasmit);
            System.out.println(diff);
        }
    }
}


 Here is solution with C++code
#include <iostream>
using namespace std;
int main() {
   long hasmit,opp;
   while(cin>>hasmit>>opp){
      long diff=opp-hasmit;
      if(diff<0) diff*=-1;
      cout<<diff<<endl;
   }
  return 0;
}

Here is solution with C code

#include <stdio.h>
main() {
   int hasmit,opp,diff;
   while(scanf("%d%d",&hasmit,&opp)!=EOF){
      diff=abs(opp-hasmit);
      printf("%d \n",diff);
   }
}

I used redirection standard input of  gcc , g++ and java compiler to execute codes on linux. You can use this code to build and test program but before it you must install gcc , g++  or jdk fisrt on your machine.
Here is the code:

alircute@alircute-Laptop:~$ g++ Hasmit.cpp -o Hasmit++
alircute@alircute-Laptop:~$ gcc Hasmit.c -o Hasmit
alircute@alircute-Laptop:~$ javac Hasmit.java
alircute@alircute-Laptop:~$ ./Hasmit++ < Hasmit.txt
420
3
11
2
alircute@alircute-Laptop:~$ ./Hasmit < Hasmit.txt
420
3
11
2
alircute@alircute-Laptop:~$ java Hasmit < Hasmit.txt
420
3
11
2
alircute@alircute-Laptop:~$

 The blue lines are source code that you execute and the red one is output program.


I just a newbie programmer , so if you have better algorithm than I. I would  so happy  if you share it  to me on my email address : etnoarelz@gmail.com  or  my Yahoo Messanger : alir.etno@yahoo.com


Read More